Compare commits
276 Commits
20240208_1
...
feature/SD
| Author | SHA1 | Date | |
|---|---|---|---|
| 21347036cc | |||
| 67170a87ca | |||
| cd042fc248 | |||
| 31f2195acb | |||
| 1b8b6f6304 | |||
| 7ab4f8a55f | |||
| 879fcb9d56 | |||
| ab761d0ac9 | |||
| b35d51f0ad | |||
| eb0b047994 | |||
| ac71a4a92a | |||
| 29677501e8 | |||
| 3821c88000 | |||
| fc52433878 | |||
| efdd30a8dd | |||
| a5ef9aebee | |||
| 900c00e6c2 | |||
| 0f3261185a | |||
| ed5817d6e2 | |||
| 2578efc638 | |||
| 0428bb9680 | |||
| 3aeb112f10 | |||
| 1f3caadc14 | |||
| 388ff5c36e | |||
| 7d7d0b508a | |||
| b0b4cc6298 | |||
| 30ddd694d1 | |||
| 7eecf7591f | |||
| ad035e63ad | |||
| 9e1e670faf | |||
| 5a0a5491cf | |||
| f85fce7127 | |||
| ec1f3939d6 | |||
| d086a88214 | |||
| 50ba382f6d | |||
| 36074a3765 | |||
| 4c490e21af | |||
| 2963c7b592 | |||
| e320f90a1a | |||
| f61df8763c | |||
| a275167a4b | |||
| 09cd7ba414 | |||
| 3ffa635387 | |||
| db8395fdd5 | |||
| 15041e3b44 | |||
| 5104bdb53f | |||
| 42858e0c30 | |||
| 10f6702573 | |||
| 3243008219 | |||
| 6b7d2057d7 | |||
| 60e43da598 | |||
| dae5d4cf21 | |||
| b7083541e8 | |||
| a26a2ee44f | |||
| a4b297dc9d | |||
| a2f169101b | |||
| eb1043eb3b | |||
| a62f804c25 | |||
| 60f9578a14 | |||
| 11bc54df6e | |||
| 831434267d | |||
| a554141182 | |||
| d5a9070a7f | |||
| 90e5874ba4 | |||
| 9e47404c91 | |||
| d4a1c85390 | |||
| 696d4a2f4b | |||
| cf3235b176 | |||
| ba198c9d2f | |||
| 574f747618 | |||
| 09ffd4090f | |||
| 50b1f43818 | |||
| aab7560ecb | |||
| 29c28367d1 | |||
| 8035b2c5c1 | |||
| bfbc459393 | |||
| a2d536d6d5 | |||
| 507aa7cd0d | |||
| 4af91e8c8d | |||
| 8f7215a57c | |||
| a71cf5517b | |||
| 5292edfd78 | |||
| f3e0ad8f60 | |||
| 26b17202df | |||
| 17b975a4fe | |||
| a94bb34c54 | |||
| 66dd299d09 | |||
| 8d2dfbf178 | |||
| bc6cd67e81 | |||
| 7ba6771112 | |||
| 4cac7be4cc | |||
| 14ce9cefc8 | |||
| 6fab1e8db5 | |||
| 7e2c4256f2 | |||
| 8c33b02dae | |||
| bc2f063ed8 | |||
| 1dc94e60a2 | |||
| f4eb510770 | |||
| c34b15aeae | |||
| 19ac975f14 | |||
| 074f939559 | |||
| d702d208ab | |||
| bbf199f6c7 | |||
| 4182ef790e | |||
| f01887dd50 | |||
| 0ca1bb46d3 | |||
| d2cfd915a4 | |||
| 64bfafbcf1 | |||
| 8e615a3ee9 | |||
| de6d9a82b7 | |||
| 9b5abfcdd4 | |||
| 857b6a150a | |||
| ffa4ded1fe | |||
| 7709c11636 | |||
| 06f8d99688 | |||
| 863d808914 | |||
| 11307be692 | |||
| 0ad90cf961 | |||
| d5c285fa45 | |||
| 8c5eba3031 | |||
| 0efbc8ba16 | |||
| 063ab02a28 | |||
| 80a65dbcb3 | |||
| cdaa89749b | |||
| edda17080d | |||
| 0871c50ceb | |||
| 3771891886 | |||
| 3aae8b5d24 | |||
| 4b17566d15 | |||
| 6128d3756c | |||
| 91bb735fb1 | |||
| 9f1489a9c8 | |||
| 02ac9d1559 | |||
| 2d6f27d8a6 | |||
| 8d143fa2ab | |||
| cc6f8dfa52 | |||
| 80333cc27e | |||
| d4883a25e7 | |||
| 504d5c8171 | |||
| ac3c048e7a | |||
| 8c2e407c10 | |||
| bb159584f0 | |||
| 3b269da398 | |||
| 94b44a723e | |||
| 7acd898115 | |||
| c751d70663 | |||
| 167feef6be | |||
| 7c7be3a89c | |||
| 1bf6f776e9 | |||
| 83acc13fe9 | |||
| 7b727538e7 | |||
| 5252a0d522 | |||
| 27cdb94dff | |||
| bd64c14e7c | |||
| d095e2c1b1 | |||
| 330a977e77 | |||
| e8df520abd | |||
| cdc9b35ccd | |||
| 0cb3aee12e | |||
| 75446207a5 | |||
| 75d1671e7b | |||
| 9a390dd6f1 | |||
| f225211ffd | |||
| d07f6ceeb2 | |||
| 65d1221fb6 | |||
| 56721f4730 | |||
| 42f5b96acb | |||
| 30374c6e98 | |||
| 0a13ab43d0 | |||
| 8b8486b3f2 | |||
| 9062f0b4f6 | |||
| a7c87523c9 | |||
| c609fd74eb | |||
| 8cfe60ae30 | |||
| 6a225715cb | |||
| f136e6b6bd | |||
| 0910a8ab50 | |||
| 407d9231e3 | |||
| 6e55d3f4af | |||
| dbb0f7c4a8 | |||
| be8dc47a94 | |||
| 71d4011d09 | |||
| 56e880e3c6 | |||
| c09af099da | |||
| 49ad5aed67 | |||
| 31d5b67ddf | |||
| baa0ddffd0 | |||
| 5d23629723 | |||
| e5a9e50742 | |||
| 77531c46e0 | |||
| ab2a1c07e1 | |||
| 9866736f04 | |||
| 7f1d091a6c | |||
| 27ef594142 | |||
| b8612733d5 | |||
| 3b0103c0f4 | |||
| 26a2646523 | |||
| 2966234133 | |||
| 5932496c97 | |||
| 501f270c86 | |||
| 21f34fd7ee | |||
| d1c131dc55 | |||
| 0b3fba112b | |||
| b36a2cff5b | |||
| dc5abf30a0 | |||
| b14b9be0aa | |||
| 2c41e6cbe7 | |||
| 3283f856ec | |||
| f1da0aeccd | |||
| 9dbfc8579b | |||
| d6aca23687 | |||
| 507498e6a7 | |||
| f1f7e8c276 | |||
| 7308e1e3e3 | |||
| 8d52017e07 | |||
| dea7babe92 | |||
| 97a6acb826 | |||
| ae03d4f5f4 | |||
| 686fea9daf | |||
| 962d3d6682 | |||
| 88287d95cb | |||
| 3406bd91b3 | |||
| c6d9ee4432 | |||
| e94198c242 | |||
| 3644be526d | |||
| 9a9142ad92 | |||
| 4e648347a5 | |||
| b84c488de0 | |||
| 3a2a8f3d4b | |||
| cf91030464 | |||
| 8d2186bfe9 | |||
| 78ed2a8da9 | |||
| 86bc5905d6 | |||
| b74d7baf84 | |||
| f0fb79b5e0 | |||
| 4b34d8a512 | |||
| 252faa7221 | |||
| 0534ddeb3e | |||
| 977c2bc050 | |||
| df46ac1e93 | |||
| eea5f9cb8b | |||
| 053641ee1d | |||
| dbf8a970f3 | |||
| 3c10bb06d5 | |||
| b698487227 | |||
| 138ee04105 | |||
| bddd9f6e4b | |||
| c608946385 | |||
| d7d862f5c4 | |||
| 23e256481b | |||
| a131410b91 | |||
| 1b31a31f50 | |||
| 2cad617ea9 | |||
| 6006d52f51 | |||
| c4f60a495e | |||
| 228f69062b | |||
| b18e445da1 | |||
| 0f4410c931 | |||
| 9f9165c780 | |||
| 11d24fe5c9 | |||
| fe2609948b | |||
| 41916d467b | |||
| a87811e3ef | |||
| f996b8c5bf | |||
| f322436c10 | |||
| 5a7cf6688c | |||
| 56ea796597 | |||
| ee1a22fcce | |||
| 265de6ffd2 | |||
| f363269313 | |||
| 4cc3732e30 | |||
| ffee3197e2 | |||
| c0dc4afd3b | |||
| f12428ae62 | |||
| 20822a5755 | |||
| 0d923a10d1 |
3
.gitattributes
vendored
3
.gitattributes
vendored
@@ -135,10 +135,13 @@ ems-contabil/src/main/java/it/integry/ems/contabil/service/ContabilService.java
|
||||
ems-contabil/src/main/java/it/integry/ems/contabil/service/DistinteIncassiDTO.java -text
|
||||
ems-contabil/src/main/java/it/integry/ems/contabil/type/ContabilImportFormat.java -text
|
||||
ems-contabil/src/main/resources/sepa/xsd/CBIBdyPaymentRequest.00.04.00.xsd -text
|
||||
ems-contabil/src/main/resources/sepa/xsd/CBIBdyPaymentRequest.00.04.01.xsd -text
|
||||
ems-contabil/src/main/resources/sepa/xsd/CBIHdrSrv.001.07.xsd -text
|
||||
ems-contabil/src/main/resources/sepa/xsd/CBIHdrTrt.001.07.xsd -text
|
||||
ems-contabil/src/main/resources/sepa/xsd/CBIPaymentRequest.00.04.00.xsd -text
|
||||
ems-contabil/src/main/resources/sepa/xsd/CBIPaymentRequestMsg.00.04.00.xsd -text
|
||||
ems-contabil/src/main/resources/sepa/xsd/CBIPaymentRequest.00.04.01.xsd -text
|
||||
ems-contabil/src/main/resources/sepa/xsd/CBIPaymentRequestMsg.00.04.01.xsd -text
|
||||
ems-contabil/src/main/resources/sepa/xsd/CBISgnInf.001.04.xsd -text
|
||||
ems-contabil/src/main/resources/sepa/xsd/binding.jxb -text
|
||||
ems-contabil/target/classes/it/integry/ems/contabil/it.integry.core.controller/ContabilController.class -text
|
||||
|
||||
@@ -108,6 +108,9 @@
|
||||
<element id="library" level="project" name="Maven: com.fasterxml.jackson.core:jackson-core:2.9.4" />
|
||||
<element id="library" level="project" name="Maven: com.fasterxml.jackson.core:jackson-databind:2.9.4" />
|
||||
<element id="library" level="project" name="Maven: com.fasterxml.jackson.dataformat:jackson-dataformat-csv:2.9.4" />
|
||||
<element id="library" level="project" name="Maven: com.alibaba:fastjson:2.0.47" />
|
||||
<element id="library" level="project" name="Maven: com.alibaba.fastjson2:fastjson2-extension:2.0.47" />
|
||||
<element id="library" level="project" name="Maven: com.alibaba.fastjson2:fastjson2:2.0.47" />
|
||||
<element id="library" level="project" name="Maven: org.springframework:spring-aop:4.2.5.RELEASE" />
|
||||
<element id="library" level="project" name="Maven: org.springframework:spring-core:4.2.5.RELEASE" />
|
||||
<element id="library" level="project" name="Maven: org.springframework:spring-instrument-tomcat:4.2.5.RELEASE" />
|
||||
@@ -254,7 +257,7 @@
|
||||
<element id="library" level="project" name="Maven: org.reflections:reflections:0.9.10" />
|
||||
<element id="library" level="project" name="Maven: org.javassist:javassist:3.19.0-GA" />
|
||||
<element id="library" level="project" name="Maven: com.google.code.findbugs:annotations:2.0.1" />
|
||||
<element id="library" level="project" name="Maven: com.google.code.gson:gson:2.5" />
|
||||
<element id="library" level="project" name="Maven: com.google.code.gson:gson:2.9.1" />
|
||||
<element id="library" level="project" name="Maven: org.apache.httpcomponents:httpclient:4.3.6" />
|
||||
<element id="library" level="project" name="Maven: org.apache.httpcomponents:httpcore:4.3.3" />
|
||||
<element id="library" level="project" name="Maven: commons-logging:commons-logging:1.1.3" />
|
||||
@@ -549,7 +552,6 @@
|
||||
<option value="$PROJECT_DIR$/ems-retail/pom.xml" />
|
||||
</set>
|
||||
</option>
|
||||
<option name="workspaceImportForciblyTurnedOn" value="true" />
|
||||
</component>
|
||||
<component name="PWA">
|
||||
<option name="wasEnabledAtLeastOnce" value="true" />
|
||||
@@ -829,6 +831,44 @@
|
||||
</option>
|
||||
</method>
|
||||
</configuration>
|
||||
<configuration default="false" name="Tomcat 7 #1 (ServerDev)" type="Remote">
|
||||
<module name="ems-engine" />
|
||||
<option name="USE_SOCKET_TRANSPORT" value="true" />
|
||||
<option name="SERVER_MODE" value="false" />
|
||||
<option name="SHMEM_ADDRESS" />
|
||||
<option name="HOST" value="serverdev" />
|
||||
<option name="PORT" value="8001" />
|
||||
<option name="AUTO_RESTART" value="false" />
|
||||
<RunnerSettings RunnerId="Debug">
|
||||
<option name="DEBUG_PORT" value="8001" />
|
||||
<option name="LOCAL" value="false" />
|
||||
</RunnerSettings>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration default="false" name="Tomcat 9 #2 (ServerDev)" type="Remote">
|
||||
<module name="ems-engine" />
|
||||
<option name="USE_SOCKET_TRANSPORT" value="true" />
|
||||
<option name="SERVER_MODE" value="false" />
|
||||
<option name="SHMEM_ADDRESS" />
|
||||
<option name="HOST" value="serverdev" />
|
||||
<option name="PORT" value="8002" />
|
||||
<option name="AUTO_RESTART" value="false" />
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration default="false" name="Tomcat #1 (ServerTomcat)" type="Remote">
|
||||
<module name="ems-engine" />
|
||||
<option name="USE_SOCKET_TRANSPORT" value="true" />
|
||||
<option name="SERVER_MODE" value="false" />
|
||||
<option name="SHMEM_ADDRESS" />
|
||||
<option name="HOST" value="servertomcat" />
|
||||
<option name="PORT" value="8000" />
|
||||
<option name="AUTO_RESTART" value="false" />
|
||||
<RunnerSettings RunnerId="Debug">
|
||||
<option name="DEBUG_PORT" value="8000" />
|
||||
<option name="LOCAL" value="false" />
|
||||
</RunnerSettings>
|
||||
<method v="2" />
|
||||
</configuration>
|
||||
<configuration default="false" name="Tomcat (FAST)" type="#com.intellij.j2ee.web.tomcat.TomcatRunConfigurationFactory" factoryName="Local" APPLICATION_SERVER_NAME="Tomcat" ALTERNATIVE_JRE_ENABLED="false" ALTERNATIVE_JRE_PATH="1.8" show_console_on_std_err="true" show_console_on_std_out="true">
|
||||
<option name="COMMON_VM_ARGUMENTS" value="-DDISABLE_DROOLS_COMPILE=TRUE -Xms256m -Xmx1024m -XX:PermSize=1024m" />
|
||||
<deployment>
|
||||
@@ -1080,6 +1120,42 @@
|
||||
<root url="jar://$MAVEN_REPOSITORY$/c3p0/c3p0/0.9.1.1/c3p0-0.9.1.1-sources.jar!/" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
<library name="Maven: com.alibaba.fastjson2:fastjson2-extension:2.0.47" type="java-imported" external-system-id="Maven">
|
||||
<properties groupId="com.alibaba.fastjson2" artifactId="fastjson2-extension" version="2.0.47" />
|
||||
<CLASSES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/alibaba/fastjson2/fastjson2-extension/2.0.47/fastjson2-extension-2.0.47.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/alibaba/fastjson2/fastjson2-extension/2.0.47/fastjson2-extension-2.0.47-javadoc.jar!/" />
|
||||
</JAVADOC>
|
||||
<SOURCES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/alibaba/fastjson2/fastjson2-extension/2.0.47/fastjson2-extension-2.0.47-sources.jar!/" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
<library name="Maven: com.alibaba.fastjson2:fastjson2:2.0.47" type="java-imported" external-system-id="Maven">
|
||||
<properties groupId="com.alibaba.fastjson2" artifactId="fastjson2" version="2.0.47" />
|
||||
<CLASSES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/alibaba/fastjson2/fastjson2/2.0.47/fastjson2-2.0.47.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/alibaba/fastjson2/fastjson2/2.0.47/fastjson2-2.0.47-javadoc.jar!/" />
|
||||
</JAVADOC>
|
||||
<SOURCES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/alibaba/fastjson2/fastjson2/2.0.47/fastjson2-2.0.47-sources.jar!/" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
<library name="Maven: com.alibaba:fastjson:2.0.47" type="java-imported" external-system-id="Maven">
|
||||
<properties groupId="com.alibaba" artifactId="fastjson" version="2.0.47" />
|
||||
<CLASSES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/alibaba/fastjson/2.0.47/fastjson-2.0.47.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/alibaba/fastjson/2.0.47/fastjson-2.0.47-javadoc.jar!/" />
|
||||
</JAVADOC>
|
||||
<SOURCES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/alibaba/fastjson/2.0.47/fastjson-2.0.47-sources.jar!/" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
<library name="Maven: com.amazonservices.mws:MWSClientJavaRuntime:1.1" type="java-imported" external-system-id="Maven">
|
||||
<properties groupId="com.amazonservices.mws" artifactId="MWSClientJavaRuntime" version="1.1" />
|
||||
<CLASSES>
|
||||
@@ -1464,16 +1540,16 @@
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/google/code/findbugs/jsr305/1.3.9/jsr305-1.3.9-sources.jar!/" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
<library name="Maven: com.google.code.gson:gson:2.5" type="java-imported" external-system-id="Maven">
|
||||
<properties groupId="com.google.code.gson" artifactId="gson" version="2.5" />
|
||||
<library name="Maven: com.google.code.gson:gson:2.9.1" type="java-imported" external-system-id="Maven">
|
||||
<properties groupId="com.google.code.gson" artifactId="gson" version="2.9.1" />
|
||||
<CLASSES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/google/code/gson/gson/2.5/gson-2.5.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/google/code/gson/gson/2.9.1/gson-2.9.1.jar!/" />
|
||||
</CLASSES>
|
||||
<JAVADOC>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/google/code/gson/gson/2.5/gson-2.5-javadoc.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/google/code/gson/gson/2.9.1/gson-2.9.1-javadoc.jar!/" />
|
||||
</JAVADOC>
|
||||
<SOURCES>
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/google/code/gson/gson/2.5/gson-2.5-sources.jar!/" />
|
||||
<root url="jar://$MAVEN_REPOSITORY$/com/google/code/gson/gson/2.9.1/gson-2.9.1-sources.jar!/" />
|
||||
</SOURCES>
|
||||
</library>
|
||||
<library name="Maven: com.google.errorprone:error_prone_annotations:2.0.18" type="java-imported" external-system-id="Maven">
|
||||
|
||||
@@ -83,6 +83,9 @@
|
||||
<classes>
|
||||
<class>it.integry.ems.response.ServiceRestResponse</class>
|
||||
</classes>
|
||||
<excludeClasses>
|
||||
<excludeClass>it.integry.ems_model.base.EntityInterface</excludeClass>
|
||||
</excludeClasses>
|
||||
<outputFile>../ts/ems-core.module.ts</outputFile>
|
||||
<outputKind>module</outputKind>
|
||||
<outputFileType>implementationFile</outputFileType>
|
||||
@@ -434,6 +437,12 @@
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba</groupId>
|
||||
<artifactId>fastjson</artifactId>
|
||||
<version>2.0.47</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Spring -->
|
||||
<dependency>
|
||||
<groupId>org.springframework</groupId>
|
||||
|
||||
@@ -359,7 +359,7 @@ public class WooCommerceArticoliDataManager {
|
||||
" where cod_mdep = dbo.getGestSetup('WOOCOMMERCE','SETUP','COD_MDEP')";
|
||||
|
||||
if (codMarts != null && codMarts.size() > 0) {
|
||||
sql += " AND lisv.cod_mart IN (" + UtilityQuery.concatFieldsWithSeparator(codMarts, ",") + ")";
|
||||
sql += " AND lisv.cod_mart IN (" + UtilityQuery.concatStringFieldsWithSeparator(codMarts, ",") + ")";
|
||||
}
|
||||
|
||||
PreparedStatement info = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
|
||||
|
||||
@@ -35,6 +35,12 @@ public class CommonConstants {
|
||||
public static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern(CommonConstants.TIME_FORMAT)
|
||||
.withZone(ZoneId.systemDefault());
|
||||
|
||||
public static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss")
|
||||
.withZone(ZoneId.systemDefault());
|
||||
|
||||
public static final DateTimeFormatter DATESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyMMdd")
|
||||
.withZone(ZoneId.systemDefault());
|
||||
|
||||
|
||||
public static final DateTimeFormatter DATE_YMD_DASHED_FORMATTER = DateTimeFormatter.ofPattern(CommonConstants.DATE_FORMAT_YMD)
|
||||
.withZone(ZoneId.systemDefault());
|
||||
|
||||
@@ -37,17 +37,10 @@ public class BooleanDeserializer extends JsonDeserializer<Boolean> {
|
||||
return Boolean.FALSE;
|
||||
}
|
||||
|
||||
// if ("N".equalsIgnoreCase(text) || text.length() == 0) {
|
||||
// return Boolean.FALSE;
|
||||
// }
|
||||
//
|
||||
// if ("Y".equalsIgnoreCase(text)) {
|
||||
// return Boolean.TRUE;
|
||||
// }
|
||||
throw ctxt.weirdStringException("", _valueClass, "only \"true\" or \"false\" recognized");
|
||||
}
|
||||
// Otherwise, no can do:
|
||||
throw ctxt.mappingException(_valueClass);
|
||||
throw ctxt.instantiationException(_valueClass, "error");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
package it.integry.ems.async.controller;
|
||||
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems.async.service.AsyncServiceNew;
|
||||
import it.integry.ems.controller.EmsController;
|
||||
import it.integry.ems.response.ServiceRestResponse;
|
||||
import it.integry.ems.response.StatusResponse;
|
||||
import it.integry.ems.status.ServiceChecker;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@Scope("request")
|
||||
@RequestMapping(EmsRestConstants.PATH_ASYNC_BASE_ROUTE)
|
||||
public class AsyncControllerNew {
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
|
||||
@Autowired
|
||||
private ServiceChecker serviceChecker;
|
||||
|
||||
@Autowired
|
||||
private AsyncServiceNew asyncServiceNew;
|
||||
|
||||
@RequestMapping(value = "/status", method = RequestMethod.GET)
|
||||
public @ResponseBody
|
||||
List<StatusResponse> status(HttpServletRequest request) {
|
||||
Method[] methods = EmsController.class.getDeclaredMethods();
|
||||
return serviceChecker.getServiceStatus(methods, EmsController.class);
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = EmsRestConstants.PATH_ASYNC_START, method = RequestMethod.GET)
|
||||
public @ResponseBody
|
||||
ServiceRestResponse start(
|
||||
HttpServletRequest request,
|
||||
@RequestParam(CommonConstants.PROFILE_DB) String configuration,
|
||||
@RequestParam String subscriptionName
|
||||
) throws Exception {
|
||||
asyncServiceNew.startSync(subscriptionName);
|
||||
return ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = EmsRestConstants.PATH_ASYNC_RETRIEVE_TRANSACTIONS, method = RequestMethod.GET)
|
||||
public @ResponseBody
|
||||
ServiceRestResponse retrieveTransactions(
|
||||
HttpServletRequest request,
|
||||
@RequestParam(CommonConstants.PROFILE_DB) String configuration,
|
||||
@RequestParam(value = "limit", required = false, defaultValue = "1") Integer limit
|
||||
) throws Exception {
|
||||
return ServiceRestResponse.createPositiveResponse(asyncServiceNew.retrieveTransactions(limit));
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = EmsRestConstants.PATH_ASYNC_UPDATE_TRANSACTION_IMPORT_ID, method = RequestMethod.GET)
|
||||
public @ResponseBody
|
||||
ServiceRestResponse updateTransactionImportID(HttpServletRequest request,
|
||||
@RequestParam Integer transactionImportID,
|
||||
@RequestParam String sender,
|
||||
@RequestParam String publicationID) throws Exception {
|
||||
|
||||
asyncServiceNew.updateTransactionImportCounterInDB(transactionImportID, publicationID, sender);
|
||||
return ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package it.integry.ems.async.dto;
|
||||
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
|
||||
public class SubscriptionDTO {
|
||||
|
||||
private String publicationId;
|
||||
private int lastTransactionIDImport = 0;
|
||||
private String entityName = null;
|
||||
private String whereCond = null;
|
||||
private MultiDBTransactionManager multiDBTransactionManager;
|
||||
|
||||
|
||||
public String getPublicationId() {
|
||||
return publicationId;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setPublicationId(String publicationId) {
|
||||
this.publicationId = publicationId;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getLastTransactionIDImport() {
|
||||
return lastTransactionIDImport;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setLastTransactionIDImport(int lastTransactionIDImport) {
|
||||
this.lastTransactionIDImport = lastTransactionIDImport;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEntityName() {
|
||||
return entityName;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setEntityName(String entityName) {
|
||||
this.entityName = entityName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getWhereCond() {
|
||||
return whereCond;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setWhereCond(String whereCond) {
|
||||
this.whereCond = whereCond;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MultiDBTransactionManager getMultiDBTransactionManager() {
|
||||
return multiDBTransactionManager;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setMultiDBTransactionManager(MultiDBTransactionManager multiDBTransactionManager) {
|
||||
this.multiDBTransactionManager = multiDBTransactionManager;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package it.integry.ems.async.dto;
|
||||
|
||||
public class SyncConfigDTO
|
||||
{
|
||||
private String endpoint;
|
||||
private String profileDb;
|
||||
private String username;
|
||||
|
||||
public String getEndpoint() {
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
public SyncConfigDTO setEndpoint(String endpoint) {
|
||||
this.endpoint = endpoint;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getProfileDb() {
|
||||
return profileDb;
|
||||
}
|
||||
|
||||
public SyncConfigDTO setProfileDb(String profileDb) {
|
||||
this.profileDb = profileDb;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public SyncConfigDTO setUsername(String username) {
|
||||
this.username = username;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
package it.integry.ems.async.dto;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
public class TransactionDTO {
|
||||
|
||||
public String publicationId;
|
||||
public int transactionId;
|
||||
public Date transactionDate;
|
||||
public String username;
|
||||
public String entityName;
|
||||
public String errorMsg;
|
||||
public String esito;
|
||||
public Date execDate;
|
||||
public String transactionJson;
|
||||
public int transactionGroupId;
|
||||
|
||||
public String getPublicationId() {
|
||||
return publicationId;
|
||||
}
|
||||
|
||||
public TransactionDTO setPublicationId(String publicationId) {
|
||||
this.publicationId = publicationId;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getTransactionId() {
|
||||
return transactionId;
|
||||
}
|
||||
|
||||
public TransactionDTO setTransactionId(int transactionId) {
|
||||
this.transactionId = transactionId;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Date getTransactionDate() {
|
||||
return transactionDate;
|
||||
}
|
||||
|
||||
public TransactionDTO setTransactionDate(Date transactionDate) {
|
||||
this.transactionDate = transactionDate;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public TransactionDTO setUsername(String username) {
|
||||
this.username = username;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEntityName() {
|
||||
return entityName;
|
||||
}
|
||||
|
||||
public TransactionDTO setEntityName(String entityName) {
|
||||
this.entityName = entityName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getErrorMsg() {
|
||||
return errorMsg;
|
||||
}
|
||||
|
||||
public TransactionDTO setErrorMsg(String errorMsg) {
|
||||
this.errorMsg = errorMsg;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEsito() {
|
||||
return esito;
|
||||
}
|
||||
|
||||
public TransactionDTO setEsito(String esito) {
|
||||
this.esito = esito;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Date getExecDate() {
|
||||
return execDate;
|
||||
}
|
||||
|
||||
public TransactionDTO setExecDate(Date execDate) {
|
||||
this.execDate = execDate;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getTransactionJson() {
|
||||
return transactionJson;
|
||||
}
|
||||
|
||||
public TransactionDTO setTransactionJson(String transactionJson) {
|
||||
this.transactionJson = transactionJson;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getTransactionGroupId() {
|
||||
return transactionGroupId;
|
||||
}
|
||||
|
||||
public TransactionDTO setTransactionGroupId(int transactionGroupId) {
|
||||
this.transactionGroupId = transactionGroupId;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,340 +0,0 @@
|
||||
package it.integry.ems.async.service;
|
||||
|
||||
import com.annimon.stream.Stream;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems.async.dto.SubscriptionDTO;
|
||||
import it.integry.ems.async.dto.SyncConfigDTO;
|
||||
import it.integry.ems.async.dto.TransactionDTO;
|
||||
import it.integry.ems.javabeans.RequestDataDTO;
|
||||
import it.integry.ems.json.JSONObjectMapper;
|
||||
import it.integry.ems.response.EsitoType;
|
||||
import it.integry.ems.response.ServiceRestResponse;
|
||||
import it.integry.ems.service.EntityProcessor;
|
||||
import it.integry.ems.service.HttpRestWrapper;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
import it.integry.ems_model.resolver.EntitySubTypeHolder;
|
||||
import it.integry.ems_model.service.SetupGest;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityHashMap;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.josql.Query;
|
||||
import org.josql.QueryResults;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.io.StringWriter;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@Scope("request")
|
||||
public class AsyncServiceNew {
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
|
||||
@Autowired
|
||||
private JSONObjectMapper jsonObjectMapper;
|
||||
|
||||
@Autowired
|
||||
private MultiDBTransactionManager multiDBTransactionManager;
|
||||
|
||||
|
||||
@Autowired
|
||||
private EntityProcessor entityProcessor;
|
||||
|
||||
@Autowired
|
||||
private RequestDataDTO requestData;
|
||||
|
||||
|
||||
@Autowired
|
||||
private SetupGest setupGest;
|
||||
|
||||
|
||||
|
||||
|
||||
public void startSync(String subscriptionName) throws Exception {
|
||||
|
||||
String jsonConfigurationString = setupGest.getSetup(multiDBTransactionManager.getPrimaryConnection(), "SINCRONIZZAZIONI_OFFLINE", "SETUP", subscriptionName);
|
||||
|
||||
if(UtilityString.isNullOrEmpty(jsonConfigurationString))
|
||||
throw new Exception("Nessuna configurazione trovata per la sincronizzazione: " + subscriptionName);
|
||||
|
||||
final List<SyncConfigDTO> syncConfigs = jsonObjectMapper.readValue(jsonConfigurationString, new TypeReference<List<SyncConfigDTO>>() {
|
||||
});
|
||||
|
||||
for (SyncConfigDTO syncConfig : syncConfigs) {
|
||||
String wsUrlEndpoint = syncConfig.getEndpoint() + EmsRestConstants.PATH_ASYNC_BASE_ROUTE + EmsRestConstants.PATH_ASYNC_RETRIEVE_TRANSACTIONS;
|
||||
|
||||
HashMap<String, String> queryParams = new HashMap<>();
|
||||
queryParams.put("profileDb", syncConfig.getProfileDb());
|
||||
|
||||
boolean shouldStop = false;
|
||||
|
||||
int importedTransactionsCounter = 0;
|
||||
|
||||
do {
|
||||
|
||||
StringBuilder responseBody = new StringBuilder();
|
||||
int status = HttpRestWrapper.callGenericGet(wsUrlEndpoint, syncConfig.getUsername(), syncConfig.getUsername(), responseBody, queryParams);
|
||||
|
||||
if (status != 200)
|
||||
throw new Exception("La richiesta \"" + wsUrlEndpoint + "\" ha generato status code: " + status + "<br />Body: " + responseBody);
|
||||
|
||||
ServiceRestResponse response = jsonObjectMapper.readValue(responseBody.toString(), ServiceRestResponse.class);
|
||||
|
||||
if (response.getEsito() == EsitoType.OK) {
|
||||
StringWriter writer = new StringWriter();
|
||||
jsonObjectMapper.writeValue(writer, response.getJsonObject());
|
||||
String dtoJson = writer.toString();
|
||||
|
||||
List<List<TransactionDTO>> transactions = jsonObjectMapper.readValue(dtoJson, new TypeReference<List<List<TransactionDTO>>>() {
|
||||
});
|
||||
|
||||
if (transactions.isEmpty() || transactions.get(0).isEmpty()) {
|
||||
if (importedTransactionsCounter == 0) logger.debug("Nessuna entity da sincronizzare");
|
||||
else logger.debug("Sincronizzazione OFFLINE terminata");
|
||||
shouldStop = true;
|
||||
} else {
|
||||
importedTransactionsCounter +=
|
||||
importTransactions(syncConfig.getEndpoint(), syncConfig.getProfileDb(), syncConfig.getUsername(), transactions);
|
||||
}
|
||||
|
||||
} else {
|
||||
throw new Exception("La richiesta \"" + wsUrlEndpoint + "\" ha generato un ESITO KO<br />Body: " + responseBody);
|
||||
}
|
||||
|
||||
} while (!shouldStop);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private int importTransactions(@NotNull String hostEndpoint, @NotNull String profileDb, @NotNull String username, @NotNull List<List<TransactionDTO>> transactionList) throws Exception {
|
||||
|
||||
int importedEntityCounter = 0;
|
||||
|
||||
|
||||
for (List<TransactionDTO> transactionDTOS : transactionList) {
|
||||
final List<Integer> transactionsIDGroups = new ArrayList<>();
|
||||
|
||||
for (TransactionDTO dto : transactionDTOS) {
|
||||
if (!transactionsIDGroups.contains(dto.transactionGroupId))
|
||||
transactionsIDGroups.add(dto.transactionGroupId);
|
||||
}
|
||||
|
||||
//Per ogni transaction group trovato mi prendo tutte le transactions
|
||||
for (int j = 0; j < transactionsIDGroups.size(); j++) {
|
||||
final int finalJ = j;
|
||||
List<TransactionDTO> transactionsToImport = Stream.of(transactionDTOS)
|
||||
.filter(transactionDTO -> transactionDTO.getTransactionGroupId() == transactionsIDGroups.get(finalJ))
|
||||
.toList();
|
||||
|
||||
List<EntityBase> entitiesToImport = new ArrayList<EntityBase>();
|
||||
|
||||
for (TransactionDTO transaction : transactionsToImport) {
|
||||
EntityBase entity = jsonObjectMapper.readValue(transaction.transactionJson, EntityBase.class);
|
||||
entitiesToImport.add(entity);
|
||||
}
|
||||
|
||||
|
||||
entityProcessor.processEntityList(null, false, true, false, entitiesToImport);
|
||||
|
||||
for (EntityBase importedEntity : entitiesToImport) {
|
||||
if (importedEntity.getException() != null) {
|
||||
throw importedEntity.getException();
|
||||
}
|
||||
}
|
||||
|
||||
importedEntityCounter += entitiesToImport.size();
|
||||
|
||||
updateTransactionImportCounterInRemote(hostEndpoint, profileDb, username, transactionsToImport);
|
||||
}
|
||||
}
|
||||
|
||||
return importedEntityCounter;
|
||||
|
||||
}
|
||||
|
||||
public List<List<TransactionDTO>> retrieveTransactions(int limit) throws Exception {
|
||||
String username = requestData.getUsername();
|
||||
|
||||
String sqlCheckActiveSubscriptions = "SELECT * " +
|
||||
" FROM stb_subscriptions_user " +
|
||||
" LEFT OUTER JOIN stb_subscriptions_user_detail ssud" +
|
||||
" on stb_subscriptions_user.publication_id = ssud.publication_id and" +
|
||||
" stb_subscriptions_user.user_name = ssud.user_name" +
|
||||
" WHERE stb_subscriptions_user.user_name = " + UtilityDB.valueToString(username) +
|
||||
" AND flag_attivo = 'S'";
|
||||
|
||||
|
||||
List<SubscriptionDTO> activeSubscriptions = new ArrayList<>();
|
||||
|
||||
//Lettura di tutte le sottoscrizioni attive (di tutte le entity)
|
||||
List<HashMap<String, Object>> result = UtilityDB.executeSimpleQuery(multiDBTransactionManager.getPrimaryConnection(), sqlCheckActiveSubscriptions);
|
||||
|
||||
if (!result.isEmpty()) {
|
||||
for (HashMap<String, Object> stringObjectHashMap : result) {
|
||||
activeSubscriptions.add(new SubscriptionDTO()
|
||||
.setPublicationId(UtilityHashMap.<String>getValueIfExists(stringObjectHashMap, "publication_id"))
|
||||
.setLastTransactionIDImport(UtilityHashMap.<Integer>getValueIfExists(stringObjectHashMap, "last_transaction_id_import"))
|
||||
.setEntityName(UtilityHashMap.<String>getValueIfExists(stringObjectHashMap, "entity_name"))
|
||||
.setWhereCond(UtilityHashMap.<String>getValueIfExists(stringObjectHashMap, "where_cond_sql")));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//Estraggo le transazione in base alle sottoscrizioni attive
|
||||
return getTransactionsFromSubscriptions(activeSubscriptions, limit);
|
||||
}
|
||||
|
||||
private List<List<TransactionDTO>> getTransactionsFromSubscriptions(List<SubscriptionDTO> subscriptionList, int limit) throws Exception {
|
||||
List<List<TransactionDTO>> groupOfTransactionsToBeExecuted = new ArrayList<>();
|
||||
|
||||
int totalTransactionsCounter = 0;
|
||||
|
||||
for (SubscriptionDTO subscriptionDTO : subscriptionList) {
|
||||
if (totalTransactionsCounter >= limit) break;
|
||||
|
||||
String sqlToRetrieveMaxGroupTransactionId = "SELECT min(transaction_group_id) as min_group, max(transaction_group_id) as max_group " +
|
||||
"FROM stb_transaction_log_db " +
|
||||
"WHERE transaction_id > " + UtilityDB.valueToString(subscriptionDTO.getLastTransactionIDImport()) + " AND " +
|
||||
"entity_name_list = " + UtilityDB.valueToString(subscriptionDTO.getEntityName());
|
||||
|
||||
HashMap<String, Object> transactionGroupsResult = UtilityDB.executeSimpleQueryOnlyFirstRow(multiDBTransactionManager.getPrimaryConnection(), sqlToRetrieveMaxGroupTransactionId);
|
||||
|
||||
if (transactionGroupsResult == null) continue;
|
||||
|
||||
Integer minTransactionGroupId = UtilityHashMap.getValueIfExists(transactionGroupsResult, "min_group");
|
||||
Integer maxTransactionGroupId = UtilityHashMap.getValueIfExists(transactionGroupsResult, "max_group");
|
||||
|
||||
if (minTransactionGroupId == null || maxTransactionGroupId == null) continue;
|
||||
|
||||
List<TransactionDTO> transactionsToBeProcessed = new ArrayList<>();
|
||||
|
||||
for (int i = minTransactionGroupId; i <= maxTransactionGroupId; i++) {
|
||||
if (totalTransactionsCounter >= limit) break;
|
||||
|
||||
String sqlToRetrieveTransactions = "SELECT * " +
|
||||
"FROM stb_transaction_log_db " +
|
||||
"WHERE transaction_group_id = " + UtilityDB.valueToString(i) + " AND " +
|
||||
"entity_name_list = " + UtilityDB.valueToString(subscriptionDTO.getEntityName()) + " " +
|
||||
"ORDER BY transaction_id";
|
||||
|
||||
List<HashMap<String, Object>> results = UtilityDB.executeSimpleQuery(multiDBTransactionManager.getPrimaryConnection(), sqlToRetrieveTransactions);
|
||||
|
||||
boolean shouldAdd = true;
|
||||
|
||||
for (HashMap<String, Object> result : results) {
|
||||
TransactionDTO transaction = new TransactionDTO()
|
||||
.setPublicationId(subscriptionDTO.getPublicationId())
|
||||
.setEntityName(UtilityHashMap.<String>getValueIfExists(result, "entity_name_list"))
|
||||
.setErrorMsg(UtilityHashMap.<String>getValueIfExists(result, "error_msg"))
|
||||
.setEsito(UtilityHashMap.<String>getValueIfExists(result, "esito"))
|
||||
.setExecDate(UtilityHashMap.<Date>getValueIfExists(result, "exec_date"))
|
||||
.setTransactionDate(UtilityHashMap.<Date>getValueIfExists(result, "transaction_date"))
|
||||
.setTransactionGroupId(UtilityHashMap.<Integer>getValueIfExists(result, "transaction_group_id"))
|
||||
.setTransactionId(UtilityHashMap.<Integer>getValueIfExists(result, "transaction_id"))
|
||||
.setTransactionJson(UtilityHashMap.<String>getValueIfExists(result, "transaction_json"))
|
||||
.setUsername(UtilityHashMap.<String>getValueIfExists(result, "user_name"));
|
||||
|
||||
if (!UtilityString.isNullOrEmpty(subscriptionDTO.getWhereCond())) {
|
||||
Class entityClass = UtilityHashMap.getValueIfExists(EntitySubTypeHolder.getMapType(), subscriptionDTO.getEntityName().toLowerCase());
|
||||
|
||||
EntityBase entity = jsonObjectMapper.readValue(transaction.transactionJson, EntityBase.class);
|
||||
|
||||
List<EntityBase> tmpList = new ArrayList<>();
|
||||
tmpList.add(entity);
|
||||
|
||||
String selectSql = "SELECT * FROM " + entityClass.getCanonicalName() + " WHERE " + subscriptionDTO.getWhereCond();
|
||||
|
||||
// Create a new Query.
|
||||
Query q = new Query();
|
||||
q.parse(selectSql);
|
||||
|
||||
QueryResults qr = q.execute(tmpList);
|
||||
tmpList = qr.getResults();
|
||||
|
||||
if (tmpList.size() == 0) {
|
||||
shouldAdd = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (shouldAdd) {
|
||||
transactionsToBeProcessed.add(transaction);
|
||||
totalTransactionsCounter++;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (transactionsToBeProcessed.size() > 0) groupOfTransactionsToBeExecuted.add(transactionsToBeProcessed);
|
||||
|
||||
}
|
||||
|
||||
return groupOfTransactionsToBeExecuted;
|
||||
}
|
||||
|
||||
|
||||
public void updateTransactionImportCounterInDB(int lastTransactionId, String publicationID, String username) throws Exception {
|
||||
String sql = "UPDATE stb_subscriptions_user " +
|
||||
"SET last_transaction_id_import = " + lastTransactionId + " " +
|
||||
"WHERE publication_id = " + UtilityDB.valueToString(publicationID) + " " +
|
||||
"AND user_name = " + UtilityDB.valueToString(username);
|
||||
|
||||
PreparedStatement psUpdate = multiDBTransactionManager.prepareStatement(sql);
|
||||
psUpdate.executeUpdate();
|
||||
multiDBTransactionManager.commitAll();
|
||||
psUpdate.close();
|
||||
}
|
||||
|
||||
private void updateTransactionImportCounterInRemote(String hostEndpoint, String profileDb, String username, List<TransactionDTO> importedTransactions) throws Exception {
|
||||
StringBuilder responseBody;
|
||||
String wsUrlEndpoint = hostEndpoint + EmsRestConstants.PATH_ASYNC_BASE_ROUTE + EmsRestConstants.PATH_ASYNC_UPDATE_TRANSACTION_IMPORT_ID;
|
||||
|
||||
List<String> publicationIDs = Stream.of(importedTransactions)
|
||||
.map(transactionDTO -> transactionDTO.getPublicationId())
|
||||
.distinct()
|
||||
.toList();
|
||||
|
||||
|
||||
List<TransactionDTO> maxOfTransactionsIDList = new ArrayList<>();
|
||||
for (final String publicationId : publicationIDs) {
|
||||
maxOfTransactionsIDList.add(Stream.of(importedTransactions)
|
||||
.filter(transactionDTO -> transactionDTO.getPublicationId().equalsIgnoreCase(publicationId))
|
||||
.max((o1, o2) -> o1.getTransactionId() - o2.getTransactionId()).get());
|
||||
}
|
||||
|
||||
for (TransactionDTO transactionDTO : maxOfTransactionsIDList) {
|
||||
int status;
|
||||
int retryCounter = 0;
|
||||
do {
|
||||
HashMap<String, String> queryParams = new HashMap<>();
|
||||
queryParams.put(CommonConstants.PROFILE_DB, profileDb);
|
||||
queryParams.put("publicationID", transactionDTO.getPublicationId());
|
||||
queryParams.put("sender", username);
|
||||
queryParams.put("transactionImportID", "" + transactionDTO.getTransactionId());
|
||||
|
||||
responseBody = new StringBuilder();
|
||||
status = HttpRestWrapper.callGenericGet(wsUrlEndpoint, username, username, responseBody, queryParams);
|
||||
|
||||
retryCounter++;
|
||||
} while (status != 200 && retryCounter < 4);
|
||||
|
||||
if (retryCounter == 4) {
|
||||
throw new Exception("La richiesta \"" + wsUrlEndpoint + "\" ha generato un ESITO KO<br />Body: " + responseBody);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -334,8 +334,8 @@ public class EmsController {
|
||||
List<EntityBase> entityList = new ArrayList<>();
|
||||
|
||||
if (obj != null) {
|
||||
if (obj instanceof EntityBase[]) {
|
||||
entityList = Arrays.asList((EntityBase[]) obj);
|
||||
if (obj instanceof List) {
|
||||
entityList = (List<EntityBase>) obj;
|
||||
} else {
|
||||
entityList.add((EntityBase) obj);
|
||||
}
|
||||
@@ -705,7 +705,7 @@ public class EmsController {
|
||||
if (ordinaSuPriorita)
|
||||
entityList = entityPropertyHolder.getEntityChain(entityList, multiDBTransactionManager.getPrimaryConnection());
|
||||
|
||||
Integer prevTransactionGroupId = null;
|
||||
Long prevTransactionGroupId = null;
|
||||
|
||||
for (EntityBase entity : entityList) {
|
||||
entity.setTransactionGroupId(prevTransactionGroupId);
|
||||
@@ -726,6 +726,7 @@ public class EmsController {
|
||||
|
||||
responseList.add(response);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error(request.getRequestURI(), e);
|
||||
response = new ServiceRestResponse(EsitoType.KO, e, multiDBTransactionManager.getPrimaryDatasource().getProfile(), entity);
|
||||
responseList.add(response);
|
||||
|
||||
@@ -13,6 +13,7 @@ import javax.annotation.PreDestroy;
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
@@ -61,6 +62,10 @@ public class DataSource {
|
||||
connection.setAutoCommit(false);
|
||||
|
||||
if (connectionModel.getConnectionType() == EmsRestConstants.DB_TYPE.MSSQL) {
|
||||
try (final PreparedStatement setNocountOn = connection.prepareStatement("SET NOCOUNT ON")) {
|
||||
boolean resultNoCount = setNocountOn.execute();
|
||||
}
|
||||
|
||||
HashMap<String, Object> resultSessionData = UtilityDB.executeSimpleQueryOnlyFirstRow(connection, "select @@spid AS session_id," +
|
||||
" user_name() AS [user_name]," +
|
||||
" suser_name() AS [suser_name]," +
|
||||
|
||||
@@ -1,13 +1,28 @@
|
||||
package it.integry.ems.dto;
|
||||
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.List;
|
||||
|
||||
public class EntityHierarchyDTO {
|
||||
|
||||
private Class<? extends EntityBase> clazz;
|
||||
private String entityName;
|
||||
private String tableName;
|
||||
private Field field;
|
||||
private boolean master;
|
||||
private List<EntityHierarchyDTO> children;
|
||||
|
||||
public Class<? extends EntityBase> getClazz() {
|
||||
return clazz;
|
||||
}
|
||||
|
||||
public EntityHierarchyDTO setClazz(Class<? extends EntityBase> clazz) {
|
||||
this.clazz = clazz;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEntityName() {
|
||||
return entityName;
|
||||
}
|
||||
@@ -24,6 +39,24 @@ public class EntityHierarchyDTO {
|
||||
this.tableName = tableName;
|
||||
}
|
||||
|
||||
public Field getField() {
|
||||
return field;
|
||||
}
|
||||
|
||||
public EntityHierarchyDTO setField(Field field) {
|
||||
this.field = field;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isMaster() {
|
||||
return master;
|
||||
}
|
||||
|
||||
public EntityHierarchyDTO setMaster(boolean master) {
|
||||
this.master = master;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<EntityHierarchyDTO> getChildren() {
|
||||
return children;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ public class ExtendedStbActivity {
|
||||
private String codJcom;
|
||||
private String codAnag;
|
||||
private String personaRif;
|
||||
private String emailPersonaRif;
|
||||
private String userName;
|
||||
private String userCreator;
|
||||
private String note;
|
||||
@@ -70,6 +71,15 @@ public class ExtendedStbActivity {
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEmailPersonaRif() {
|
||||
return emailPersonaRif;
|
||||
}
|
||||
|
||||
public ExtendedStbActivity setEmailPersonaRif(String emailPersonaRif) {
|
||||
this.emailPersonaRif = emailPersonaRif;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getUserName() {
|
||||
return userName;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ public class StbActivityEmailObject {
|
||||
private String subject;
|
||||
private List<StbActivityEmailObjectAddress> to;
|
||||
private String body;
|
||||
private boolean bodyInBase64;
|
||||
private List<StbActivityEmailObjectAttachment> attachments;
|
||||
|
||||
public StbActivityEmailObjectAddress getFrom() {
|
||||
@@ -77,6 +78,15 @@ public class StbActivityEmailObject {
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isBodyInBase64() {
|
||||
return bodyInBase64;
|
||||
}
|
||||
|
||||
public StbActivityEmailObject setBodyInBase64(boolean bodyInBase64) {
|
||||
this.bodyInBase64 = bodyInBase64;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<StbActivityEmailObjectAttachment> getAttachments() {
|
||||
return attachments;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.swing.text.html.parser.Entity;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -34,7 +33,8 @@ public class DynamicCacheService {
|
||||
|
||||
public enum Keys {
|
||||
DATI_AZIENDA_KEY,
|
||||
ENTITY_LOGGER_SETUP
|
||||
ENTITY_LOGGER_SETUP,
|
||||
GRIGLIA_ACQUISTO_KEY
|
||||
}
|
||||
|
||||
public void addItem(Keys key, int invalidateTimeInMins, RunnableWithReturn<Object> refreshAction) {
|
||||
@@ -79,14 +79,14 @@ public class DynamicCacheService {
|
||||
}
|
||||
|
||||
|
||||
public <T extends EntityBase>List<T> getEntity(Keys key, String dbName) {
|
||||
public <T extends EntityBase> List<T> getEntity(Keys key, String dbName) {
|
||||
dbName = dbName.toLowerCase();
|
||||
|
||||
final HashMap<String, List<? extends EntityBase>> cachedEntitiesByDB = (HashMap<String, List<? extends EntityBase>>) cacheData.getOrDefault(key, null);
|
||||
if(cachedEntitiesByDB == null) return null;
|
||||
if (cachedEntitiesByDB == null) return null;
|
||||
|
||||
final List<T> cachedEntityList = (List<T>) cachedEntitiesByDB.getOrDefault(dbName, null);
|
||||
if(cachedEntityList == null) return null;
|
||||
if (cachedEntityList == null) return null;
|
||||
|
||||
return cachedEntityList;
|
||||
}
|
||||
@@ -99,11 +99,60 @@ public class DynamicCacheService {
|
||||
String sql = "SELECT * FROM " + tableName;
|
||||
List<? extends EntityBase> entities = UtilityDB.executeSimpleQueryDTO(multiDBTransactionManager.getPrimaryConnection(), sql, clazz);
|
||||
|
||||
cachedEntitiesByDB.putIfAbsent(dbName, entities);
|
||||
cachedEntitiesByDB.putIfAbsent(dbName.toLowerCase(), entities);
|
||||
} finally {
|
||||
multiDBTransactionManager.closeAll();
|
||||
}
|
||||
}
|
||||
|
||||
public void addQuery(Keys key, int invalidateTimeInMins, String query, Class<?> clazz, List<String> dbNames) {
|
||||
List<String> finalDbNames = dbNames.stream().map(String::toLowerCase).collect(Collectors.toList());
|
||||
|
||||
RunnableWithReturn<Object> refreshAction = () -> {
|
||||
|
||||
Map<String, List<AvailableConnectionsModel>> databases = settingsModel.getAvailableConnections()
|
||||
.stream()
|
||||
.filter(AvailableConnectionsModel::getInternalDb)
|
||||
.filter(x -> finalDbNames.contains(x.getDbName().toLowerCase()))
|
||||
.collect(Collectors.groupingBy(AvailableConnectionsModel::getDbName));
|
||||
|
||||
final HashMap<String, List<?>> cacheQueryByDB = new HashMap<>();
|
||||
|
||||
for (String dbName : databases.keySet()) {
|
||||
try {
|
||||
String profileName = databases.get(dbName).get(0).getProfileName();
|
||||
cacheQueryByDB(dbName, profileName, query, clazz, cacheQueryByDB);
|
||||
} catch (Exception ex) {
|
||||
logger.error(ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
return cacheQueryByDB;
|
||||
};
|
||||
|
||||
addItem(key, invalidateTimeInMins, refreshAction);
|
||||
}
|
||||
|
||||
private void cacheQueryByDB(String dbName, String profileName, String query, Class<?> clazz, HashMap<String, List<?>> cacheObjectByDB) throws Exception {
|
||||
MultiDBTransactionManager m = new MultiDBTransactionManager(profileName, false);
|
||||
|
||||
try {
|
||||
List<?> objects = UtilityDB.executeSimpleQueryDTO(m.getPrimaryConnection(), query, clazz);
|
||||
cacheObjectByDB.putIfAbsent(dbName.toLowerCase(), objects);
|
||||
} finally {
|
||||
m.closeAll();
|
||||
}
|
||||
}
|
||||
|
||||
public <T extends EntityBase> List<T> getObject(Keys key, String dbName) {
|
||||
dbName = dbName.toLowerCase();
|
||||
|
||||
final HashMap<String, List<?>> cacheObjectByDB = (HashMap<String, List<?>>) cacheData.getOrDefault(key, null);
|
||||
if (cacheObjectByDB == null) return null;
|
||||
|
||||
final List<T> cachedEntityList = (List<T>) cacheObjectByDB.getOrDefault(dbName, null);
|
||||
if (cachedEntityList == null) return null;
|
||||
|
||||
return cachedEntityList;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package it.integry.ems.menu;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems.menu.dto.MenuConfigDTO;
|
||||
import it.integry.ems.menu.dto.StbMenuDTO;
|
||||
import it.integry.ems.menu.dto.StbMenuOpzDTO;
|
||||
import it.integry.ems.menu.dto.StbTipoAziendaDTO;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityLocalDate;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class MenuStaticCreator {
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("Running the Menu UPDATE");
|
||||
|
||||
String connectionString = String.format("jdbc:sqlserver://%s;databaseName=%s;applicationName=%s", "SERVERDB2019", "studioml", "IntelliJ Connection");
|
||||
String username = "sa";
|
||||
String password = "sa";
|
||||
|
||||
Connection connection = DriverManager.getConnection(connectionString, username, password);
|
||||
connection.setTransactionIsolation(java.sql.Connection.TRANSACTION_READ_UNCOMMITTED);
|
||||
connection.setAutoCommit(false);
|
||||
|
||||
final String baseProjectPath = new File("").getAbsolutePath() + "\\ems-core\\src\\main\\";
|
||||
final String menuJsonResourceFolder = baseProjectPath + "resources\\menus\\";
|
||||
|
||||
ObjectMapper jsonObjectMapper = new ObjectMapper();
|
||||
|
||||
final List<StbMenuOpzDTO> stbMenuOpzs = UtilityDB.executeSimpleQueryDTO(connection, "SELECT * FROM stb_menu_opz", StbMenuOpzDTO.class);
|
||||
|
||||
final List<StbTipoAziendaDTO> stbTipoAziendas = UtilityDB.executeSimpleQueryDTO(connection, "SELECT * FROM stb_tipo_azienda", StbTipoAziendaDTO.class);
|
||||
|
||||
final List<StbMenuDTO> stbMenus = UtilityDB.executeSimpleQueryDTO(connection, "SELECT * FROM stb_menu", StbMenuDTO.class);
|
||||
final Map<String, List<StbMenuDTO>> menusByAzienda = stbMenus.stream().collect(Collectors.groupingBy(StbMenuDTO::getTipoAzienda));
|
||||
|
||||
|
||||
MenuConfigDTO menuConfigDTO = new MenuConfigDTO(Integer.parseInt(CommonConstants.DATESTAMP_FORMATTER.format(UtilityLocalDate.getNow())))
|
||||
.setStbMenuOpz(stbMenuOpzs)
|
||||
.setStbTipoAzienda(stbTipoAziendas)
|
||||
.setMenusByAzienda(menusByAzienda);
|
||||
|
||||
writeContentToFile(menuJsonResourceFolder + "menu_config.json", jsonObjectMapper.writeValueAsString(menuConfigDTO), true);
|
||||
|
||||
connection.close();
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static void writeContentToFile(String filePath, String content, boolean overwrite) throws IOException {
|
||||
File f = new File(filePath);
|
||||
if (overwrite && f.exists()) f.delete();
|
||||
|
||||
FileOutputStream outputStream = new FileOutputStream(filePath);
|
||||
byte[] strToBytes = content.getBytes();
|
||||
outputStream.write(strToBytes);
|
||||
|
||||
outputStream.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package it.integry.ems.menu.controller;
|
||||
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems.menu.service.MenuConfigurationService;
|
||||
import it.integry.ems.response.ServiceRestResponse;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@Scope("request")
|
||||
@RequestMapping("system/menu")
|
||||
public class MenuConfigurationController {
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
@Autowired
|
||||
private MenuConfigurationService menuConfigurationService;
|
||||
|
||||
@Autowired
|
||||
private MultiDBTransactionManager multiDBTransactionManager;
|
||||
|
||||
@RequestMapping(value = "refresh", method = RequestMethod.GET)
|
||||
public @ResponseBody
|
||||
ServiceRestResponse refresh(@RequestParam(CommonConstants.PROFILE_DB) String profileDB) throws Exception {
|
||||
menuConfigurationService.refresh(multiDBTransactionManager.getPrimaryConnection());
|
||||
return ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package it.integry.ems.menu.dto;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class MenuConfigDTO {
|
||||
|
||||
private int version;
|
||||
private List<StbMenuOpzDTO> stbMenuOpz;
|
||||
private List<StbTipoAziendaDTO> stbTipoAzienda;
|
||||
private Map<String, List<StbMenuDTO>> menusByAzienda;
|
||||
|
||||
public MenuConfigDTO() {
|
||||
}
|
||||
|
||||
public MenuConfigDTO(int version) {
|
||||
this.version = version;
|
||||
}
|
||||
|
||||
public int getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public MenuConfigDTO setVersion(int version) {
|
||||
this.version = version;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<StbMenuOpzDTO> getStbMenuOpz() {
|
||||
return stbMenuOpz;
|
||||
}
|
||||
|
||||
public MenuConfigDTO setStbMenuOpz(List<StbMenuOpzDTO> stbMenuOpz) {
|
||||
this.stbMenuOpz = stbMenuOpz;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<StbTipoAziendaDTO> getStbTipoAzienda() {
|
||||
return stbTipoAzienda;
|
||||
}
|
||||
|
||||
public MenuConfigDTO setStbTipoAzienda(List<StbTipoAziendaDTO> stbTipoAzienda) {
|
||||
this.stbTipoAzienda = stbTipoAzienda;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Map<String, List<StbMenuDTO>> getMenusByAzienda() {
|
||||
return menusByAzienda;
|
||||
}
|
||||
|
||||
public MenuConfigDTO setMenusByAzienda(Map<String, List<StbMenuDTO>> menusByAzienda) {
|
||||
this.menusByAzienda = menusByAzienda;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
283
ems-core/src/main/java/it/integry/ems/menu/dto/StbMenuDTO.java
Normal file
283
ems-core/src/main/java/it/integry/ems/menu/dto/StbMenuDTO.java
Normal file
@@ -0,0 +1,283 @@
|
||||
package it.integry.ems.menu.dto;
|
||||
|
||||
import it.integry.ems_model.annotation.SqlField;
|
||||
import it.integry.ems_model.entity.StbMenu;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
|
||||
public class StbMenuDTO {
|
||||
|
||||
private String type = "stb_menu";
|
||||
|
||||
@SqlField(value = "cod_opz", maxLength = 5, nullable = false)
|
||||
private String codOpz;
|
||||
|
||||
@SqlField(value = "cod_parent", maxLength = 5, nullable = false)
|
||||
private String codParent;
|
||||
|
||||
@SqlField(value = "tipo_azienda", maxLength = 40, nullable = false)
|
||||
private String tipoAzienda;
|
||||
|
||||
@SqlField(value = "descrizione", maxLength = 255, nullable = true)
|
||||
private String descrizione;
|
||||
|
||||
@SqlField(value = "descrizione_estesa", maxLength = 8000, nullable = true)
|
||||
private String descrizioneEstesa;
|
||||
|
||||
@SqlField(value = "entity_name", maxLength = 40, nullable = true)
|
||||
private String entityName;
|
||||
|
||||
@SqlField(value = "flag_attivo", maxLength = 1, nullable = true, defaultObjectValue = "S")
|
||||
private String flagAttivo;
|
||||
|
||||
@SqlField(value = "flag_printer_setup", maxLength = 1, nullable = true, defaultObjectValue = "N")
|
||||
private String flagPrinterSetup;
|
||||
|
||||
@SqlField(value = "gest_name", maxLength = 40, nullable = true)
|
||||
private String gestName;
|
||||
|
||||
@SqlField(value = "note", maxLength = 255, nullable = true)
|
||||
private String note;
|
||||
|
||||
@SqlField(value = "object_type", maxLength = 5, nullable = true)
|
||||
private String objectType;
|
||||
|
||||
@SqlField(value = "open_type", maxLength = 1, nullable = true)
|
||||
private String openType;
|
||||
|
||||
@SqlField(value = "parameter", maxLength = 255, nullable = true)
|
||||
private String parameter;
|
||||
|
||||
@SqlField(value = "picture_menu", maxLength = 1024, nullable = true)
|
||||
private String pictureMenu;
|
||||
|
||||
@SqlField(value = "picture_select", maxLength = 1024, nullable = true)
|
||||
private String pictureSelect;
|
||||
|
||||
@SqlField(value = "pos", nullable = true)
|
||||
private Integer pos;
|
||||
|
||||
@SqlField(value = "pos_cliente", nullable = true)
|
||||
private Integer posCliente;
|
||||
|
||||
@SqlField(value = "pos_tipo_azienda", nullable = true)
|
||||
private Integer posTipoAzienda;
|
||||
|
||||
@SqlField(value = "type", maxLength = -1, nullable = true, defaultObjectValue = "F")
|
||||
private String menuType;
|
||||
|
||||
@SqlField(value = "url_descrizione", maxLength = 1024, nullable = true)
|
||||
private String urlDescrizione;
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public StbMenuDTO setType(String type) {
|
||||
this.type = type;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getCodOpz() {
|
||||
return codOpz;
|
||||
}
|
||||
|
||||
public StbMenuDTO setCodOpz(String codOpz) {
|
||||
this.codOpz = codOpz;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getCodParent() {
|
||||
return codParent;
|
||||
}
|
||||
|
||||
public StbMenuDTO setCodParent(String codParent) {
|
||||
this.codParent = codParent;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getTipoAzienda() {
|
||||
return tipoAzienda;
|
||||
}
|
||||
|
||||
public StbMenuDTO setTipoAzienda(String tipoAzienda) {
|
||||
this.tipoAzienda = tipoAzienda;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDescrizione() {
|
||||
return descrizione;
|
||||
}
|
||||
|
||||
public StbMenuDTO setDescrizione(String descrizione) {
|
||||
this.descrizione = descrizione;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDescrizioneEstesa() {
|
||||
return descrizioneEstesa;
|
||||
}
|
||||
|
||||
public StbMenuDTO setDescrizioneEstesa(String descrizioneEstesa) {
|
||||
this.descrizioneEstesa = descrizioneEstesa;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEntityName() {
|
||||
return entityName;
|
||||
}
|
||||
|
||||
public StbMenuDTO setEntityName(String entityName) {
|
||||
this.entityName = entityName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getFlagAttivo() {
|
||||
return flagAttivo;
|
||||
}
|
||||
|
||||
public StbMenuDTO setFlagAttivo(String flagAttivo) {
|
||||
this.flagAttivo = flagAttivo;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getFlagPrinterSetup() {
|
||||
return flagPrinterSetup;
|
||||
}
|
||||
|
||||
public StbMenuDTO setFlagPrinterSetup(String flagPrinterSetup) {
|
||||
this.flagPrinterSetup = flagPrinterSetup;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getGestName() {
|
||||
return gestName;
|
||||
}
|
||||
|
||||
public StbMenuDTO setGestName(String gestName) {
|
||||
this.gestName = gestName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getNote() {
|
||||
return note;
|
||||
}
|
||||
|
||||
public StbMenuDTO setNote(String note) {
|
||||
this.note = note;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getObjectType() {
|
||||
return objectType;
|
||||
}
|
||||
|
||||
public StbMenuDTO setObjectType(String objectType) {
|
||||
this.objectType = objectType;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getOpenType() {
|
||||
return openType;
|
||||
}
|
||||
|
||||
public StbMenuDTO setOpenType(String openType) {
|
||||
this.openType = openType;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getParameter() {
|
||||
return parameter;
|
||||
}
|
||||
|
||||
public StbMenuDTO setParameter(String parameter) {
|
||||
this.parameter = parameter;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPictureMenu() {
|
||||
return pictureMenu;
|
||||
}
|
||||
|
||||
public StbMenuDTO setPictureMenu(String pictureMenu) {
|
||||
this.pictureMenu = pictureMenu;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPictureSelect() {
|
||||
return pictureSelect;
|
||||
}
|
||||
|
||||
public StbMenuDTO setPictureSelect(String pictureSelect) {
|
||||
this.pictureSelect = pictureSelect;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Integer getPos() {
|
||||
return pos;
|
||||
}
|
||||
|
||||
public StbMenuDTO setPos(Integer pos) {
|
||||
this.pos = pos;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Integer getPosCliente() {
|
||||
return posCliente;
|
||||
}
|
||||
|
||||
public StbMenuDTO setPosCliente(Integer posCliente) {
|
||||
this.posCliente = posCliente;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Integer getPosTipoAzienda() {
|
||||
return posTipoAzienda;
|
||||
}
|
||||
|
||||
public StbMenuDTO setPosTipoAzienda(Integer posTipoAzienda) {
|
||||
this.posTipoAzienda = posTipoAzienda;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getMenuType() {
|
||||
return menuType;
|
||||
}
|
||||
|
||||
public StbMenuDTO setMenuType(String menuType) {
|
||||
this.menuType = menuType;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getUrlDescrizione() {
|
||||
return urlDescrizione;
|
||||
}
|
||||
|
||||
public StbMenuDTO setUrlDescrizione(String urlDescrizione) {
|
||||
this.urlDescrizione = urlDescrizione;
|
||||
return this;
|
||||
}
|
||||
|
||||
public StbMenu toEntity() {
|
||||
return new StbMenu()
|
||||
.setCodOpz(getCodOpz())
|
||||
.setCodParent(UtilityString.isNullOrEmpty(getCodParent()) ? "ROOT" : getCodParent())
|
||||
.setTipoAzienda(getTipoAzienda())
|
||||
.setDescrizione(getDescrizione())
|
||||
.setDescrizioneEstesa(getDescrizioneEstesa())
|
||||
.setEntityName(getEntityName())
|
||||
.setFlagAttivo(getFlagAttivo())
|
||||
.setFlagPrinterSetup(getFlagPrinterSetup())
|
||||
.setGestName(getGestName())
|
||||
.setNote(getNote())
|
||||
.setObjectType(getObjectType())
|
||||
.setOpenType(getOpenType())
|
||||
.setParameter(getParameter())
|
||||
.setPictureMenu(getPictureMenu())
|
||||
.setPictureSelect(getPictureSelect())
|
||||
.setPos(getPos())
|
||||
.setPosCliente(getPosCliente())
|
||||
.setPosTipoAzienda(getPosTipoAzienda())
|
||||
.setMenuType(getMenuType())
|
||||
.setUrlDescrizione(getUrlDescrizione());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package it.integry.ems.menu.dto;
|
||||
|
||||
import it.integry.ems_model.annotation.SqlField;
|
||||
import it.integry.ems_model.entity.StbMenuOpz;
|
||||
|
||||
public class StbMenuOpzDTO {
|
||||
|
||||
private String type = "stb_menu_opz";
|
||||
|
||||
@SqlField(value = "cod_opz", maxLength = 5, nullable = false)
|
||||
private String codOpz;
|
||||
|
||||
@SqlField(value = "descrizione", maxLength = 255, nullable = false)
|
||||
private String descrizione;
|
||||
|
||||
@SqlField(value = "entity_name", maxLength = 40, nullable = true)
|
||||
private String entityName;
|
||||
|
||||
@SqlField(value = "flag_printer_setup", maxLength = 1, nullable = true, defaultObjectValue = "N")
|
||||
private String flagPrinterSetup;
|
||||
|
||||
@SqlField(value = "gest_name", maxLength = 40, nullable = true)
|
||||
private String gestName;
|
||||
|
||||
@SqlField(value = "is_deprecated", maxLength = 1, nullable = false, defaultObjectValue = "N")
|
||||
private String isDeprecated;
|
||||
|
||||
@SqlField(value = "note", maxLength = 255, nullable = true)
|
||||
private String note;
|
||||
|
||||
@SqlField(value = "object_type", maxLength = 5, nullable = true)
|
||||
private String objectType;
|
||||
|
||||
@SqlField(value = "open_type", maxLength = 1, nullable = true)
|
||||
private String openType;
|
||||
|
||||
@SqlField(value = "parameter", maxLength = 255, nullable = true)
|
||||
private String parameter;
|
||||
|
||||
@SqlField(value = "picture_menu", maxLength = 1024, nullable = true)
|
||||
private String pictureMenu;
|
||||
|
||||
@SqlField(value = "picture_select", maxLength = 1024, nullable = true)
|
||||
private String pictureSelect;
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setType(String type) {
|
||||
this.type = type;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getCodOpz() {
|
||||
return codOpz;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setCodOpz(String codOpz) {
|
||||
this.codOpz = codOpz;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDescrizione() {
|
||||
return descrizione;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setDescrizione(String descrizione) {
|
||||
this.descrizione = descrizione;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEntityName() {
|
||||
return entityName;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setEntityName(String entityName) {
|
||||
this.entityName = entityName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getFlagPrinterSetup() {
|
||||
return flagPrinterSetup;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setFlagPrinterSetup(String flagPrinterSetup) {
|
||||
this.flagPrinterSetup = flagPrinterSetup;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getGestName() {
|
||||
return gestName;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setGestName(String gestName) {
|
||||
this.gestName = gestName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getIsDeprecated() {
|
||||
return isDeprecated;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setIsDeprecated(String isDeprecated) {
|
||||
this.isDeprecated = isDeprecated;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getNote() {
|
||||
return note;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setNote(String note) {
|
||||
this.note = note;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getObjectType() {
|
||||
return objectType;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setObjectType(String objectType) {
|
||||
this.objectType = objectType;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getOpenType() {
|
||||
return openType;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setOpenType(String openType) {
|
||||
this.openType = openType;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getParameter() {
|
||||
return parameter;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setParameter(String parameter) {
|
||||
this.parameter = parameter;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPictureMenu() {
|
||||
return pictureMenu;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setPictureMenu(String pictureMenu) {
|
||||
this.pictureMenu = pictureMenu;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPictureSelect() {
|
||||
return pictureSelect;
|
||||
}
|
||||
|
||||
public StbMenuOpzDTO setPictureSelect(String pictureSelect) {
|
||||
this.pictureSelect = pictureSelect;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public StbMenuOpz toEntity() {
|
||||
return new StbMenuOpz()
|
||||
.setCodOpz(getCodOpz())
|
||||
.setDescrizione(getDescrizione())
|
||||
.setEntityName(getEntityName())
|
||||
.setFlagPrinterSetup(getFlagPrinterSetup())
|
||||
.setGestName(getGestName())
|
||||
.setIsDeprecated(getIsDeprecated())
|
||||
.setNote(getNote())
|
||||
.setObjectType(getObjectType())
|
||||
.setOpenType(getOpenType())
|
||||
.setParameter(getParameter())
|
||||
.setPictureMenu(getPictureMenu())
|
||||
.setPictureSelect(getPictureSelect());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package it.integry.ems.menu.dto;
|
||||
|
||||
import it.integry.ems_model.annotation.SqlField;
|
||||
import it.integry.ems_model.entity.StbTipoAzienda;
|
||||
|
||||
public class StbTipoAziendaDTO {
|
||||
|
||||
private String type = "stb_tipo_azienda";
|
||||
|
||||
@SqlField(value = "tipo_azienda", maxLength = 40, nullable = false)
|
||||
private String tipoAzienda;
|
||||
|
||||
@SqlField(value = "descrizione", maxLength = 1024)
|
||||
private String descrizione;
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public StbTipoAziendaDTO setType(String type) {
|
||||
this.type = type;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getTipoAzienda() {
|
||||
return tipoAzienda;
|
||||
}
|
||||
|
||||
public StbTipoAziendaDTO setTipoAzienda(String tipoAzienda) {
|
||||
this.tipoAzienda = tipoAzienda;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDescrizione() {
|
||||
return descrizione;
|
||||
}
|
||||
|
||||
public StbTipoAziendaDTO setDescrizione(String descrizione) {
|
||||
this.descrizione = descrizione;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public StbTipoAzienda toEntity() {
|
||||
return new StbTipoAzienda()
|
||||
.setTipoAzienda(getTipoAzienda())
|
||||
.setDescrizione(getDescrizione());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package it.integry.ems.menu.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import it.integry.annotations.PostContextAutowired;
|
||||
import it.integry.annotations.PostContextConstruct;
|
||||
import it.integry.ems.menu.dto.MenuConfigDTO;
|
||||
import it.integry.ems.menu.dto.StbMenuDTO;
|
||||
import it.integry.ems.menu.dto.StbMenuOpzDTO;
|
||||
import it.integry.ems.menu.dto.StbTipoAziendaDTO;
|
||||
import it.integry.ems.settings.SettingsController;
|
||||
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.utility.UtilityDebug;
|
||||
import it.integry.ems_model.entity.Azienda;
|
||||
import it.integry.ems_model.entity.StbMenu;
|
||||
import it.integry.ems_model.entity.StbMenuOpz;
|
||||
import it.integry.ems_model.entity.StbTipoAzienda;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.sql.Connection;
|
||||
import java.util.List;
|
||||
|
||||
import static it.integry.ems_model.utility.UtilityDB.executeStatement;
|
||||
|
||||
@Service
|
||||
public class MenuConfigurationService {
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
|
||||
@Autowired
|
||||
private SettingsController settingsController;
|
||||
|
||||
@PostContextAutowired
|
||||
private MultiDBTransactionManager multiDBTransactionManager;
|
||||
|
||||
@PostContextConstruct(priority = 5)
|
||||
public void init() throws Exception {
|
||||
if(UtilityDebug.isDebugExecution()) return;
|
||||
|
||||
logger.debug(MenuConfigurationService.class.getSimpleName() + ": Refresh menu");
|
||||
|
||||
final MenuConfigDTO menuConfig = loadMenuData();
|
||||
|
||||
for (AdvancedDataSource advancedDataSource : multiDBTransactionManager.getActiveConnections()) {
|
||||
|
||||
if (advancedDataSource.getDataSource().getDbName().equalsIgnoreCase("studioml") || isHistoryDB(advancedDataSource))
|
||||
continue;
|
||||
|
||||
try {
|
||||
//LocalDateTime startTime = UtilityLocalDate.getNowTime();
|
||||
internalRefresh(advancedDataSource.getConnection(), menuConfig);
|
||||
//logger.debug("Menu refresh time: " + ChronoUnit.SECONDS.between(startTime, UtilityLocalDate.getNowTime()));
|
||||
} catch (Exception ex) {
|
||||
logger.error("Errore durante l'aggiornamento del menu di " + advancedDataSource.getProfileName(), ex);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isHistoryDB(AdvancedDataSource advancedDataSource) throws Exception {
|
||||
String historyProfileDB = settingsController.getHistoryProfileDb();
|
||||
return historyProfileDB.equalsIgnoreCase(advancedDataSource.getProfileName());
|
||||
}
|
||||
|
||||
public void refresh(Connection connection) throws Exception {
|
||||
final MenuConfigDTO menuConfig = loadMenuData();
|
||||
internalRefresh(connection, menuConfig);
|
||||
}
|
||||
|
||||
private MenuConfigDTO loadMenuData() throws IOException {
|
||||
|
||||
ObjectMapper jsonObjectMapper = new ObjectMapper();
|
||||
ClassLoader classLoader = getClass().getClassLoader();
|
||||
|
||||
final URL resourceMenuConfigURL = classLoader.getResource("menus/menu_config.json");
|
||||
final MenuConfigDTO menuConfig = jsonObjectMapper.readValue(resourceMenuConfigURL, MenuConfigDTO.class);
|
||||
|
||||
return menuConfig;
|
||||
}
|
||||
|
||||
private void internalRefresh(Connection connection, MenuConfigDTO menuConfig) throws Exception {
|
||||
final Azienda azienda = Azienda.getDefaultAzienda(connection);
|
||||
int lastMenuUpd = Integer.parseInt(azienda.getLastUpgDbMenu().replace("QM", ""));
|
||||
|
||||
if (menuConfig.getVersion() <= lastMenuUpd)
|
||||
return;
|
||||
|
||||
executeStatement(connection, "DELETE FROM stb_menu",
|
||||
"EXECUTE dbo.DropForeignKey 'azienda', 'stb_tipo_azienda'",
|
||||
"DELETE FROM stb_tipo_azienda",
|
||||
"DELETE FROM stb_menu_opz");
|
||||
|
||||
for (StbMenuOpzDTO stbMenuOpzDto : menuConfig.getStbMenuOpz()) {
|
||||
StbMenuOpz stbMenuOpz = stbMenuOpzDto.toEntity();
|
||||
stbMenuOpz.setOperation(OperationType.INSERT);
|
||||
stbMenuOpz.manageWithParentConnection(connection);
|
||||
}
|
||||
|
||||
for (StbTipoAziendaDTO stbTipoAziendaDto : menuConfig.getStbTipoAzienda()) {
|
||||
StbTipoAzienda stbTipoAzienda = stbTipoAziendaDto.toEntity();
|
||||
stbTipoAzienda.setOperation(OperationType.INSERT);
|
||||
stbTipoAzienda.manageWithParentConnection(connection);
|
||||
}
|
||||
|
||||
List<StbMenuDTO> stbMenus = menuConfig.getMenusByAzienda().get(azienda.getTipoAzienda().toUpperCase());
|
||||
|
||||
if (stbMenus == null)
|
||||
logger.error("Nessuna configurazione trovata per il menu " + azienda.getTipoAzienda() + " di " + azienda.getNomeDitta());
|
||||
else
|
||||
for (StbMenuDTO stbMenuDto : stbMenus) {
|
||||
StbMenu stbMenu = stbMenuDto.toEntity();
|
||||
stbMenu.setOperation(OperationType.INSERT);
|
||||
stbMenu.manageWithParentConnection(connection);
|
||||
}
|
||||
|
||||
|
||||
executeStatement(connection, "ALTER TABLE azienda ADD CONSTRAINT FK_azienda_stb_tipo_azienda FOREIGN KEY (tipo_azienda) REFERENCES stb_tipo_azienda ( tipo_azienda )",
|
||||
"DELETE FROM stb_abil WHERE cod_opz not in (select cod_opz from stb_menu_opz )",
|
||||
"INSERT INTO stb_Abil SELECT opz2Abil.cod_parent AS cod_opz, opz2Abil.user_name, 'S' flag_Abil, NULL gest_name\n" +
|
||||
"FROM (SELECT DISTINCT opz.cod_parent, abil.user_name\n" +
|
||||
" FROM stb_menu opz\n" +
|
||||
" LEFT OUTER JOIN stb_menu root ON opz.cod_parent = root.cod_opz,\n" +
|
||||
" stb_abil Abil,\n" +
|
||||
" azienda\n" +
|
||||
" WHERE opz.cod_parent <> 'ROOT'\n" +
|
||||
" AND ISNULL(root.cod_parent, '') <> 'WM002'\n" +
|
||||
" AND opz.cod_opz = abil.cod_opz\n" +
|
||||
" AND opz.tipo_azienda = azienda.tipo_azienda\n" +
|
||||
" AND abil.flag_Abil <> 'N') Opz2Abil\n" +
|
||||
" LEFT OUTER JOIN stb_Abil ON stb_Abil.cod_opz = Opz2Abil.cod_parent AND stb_abil.user_name = Opz2Abil.user_name\n" +
|
||||
"WHERE stb_abil.cod_opz IS NULL",
|
||||
"UPDATE azienda SET last_upg_db_menu = " + UtilityDB.valueToString("QM" + menuConfig.getVersion()));
|
||||
|
||||
|
||||
connection.commit();
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,8 @@ public class MetricFilter implements Filter {
|
||||
double stopTime = System.nanoTime();
|
||||
double execTime = (stopTime - startTime) / 1000000000;
|
||||
// final int status = ((HttpServletResponse) response).getStatus();
|
||||
Double duration = Double.valueOf(execTime);
|
||||
metricService.updateCountTimeForService(req, duration);
|
||||
|
||||
metricService.updateCountTimeForService(req, execTime);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import it.integry.ems.utility.UtilityDebug;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
import it.integry.ems_model.entity.Azienda;
|
||||
import it.integry.ems_model.entity.StbMigrationStatus;
|
||||
import it.integry.ems_model.exception.DataConverterNotFoundException;
|
||||
import it.integry.ems_model.rulescompleting.DroolsDataCompleting;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
@@ -25,9 +26,9 @@ import org.reflections.Reflections;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.Statement;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -65,7 +66,13 @@ public class MigrationService {
|
||||
.sortBy(Class::getSimpleName)
|
||||
.toList());
|
||||
|
||||
if (UtilityDebug.isDebugExecution())
|
||||
return;
|
||||
|
||||
startMigrationsGlobally(multiDBTransactionManager);
|
||||
}
|
||||
|
||||
public void startMigrationsGlobally(MultiDBTransactionManager multiDBTransactionManager) {
|
||||
List<AdvancedDataSource> advancedDataSources;
|
||||
|
||||
try {
|
||||
@@ -85,38 +92,22 @@ public class MigrationService {
|
||||
}
|
||||
}
|
||||
|
||||
private void initLastVersionField(AdvancedDataSource advancedDataSource) throws Exception {
|
||||
|
||||
String sql = "SELECT CAST(COUNT(*) AS BIT) as exist " +
|
||||
"FROM sys.columns " +
|
||||
"WHERE Name = N'last_migration' " +
|
||||
" AND Object_ID = Object_ID(N'dbo.azienda')";
|
||||
|
||||
boolean fieldExists = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sql);
|
||||
|
||||
if (!fieldExists) {
|
||||
String alterTableSql = "ALTER TABLE azienda ADD last_migration VARCHAR(14)";
|
||||
Statement statement = advancedDataSource.getConnection().createStatement();
|
||||
statement.execute(alterTableSql);
|
||||
statement.close();
|
||||
|
||||
advancedDataSource.getConnection().commit();
|
||||
}
|
||||
}
|
||||
|
||||
public void executeMigrationGroup(AdvancedDataSource advancedDataSource) {
|
||||
try {
|
||||
initLastVersionField(advancedDataSource);
|
||||
migrateStatus(advancedDataSource);
|
||||
List<StbMigrationStatus> migrationStatuses = retrieveAllMigrationsStatus(advancedDataSource);
|
||||
|
||||
for (Class<? extends MigrationModelInterface> migrationClass : allMigrationsList) {
|
||||
long migrationNumber = Long.parseLong(migrationClass.getSimpleName().replace("Migration_", ""));
|
||||
|
||||
if (migrationStatuses.stream().anyMatch(x -> x.getMigrationCode() == migrationNumber && (x.isCompleted() || x.isSkipped())))
|
||||
continue;
|
||||
|
||||
try {
|
||||
long lastMigration = getLastMigrationFromDB(advancedDataSource);
|
||||
|
||||
if (migrationNumber <= lastMigration) continue;
|
||||
|
||||
//LocalDateTime startTime = UtilityLocalDate.getNowTime();
|
||||
executeMigration(migrationClass, advancedDataSource, settingsController, settingsModel, droolsDataCompleting);
|
||||
//logger.debug("MIGRATION TIME: " + ChronoUnit.SECONDS.between(startTime, UtilityLocalDate.getNowTime()));
|
||||
|
||||
updateLastMigrationIntoDB(advancedDataSource, migrationNumber);
|
||||
|
||||
advancedDataSource.getConnection().commit();
|
||||
@@ -155,22 +146,11 @@ public class MigrationService {
|
||||
MigrationModelInterface migrationInstance = migrationClass.newInstance();
|
||||
migrationInstance.init(advancedDataSource, settingsController, settingsModel, droolsDataCompleting);
|
||||
migrationInstance.up();
|
||||
}
|
||||
|
||||
private Long getLastMigrationFromDB(AdvancedDataSource advancedDataSource) throws Exception {
|
||||
String sql = "SELECT last_migration FROM azienda";
|
||||
String lastMigration = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sql);
|
||||
lastMigration = UtilityString.isNullOrEmpty(lastMigration) ? "-1" : lastMigration;
|
||||
|
||||
return Long.parseLong(lastMigration);
|
||||
advancedDataSource.getConnection().commit();
|
||||
}
|
||||
|
||||
public void updateLastMigrationIntoDB(AdvancedDataSource advancedDataSource, long lastMigraton) throws Exception {
|
||||
String updateSql = "UPDATE azienda SET last_migration = " + UtilityDB.valueToString(String.valueOf(lastMigraton));
|
||||
PreparedStatement ps = advancedDataSource.getConnection().prepareStatement(updateSql);
|
||||
ps.executeUpdate();
|
||||
ps.close();
|
||||
|
||||
String sql = "SELECT * FROM " + StbMigrationStatus.ENTITY + " WHERE migration_code = " + lastMigraton;
|
||||
StbMigrationStatus stbMigrationStatus = UtilityDB.executeSimpleQueryOnlyFirstRowDTO(advancedDataSource.getConnection(), sql, StbMigrationStatus.class);
|
||||
|
||||
@@ -200,6 +180,55 @@ public class MigrationService {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
|
||||
private void migrateStatus(AdvancedDataSource advancedDataSource) throws Exception {
|
||||
final long lastMigrationNumber = getLastMigrationFromDB(advancedDataSource);
|
||||
final List<Long> alreadyExecutedMigrations = retrieveAllMigrationsStatus(advancedDataSource)
|
||||
.stream()
|
||||
.map(StbMigrationStatus::getMigrationCode)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
final List<StbMigrationStatus> migrationStatusesToMigrate = allMigrationsList.stream()
|
||||
.map(x -> Long.parseLong(x.getSimpleName().replace("Migration_", "")))
|
||||
.filter(x -> x <= lastMigrationNumber && !alreadyExecutedMigrations.contains(x))
|
||||
.map(x -> {
|
||||
final StbMigrationStatus stbMigrationStatus = new StbMigrationStatus()
|
||||
.setMigrationCode(x)
|
||||
.setCompleted(true);
|
||||
stbMigrationStatus.setOperation(OperationType.INSERT);
|
||||
return stbMigrationStatus;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
for (StbMigrationStatus stbMigrationStatus : migrationStatusesToMigrate)
|
||||
stbMigrationStatus.manageWithParentConnection(advancedDataSource.getConnection());
|
||||
|
||||
|
||||
advancedDataSource.getConnection().commit();
|
||||
}
|
||||
|
||||
private Long getLastMigrationFromDB(AdvancedDataSource advancedDataSource) throws Exception {
|
||||
String sql = "SELECT last_migration FROM azienda";
|
||||
String lastMigration = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(advancedDataSource.getConnection(), sql);
|
||||
lastMigration = UtilityString.isNullOrEmpty(lastMigration) ? "-1" : lastMigration;
|
||||
|
||||
return Long.parseLong(lastMigration);
|
||||
}
|
||||
|
||||
|
||||
private List<StbMigrationStatus> retrieveAllMigrationsStatus(AdvancedDataSource advancedDataSource) throws SQLException, IOException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
String sql = "SELECT * FROM " + StbMigrationStatus.ENTITY;
|
||||
List<StbMigrationStatus> stbMigrationStatuses = UtilityDB.executeSimpleQueryDTO(advancedDataSource.getConnection(), sql, StbMigrationStatus.class);
|
||||
|
||||
if (stbMigrationStatuses == null) return new ArrayList<>();
|
||||
|
||||
stbMigrationStatuses = stbMigrationStatuses.stream()
|
||||
.sorted(Comparator.comparing(StbMigrationStatus::getMigrationCode))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return stbMigrationStatuses;
|
||||
}
|
||||
|
||||
private void trackMigrationError(AdvancedDataSource advancedDataSource, long migrationCode, Exception e) {
|
||||
migrationsErrorMapByProfiles.putIfAbsent(advancedDataSource.getProfileName(), true);
|
||||
migrationsErrorMapByProfiles.replace(advancedDataSource.getProfileName(), true);
|
||||
@@ -243,7 +272,7 @@ public class MigrationService {
|
||||
|
||||
public boolean isAnyMigrationFailed() {
|
||||
for (String profileDb : migrationsErrorMapByProfiles.keySet())
|
||||
if(migrationsErrorMapByProfiles.get(profileDb)) return true;
|
||||
if (migrationsErrorMapByProfiles.get(profileDb)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1,20 +1,23 @@
|
||||
package it.integry.ems.migration._base;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import it.integry.ems.schedule.new_cron_job.dto.operations.base_classes.BaseScheduledOperationDTO;
|
||||
import it.integry.ems.schedule.new_cron_job.service.AutomatedOperationHandlerComponent;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.settings.SettingsController;
|
||||
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
|
||||
import it.integry.ems.utility.UtilityDebug;
|
||||
import it.integry.ems_model.entity.StbGestSetup;
|
||||
import it.integry.ems_model.rulescompleting.DroolsDataCompleting;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.Query;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.web.context.ContextLoader;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.*;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@@ -33,8 +36,9 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
this.droolsDataCompleting = droolsDataCompleting;
|
||||
}
|
||||
|
||||
protected <R>R getContextBean(Class<R> clazz) {
|
||||
TypeReference<R> type = new TypeReference<R>() {};
|
||||
protected <R> R getContextBean(Class<R> clazz) {
|
||||
TypeReference<R> type = new TypeReference<R>() {
|
||||
};
|
||||
return ContextLoader.getCurrentWebApplicationContext().getBean(clazz);
|
||||
}
|
||||
|
||||
@@ -68,9 +72,114 @@ public abstract class BaseMigration implements MigrationModelInterface {
|
||||
return val != null && val == 1;
|
||||
}
|
||||
|
||||
|
||||
public void createTable(Connection connection, String sql) throws SQLException {
|
||||
protected void renameColumn(Connection connection, String tableName, String oldColumnname, String newColumnName) throws SQLException {
|
||||
String sql = "exec sp_rename 'dbo." + tableName + "." + oldColumnname + "', " + newColumnName + ", 'COLUMN'";
|
||||
executeStatement(connection, sql);
|
||||
}
|
||||
|
||||
protected boolean existsTable(Connection connection, String tableName) throws SQLException {
|
||||
String sql = Query.format("SELECT CAST(COUNT(*) AS BIT) AS exist FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N%s", tableName);
|
||||
|
||||
return UtilityDB.<Boolean>executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
}
|
||||
|
||||
|
||||
protected long executeInsertStatement(Connection connection, String sql) throws SQLException {
|
||||
long generatedId = -1;
|
||||
|
||||
try (PreparedStatement pstmt = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
|
||||
|
||||
int affectedRows = pstmt.executeUpdate();
|
||||
|
||||
if (affectedRows > 0) {
|
||||
// get the ID back
|
||||
try (ResultSet rs = pstmt.getGeneratedKeys()) {
|
||||
if (rs.next()) {
|
||||
generatedId = rs.getLong(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return generatedId;
|
||||
}
|
||||
|
||||
public void updateFunction(Connection connection, String sql) throws SQLException {
|
||||
executeStatement(connection, sql);
|
||||
}
|
||||
|
||||
protected void dropTable(Connection connection, String tableName) throws SQLException {
|
||||
String dropSql = "DROP TABLE " + tableName;
|
||||
executeStatement(connection, dropSql);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
protected void createSetup(Connection connection, String gestName, String section, String keySection, String value, String description, String codQuery) throws Exception {
|
||||
StbGestSetup stbGestSetup = new StbGestSetup()
|
||||
.setGestName(gestName)
|
||||
.setSection(section)
|
||||
.setKeySection(keySection)
|
||||
.setValue(value)
|
||||
.setDescription(description)
|
||||
.setQueryDefault(codQuery);
|
||||
|
||||
stbGestSetup.setOperation(OperationType.INSERT);
|
||||
|
||||
stbGestSetup.manageWithParentConnection(connection);
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected void deleteSetup(Connection connection, String gestName, String section, String keySection) throws Exception {
|
||||
StbGestSetup stbGestSetup = new StbGestSetup()
|
||||
.setGestName(gestName)
|
||||
.setSection(section)
|
||||
.setKeySection(keySection);
|
||||
|
||||
stbGestSetup.setOperation(OperationType.DELETE);
|
||||
stbGestSetup.manageWithParentConnection(connection);
|
||||
}
|
||||
|
||||
protected void updateSetupValue(Connection connection, String gestName, String section, String keySection, String newValue) throws Exception {
|
||||
StbGestSetup stbGestSetup = new StbGestSetup()
|
||||
.setGestName(gestName)
|
||||
.setSection(section)
|
||||
.setKeySection(keySection)
|
||||
.setValue(newValue);
|
||||
|
||||
stbGestSetup.setOperation(OperationType.UPDATE);
|
||||
stbGestSetup.manageWithParentConnection(connection);
|
||||
}
|
||||
|
||||
protected void addAutomatedOperation(BaseScheduledOperationDTO operation) {
|
||||
new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(120 * 1000);
|
||||
|
||||
AutomatedOperationHandlerComponent automatedOperationHandlerComponent = ContextLoader.getCurrentWebApplicationContext().getBean(AutomatedOperationHandlerComponent.class);
|
||||
automatedOperationHandlerComponent.add(operation);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
protected void addAutomatedOperations(List<? extends BaseScheduledOperationDTO> operations) {
|
||||
new Thread(() -> {
|
||||
try {
|
||||
Thread.sleep(120 * 1000);
|
||||
|
||||
AutomatedOperationHandlerComponent automatedOperationHandlerComponent = ContextLoader.getCurrentWebApplicationContext().getBean(AutomatedOperationHandlerComponent.class);
|
||||
for (BaseScheduledOperationDTO operation : operations)
|
||||
automatedOperationHandlerComponent.add(operation);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,12 @@ public class MigrationSetupController {
|
||||
return ServiceRestResponse.createPositiveResponse(migrationSetupService.retrieveAll());
|
||||
}
|
||||
|
||||
@RequestMapping(value = "executeAll", method = RequestMethod.GET)
|
||||
public @ResponseBody ServiceRestResponse executeAll() throws Exception {
|
||||
migrationSetupService.executeAll();
|
||||
return ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "{migrationCode}/retry", method = RequestMethod.POST)
|
||||
public @ResponseBody ServiceRestResponse retryMigration(@PathVariable long migrationCode) throws Exception {
|
||||
migrationSetupService.retry(migrationCode);
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
|
||||
public class Migration_20240205105025 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
updateFunction(advancedDataSource.getConnection(), "ALTER FUNCTION [dbo].[f_getEAN128UL](@gestione VARCHAR(1), @dataCollo DATETIME, @serCollo VARCHAR(2), @numCollo int, @customPrefissoEan VARCHAR(7))\n" +
|
||||
" RETURNS TABLE AS\n" +
|
||||
" RETURN\n" +
|
||||
"\n" +
|
||||
"-- DECLARE @gestione AS VARCHAR(1) = 'L'\n" +
|
||||
"-- DECLARE @serCollo AS VARCHAR(10) = '/'\n" +
|
||||
"-- DECLARE @numCollo AS INT = 4427\n" +
|
||||
"-- DECLARE @dataCollo AS DATETIME = '2024-02-05';\n" +
|
||||
"-- DECLARE @customPrefissoEan AS VARCHAR(7);-- = '8017596';\n" +
|
||||
"\n" +
|
||||
"WITH barcodes AS (\n" +
|
||||
" SELECT CONCAT(CASE WHEN @customPrefissoEan IS NULL THEN azienda.prefisso_ean ELSE @customPrefissoEan END,\n" +
|
||||
" CAST(CAST(mtb_colt.num_collo / 100000 AS INT) AS varchar),\n" +
|
||||
" CASE mtb_colt.gestione\n" +
|
||||
" WHEN 'A' THEN '1'\n" +
|
||||
" WHEN 'L' THEN '2'\n" +
|
||||
" WHEN 'V' THEN '3' END,\n" +
|
||||
" RIGHT(CAST(DATEPART(YEAR, mtb_colt.data_collo) AS varchar), 2),\n" +
|
||||
" RIGHT(FORMAT(mtb_colt.num_collo, REPLICATE('0', 5)), 5)) AS AI_00,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN mtb_aart.cod_barre_imb IS NOT NULL AND LEN(mtb_aart.cod_barre_imb) < 14 THEN\n" +
|
||||
" FORMAT(CONVERT(NUMERIC, ISNULL(NULLIF(mtb_aart.cod_barre_imb, ''), '0')), REPLICATE('0', 13))\n" +
|
||||
" ELSE mtb_aart.cod_barre_imb\n" +
|
||||
" END AS AI_01,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN mtb_aart.bar_code IS NOT NULL AND LEN(mtb_aart.bar_code) < 14\n" +
|
||||
" THEN\n" +
|
||||
" FORMAT(CONVERT(BIGINT, mtb_aart.bar_code), REPLICATE('0', 14))\n" +
|
||||
" ELSE mtb_aart.bar_code\n" +
|
||||
" END AS AI_02,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN mtb_colr.partita_mag IS NOT NULL THEN\n" +
|
||||
" mtb_colr.partita_mag + CHAR(29)\n" +
|
||||
" END AS AI_10,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN mtb_partita_mag.data_scad IS NOT NULL THEN\n" +
|
||||
" REPLACE(CONVERT(varchar(10), mtb_partita_mag.data_scad, 2), '.', '')\n" +
|
||||
" END AS AI_15,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_aart.peso_kg * mtb_colr.qta_cnf AS INTEGER)) <= 6 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_aart.peso_kg * mtb_colr.qta_cnf, '000000'), '.', '')\n" +
|
||||
" END AS AI_3100,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_aart.peso_kg * mtb_colr.qta_cnf AS INTEGER)) <= 5 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_aart.peso_kg * mtb_colr.qta_cnf, '00000.0'), '.', '')\n" +
|
||||
" END AS AI_3101,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_aart.peso_kg * mtb_colr.qta_cnf AS INTEGER)) <= 4 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_aart.peso_kg * mtb_colr.qta_cnf, '0000.00'), '.', '')\n" +
|
||||
" END AS AI_3102,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_aart.peso_kg * mtb_colr.qta_cnf AS INTEGER)) <= 3 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_aart.peso_kg * mtb_colr.qta_cnf, '000.000'), '.', '')\n" +
|
||||
" END AS AI_3103,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_aart.peso_kg * mtb_colr.qta_cnf AS INTEGER)) <= 2 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_aart.peso_kg * mtb_colr.qta_cnf, '00.0000'), '.', '')\n" +
|
||||
" END AS AI_3104,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_aart.peso_kg * mtb_colr.qta_cnf AS INTEGER)) <= 1 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_aart.peso_kg * mtb_colr.qta_cnf, '0.00000'), '.', '')\n" +
|
||||
" END AS AI_3105,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_colt.peso_kg AS INTEGER)) <= 6 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_colt.peso_kg, '000000'), '.', '')\n" +
|
||||
" END AS AI_3300,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_colt.peso_kg AS INTEGER)) <= 5 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_colt.peso_kg, '00000.0'), '.', '')\n" +
|
||||
" END AS AI_3301,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_colt.peso_kg AS INTEGER)) <= 4 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_colt.peso_kg, '0000.00'), '.', '')\n" +
|
||||
" END AS AI_3302,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_colt.peso_kg AS INTEGER)) <= 3 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_colt.peso_kg, '000.000'), '.', '')\n" +
|
||||
" END AS AI_3303,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_colt.peso_kg AS INTEGER)) <= 2 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_colt.peso_kg, '00.0000'), '.', '')\n" +
|
||||
" END AS AI_3304,\n" +
|
||||
" CASE\n" +
|
||||
" WHEN LEN(CAST(mtb_colt.peso_kg AS INTEGER)) <= 1 THEN\n" +
|
||||
" REPLACE(FORMAT(mtb_colt.peso_kg, '0.00000'), '.', '')\n" +
|
||||
" END AS AI_3305,\n" +
|
||||
" CONVERT(varchar, CONVERT(integer, SUM(mtb_colr.qta_col / mtb_colr.qta_cnf))) AS AI_37\n" +
|
||||
" FROM mtb_colt\n" +
|
||||
" INNER JOIN mtb_colr\n" +
|
||||
" ON mtb_colt.gestione = mtb_colr.gestione and mtb_colt.data_collo = mtb_colr.data_collo and\n" +
|
||||
" mtb_colt.ser_collo = mtb_colr.ser_collo and mtb_colt.num_collo = mtb_colr.num_collo\n" +
|
||||
" INNER JOIN mtb_aart ON mtb_colr.cod_mart = mtb_aart.cod_mart\n" +
|
||||
" LEFT outer JOIN mtb_partita_mag ON mtb_colr.cod_mart = mtb_partita_mag.cod_mart AND\n" +
|
||||
" mtb_colr.partita_mag = mtb_partita_mag.partita_mag,\n" +
|
||||
" azienda\n" +
|
||||
" WHERE mtb_colt.gestione = @gestione\n" +
|
||||
" AND mtb_colt.data_collo = @dataCollo\n" +
|
||||
" AND mtb_colt.ser_collo = @serCollo\n" +
|
||||
" AND mtb_colt.num_collo = @numCollo\n" +
|
||||
" GROUP BY mtb_colr.qta_col,\n" +
|
||||
" mtb_colr.qta_cnf,\n" +
|
||||
" mtb_colt.data_vers,\n" +
|
||||
" nome_ditta,\n" +
|
||||
" azienda.indirizzo,\n" +
|
||||
" azienda.cap,\n" +
|
||||
" azienda.citta,\n" +
|
||||
" azienda.prov,\n" +
|
||||
" prefisso_ean,\n" +
|
||||
" mtb_colt.data_collo,\n" +
|
||||
" mtb_colt.num_collo,\n" +
|
||||
" mtb_aart.cod_barre_imb,\n" +
|
||||
" mtb_aart.bar_code,\n" +
|
||||
" mtb_aart.descrizione_estesa,\n" +
|
||||
" mtb_colr.partita_mag,\n" +
|
||||
" mtb_partita_mag.data_scad,\n" +
|
||||
" mtb_colt.peso_netto_kg,\n" +
|
||||
" mtb_colr.cod_mart, \n" +
|
||||
"\t\t\t mtb_colt.gestione,\n" +
|
||||
"\t\t\t mtb_colt.peso_kg,\n" +
|
||||
"\t\t\t mtb_aart.peso_kg\n" +
|
||||
"),\n" +
|
||||
" appoggio AS (\n" +
|
||||
" SELECT CONCAT(\n" +
|
||||
" REPLICATE('0', 17 - LEN(AI_00)),\n" +
|
||||
" AI_00) AS AI_00,\n" +
|
||||
" CASE WHEN AI_01 IS NOT NULL AND LEN(AI_01) = 13 THEN CONCAT(AI_01, dbo.getCheckDigitITF14(AI_01)) ELSE AI_01 END AS AI_01,\n" +
|
||||
" AI_02,\n" +
|
||||
" AI_10,\n" +
|
||||
" AI_15,\n" +
|
||||
" AI_3100,\n" +
|
||||
" AI_3101,\n" +
|
||||
" AI_3102,\n" +
|
||||
" AI_3103,\n" +
|
||||
" AI_3104,\n" +
|
||||
" AI_3105,\n" +
|
||||
" AI_3300,\n" +
|
||||
" AI_3301,\n" +
|
||||
" AI_3302,\n" +
|
||||
" AI_3303,\n" +
|
||||
" AI_3304,\n" +
|
||||
" AI_3305,\n" +
|
||||
" AI_37\n" +
|
||||
" FROM barcodes\n" +
|
||||
" )\n" +
|
||||
"SELECT CONCAT(AI_00,\n" +
|
||||
" dbo.getCheckDigitSSCC(AI_00)) AS AI_00,\n" +
|
||||
" AI_01,\n" +
|
||||
" AI_02,\n" +
|
||||
" AI_10,\n" +
|
||||
" AI_15,\n" +
|
||||
" AI_3100,\n" +
|
||||
" AI_3101,\n" +
|
||||
" AI_3102,\n" +
|
||||
" AI_3103,\n" +
|
||||
" AI_3104,\n" +
|
||||
" AI_3105,\n" +
|
||||
" AI_3300,\n" +
|
||||
" AI_3301,\n" +
|
||||
" AI_3302,\n" +
|
||||
" AI_3303,\n" +
|
||||
" AI_3304,\n" +
|
||||
" AI_3305,\n" +
|
||||
" AI_37\n" +
|
||||
"FROM appoggio");
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
import it.integry.ems_model.utility.Query;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityHashMap;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
public class Migration_20240212000000 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
String sql = "SELECT * FROM stb_publications";
|
||||
final List<HashMap<String, Object>> oldStbPublications = UtilityDB.executeSimpleQuery(advancedDataSource.getConnection(), sql);
|
||||
|
||||
sql = "SELECT * FROM stb_publications_detail";
|
||||
final List<HashMap<String, Object>> oldStbPublicationsDetails = UtilityDB.executeSimpleQuery(advancedDataSource.getConnection(), sql);
|
||||
|
||||
dropOldTables(advancedDataSource.getConnection());
|
||||
createNewTables(advancedDataSource.getConnection());
|
||||
|
||||
|
||||
for (HashMap<String, Object> oldStbPublication : oldStbPublications) {
|
||||
String publicationDescription = UtilityHashMap.getValueIfExists(oldStbPublication, "publication_description");
|
||||
|
||||
String insertSql = Query.format("INSERT INTO stb_publications (publication_description) VALUES (%s)", publicationDescription);
|
||||
long generatedId = executeInsertStatement(advancedDataSource.getConnection(), insertSql);
|
||||
oldStbPublication.putIfAbsent("id", generatedId);
|
||||
}
|
||||
|
||||
|
||||
for (HashMap<String, Object> oldStbPublicationDetail : oldStbPublicationsDetails) {
|
||||
String active = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "syncronize");
|
||||
String oldId = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "publication_id");
|
||||
String entityName = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "entity_name");
|
||||
String whereCondSql = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "where_cond_sql");
|
||||
String recalcColumns = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "recalc_columns");
|
||||
String whereCond = UtilityHashMap.getValueIfExists(oldStbPublicationDetail, "where_cond");
|
||||
|
||||
Long newParentId = getNewGeneratedIdFromOldKey(oldId, oldStbPublications);
|
||||
|
||||
String insertSql = Query.format("INSERT INTO stb_publications_detail " +
|
||||
"(stb_publication_id, entity_name, where_cond_sql, recalc_columns, active, where_cond, ready_to_transmit) " +
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s)",
|
||||
newParentId,
|
||||
entityName,
|
||||
whereCondSql,
|
||||
recalcColumns,
|
||||
active.equalsIgnoreCase("S") || active.equalsIgnoreCase("R"),
|
||||
whereCond,
|
||||
true);
|
||||
long generatedId = executeInsertStatement(advancedDataSource.getConnection(), insertSql);
|
||||
oldStbPublicationDetail.putIfAbsent("id", generatedId);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
|
||||
private void dropOldTables(@NotNull Connection connection) throws SQLException {
|
||||
dropTable(connection, "stb_publications_detail");
|
||||
dropTable(connection, "stb_publications");
|
||||
}
|
||||
|
||||
private void createNewTables(@NotNull Connection connection) throws SQLException {
|
||||
String createSql = "CREATE TABLE dbo.stb_publications\n" +
|
||||
"(\n" +
|
||||
" id BIGINT IDENTITY,\n" +
|
||||
" publication_description VARCHAR(1024) NOT NULL\n" +
|
||||
")";
|
||||
executeStatement(connection, createSql);
|
||||
|
||||
createSql = "CREATE UNIQUE CLUSTERED INDEX stb_publications_id_uindex\n" +
|
||||
" ON dbo.stb_publications (id)";
|
||||
executeStatement(connection, createSql);
|
||||
|
||||
createSql = "CREATE TABLE dbo.stb_publications_detail\n" +
|
||||
"(\n" +
|
||||
" id BIGINT IDENTITY\n" +
|
||||
" CONSTRAINT stb_publications_detail_pk\n" +
|
||||
" PRIMARY KEY,\n" +
|
||||
" stb_publication_id BIGINT NOT NULL\n" +
|
||||
" CONSTRAINT stb_publications_detail_stb_publications_id_fk\n" +
|
||||
" REFERENCES dbo.stb_publications (id),\n" +
|
||||
" entity_name VARCHAR(40) NOT NULL,\n" +
|
||||
" active BIT DEFAULT 1 NOT NULL,\n" +
|
||||
" ready_to_transmit BIT DEFAULT 0 NOT NULL,\n" +
|
||||
" where_cond_sql VARCHAR(MAX),\n" +
|
||||
" recalc_columns VARCHAR(MAX),\n" +
|
||||
" where_cond VARCHAR(MAX)" +
|
||||
")";
|
||||
executeStatement(connection, createSql);
|
||||
}
|
||||
|
||||
public Long getNewGeneratedIdFromOldKey(String oldKey, List<HashMap<String, Object>> oldList) {
|
||||
return oldList.stream()
|
||||
.filter(x -> ((String) x.getOrDefault("publication_id", "")).equalsIgnoreCase(oldKey))
|
||||
.map(x -> (long) x.getOrDefault("id", -1))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
|
||||
public class Migration_20240212000001 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
if(!existsTable(advancedDataSource.getConnection(), "stb_transaction_log_db"))
|
||||
return;
|
||||
|
||||
dropTable(advancedDataSource.getConnection(), "stb_transaction_log_db");
|
||||
dropTable(advancedDataSource.getConnection(), "stb_transaction_log");
|
||||
|
||||
String createTransactionTableSql = "\n" +
|
||||
"CREATE TABLE dbo.stb_transaction_log\n" +
|
||||
"(\n" +
|
||||
" id BIGINT IDENTITY\n" +
|
||||
" CONSTRAINT stb_transaction_log_pk\n" +
|
||||
" PRIMARY KEY,\n" +
|
||||
" publication_group_id BIGINT NOT NULL,\n" +
|
||||
" created_at DATETIME DEFAULT GETDATE() NOT NULL,\n" +
|
||||
" user_name VARCHAR(40),\n" +
|
||||
" entities VARCHAR(MAX),\n" +
|
||||
" entities_json VARCHAR(MAX) NOT NULL,\n" +
|
||||
" group_id BIGINT NOT NULL\n" +
|
||||
")";
|
||||
|
||||
executeStatement(advancedDataSource.getConnection(), createTransactionTableSql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
|
||||
public class Migration_20240212000002 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
String sql = "ALTER TABLE dbo.stb_publications_detail\n" +
|
||||
" ADD export_history BIT DEFAULT 0 NOT NULL";
|
||||
|
||||
executeStatement(advancedDataSource.getConnection(), sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
|
||||
public class Migration_20240219094933 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
String sql = "ALTER TABLE mtb_colt\n" +
|
||||
" ADD barcode_ul VARCHAR(20)";
|
||||
|
||||
executeStatement(advancedDataSource.getConnection(), sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
|
||||
public class Migration_20240219103840 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
createSetup(advancedDataSource.getConnection(),
|
||||
"PICKING", "ACCETTAZIONE", "FLAG_ALLOW_BARCODE_FORNITORE", "N",
|
||||
"Abilita la possibilità di effettuare l'accettazione merci utilizzando direttamente l'SSCC del fornitore (salvato poi nella colonna barcode_pedana)",
|
||||
"SI_NO");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
|
||||
public class Migration_20240220114903 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
String sql = "EXEC DropDefault 'mtb_colr', 'causale';\n" +
|
||||
"ALTER TABLE mtb_colr\n" +
|
||||
" ALTER COLUMN causale TINYINT NOT NULL;\n" +
|
||||
"ALTER TABLE mtb_colr\n" +
|
||||
" ADD DEFAULT 0 FOR causale;";
|
||||
|
||||
executeStatement(advancedDataSource.getConnection(), sql);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
|
||||
public class Migration_20240221190821 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
createSetup(advancedDataSource.getConnection(),
|
||||
"DATI_AZIENDA", "SETUP", "FLAG_ANSI_PADDING", "N",
|
||||
"Abilita l'ansi padding nella connessione del gestionale. Il valore suggerito è ON (prima era OFF).",
|
||||
"SI_NO");
|
||||
|
||||
createSetup(advancedDataSource.getConnection(),
|
||||
"DATI_AZIENDA", "SETUP", "FLAG_CONCAT_NULL_YIELDS_NULL", "N",
|
||||
"Abilita il concat null yields null nella connessione del gestionale. Il valore suggerito è ON (prima era OFF).",
|
||||
"SI_NO");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
|
||||
public class Migration_20240228160024 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
dropTable(advancedDataSource.getConnection(), "stb_subscriptions_user_detail");
|
||||
dropTable(advancedDataSource.getConnection(), "stb_subscriptions_user");
|
||||
|
||||
executeStatement(advancedDataSource.getConnection(),
|
||||
|
||||
"CREATE TABLE dbo.stb_remote_subscription\n" +
|
||||
"(\n" +
|
||||
" id BIGINT IDENTITY\n" +
|
||||
" CONSTRAINT stb_remote_subscription_pk\n" +
|
||||
" PRIMARY KEY,\n" +
|
||||
" publication_id BIGINT NOT NULL,\n" +
|
||||
" publication_description VARCHAR(MAX),\n" +
|
||||
" endpoint_protocol VARCHAR(5) DEFAULT 'HTTP' NOT NULL,\n" +
|
||||
" endpoint_host VARCHAR(MAX) NOT NULL,\n" +
|
||||
" endpoint_port INT DEFAULT 80 NOT NULL,\n" +
|
||||
" username VARCHAR(MAX) NOT NULL,\n" +
|
||||
" password VARCHAR(MAX) NOT NULL,\n" +
|
||||
" profile_db VARCHAR(MAX) NOT NULL,\n" +
|
||||
" last_transaction_id BIGINT,\n" +
|
||||
" last_transaction_id_imported BIGINT,\n" +
|
||||
" active BIT DEFAULT 0 NOT NULL\n" +
|
||||
")",
|
||||
|
||||
"EXEC sp_addextendedproperty 'MS_Description', 'HTTP or HTTPS', 'SCHEMA', 'dbo', 'TABLE', 'stb_remote_subscription',\n" +
|
||||
" 'COLUMN', 'endpoint_protocol'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
|
||||
public class Migration_20240304165725 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
if (advancedDataSource.getProfileName().equalsIgnoreCase("carelli") ||
|
||||
advancedDataSource.getProfileName().equalsIgnoreCase("gestfood") ||
|
||||
advancedDataSource.getProfileName().equalsIgnoreCase("panimal")) {
|
||||
|
||||
String sql = "UPDATE carelli_giacenza_prog\n" +
|
||||
"SET tipo_car = 'R'\n" +
|
||||
"WHERE tipo_car = 'C'";
|
||||
|
||||
executeStatement(advancedDataSource.getConnection(), sql);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import com.annimon.stream.Stream;
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
import it.integry.ems.schedule.new_cron_job.dto.AutomatedOperationTypeEnum;
|
||||
import it.integry.ems.schedule.new_cron_job.dto.operations.ExportAutomatedOperationDTO;
|
||||
import it.integry.ems.schedule.new_cron_job.dto.operations.base_classes.BaseAutomatedOperationDTO;
|
||||
import it.integry.ems.schedule.new_cron_job.service.AutomatedOperationHandlerComponent;
|
||||
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
|
||||
public class Migration_20240307103608 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
List<String> elencoDb = new ArrayList<String>() {{
|
||||
add("CARELLI");
|
||||
add("GESTFOOD");
|
||||
add("PANIMAL");
|
||||
}};
|
||||
|
||||
if (elencoDb.stream().noneMatch(x -> x.equalsIgnoreCase(advancedDataSource.getDataSource().getDbName())))
|
||||
return;
|
||||
|
||||
String sql =
|
||||
"SELECT UPPER(stb_user.user_name) AS user_name,\n" +
|
||||
" dbo.sys_dcd_pss(stb_user.password) AS password,\n" +
|
||||
" mtb_depo.cod_mdep\n" +
|
||||
"FROM stb_user\n" +
|
||||
" INNER JOIN wtb_depo ON stb_user.user_name = wtb_depo.user_name\n" +
|
||||
" INNER JOIN mtb_depo ON wtb_depo.cod_mdep = mtb_depo.cod_mdep\n" +
|
||||
" INNER JOIN wtb_users_info\n" +
|
||||
" ON stb_user.user_name = wtb_users_info.user_name AND wtb_users_info.export_type = 'VARIAZIONE PV'\n" +
|
||||
"WHERE stb_user.flag_attivo = 'S'\n" +
|
||||
" AND mtb_depo.flag_movimentabile = 'S'\n" +
|
||||
" AND wtb_users_info.flag_state = 'S'\n" +
|
||||
" AND stb_user.key_group = '10'";
|
||||
|
||||
List<HashMap<String, Object>> elencoUtenti = UtilityDB.executeSimpleQuery(advancedDataSource.getConnection(), sql);
|
||||
|
||||
List<ExportAutomatedOperationDTO> operations = new ArrayList<>();
|
||||
for (HashMap<String, Object> user : elencoUtenti) {
|
||||
final String operationName = "Invio Variazioni Griglia - " + user.get("cod_mdep");
|
||||
|
||||
|
||||
ExportAutomatedOperationDTO exportAutomatedOperationDTO =
|
||||
new ExportAutomatedOperationDTO()
|
||||
.setFormat("XML_DIALOGO")
|
||||
.setType("VARIAZIONE PV")
|
||||
.setUsername((String) user.get("user_name"))
|
||||
.setPassword((String) user.get("password"))
|
||||
.setJsonRequest("{ \t\"tipoReport\": \"G\" }")
|
||||
.setProfileDb(advancedDataSource.getProfileName());
|
||||
exportAutomatedOperationDTO
|
||||
.setCronTrigger("0 0 22 1/1 * *")
|
||||
.setName(operationName);
|
||||
|
||||
operations.add(exportAutomatedOperationDTO);
|
||||
|
||||
}
|
||||
|
||||
addAutomatedOperations(operations);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package it.integry.ems.migration.model;
|
||||
|
||||
import it.integry.ems.migration._base.BaseMigration;
|
||||
import it.integry.ems.migration._base.MigrationModelInterface;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class Migration_20240307123633 extends BaseMigration implements MigrationModelInterface {
|
||||
|
||||
@Override
|
||||
public void up() throws Exception {
|
||||
if (isHistoryDB())
|
||||
return;
|
||||
|
||||
List<String> elencoDb = new ArrayList<String>() {{
|
||||
add("CARELLI");
|
||||
add("GESTFOOD");
|
||||
add("PANIMAL");
|
||||
}};
|
||||
|
||||
if (elencoDb.stream().noneMatch(x -> x.equalsIgnoreCase(advancedDataSource.getDataSource().getDbName())))
|
||||
return;
|
||||
|
||||
executeStatement(advancedDataSource.getConnection(), "UPDATE vtb_promo SET flag_tipo_promo = 'T' WHERE cod_promo like '%TAGLIO%'");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void down() throws Exception {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package it.integry.ems.migration.service;
|
||||
|
||||
import com.annimon.stream.Stream;
|
||||
import it.integry.ems.javabeans.RequestDataDTO;
|
||||
import it.integry.ems.migration.MigrationService;
|
||||
import it.integry.ems.migration.dto.MigrationStatusDTO;
|
||||
@@ -124,4 +125,16 @@ public class MigrationSetupService {
|
||||
migrationService.updateLastMigrationIntoDB(advancedDataSource, migrationCode);
|
||||
migrationService.executeMigrationGroup(advancedDataSource);
|
||||
}
|
||||
|
||||
|
||||
public void executeAll() throws Exception {
|
||||
for (AvailableConnectionsModel availableConnectionsModel : settingsModel.getAvailableConnections()) {
|
||||
if (!Stream.of(multiDBTransactionManager.getActiveConnections())
|
||||
.anyMatch(advancedDataSource -> advancedDataSource.getDataSource().getDbName().equalsIgnoreCase(availableConnectionsModel.getDbName()))) {
|
||||
multiDBTransactionManager.addConnection(availableConnectionsModel);
|
||||
}
|
||||
}
|
||||
|
||||
migrationService.startMigrationsGlobally(multiDBTransactionManager);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,7 +21,6 @@ import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.kie.api.runtime.rule.ConsequenceException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
@@ -80,9 +79,6 @@ public class ServiceRestResponse {
|
||||
public ServiceRestResponse(EsitoType esito, String profileDb, Exception e) {
|
||||
this(esito);
|
||||
|
||||
if (esito == EsitoType.KO)
|
||||
e.printStackTrace();
|
||||
|
||||
this.profileDB = profileDb;
|
||||
this.errorType = e.getClass().getCanonicalName();
|
||||
this.errorMessage = e.getMessage();
|
||||
|
||||
@@ -447,31 +447,31 @@ public class AccountingBusinessLogic {
|
||||
if (UtilityString.isNullOrEmpty(tipoPartita)) tipoPartita = 1;
|
||||
|
||||
BigDecimal impScad = ctbScadOrig.getImpDare().subtract(ctbScadOrig.getImpAvere());
|
||||
Date dataPag = ctbScadOrig.getDataPag();
|
||||
impScad = impScad.abs();
|
||||
|
||||
if (residuo.compareTo(BigDecimal.ZERO) > 0 && dataPag == null) {
|
||||
if (!UtilityBigDecimal.isNullOrZero(residuo) && ctbScadOrig.getDataPag() == null ) {
|
||||
residuo = residuo.abs();
|
||||
if (residuo.compareTo(impScad) >= 0) {
|
||||
if (residuo.equals(impScad)) {
|
||||
if (UtilityBigDecimal.equalsOrGreaterThan(residuo, impScad)) {
|
||||
if (UtilityBigDecimal.equalsTo(residuo, impScad)) {
|
||||
residuo = BigDecimal.ZERO;
|
||||
} else {
|
||||
// il controllo del segno della partita è necessario solo nel caso in cui si passa un importo a copertuta di più scadenze che si possono compensare
|
||||
// registrazione dei titoli
|
||||
if (tipoPartita == 1 || countScad == 1) {
|
||||
if (tipoPartita == TipoPartita.ATTIVA.getValue() || countScad == 1) {
|
||||
residuo = residuo.subtract(impScad);
|
||||
} else if (tipoPartita == 0) {
|
||||
residuo = residuo.add(impScad);
|
||||
}
|
||||
}
|
||||
|
||||
if (ctbScadOrig.getImpDare().compareTo(BigDecimal.ZERO) > 0) {
|
||||
if (!UtilityBigDecimal.isNullOrZero(ctbScadOrig.getImpDare())) {
|
||||
ctbScadOrig.setImpAvere(impScad);
|
||||
} else {
|
||||
ctbScadOrig.setImpDare(impScad);
|
||||
}
|
||||
ctbScadOrig.setDataPag(dataCmov);
|
||||
ctbScadOrig.setIdRigaMov(idRigaMov);
|
||||
ctbScadOrig.setOperation(OperationType.INSERT_OR_UPDATE);
|
||||
} else {
|
||||
//Clona scadenza
|
||||
CtbScad ctbScadNew = (CtbScad) ctbScadOrig.clone();
|
||||
@@ -481,6 +481,7 @@ public class AccountingBusinessLogic {
|
||||
ctbScadOrig.setImpAvere(residuo);
|
||||
ctbScadOrig.setDataPag(dataCmov);
|
||||
ctbScadOrig.setIdRigaMov(idRigaMov);
|
||||
ctbScadOrig.setOperation(OperationType.INSERT_OR_UPDATE);
|
||||
|
||||
// calcola importo residuo della nuova scadenza
|
||||
residuo = residuo.subtract(impScad);
|
||||
@@ -494,6 +495,7 @@ public class AccountingBusinessLogic {
|
||||
} else {
|
||||
ctbScadNew.setImpAvere(residuo.abs());
|
||||
}
|
||||
residuo = BigDecimal.ZERO;
|
||||
}
|
||||
}
|
||||
elencoScadenzeNew.add(ctbScadOrig);
|
||||
|
||||
@@ -27,6 +27,8 @@ import java.sql.ResultSet;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
|
||||
import static it.integry.ems.rules.completing.QueryRules.getSingleValue;
|
||||
|
||||
@Service
|
||||
@Scope("request")
|
||||
public class LoadColliService {
|
||||
@@ -262,6 +264,16 @@ public class LoadColliService {
|
||||
dtbDoct.setMtbColt(mtbColt);
|
||||
}
|
||||
|
||||
// Acquisizione ID_LOTTO del primo collo da agganciare
|
||||
if (loadDatiFromDB) {
|
||||
query = "SELECT TOP 1 id_lotto FROM mtb_colt ";
|
||||
query = UtilityDB.addwhereCond(query, whereCond, false);
|
||||
Integer idLotto = (Integer) getSingleValue(multiDBTransactionManager.getPrimaryConnection(), query);
|
||||
if (idLotto != null){
|
||||
dtbDoct.setIdLotto(idLotto);
|
||||
}
|
||||
}
|
||||
|
||||
Stream.of(loadColli.getColli()).forEach(x -> x.setUpdateColliFromDoc(true));
|
||||
|
||||
//AGGIUNGERE CAMPI CHE PASSIAMO DA FUORI
|
||||
@@ -585,7 +597,8 @@ public class LoadColliService {
|
||||
" dtb_ordr.cod_promo as 'cod_promo', " +
|
||||
" dtb_ordr.cod_art_for as 'cod_art_for', " +
|
||||
" mvw_kit.flag_kit as 'articolo_composto', " +
|
||||
" IsNull(mvw_colr_sum.cod_jcom, dtb_ordr.cod_jcom) as 'cod_jcom', " +
|
||||
/*" IsNull(mvw_colr_sum.cod_jcom, dtb_ordr.cod_jcom) as 'cod_jcom', " +*/
|
||||
" dtb_ordr.cod_jcom as 'cod_jcom', " +
|
||||
" IsNull(dtb_ordr.unt_ord2, mtb_aart.unt_mis2) as 'unt_doc2', " +
|
||||
" IsNull(dtb_ordr.unt_ord3, mtb_aart.unt_mis3) as 'unt_doc3', " +
|
||||
" mtb_aart.tara_kg as 'tara_kg', " +
|
||||
@@ -652,7 +665,8 @@ public class LoadColliService {
|
||||
" mtb_aart.flag_stato, " +
|
||||
" dtb_ordr.cod_art_for, " +
|
||||
" mvw_kit.flag_kit, " +
|
||||
" IsNull(mvw_colr_sum.cod_jcom, dtb_ordr.cod_jcom), " +
|
||||
/*" IsNull(mvw_colr_sum.cod_jcom, dtb_ordr.cod_jcom), " +*/
|
||||
" dtb_ordr.cod_jcom, " +
|
||||
" IsNull(dtb_ordr.unt_ord2, mtb_aart.unt_mis2), " +
|
||||
" IsNull(dtb_ordr.unt_ord3, mtb_aart.unt_mis3), " +
|
||||
" mtb_aart.tara_kg, " +
|
||||
|
||||
@@ -18,4 +18,8 @@ public enum TipoPartita {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Integer getValue() {
|
||||
return this.value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.*;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.sql.*;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
@@ -451,6 +452,7 @@ public class AccountingRules extends QueryRules {
|
||||
List<CtbScad> elencoScadenzeNew = new ArrayList<>();
|
||||
String finalDesAgg = desAgg;
|
||||
for (CtbScad scad : ctbMovr.getCtbScad()) {
|
||||
|
||||
CtbScad ctbScad = (CtbScad) scad.clone();
|
||||
|
||||
com.annimon.stream.Optional<CtbParr> ctbParrFirst = Stream.of(elencoPartite)
|
||||
@@ -466,24 +468,29 @@ public class AccountingRules extends QueryRules {
|
||||
if (ctbParrFirst.isPresent()) {
|
||||
elencoPartite.remove(ctbParrFirst.get());
|
||||
ctbParr = ctbParrFirst.get();
|
||||
if (ctbParr.getTipoPartitaEnum() == TipoPartita.PASSIVA) {
|
||||
ctbParr.setImpDare(ctbParr.getImpDare().add(ctbScad.getImpDare()));
|
||||
if (UtilityBigDecimal.greaterThan(ctbMovr.getImpDare(), BigDecimal.ZERO)) {
|
||||
ctbParr.setImpDare(ctbParr.getImpDare().add(ctbScad.getImpDare().divide(ctbParr.getCambioDiviScad()).setScale(5, RoundingMode.HALF_UP)));
|
||||
} else {
|
||||
ctbParr.setImpAvere(ctbParr.getImpAvere().add(ctbScad.getImpAvere()));
|
||||
ctbParr.setImpAvere(ctbParr.getImpAvere().add(ctbScad.getImpAvere().divide(ctbParr.getCambioDiviScad()).setScale(5, RoundingMode.HALF_UP)));
|
||||
}
|
||||
} else {
|
||||
Integer tipoPartita = ctbMovr.getTipoPartita();
|
||||
if (tipoPartita == null) {
|
||||
String sql =
|
||||
"SELECT Cast(tipo_partita as integer) as tipo_partita " +
|
||||
" FROM ctb_part " +
|
||||
" WHERE cod_anag = " + UtilityDB.valueToString(ctbScad.getCodAnag()) + " AND " +
|
||||
"tipo_anag = " + UtilityDB.valueToString(ctbScad.getTipoAnag()) + " AND " +
|
||||
"anno_part = " + UtilityDB.valueToString(ctbScad.getAnnoPart()) + " AND " +
|
||||
"ser_doc = " + UtilityDB.valueToString(ctbScad.getSerDoc()) + " AND " +
|
||||
"num_doc = " + UtilityDB.valueToString(ctbScad.getNumDoc());
|
||||
|
||||
tipoPartita = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql);
|
||||
BigDecimal cambioScad = BigDecimal.ONE;
|
||||
Integer tipoPartita = ctbMovr.getTipoPartita();
|
||||
|
||||
String sql =
|
||||
"SELECT Cast(tipo_partita as integer) as tipo_partita, cambio " +
|
||||
" FROM ctb_part " +
|
||||
" WHERE cod_anag = " + UtilityDB.valueToString(ctbScad.getCodAnag()) + " AND " +
|
||||
"tipo_anag = " + UtilityDB.valueToString(ctbScad.getTipoAnag()) + " AND " +
|
||||
"anno_part = " + UtilityDB.valueToString(ctbScad.getAnnoPart()) + " AND " +
|
||||
"ser_doc = " + UtilityDB.valueToString(ctbScad.getSerDoc()) + " AND " +
|
||||
"num_doc = " + UtilityDB.valueToString(ctbScad.getNumDoc());
|
||||
|
||||
HashMap<String, Object> datiCtbPart = UtilityDB.executeSimpleQueryOnlyFirstRow(conn, sql);
|
||||
if ( UtilityHashMap.isPresent(datiCtbPart)) {
|
||||
if ( tipoPartita == null ) tipoPartita = UtilityHashMap.getValueIfExists(datiCtbPart, "tipo_partita");
|
||||
cambioScad = UtilityHashMap.getValueIfExists(datiCtbPart, "cambio", BigDecimal.ONE);
|
||||
}
|
||||
|
||||
ctbScad.setTipoAnag(UtilityString.isNullOrEmpty(ctbScad.getTipoAnag()) ? ctbMovr.getTipoAnag() : ctbScad.getTipoAnag())
|
||||
@@ -492,7 +499,6 @@ public class AccountingRules extends QueryRules {
|
||||
.setSerDoc(UtilityString.isNullOrEmpty(ctbScad.getSerDoc()) ? ctbMovr.getSerDoc() : ctbScad.getSerDoc())
|
||||
.setNumDoc(UtilityString.isNullOrEmpty(ctbScad.getNumDoc()) ? ctbMovr.getNumDoc() : ctbScad.getNumDoc());
|
||||
|
||||
|
||||
ctbParr =
|
||||
new CtbParr()
|
||||
.setCodCcon(ctbMovr.getCodCcon())
|
||||
@@ -503,12 +509,13 @@ public class AccountingRules extends QueryRules {
|
||||
.setNumDoc(ctbScad.getNumDoc())
|
||||
.setDataCmov(ctbMovr.getDataCmov())
|
||||
.setIdRiga(ctbMovr.getIdRiga())
|
||||
.setImpDare(TipoPartita.fromValue(tipoPartita) == TipoPartita.PASSIVA ? ctbScad.getImpDare() : BigDecimal.ZERO)
|
||||
.setImpAvere(TipoPartita.fromValue(tipoPartita) == TipoPartita.ATTIVA ? ctbScad.getImpAvere() : BigDecimal.ZERO)
|
||||
.setImpDare(UtilityBigDecimal.greaterThan(ctbMovr.getImpDare(), BigDecimal.ZERO) ? ctbScad.getImpDare().divide(cambioScad).setScale(5, RoundingMode.HALF_UP) : BigDecimal.ZERO)
|
||||
.setImpAvere(UtilityBigDecimal.greaterThan(ctbMovr.getImpAvere(), BigDecimal.ZERO) ? ctbScad.getImpAvere().divide(cambioScad).setScale(5, RoundingMode.HALF_UP) : BigDecimal.ZERO)
|
||||
.setCodCcau(ctbMovr.getCodCcau())
|
||||
.setDesAgg(finalDesAgg)
|
||||
.setTipoPartita(tipoPartita)
|
||||
.setChiudiScad(ctbMovr.getChiudiScad());
|
||||
.setChiudiScad(ctbMovr.getChiudiScad())
|
||||
.setCambioDiviScad(cambioScad);
|
||||
ctbParr.setOperation(OperationType.INSERT_OR_UPDATE);
|
||||
}
|
||||
|
||||
@@ -533,23 +540,39 @@ public class AccountingRules extends QueryRules {
|
||||
}
|
||||
ctbMovr.setCtbScad(elencoScadenzeNew);
|
||||
} else {
|
||||
CtbParr ctbParr =
|
||||
new CtbParr()
|
||||
.setCodCcon(ctbMovr.getCodCcon())
|
||||
.setTipoAnag(ctbMovr.getTipoAnag())
|
||||
.setCodAnag(ctbMovr.getCodAnag())
|
||||
.setAnnoPart(ctbMovr.getAnnoPart())
|
||||
.setSerDoc(ctbMovr.getSerDoc())
|
||||
.setNumDoc(ctbMovr.getNumDoc())
|
||||
.setDataCmov(ctbMovr.getDataCmov())
|
||||
.setIdRiga(ctbMovr.getIdRiga())
|
||||
.setImpDare(ctbMovr.getImpDare())
|
||||
.setImpAvere(ctbMovr.getImpAvere())
|
||||
.setCodCcau(ctbMovr.getCodCcau())
|
||||
.setDesAgg(desAgg)
|
||||
.setChiudiScad(ctbMovr.getChiudiScad());
|
||||
ctbParr.setOperation(OperationType.INSERT_OR_UPDATE);
|
||||
elencoPartite.add(ctbParr);
|
||||
String sql =
|
||||
Query.format(
|
||||
"SELECT cast(case when count(*) > 1 THEN 1 ELSE 0 eND as bit)" +
|
||||
" FROM ctb_parr " +
|
||||
" WHERE cod_anag = %s AND " +
|
||||
"tipo_anag = %s AND " +
|
||||
"anno_part = %s AND " +
|
||||
"ser_doc = %s AND " +
|
||||
"num_doc = %s AND " +
|
||||
"id_riga = %s ",
|
||||
ctbMovr.getCodAnag(), ctbMovr.getTipoAnag(), ctbMovr.getAnnoPart(), ctbMovr.getSerDoc(), ctbMovr.getNumDoc(), ctbMovr.getIdRiga());
|
||||
|
||||
boolean existRow = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql);
|
||||
|
||||
if (!existRow) {
|
||||
CtbParr ctbParr =
|
||||
new CtbParr()
|
||||
.setCodCcon(ctbMovr.getCodCcon())
|
||||
.setTipoAnag(ctbMovr.getTipoAnag())
|
||||
.setCodAnag(ctbMovr.getCodAnag())
|
||||
.setAnnoPart(ctbMovr.getAnnoPart())
|
||||
.setSerDoc(ctbMovr.getSerDoc())
|
||||
.setNumDoc(ctbMovr.getNumDoc())
|
||||
.setDataCmov(ctbMovr.getDataCmov())
|
||||
.setIdRiga(ctbMovr.getIdRiga())
|
||||
.setImpDare(ctbMovr.getImpDare())
|
||||
.setImpAvere(ctbMovr.getImpAvere())
|
||||
.setCodCcau(ctbMovr.getCodCcau())
|
||||
.setDesAgg(desAgg)
|
||||
.setChiudiScad(ctbMovr.getChiudiScad());
|
||||
ctbParr.setOperation(OperationType.INSERT_OR_UPDATE);
|
||||
elencoPartite.add(ctbParr);
|
||||
}
|
||||
}
|
||||
return elencoPartite;
|
||||
}
|
||||
@@ -891,7 +914,7 @@ public class AccountingRules extends QueryRules {
|
||||
ResultSetMapper resultSetMapper = new ResultSetMapper();
|
||||
List<CtbScad> ctbScad = resultSetMapper.mapQuerySetToList(conn, sql, CtbScad.class);
|
||||
if (ctbMovr.getOperation() == OperationType.DELETE && ctbScad.size() > 0) {
|
||||
Stream.of(ctbScad).forEach(x -> {
|
||||
for ( CtbScad x: ctbScad) {
|
||||
x.setOperation(x.getIsInsoluto() ? OperationType.DELETE : OperationType.UPDATE);
|
||||
CrlScadParr crlScadParr =
|
||||
new CrlScadParr()
|
||||
@@ -905,8 +928,9 @@ public class AccountingRules extends QueryRules {
|
||||
.setNumCmov(ctbMovr.getNumCmov())
|
||||
.setId(x.getPkRelazione());
|
||||
crlScadParr.setOperation(OperationType.DELETE);
|
||||
if (x.getCrlScadParr() == null ) x.setCrlScadParr(new ArrayList<>());
|
||||
x.getCrlScadParr().add(crlScadParr);
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
return ctbScad;
|
||||
|
||||
@@ -4,7 +4,8 @@ import com.annimon.stream.ComparatorCompat;
|
||||
import com.annimon.stream.Optional;
|
||||
import com.annimon.stream.Stream;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems_model.annotation.*;
|
||||
import it.integry.ems_model.annotation.ReloadRow;
|
||||
import it.integry.ems_model.annotation.SqlField;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
import it.integry.ems_model.db.ResultSetMapper;
|
||||
@@ -16,7 +17,6 @@ import it.integry.ems_model.rulescompleting.DroolsDataCompleting;
|
||||
import it.integry.ems_model.types.ApplicationName;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.*;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.springframework.expression.Expression;
|
||||
import org.springframework.expression.ExpressionParser;
|
||||
import org.springframework.expression.spel.standard.SpelExpressionParser;
|
||||
@@ -179,7 +179,7 @@ public class CommonRules extends QueryRules {
|
||||
Object object = field.get(testata);
|
||||
if (object != null && field.getType().isAssignableFrom(List.class) && ( field.getAnnotation(ReloadRow.class) != null || testata.getOperation() == OperationType.SUBSTITUTE)) {
|
||||
List<? extends EntityBase> rows = (ArrayList<EntityBase>) object;
|
||||
List<EntityBase> list = null;
|
||||
List<? extends EntityBase> list = null;
|
||||
if (testata.getOperation() != OperationType.DELETE_THEN_INSERT &&
|
||||
testata.getOperation() != OperationType.INSERT) {
|
||||
list = UtilityDB.reloadOnlyDbRow(conn, testata, rows, field);
|
||||
|
||||
@@ -41,7 +41,7 @@ public class ConfigActivityRules extends QueryRules {
|
||||
}
|
||||
} else {
|
||||
List<Date> dataDaControllare = new ArrayList<>();
|
||||
if (stbActivity.getEstimatedDate() != null) dataDaControllare.add(stbActivity.getEstimatedDate());
|
||||
//if (stbActivity.getEstimatedDate() != null) dataDaControllare.add(stbActivity.getEstimatedDate());
|
||||
if (stbActivity.getEffectiveDate() != null) dataDaControllare.add(stbActivity.getEffectiveDate());
|
||||
|
||||
for (Date data : dataDaControllare) {
|
||||
|
||||
@@ -824,7 +824,7 @@ public class DocOrdRules extends QueryRules {
|
||||
.setGestione(ordine.getGestione())
|
||||
.setDataOrd(ordine.getDataOrd())
|
||||
.setNumOrd(ordine.getNumOrd())
|
||||
.setPartitaMag(dtbOrdt.getOperation() == OperationType.DELETE ? EmsRestConstants.NULL : dtbOrdt.getPartitaMag())
|
||||
.setPartitaMag(dtbOrdt.getOperation() == OperationType.DELETE || ordine.getFlagScollegaPartitaMag() ? EmsRestConstants.NULL : dtbOrdt.getPartitaMag())
|
||||
);
|
||||
|
||||
righeOrdine.forEach(rigaOrdine -> rigaOrdine.setOperation(OperationType.UPDATE));
|
||||
|
||||
@@ -3,7 +3,6 @@ package it.integry.ems.rules.completing;
|
||||
import com.annimon.stream.Stream;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems.rules.completing.dto.DatiPartitaMagDTO;
|
||||
import it.integry.ems_model.annotation.SqlField;
|
||||
import it.integry.ems_model.config.EmsRestConstants;
|
||||
import it.integry.ems_model.entity.MtbColr;
|
||||
import it.integry.ems_model.entity.MtbCols;
|
||||
@@ -11,12 +10,13 @@ import it.integry.ems_model.entity.MtbColt;
|
||||
import it.integry.ems_model.entity.MtbPartitaMag;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.*;
|
||||
import org.springframework.util.ReflectionUtils;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.sql.*;
|
||||
import java.sql.CallableStatement;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Types;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
@@ -77,9 +77,9 @@ public class PackagesRules extends QueryRules {
|
||||
|
||||
String sql =
|
||||
"SELECT Cast(count(*) as bit) " +
|
||||
" FROM mtb_partita_mag " +
|
||||
" WHERE mtb_partita_mag.cod_mart = " + UtilityDB.valueToString(mtbColr.getCodMart()) + " AND " +
|
||||
"mtb_partita_mag.partita_mag = "+ UtilityDB.valueToString(mtbColr.getPartitaMag());
|
||||
" FROM mtb_partita_mag " +
|
||||
" WHERE mtb_partita_mag.cod_mart = " + UtilityDB.valueToString(mtbColr.getCodMart()) + " AND " +
|
||||
"mtb_partita_mag.partita_mag = " + UtilityDB.valueToString(mtbColr.getPartitaMag());
|
||||
|
||||
boolean existPartita = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql);
|
||||
|
||||
@@ -88,14 +88,14 @@ public class PackagesRules extends QueryRules {
|
||||
operation = OperationType.INSERT;
|
||||
sql =
|
||||
"SELECT CASE\n" +
|
||||
" WHEN dbo.getgestsetup('MTB_PARTITA_MAG', 'SETUP', 'DESCRIZIONE_PARTITA_FORNITORE') = 'S' THEN\n" +
|
||||
" gtb_anag.rag_soc\n" +
|
||||
" ELSE NULL END\n" +
|
||||
"FROM dtb_ordt \n" +
|
||||
" INNER JOIN gtb_anag ON dtb_ordt.cod_anag = gtb_anag.cod_anag\n" +
|
||||
"WHERE dtb_ordt.gestione = " + UtilityDB.valueToString(mtbColr.getGestione()) + "\n" +
|
||||
" AND dtb_ordt.data_ord = " + UtilityDB.valueDateToString(mtbColr.getDataOrd(), CommonConstants.DATE_FORMAT_YMD) + "\n" +
|
||||
" AND dtb_ordt.num_ord = " + UtilityDB.valueToString(mtbColr.getNumOrd());
|
||||
" WHEN dbo.getgestsetup('MTB_PARTITA_MAG', 'SETUP', 'DESCRIZIONE_PARTITA_FORNITORE') = 'S' THEN\n" +
|
||||
" gtb_anag.rag_soc\n" +
|
||||
" ELSE NULL END\n" +
|
||||
"FROM dtb_ordt \n" +
|
||||
" INNER JOIN gtb_anag ON dtb_ordt.cod_anag = gtb_anag.cod_anag\n" +
|
||||
"WHERE dtb_ordt.gestione = " + UtilityDB.valueToString(mtbColr.getGestione()) + "\n" +
|
||||
" AND dtb_ordt.data_ord = " + UtilityDB.valueDateToString(mtbColr.getDataOrd(), CommonConstants.DATE_FORMAT_YMD) + "\n" +
|
||||
" AND dtb_ordt.num_ord = " + UtilityDB.valueToString(mtbColr.getNumOrd());
|
||||
|
||||
String descrPartita = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql);
|
||||
partita.setDescrizione(descrPartita);
|
||||
@@ -142,7 +142,7 @@ public class PackagesRules extends QueryRules {
|
||||
return codVlis;
|
||||
}
|
||||
|
||||
public static HashMap<String, Object> completeDimensioniCollo(Connection connection, String codTcol) throws Exception{
|
||||
public static HashMap<String, Object> completeDimensioniCollo(Connection connection, String codTcol) throws Exception {
|
||||
String sql =
|
||||
Query.format("select lunghezza_cm, larghezza_cm, altezza_cm from mtb_tcol where cod_tcol = %s ", codTcol);
|
||||
|
||||
@@ -174,7 +174,7 @@ public class PackagesRules extends QueryRules {
|
||||
"GROUP BY posizione, cod_mdep";
|
||||
|
||||
final HashMap<String, Object> result = UtilityDB.executeSimpleQueryOnlyFirstRow(connection, sql);
|
||||
if(result == null) return false;
|
||||
if (result == null) return false;
|
||||
|
||||
boolean colloExists = UtilityHashMap.getValueIfExists(result, "exist");
|
||||
String prevPosizione = UtilityHashMap.getValueIfExists(result, "posizione");
|
||||
@@ -188,14 +188,14 @@ public class PackagesRules extends QueryRules {
|
||||
public static void insertMtbCols(MtbColt mtbColt, MtbCols.Causale causale) {
|
||||
//if(mtbColt.getMtbCols().isEmpty()) {
|
||||
|
||||
MtbCols mtbCols = new MtbCols()
|
||||
.setCausale(causale)
|
||||
.setCodMdep(mtbColt.getCodMdep())
|
||||
.setDataMove(new Date())
|
||||
.setPosizione(mtbColt.getPosizione())
|
||||
.setModificatoDa(mtbColt.getPreparatoDa());
|
||||
mtbCols.setOperation(OperationType.INSERT);
|
||||
mtbColt.getMtbCols().add(mtbCols);
|
||||
MtbCols mtbCols = new MtbCols()
|
||||
.setCausale(causale)
|
||||
.setCodMdep(mtbColt.getCodMdep())
|
||||
.setDataMove(new Date())
|
||||
.setPosizione(mtbColt.getPosizione())
|
||||
.setModificatoDa(mtbColt.getPreparatoDa());
|
||||
mtbCols.setOperation(OperationType.INSERT);
|
||||
mtbColt.getMtbCols().add(mtbCols);
|
||||
//}
|
||||
}
|
||||
|
||||
@@ -295,8 +295,8 @@ public class PackagesRules extends QueryRules {
|
||||
"SELECT dtb_ordt.cod_anag, " +
|
||||
" dtb_ordt.cod_vdes, " +
|
||||
" dtb_ordt.rif_ord " +
|
||||
" FROM dtb_ordt " +
|
||||
" WHERE gestione = " + UtilityDB.valueToString(mtbColt.getGestione()) + " AND " +
|
||||
" FROM dtb_ordt " +
|
||||
" WHERE gestione = " + UtilityDB.valueToString(mtbColt.getGestione()) + " AND " +
|
||||
" data_ord = " + UtilityDB.valueDateToString(mtbColt.getDataOrd(), CommonConstants.DATE_FORMAT_YMD) + " AND " +
|
||||
" num_ord = " + UtilityDB.valueToString(mtbColt.getNumOrd());
|
||||
|
||||
@@ -355,10 +355,10 @@ public class PackagesRules extends QueryRules {
|
||||
}
|
||||
|
||||
public static void completeFlagColloAnonimo(MtbColt mtbColt) {
|
||||
if (mtbColt.getDataDoc() == null || mtbColt.getOperation() == OperationType.DELETE){
|
||||
if ( UtilityString.isNullOrEmpty(mtbColt.getCodAnag()) &&
|
||||
if (mtbColt.getDataDoc() == null || mtbColt.getOperation() == OperationType.DELETE) {
|
||||
if (UtilityString.isNullOrEmpty(mtbColt.getCodAnag()) &&
|
||||
UtilityString.isNullOrEmpty(mtbColt.getCodVdes()) &&
|
||||
mtbColt.getDataOrd() == null && mtbColt.getNumOrd() == null){
|
||||
mtbColt.getDataOrd() == null && mtbColt.getNumOrd() == null) {
|
||||
mtbColt.setFlagColloAnonimo("S");
|
||||
} else {
|
||||
mtbColt.setFlagColloAnonimo("N");
|
||||
@@ -381,8 +381,8 @@ public class PackagesRules extends QueryRules {
|
||||
if (mtbColt.getCalcPeso()) {
|
||||
mtbColt.setPesoKg(pesoLordo);
|
||||
mtbColt.setPesoNettoKg(pesoNetto);
|
||||
|
||||
mtbColt.setOperation(OperationType.INSERT_OR_UPDATE);
|
||||
if (mtbColt.getOperation() != OperationType.SUBSTITUTE)
|
||||
mtbColt.setOperation(OperationType.INSERT_OR_UPDATE);
|
||||
} else if (!mtbColt.getCalcPeso() && righe.size() > 0 && UtilityBigDecimal.greaterThan(pesoLordo, BigDecimal.ZERO) && UtilityBigDecimal.greaterThan(pesoNetto, BigDecimal.ZERO)) {
|
||||
long countRowKG = Stream.of(righe).filter(x -> x.getOperation() != OperationType.DELETE && "S".equalsIgnoreCase(x.getArtAPeso())).count();
|
||||
long countNewRows = Stream.of(righe)
|
||||
@@ -440,26 +440,27 @@ public class PackagesRules extends QueryRules {
|
||||
|
||||
if (UtilityHashMap.isPresent(datiOrdine))
|
||||
mtbcolt
|
||||
.setCodAnag(mtbcolt.getCodAnag()==null?UtilityHashMap.getValueIfExists(datiOrdine, "cod_anag"):mtbcolt.getCodAnag())
|
||||
.setCodVdes(mtbcolt.getCodVdes()== null?UtilityHashMap.getValueIfExists(datiOrdine, "cod_vdes"):mtbcolt.getCodVdes())
|
||||
.setCodAnag(mtbcolt.getCodAnag() == null ? UtilityHashMap.getValueIfExists(datiOrdine, "cod_anag") : mtbcolt.getCodAnag())
|
||||
.setCodVdes(mtbcolt.getCodVdes() == null ? UtilityHashMap.getValueIfExists(datiOrdine, "cod_vdes") : mtbcolt.getCodVdes())
|
||||
.setRifOrd(UtilityHashMap.getValueIfExists(datiOrdine, "rif_ord"));
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public static String getSerCollo(Connection conn, String codMdep) throws Exception {
|
||||
String sql =
|
||||
"SELECT dbo.f_getSerCollo(" + UtilityDB.valueToString(codMdep) + ")";
|
||||
|
||||
String serDoc = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql);
|
||||
|
||||
if (serDoc == null){
|
||||
if (serDoc == null) {
|
||||
serDoc = (String) CommonRules.completeWithDefault(MtbColt.class, "serCollo");
|
||||
}
|
||||
return serDoc;
|
||||
}
|
||||
|
||||
public static boolean checkForAnyColloRif(Connection conn, String gestione, String serCollo, int numCollo, Date dataCollo) throws Exception{
|
||||
public static boolean checkForAnyColloRif(Connection conn, String gestione, String serCollo, int numCollo, Date dataCollo) throws Exception {
|
||||
String sql = "SELECT count(*) " +
|
||||
"FROM mtb_colr " +
|
||||
"WHERE gestione_rif = " + UtilityDB.valueToString(gestione) +
|
||||
@@ -469,7 +470,7 @@ public class PackagesRules extends QueryRules {
|
||||
|
||||
int countColliRif = (int) getSingleValue(conn, sql);
|
||||
|
||||
if ( countColliRif > 0){
|
||||
if (countColliRif > 0) {
|
||||
throw new Exception("Impossibile cancellare il collo, ci sono altri colli che hanno un riferimento a questo.");
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -159,6 +159,31 @@ public class SalesRules extends QueryRules {
|
||||
return untMisVend;
|
||||
}
|
||||
|
||||
public static VtbList insertVtbList(Connection connection, VtbListData vtbListData) throws SQLException {
|
||||
String sql = Query.format(
|
||||
"SELECT CAST(COUNT(*) AS BIT) FROM vtb_list WHERE cod_vlis = %s",
|
||||
vtbListData.getCodVlis()
|
||||
);
|
||||
|
||||
Boolean countVtbList = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(connection, sql);
|
||||
|
||||
if (!countVtbList) {
|
||||
VtbList vtbList = new VtbList();
|
||||
|
||||
vtbList
|
||||
.setCodVlis(vtbListData.getCodVlis())
|
||||
.setDescrizione(vtbListData.getDescrizione())
|
||||
.setCodDivi(vtbListData.getCodDivi());
|
||||
|
||||
vtbList.setOperation(OperationType.INSERT);
|
||||
|
||||
return vtbList;
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
public static VtbPromo completePromoVend(VtbListData vtbListData) {
|
||||
if (vtbListData.getVtbPromo() != null) {
|
||||
VtbPromo vtbPromo = vtbListData.getVtbPromo().setCodPromo(vtbListData.getCodPromo());
|
||||
@@ -486,6 +511,8 @@ public class SalesRules extends QueryRules {
|
||||
valUntIva != null) {
|
||||
|
||||
BigDecimal percAliq = (BigDecimal) DroolsUtil.getEntityFieldValue(entity, "perc_aliq");
|
||||
if ( percAliq == null )
|
||||
throw new Exception ( String.format("Aliquota iva mancante sull'articolo ", entity.getCodMart()));
|
||||
BigDecimal valUnt = CommonRules.scorporoIva(valUntIva, percAliq);
|
||||
entity.setValUnt(valUnt);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ public class ForeignKeyDTO {
|
||||
put(CtbIreg.ENTITY, "Codice registro documenti inesistente");
|
||||
put(WtbJrept.ENTITY, "Report inesistente");
|
||||
put(StbDevice.ENTITY, "Dispositivo inesistente");
|
||||
put(StbPublications.ENTITY, "Pubblicazione inesistente");
|
||||
}};
|
||||
|
||||
String tableName;
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.annimon.stream.Stream;
|
||||
import it.integry.annotations.PostContextAutowired;
|
||||
import it.integry.annotations.PostWebServerConstruct;
|
||||
import it.integry.ems.schedule.new_cron_job.dto.AutomatedOperationTypeEnum;
|
||||
import it.integry.ems.schedule.new_cron_job.dto.operations.ExportAutomatedOperationDTO;
|
||||
import it.integry.ems.schedule.new_cron_job.dto.operations.ServiceCallAutomatedOperationDTO;
|
||||
import it.integry.ems.schedule.new_cron_job.dto.operations.base_classes.BaseAutomatedOperationDTO;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionsModel;
|
||||
@@ -11,6 +12,7 @@ import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.utility.UtilityDebug;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -43,7 +45,6 @@ public class DefaultAutomatedOperationHandlerComponent {
|
||||
|
||||
if (!UtilityDebug.isDebugExecution() && !UtilityDebug.isIntegryServer()) {
|
||||
deleteJobFileDeleter(multiDBTransactionManager);
|
||||
//initFileDeleterJob(multiDBTransactionManager);
|
||||
initServerInfoCheckJob();
|
||||
initRemoveFpxInvioFilesJob();
|
||||
initChkAutofatture();
|
||||
@@ -51,6 +52,7 @@ public class DefaultAutomatedOperationHandlerComponent {
|
||||
initMinioOrphanFileCleaner(multiDBTransactionManager);
|
||||
initPassaggioAnno(multiDBTransactionManager);
|
||||
}
|
||||
|
||||
} catch (Exception ex) {
|
||||
|
||||
}
|
||||
@@ -161,43 +163,6 @@ public class DefaultAutomatedOperationHandlerComponent {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void initFileDeleterJob(MultiDBTransactionManager data) {
|
||||
try {
|
||||
List<AdvancedDataSource> activeConnections = data.getActiveConnections();
|
||||
|
||||
HashMap<AutomatedOperationTypeEnum, List<BaseAutomatedOperationDTO>> activeOperations = automatedOperationHandlerComponent.get(AutomatedOperationTypeEnum.METHOD_CALLS, null);
|
||||
if (!activeOperations.containsKey(AutomatedOperationTypeEnum.METHOD_CALLS))
|
||||
activeOperations.put(AutomatedOperationTypeEnum.METHOD_CALLS, new ArrayList<>());
|
||||
|
||||
activeConnections = Stream.of(activeConnections)
|
||||
.filter(x -> x.isInternalDb() && x.getDataSource().getProfile().equalsIgnoreCase(x.getDataSource().getDbName()))
|
||||
.toList();
|
||||
|
||||
for (AdvancedDataSource activeConnection : activeConnections) {
|
||||
final String filesDeleterOperationName = "File deleter " + activeConnection.getProfileName().toUpperCase();
|
||||
|
||||
boolean jobExists = Stream.of(activeOperations.get(AutomatedOperationTypeEnum.METHOD_CALLS))
|
||||
.anyMatch(iScheduledOperation -> iScheduledOperation.getName().equals(filesDeleterOperationName));
|
||||
|
||||
if (!jobExists) {
|
||||
ServiceCallAutomatedOperationDTO serviceCallAutomatedOperationDTO = new ServiceCallAutomatedOperationDTO()
|
||||
.setMethodName("cleanDirectories")
|
||||
.setProfileDb(activeConnection.getProfileName());
|
||||
serviceCallAutomatedOperationDTO
|
||||
.setCronTrigger("0 0 0 1/1 * ?")
|
||||
.setName(filesDeleterOperationName);
|
||||
|
||||
automatedOperationHandlerComponent.add(serviceCallAutomatedOperationDTO);
|
||||
}
|
||||
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteJobFileDeleter(MultiDBTransactionManager data) {
|
||||
try {
|
||||
List<AdvancedDataSource> activeConnections = data.getActiveConnections();
|
||||
|
||||
@@ -993,7 +993,7 @@ public class EmsServices {
|
||||
}
|
||||
|
||||
public List<EntityHierarchyDTO> getEntityMapping() {
|
||||
return entityPropertyHolder.getEntityMapping();
|
||||
return entityPropertyHolder.getEntityHierarchyMap();
|
||||
}
|
||||
|
||||
public List<EntityFieldDTO> getEntityDetails(String entityName) {
|
||||
|
||||
@@ -13,7 +13,6 @@ import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.utility.UtilityDebug;
|
||||
import it.integry.ems_model.annotation.EntityChild;
|
||||
import it.integry.ems_model.annotation.SqlField;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.base.EntityInterface;
|
||||
import it.integry.ems_model.entity.StbLogEntitySetup;
|
||||
import it.integry.ems_model.resolver.SqlFieldHolder;
|
||||
@@ -154,7 +153,7 @@ public class EntityLoggerNewService {
|
||||
|
||||
String columns = StringUtils.join(entityMap.keySet(), ", ");
|
||||
String values = StringUtils.join(Stream.of(entityMap.values())
|
||||
.map(SqlFieldHolder::getSqlValueField).toList(), ", ");
|
||||
.map(SqlFieldHolder::getSqlValueFieldAsString).toList(), ", ");
|
||||
|
||||
String sql = "INSERT INTO " + entityToLog.getEntity().getTableName() +
|
||||
"(" + columns + ") VALUES (" + values + ")";
|
||||
|
||||
@@ -9,11 +9,9 @@ import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems.datasource.DataSource;
|
||||
import it.integry.ems.dto.EntityPermissionsDTO;
|
||||
import it.integry.ems.exception.InvalidPermissionsException;
|
||||
import it.integry.ems.exception.PrimaryDatabaseNotPresentException;
|
||||
import it.integry.ems.javabeans.RequestDataDTO;
|
||||
import it.integry.ems.json.JSONObjectMapper;
|
||||
import it.integry.ems.model.ColumnMetadataDTO;
|
||||
import it.integry.ems.object_storage.minio.sdk.errors.MinioException;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems.sync.MultiDBTransaction.AdvancedDataSource;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
@@ -24,7 +22,7 @@ import it.integry.ems_model.annotation.Master;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.base.EntityInterface;
|
||||
import it.integry.ems_model.base.EntityPropertyHolder;
|
||||
import it.integry.ems_model.exception.*;
|
||||
import it.integry.ems_model.exception.EntityException;
|
||||
import it.integry.ems_model.resolver.ResultSetSerializer;
|
||||
import it.integry.ems_model.rulescompleting.DroolsDataCompleting;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
@@ -38,14 +36,9 @@ import org.josql.QueryResults;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.xmlpull.v1.XmlPullParserException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.StringWriter;
|
||||
import java.lang.annotation.Annotation;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.sql.*;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
@@ -97,7 +90,7 @@ public class EntityProcessor {
|
||||
username = requestDataDTO.getUsername();
|
||||
}
|
||||
|
||||
return (T) processEntity(entity, true, false, username, multiDBTransactionManager, true);
|
||||
return (T) processEntity(entity, true, false, username, multiDBTransactionManager, true, false);
|
||||
}
|
||||
|
||||
public EntityBase processEntity(EntityInterface entity, boolean skipCommit, MultiDBTransactionManager multiDBTransactionManager) throws Exception {
|
||||
@@ -108,13 +101,20 @@ public class EntityProcessor {
|
||||
username = requestDataDTO.getUsername();
|
||||
}
|
||||
|
||||
return (EntityBase) processEntity(entity, true, skipCommit, username, multiDBTransactionManager, true);
|
||||
return (EntityBase) processEntity(entity, true, skipCommit, username, multiDBTransactionManager, true, false);
|
||||
}
|
||||
|
||||
public EntityBase processEntity(EntityInterface entity, Boolean isSync,
|
||||
boolean skipCommit, String username,
|
||||
MultiDBTransactionManager mdb) throws Exception {
|
||||
return (EntityBase) processEntity(entity, true, skipCommit, username, mdb, true);
|
||||
return (EntityBase) processEntity(entity, isSync, skipCommit, username, mdb, true, false);
|
||||
}
|
||||
|
||||
public Object processEntity(EntityInterface entity, Boolean isSync,
|
||||
boolean skipCommit, String username,
|
||||
MultiDBTransactionManager mdb,
|
||||
boolean completeEntity) throws Exception {
|
||||
return processEntity(entity, isSync, skipCommit, username, mdb, completeEntity, false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -132,7 +132,7 @@ public class EntityProcessor {
|
||||
public Object processEntity(EntityInterface entity, Boolean isSync,
|
||||
boolean skipCommit, String username,
|
||||
MultiDBTransactionManager mdb,
|
||||
boolean completeEntity) throws Exception {
|
||||
boolean completeEntity, boolean overrideEntityChildCheck) throws Exception {
|
||||
|
||||
try {
|
||||
entity.setEntityHolder(entityPropertyHolder);
|
||||
@@ -144,7 +144,7 @@ public class EntityProcessor {
|
||||
entity.setOperation(OperationType.NO_OP);
|
||||
}
|
||||
|
||||
this.checkEntityChildsUsage(entity, mdb);
|
||||
if (!overrideEntityChildCheck) this.checkEntityChildsUsage(entity, mdb);
|
||||
|
||||
if (settingsModel.isEnablePermissionCheck() && !checkUserPermissions(entity))
|
||||
throw new InvalidPermissionsException();
|
||||
@@ -155,23 +155,10 @@ public class EntityProcessor {
|
||||
return entity.selectAndMergeEntity(mdb.getPrimaryConnection(), (EntityBase) entity);
|
||||
//return entity;
|
||||
} else if (entity.getOperation() == OperationType.SELECT) {
|
||||
String json = (String) entity.select(mdb.getPrimaryConnection());
|
||||
if (json != null) {
|
||||
EntityBase[] entityList = null;
|
||||
//json to entity
|
||||
if (json.charAt(0) == '[') {
|
||||
entityList = jsonObjectMapper.readValue(json, EntityBase[].class);
|
||||
} else if (json.charAt(0) == '{') {
|
||||
EntityBase ent = jsonObjectMapper.readValue(json, EntityBase.class);
|
||||
entityList = new EntityBase[]{ent};
|
||||
}
|
||||
|
||||
for (int i = 0; i < entityList.length; i++) {
|
||||
entityList[i].setOperation(entity.getOperation());
|
||||
}
|
||||
List<? extends EntityBase> entityList = entity.select(mdb.getPrimaryConnection());
|
||||
return entityList;
|
||||
|
||||
return entityList;
|
||||
}
|
||||
} else {
|
||||
processInternal(entity, isSync, mdb, completeEntity);
|
||||
}
|
||||
@@ -472,27 +459,22 @@ public class EntityProcessor {
|
||||
}
|
||||
|
||||
|
||||
public List<EntityBase> processEntityList(List<? extends EntityBase> entities, boolean singleTransaction) throws SQLException, IOException, PrimaryDatabaseNotPresentException, MergeEntityDBToObjectException, DataConverterNotFoundException, MinioException, XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException, NoSuchFieldException, FieldMissingException, IllegalAccessException, ConverterNotConfiguredException, InstantiationException, RulesNotCompiledException, InvocationTargetException {
|
||||
return processEntityList(null, true, singleTransaction, false, entities);
|
||||
public List<EntityBase> processEntityList(List<? extends EntityBase> entities, boolean singleTransaction) throws Exception {
|
||||
return processEntityList(entities, null, true, singleTransaction, false, mDbTransactManager, true, false);
|
||||
}
|
||||
|
||||
public List<EntityBase> processEntityList(List<? extends EntityBase> entities, MultiDBTransactionManager multiDBTransactionManager, boolean singleTransaction) throws SQLException, IOException, PrimaryDatabaseNotPresentException, MergeEntityDBToObjectException, DataConverterNotFoundException, MinioException, XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException, NoSuchFieldException, FieldMissingException, IllegalAccessException, ConverterNotConfiguredException, InstantiationException, RulesNotCompiledException, InvocationTargetException {
|
||||
return processEntityList(null, true, singleTransaction, false, entities, multiDBTransactionManager);
|
||||
public List<EntityBase> processEntityList(List<? extends EntityBase> entities, MultiDBTransactionManager multiDBTransactionManager, boolean singleTransaction) throws Exception {
|
||||
return processEntityList(entities, null, true, singleTransaction, false, multiDBTransactionManager, true, false);
|
||||
}
|
||||
|
||||
public List<EntityBase> processEntityList(List<? extends EntityBase> entities, boolean isSync, boolean singleTransaction, boolean ordinaSuPriorita) throws SQLException, IOException, PrimaryDatabaseNotPresentException, MergeEntityDBToObjectException, DataConverterNotFoundException, MinioException, XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException, NoSuchFieldException, FieldMissingException, IllegalAccessException, ConverterNotConfiguredException, InstantiationException, RulesNotCompiledException, InvocationTargetException {
|
||||
return processEntityList(null, isSync, singleTransaction, ordinaSuPriorita, entities);
|
||||
public List<EntityBase> processEntityList(List<? extends EntityBase> entities, boolean isSync, boolean singleTransaction, boolean ordinaSuPriorita) throws Exception {
|
||||
return processEntityList(entities, null, isSync, singleTransaction, ordinaSuPriorita, mDbTransactManager, true, false);
|
||||
}
|
||||
|
||||
public List<EntityBase> processEntityList(List<? extends EntityBase> entities, String username, boolean isSync, boolean singleTransaction, boolean ordinaSuPriorita) throws SQLException, IOException, PrimaryDatabaseNotPresentException, MergeEntityDBToObjectException, DataConverterNotFoundException, MinioException, XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException, NoSuchFieldException, FieldMissingException, IllegalAccessException, ConverterNotConfiguredException, InstantiationException, RulesNotCompiledException, InvocationTargetException {
|
||||
return processEntityList(username, isSync, singleTransaction, ordinaSuPriorita, entities);
|
||||
public List<EntityBase> processEntityList(List<? extends EntityBase> entities, String username, boolean isSync, boolean singleTransaction, boolean ordinaSuPriorita) throws Exception {
|
||||
return processEntityList(entities, username, isSync, singleTransaction, ordinaSuPriorita, mDbTransactManager, true, false);
|
||||
}
|
||||
|
||||
public List<EntityBase> processEntityList(String username, boolean isSync, boolean singleTransaction, boolean ordinaSuPriorita, List<? extends EntityBase> entities) throws SQLException, IOException, PrimaryDatabaseNotPresentException, MergeEntityDBToObjectException, DataConverterNotFoundException, MinioException, XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException, NoSuchFieldException, FieldMissingException, IllegalAccessException, ConverterNotConfiguredException, InstantiationException, RulesNotCompiledException, InvocationTargetException {
|
||||
return processEntityList(username, isSync, singleTransaction, ordinaSuPriorita, entities, mDbTransactManager);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Entity List Processor
|
||||
*
|
||||
@@ -505,7 +487,12 @@ public class EntityProcessor {
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public List<EntityBase> processEntityList(String username, boolean isSync, boolean singleTransaction, boolean ordinaSuPriorita, List<? extends EntityBase> entities, MultiDBTransactionManager multiDBTransactionManager) throws PrimaryDatabaseNotPresentException, SQLException, IOException, MergeEntityDBToObjectException, DataConverterNotFoundException, MinioException, XmlPullParserException, NoSuchAlgorithmException, InvalidKeyException, NoSuchFieldException, FieldMissingException, IllegalAccessException, ConverterNotConfiguredException, InstantiationException, RulesNotCompiledException, InvocationTargetException {
|
||||
public List<EntityBase> processEntityList(List<? extends EntityBase> entities, String username,
|
||||
boolean isSync,
|
||||
boolean singleTransaction,
|
||||
boolean ordinaSuPriorita,
|
||||
MultiDBTransactionManager multiDBTransactionManager,
|
||||
boolean completeEntity, boolean overrideEntityChildCheck) throws Exception {
|
||||
|
||||
if (UtilityString.isNullOrEmpty(username) && requestDataDTO != null && requestDataDTO.isValidUsername()) {
|
||||
username = requestDataDTO.getUsername();
|
||||
@@ -518,13 +505,13 @@ public class EntityProcessor {
|
||||
entities = entityPropertyHolder.getEntityChain(entities, multiDBTransactionManager.getPrimaryDatasource().getConnection());
|
||||
}
|
||||
|
||||
Integer prevTransactionGroupId = null;
|
||||
Long prevTransactionGroupId = null;
|
||||
|
||||
for (int i = 0; i < entities.size(); i++) {
|
||||
EntityBase entity = entities.get(i);
|
||||
entity.setTransactionGroupId(prevTransactionGroupId);
|
||||
try {
|
||||
EntityBase entityResult = (EntityBase) this.processEntity(entity, isSync, singleTransaction, username, multiDBTransactionManager, true);
|
||||
EntityBase entityResult = (EntityBase) this.processEntity(entity, isSync, singleTransaction, username, multiDBTransactionManager, completeEntity, overrideEntityChildCheck);
|
||||
prevTransactionGroupId = entity.getTransactionGroupId();
|
||||
if (entityResult != null) {
|
||||
entityList.add(entityResult);
|
||||
|
||||
@@ -46,6 +46,7 @@ import java.io.*;
|
||||
import java.net.InetAddress;
|
||||
import java.net.SocketTimeoutException;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
@@ -552,13 +553,13 @@ public class MailService {
|
||||
|
||||
public byte[] createEmlFile(StbActivityEmailObject emailObject) throws MessagingException, IOException {
|
||||
Message message = new MimeMessage(Session.getInstance(System.getProperties()));
|
||||
message.setFrom(new InternetAddress(emailObject.getFrom().getDisplayName() + "<" + emailObject.getFrom().getEmailAddress() + ">"));
|
||||
message.setFrom(new InternetAddress(emailObject.getFrom().getDisplayName().replaceAll(",", "") + "<" + emailObject.getFrom().getEmailAddress().replaceAll(",", "") + ">"));
|
||||
message.setSentDate(emailObject.getDateTimeCreated());
|
||||
|
||||
List<InternetAddress> toList = Stream.of(emailObject.getTo())
|
||||
.map(x -> {
|
||||
try {
|
||||
return new InternetAddress(x.getDisplayName() + "<" + x.getEmailAddress() + ">");
|
||||
return new InternetAddress(x.getDisplayName().replaceAll(",", "") + "<" + x.getEmailAddress().replaceAll(",", "") + ">");
|
||||
} catch (AddressException e) {
|
||||
logger.error(e);
|
||||
return null;
|
||||
@@ -572,6 +573,9 @@ public class MailService {
|
||||
|
||||
String body = emailObject.getBody();
|
||||
|
||||
if(body != null && emailObject.isBodyInBase64())
|
||||
body = new String(Base64.decodeBase64(body), StandardCharsets.UTF_8);
|
||||
|
||||
body = body.replaceAll("@.{8}\\..{8}", "");
|
||||
|
||||
message.setSubject(emailObject.getSubject());
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
package it.integry.ems.sync;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement;
|
||||
import it.integry.annotations.PostContextConstruct;
|
||||
import it.integry.ems.datasource.DataSource;
|
||||
import it.integry.ems.json.JSONObjectMapper;
|
||||
import it.integry.ems.looper.service.LooperService;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.sync.dto.ExportHistoryGroupDTO;
|
||||
import it.integry.ems.sync.dto.ExportHistoryItemDTO;
|
||||
import it.integry.ems.sync.dto.ExportHistoryStatusDTO;
|
||||
import it.integry.ems.sync.dto.PublicationDTO;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.base.EntityPropertyHolder;
|
||||
import it.integry.ems_model.entity.StbPublications;
|
||||
import it.integry.ems_model.entity.StbPublicationsDetail;
|
||||
import it.integry.ems_model.entity.StbTransactionLog;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityLocalDate;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.AbstractMap;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class AsyncHistoryManager {
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
@Autowired
|
||||
private LooperService looperService;
|
||||
|
||||
@Autowired
|
||||
private EntityPropertyHolder entityPropertyHolder;
|
||||
|
||||
@Autowired
|
||||
private JSONObjectMapper jsonObjectMapper;
|
||||
|
||||
//Implement check list like distribuzione
|
||||
private final AtomicReference<List<ExportHistoryGroupDTO>> currentlyInExecutionG = new AtomicReference<>(new ArrayList<>());
|
||||
|
||||
|
||||
@PostContextConstruct
|
||||
public void init() {
|
||||
this.looperService.add(this::consumeRetrieveQueue, 10 * 1000, "async-history-read");
|
||||
this.looperService.add(this::consumeProcessedQueue, 2 * 1000, "async-history-save");
|
||||
}
|
||||
|
||||
public void addToExportQueue(DataSource dataSource, long groupId, PublicationDTO publication) throws Exception {
|
||||
|
||||
tryAddInExecutionList(groupId, dataSource, new ExportHistoryItemDTO()
|
||||
.setPublication(publication));
|
||||
}
|
||||
|
||||
private void tryAddInExecutionList(long groupId, DataSource dataSource, ExportHistoryItemDTO exportHistoryItemDTO) throws Exception {
|
||||
|
||||
ExportHistoryGroupDTO currentlyInExec = currentlyInExecutionG.get().stream()
|
||||
.filter(x -> x.getGroupId() == groupId)
|
||||
.findFirst().orElseGet(() ->
|
||||
{
|
||||
final ExportHistoryGroupDTO exportHistoryGroupDTO = new ExportHistoryGroupDTO()
|
||||
.setDataSource(dataSource)
|
||||
.setGroupId(groupId);
|
||||
|
||||
currentlyInExecutionG.get().add(exportHistoryGroupDTO);
|
||||
return exportHistoryGroupDTO;
|
||||
});
|
||||
|
||||
List<ExportHistoryItemDTO> list = currentlyInExec.getItems();
|
||||
final boolean alreadyRegistered = list.stream()
|
||||
.anyMatch(x -> x.getPublication().getId() == exportHistoryItemDTO.getPublication().getId());
|
||||
|
||||
if (alreadyRegistered) {
|
||||
throw new Exception("Il sistema sta già elaborando questa publication");
|
||||
}
|
||||
|
||||
currentlyInExec.setTotalItemCount(currentlyInExec.getTotalItemCount() + countExistingItems(dataSource, exportHistoryItemDTO));
|
||||
|
||||
list.add(exportHistoryItemDTO);
|
||||
}
|
||||
|
||||
private void consumeRetrieveQueue() {
|
||||
|
||||
for (ExportHistoryGroupDTO currentGroup : currentlyInExecutionG.get()) {
|
||||
List<ExportHistoryItemDTO> entitiesToExport = currentGroup.getItems();
|
||||
|
||||
if (currentGroup.getStartTime() != null)
|
||||
continue;
|
||||
|
||||
currentGroup.setStartTime(UtilityLocalDate.getNowTime());
|
||||
|
||||
for (ExportHistoryItemDTO entityToExport : entitiesToExport) {
|
||||
try {
|
||||
internalExportEntity(currentGroup, entityToExport);
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
logger.error(ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
|
||||
currentGroup.setCompletedRead(true);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void internalExportEntity(ExportHistoryGroupDTO exportHistoryGroup, ExportHistoryItemDTO entityHistoryToExport) throws Exception {
|
||||
if (entityHistoryToExport.getStartDate() == null)
|
||||
entityHistoryToExport.setStartDate(UtilityLocalDate.getNowTime());
|
||||
|
||||
final Class<? extends EntityBase> entityClass = entityPropertyHolder.getEntityClassFromTableName(entityHistoryToExport.getPublication().getEntityName());
|
||||
|
||||
try (MultiDBTransactionManager newConnection = new MultiDBTransactionManager(exportHistoryGroup.getDataSource().getProfile())) {
|
||||
retrieveEntitiesByChunk(newConnection.getPrimaryConnection(), exportHistoryGroup, entityHistoryToExport, entityClass);
|
||||
}
|
||||
}
|
||||
|
||||
private long countExistingItems(DataSource dataSource, ExportHistoryItemDTO entityHistoryToExport) throws Exception {
|
||||
final Class<? extends EntityBase> entityClass = entityPropertyHolder.getEntityClassFromTableName(entityHistoryToExport.getPublication().getEntityName());
|
||||
|
||||
try (MultiDBTransactionManager newConnection = new MultiDBTransactionManager(dataSource.getProfile())) {
|
||||
String sql = "SELECT CONVERT(BIGINT, COUNT(*)) FROM " + entityClass.newInstance().getTableName();
|
||||
return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(newConnection.getPrimaryConnection(), sql);
|
||||
}
|
||||
}
|
||||
|
||||
private void retrieveEntitiesByChunk(Connection connection, ExportHistoryGroupDTO exportHistoryGroup, ExportHistoryItemDTO exportHistoryItem, Class<? extends EntityBase> entityClass) throws Exception {
|
||||
|
||||
String innerSql = "SELECT * " +
|
||||
"FROM " + exportHistoryItem.getPublication().getEntityName();
|
||||
innerSql = UtilityDB.addwhereCond(innerSql, exportHistoryItem.getPublication().getWhereCondSql(), true);
|
||||
|
||||
UtilityDB.executeSimpleQueryDTOAsync(connection, innerSql, entityClass, data -> {
|
||||
|
||||
exportHistoryGroup.setProcessedItemCount(exportHistoryGroup.getProcessedItemCount() + 1);
|
||||
// exportHistoryItem.getToProcessQueue().add(JSON.toJSONString(data));
|
||||
|
||||
data.setOperation(OperationType.INSERT);
|
||||
|
||||
try {
|
||||
exportHistoryGroup.getToProcessQueue().add(new AbstractMap.SimpleEntry<>(exportHistoryItem.getPublication().getEntityName(), jsonObjectMapper.writeValueAsString(data)));
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
|
||||
while ((float) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / Runtime.getRuntime().totalMemory() > 0.9f) {
|
||||
logger.debug("Memory limit reached: " + (((float) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / Runtime.getRuntime().totalMemory()) * 100) + "%");
|
||||
try {
|
||||
Thread.sleep(1 * 1000);
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
private void consumeProcessedQueue() {
|
||||
List<ExportHistoryGroupDTO> list = currentlyInExecutionG.get();
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
ExportHistoryGroupDTO currentGroup = list.get(i);
|
||||
try {
|
||||
internalProcessQueue(currentGroup);
|
||||
|
||||
if (currentGroup.isCompletedRead() && currentGroup.getEndTime() == null) {
|
||||
currentGroup.setEndTime(UtilityLocalDate.getNowTime());
|
||||
updateReadyToTransmit(currentGroup);
|
||||
list.remove(i--);
|
||||
}
|
||||
|
||||
currentGroup.getDataSource().getConnection().commit();
|
||||
} catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
logger.error(ex.getMessage(), ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void internalProcessQueue(ExportHistoryGroupDTO currentGroup) throws Exception {
|
||||
String insertSQL = "INSERT INTO " + StbTransactionLog.ENTITY + " (publication_group_id, created_at, user_name, entities, entities_json, group_id)" +
|
||||
" VALUES (?, ?, ?, ?, ?, ?)";
|
||||
|
||||
try (MultiDBTransactionManager multiDBTransactionManager = new MultiDBTransactionManager(currentGroup.getDataSource().getProfile())) {
|
||||
|
||||
while (!currentGroup.getToProcessQueue().isEmpty()) {
|
||||
try (SQLServerPreparedStatement insertBulkPs = (SQLServerPreparedStatement) multiDBTransactionManager.prepareStatement(insertSQL)) {
|
||||
Map.Entry<String, String> entityJson;
|
||||
while ((entityJson = currentGroup.getToProcessQueue().poll()) != null) {
|
||||
insertBulkPs.setLong(1, currentGroup.getGroupId());
|
||||
insertBulkPs.setObject(2, UtilityLocalDate.getNowTime());
|
||||
insertBulkPs.setString(3, null);
|
||||
insertBulkPs.setString(4, entityJson.getKey());
|
||||
insertBulkPs.setString(5, entityJson.getValue());
|
||||
insertBulkPs.setLong(6, Long.MIN_VALUE + currentGroup.getSyncronizedItemCount());
|
||||
|
||||
insertBulkPs.addBatch();
|
||||
currentGroup.setSyncronizedItemCount(currentGroup.getSyncronizedItemCount() + 1);
|
||||
}
|
||||
|
||||
insertBulkPs.executeLargeBatch();
|
||||
|
||||
System.gc();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private void updateReadyToTransmit(ExportHistoryGroupDTO exportHistoryGroup) throws Exception {
|
||||
StbPublications stbPublications = new StbPublications()
|
||||
.setId(exportHistoryGroup.getGroupId());
|
||||
stbPublications.setOperation(OperationType.NO_OP);
|
||||
|
||||
stbPublications.setStbPublicationsDetails(exportHistoryGroup.getItems().stream()
|
||||
.map(x -> {
|
||||
StbPublicationsDetail stbPublicationsDetail = new StbPublicationsDetail()
|
||||
.setId(x.getPublication().getId())
|
||||
.setReadyToTransmit(true);
|
||||
|
||||
stbPublicationsDetail.setOperation(OperationType.UPDATE);
|
||||
return stbPublicationsDetail;
|
||||
})
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
stbPublications.manageWithParentConnection(exportHistoryGroup.getDataSource().getConnection());
|
||||
}
|
||||
|
||||
public List<ExportHistoryStatusDTO> getStatus() {
|
||||
List<ExportHistoryStatusDTO> statusList = new ArrayList<>();
|
||||
|
||||
for (ExportHistoryGroupDTO currentGroup : currentlyInExecutionG.get()) {
|
||||
|
||||
final LocalDateTime startDate = currentGroup.getStartTime();
|
||||
|
||||
long totalCount = 0;
|
||||
long processedCount = 0;
|
||||
long itemsPerSec = 1;
|
||||
LocalDateTime estimatedEnd = currentGroup.getEndTime();
|
||||
|
||||
if (startDate != null) {
|
||||
totalCount = currentGroup.getTotalItemCount();
|
||||
processedCount = currentGroup.getSyncronizedItemCount();
|
||||
|
||||
final long secondsBetween = ChronoUnit.SECONDS.between(startDate, estimatedEnd != null ? estimatedEnd : UtilityLocalDate.getNowTime());
|
||||
itemsPerSec = processedCount / (secondsBetween == 0 ? 1 : secondsBetween);
|
||||
|
||||
double secsToEnd = (double) totalCount / (itemsPerSec == 0 ? 1 : itemsPerSec);
|
||||
estimatedEnd = startDate.plusSeconds((long) secsToEnd);
|
||||
}
|
||||
|
||||
|
||||
statusList.add(new ExportHistoryStatusDTO()
|
||||
.setPublicationGroupId(currentGroup.getGroupId())
|
||||
.setStartedAt(startDate)
|
||||
.setTotalCount(totalCount)
|
||||
.setProcessedCount(processedCount)
|
||||
.setSpeedPerMinute((int) (itemsPerSec * 60))
|
||||
.setEstimatedEnd(estimatedEnd));
|
||||
|
||||
}
|
||||
|
||||
return statusList;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package it.integry.ems.sync;
|
||||
|
||||
import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement;
|
||||
import it.integry.annotations.PostContextConstruct;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.ems.json.JSONObjectMapper;
|
||||
import it.integry.ems.looper.service.LooperService;
|
||||
import it.integry.ems.settings.Model.AvailableConnectionsModel;
|
||||
@@ -11,7 +11,10 @@ import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.utility.UtilityDebug;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.entity.StbPublicationsDetail;
|
||||
import it.integry.ems_model.entity.StbTransactionLog;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityLocalDate;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
@@ -21,11 +24,9 @@ import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.context.ContextLoader;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
@@ -45,11 +46,13 @@ public class AsyncManager {
|
||||
|
||||
private final static HashMap<String, List<StbPublicationsDetail>> cachedSetup = new HashMap<>();
|
||||
|
||||
private final static ConcurrentLinkedQueue<Map.Entry<String, StbTransactionLog>> toBeSavedQueue = new ConcurrentLinkedQueue<>();
|
||||
|
||||
@PostContextConstruct
|
||||
public void init() {
|
||||
if (!UtilityDebug.isDebugExecution() && !UtilityDebug.isIntegryServer()) {
|
||||
looperService.add(this::internalCachePublicationsSetup, 5 * 60 * 1000, AsyncManager.class.getName());
|
||||
looperService.add(this::internalCachePublicationsSetup, 5 * 60 * 1000, "sync-setup-cache");
|
||||
looperService.add(this::consumeToBeSavedQueue, 20 * 1000, "sync-flush-data");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -84,7 +87,7 @@ public class AsyncManager {
|
||||
MultiDBTransactionManager multiDBTransactionManager = new MultiDBTransactionManager(profileName, false);
|
||||
|
||||
try {
|
||||
String sql = "SELECT * FROM " + StbPublicationsDetail.ENTITY + " WHERE syncronize = 'R'";
|
||||
String sql = "SELECT * FROM " + StbPublicationsDetail.ENTITY + " WHERE active = 1";
|
||||
List<StbPublicationsDetail> publications = UtilityDB.executeSimpleQueryDTO(multiDBTransactionManager.getPrimaryConnection(), sql, StbPublicationsDetail.class);
|
||||
|
||||
cachedSetup.putIfAbsent(dbName, publications);
|
||||
@@ -93,9 +96,9 @@ public class AsyncManager {
|
||||
}
|
||||
}
|
||||
|
||||
public static String getPublicationIdIfExists(String dbName, EntityBase entityBase) throws Exception {
|
||||
public static long getPublicationIdIfExists(String dbName, EntityBase entityBase) throws Exception {
|
||||
if (!cachedSetup.containsKey(dbName) || cachedSetup.get(dbName) == null || cachedSetup.get(dbName).isEmpty())
|
||||
return null;
|
||||
return 0;
|
||||
|
||||
String tableName = entityBase.getTableName().toUpperCase();
|
||||
StbPublicationsDetail activePublication = cachedSetup.get(dbName).stream()
|
||||
@@ -104,16 +107,16 @@ public class AsyncManager {
|
||||
.orElse(null);
|
||||
|
||||
if (activePublication == null)
|
||||
return null;
|
||||
return 0;
|
||||
|
||||
logger.debug("SYNC OFFLINE ABILITATA SU " + tableName);
|
||||
//logger.debug("SYNC OFFLINE ABILITATA SU " + tableName);
|
||||
|
||||
List<EntityBase> myObjs = new ArrayList<>();
|
||||
myObjs.add(entityBase);
|
||||
|
||||
String selectSql = "SELECT * FROM " + entityBase.getClass().getCanonicalName();
|
||||
if (!UtilityString.isNullOrEmpty(activePublication.getWhereCondSql())) {
|
||||
selectSql = selectSql + " WHERE " + activePublication.getWhereCondSql();
|
||||
if (!UtilityString.isNullOrEmpty(activePublication.getWhereCondField())) {
|
||||
selectSql = selectSql + " WHERE " + activePublication.getWhereCondField();
|
||||
}
|
||||
|
||||
// Create a new Query.
|
||||
@@ -124,55 +127,97 @@ public class AsyncManager {
|
||||
List<?> res = qr.getResults();
|
||||
|
||||
if (res == null || res.isEmpty())
|
||||
return null;
|
||||
return 0;
|
||||
|
||||
return activePublication.getPublicationId();
|
||||
return activePublication.getStbPublicationId();
|
||||
}
|
||||
|
||||
|
||||
public static void saveNewTransaction(Connection connection, EntityBase entityBase, int transactionGroupId) throws Exception {
|
||||
|
||||
String transactionDate = new SimpleDateFormat(CommonConstants.DATETIME_FORMAT_YMD).format(new Date());
|
||||
int transactionId = 0;
|
||||
|
||||
Integer tmpTransactionId = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(
|
||||
connection, "SELECT max(transaction_id) as max_id from stb_transaction_log_db");
|
||||
|
||||
if (tmpTransactionId != null) transactionId = tmpTransactionId;
|
||||
transactionId++; //Incremento l'ID
|
||||
public static Long saveNewTransaction(Connection connection, String dbName, EntityBase entityBase, long publicationId, Long transactionGroupId) throws Exception {
|
||||
//TODO: Calc transaction group ID here
|
||||
if (transactionGroupId == null) transactionGroupId = getNextTransactionGroupId(connection, dbName);
|
||||
|
||||
JSONObjectMapper jsonObjectMapper = ContextLoader.getCurrentWebApplicationContext().getBean(JSONObjectMapper.class);
|
||||
|
||||
StringWriter writer = new StringWriter();
|
||||
jsonObjectMapper.writeValue(writer, entityBase);
|
||||
|
||||
String entityName = entityBase.getTableName().toUpperCase();
|
||||
|
||||
String sql =
|
||||
"INSERT INTO stb_transaction_log_db(transaction_id, transaction_group_id, transaction_date, user_name, transaction_json, entity_name_list) " +
|
||||
"VALUES (" + transactionId + "," + transactionGroupId + ",'" + transactionDate + "', null, '%s', " + UtilityDB.valueToString(entityName) + ")";
|
||||
|
||||
String jsonString = writer.toString().replace("'", "''");
|
||||
|
||||
sql = String.format(sql, jsonString);
|
||||
|
||||
PreparedStatement psExec = connection.prepareStatement(sql);
|
||||
psExec.executeUpdate();
|
||||
psExec.close();
|
||||
|
||||
}
|
||||
|
||||
|
||||
public static int getNextTransactionGroupId(Connection connection) throws Exception {
|
||||
int transactionGroupId = 0;
|
||||
|
||||
Integer tmpTransactionGroupId = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(
|
||||
connection, "SELECT MAX(transaction_group_id) AS max_id from stb_transaction_log_db");
|
||||
|
||||
if (tmpTransactionGroupId != null) transactionGroupId = tmpTransactionGroupId;
|
||||
transactionGroupId++; //Incremento l'ID
|
||||
StbTransactionLog stbTransactionLog = new StbTransactionLog()
|
||||
.setCreatedAt(UtilityLocalDate.getNowTime())
|
||||
.setEntities(entityBase.getTableName().toUpperCase())
|
||||
.setEntitiesJson(jsonObjectMapper.writeValueAsString(entityBase))
|
||||
.setPublicationGroupId(publicationId)
|
||||
.setUserName(entityBase.getUsername())
|
||||
.setGroupId(transactionGroupId);
|
||||
stbTransactionLog.setOperation(OperationType.INSERT);
|
||||
|
||||
toBeSavedQueue.add(new AbstractMap.SimpleEntry<>(dbName, stbTransactionLog));
|
||||
return transactionGroupId;
|
||||
}
|
||||
|
||||
|
||||
public static long getNextTransactionGroupId(Connection connection, String dbName) throws Exception {
|
||||
|
||||
final long maxToBeProcessed = toBeSavedQueue.stream().filter(x -> x.getKey().equalsIgnoreCase(dbName))
|
||||
.map(x -> x.getValue().getGroupId())
|
||||
.max(Long::compare)
|
||||
.orElse(0L);
|
||||
|
||||
long transactionGroupId = 0;
|
||||
|
||||
if (maxToBeProcessed <= 0) {
|
||||
Long tmpTransactionGroupId = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(
|
||||
connection, "SELECT MAX(group_id) AS max_id FROM " + StbTransactionLog.ENTITY);
|
||||
|
||||
tmpTransactionGroupId = tmpTransactionGroupId != 0 ? tmpTransactionGroupId : 0L;
|
||||
|
||||
transactionGroupId = Math.max(maxToBeProcessed, tmpTransactionGroupId);
|
||||
} else {
|
||||
transactionGroupId = maxToBeProcessed;
|
||||
}
|
||||
|
||||
transactionGroupId++; //Incremento l'ID
|
||||
return transactionGroupId;
|
||||
}
|
||||
|
||||
|
||||
private void consumeToBeSavedQueue() {
|
||||
if (cachedSetup.entrySet().stream().anyMatch(x -> x.getValue() != null && x.getValue().stream().anyMatch(y -> !y.isReadyToTransmit())))
|
||||
return;
|
||||
|
||||
List<String> dbNamesToConnect = toBeSavedQueue.stream().map(Map.Entry::getKey).distinct().collect(Collectors.toList());
|
||||
|
||||
final List<AvailableConnectionsModel> databaseConnections = settingsModel.getAvailableConnections().stream()
|
||||
.filter(x -> dbNamesToConnect.stream().anyMatch(y -> x.getDbName().equalsIgnoreCase(y)))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
String insertSQL = "INSERT INTO " + StbTransactionLog.ENTITY + " (publication_group_id, created_at, user_name, entities, entities_json, group_id)" +
|
||||
" VALUES (?, ?, ?, ?, ?, ?)";
|
||||
|
||||
Map.Entry<String, StbTransactionLog> itemToSave = null;
|
||||
while ((itemToSave = toBeSavedQueue.poll()) != null) {
|
||||
final Map.Entry<String, StbTransactionLog> finalItemToSave = itemToSave;
|
||||
final StbTransactionLog stbTransactionLog = finalItemToSave.getValue();
|
||||
|
||||
AvailableConnectionsModel connectionModel = databaseConnections.stream()
|
||||
.filter(x -> x.getDbName().equalsIgnoreCase(finalItemToSave.getKey()))
|
||||
.findFirst()
|
||||
.get();
|
||||
|
||||
try (MultiDBTransactionManager multiDBTransactionManager = new MultiDBTransactionManager(connectionModel);
|
||||
SQLServerPreparedStatement insertBulkPs = (SQLServerPreparedStatement) multiDBTransactionManager.prepareStatement(insertSQL)) {
|
||||
|
||||
insertBulkPs.setLong(1, stbTransactionLog.getPublicationGroupId());
|
||||
insertBulkPs.setObject(2, stbTransactionLog.getCreatedAt());
|
||||
insertBulkPs.setString(3, stbTransactionLog.getUserName());
|
||||
insertBulkPs.setString(4, stbTransactionLog.getEntities());
|
||||
insertBulkPs.setString(5, stbTransactionLog.getEntitiesJson());
|
||||
insertBulkPs.setLong(6, stbTransactionLog.getGroupId());
|
||||
|
||||
|
||||
insertBulkPs.executeLargeUpdate();
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,6 +46,10 @@ public class MultiDBTransactionManager implements AutoCloseable{
|
||||
public MultiDBTransactionManager() {
|
||||
}
|
||||
|
||||
public MultiDBTransactionManager(AvailableConnectionsModel connectionsModel) throws Exception {
|
||||
this(connectionsModel.getProfileName(), true);
|
||||
}
|
||||
|
||||
public MultiDBTransactionManager(String profileDb) throws Exception {
|
||||
this(profileDb, true);
|
||||
}
|
||||
@@ -79,6 +83,10 @@ public class MultiDBTransactionManager implements AutoCloseable{
|
||||
this.dbPrimary = null;
|
||||
}
|
||||
|
||||
public void addConnection(AvailableConnectionsModel availableConnectionsModel) throws Exception {
|
||||
this.addConnection(availableConnectionsModel.getProfileName());
|
||||
}
|
||||
|
||||
public void addConnection(String profileName) throws Exception {
|
||||
DataSource ds = new DataSource();
|
||||
ds.initialize(profileName);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package it.integry.ems.sync.controller;
|
||||
|
||||
import it.integry.ems.response.ServiceRestResponse;
|
||||
import it.integry.ems.sync.service.RemoteSynchronizationService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@Scope("request")
|
||||
@RequestMapping("system/remote-sync")
|
||||
public class RemoteSynchronizationController {
|
||||
|
||||
@Autowired
|
||||
private RemoteSynchronizationService remoteSynchronizationService;
|
||||
|
||||
@RequestMapping(value = "publications/{groupId}/start", method = RequestMethod.GET)
|
||||
public ServiceRestResponse startPublication(@PathVariable long groupId) throws Exception {
|
||||
remoteSynchronizationService.startPublication(groupId);
|
||||
return ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
|
||||
@RequestMapping(value = "publications/status", method = RequestMethod.GET)
|
||||
public ServiceRestResponse statusPublication() {
|
||||
return ServiceRestResponse.createPositiveResponse(remoteSynchronizationService.getPublicationStatus());
|
||||
}
|
||||
|
||||
|
||||
|
||||
@RequestMapping(value = "subscription/{subscriptionId}/run", method = RequestMethod.GET)
|
||||
public ServiceRestResponse runSubscription(@PathVariable long subscriptionId) throws Exception {
|
||||
remoteSynchronizationService.runSubscription(subscriptionId);
|
||||
return ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package it.integry.ems.sync.controller;
|
||||
|
||||
import it.integry.ems.response.ServiceRestResponse;
|
||||
import it.integry.ems.sync.dto.*;
|
||||
import it.integry.ems.sync.service.RemoteSynchronizationSetupService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@RestController
|
||||
@Scope("request")
|
||||
@RequestMapping("system/remote-sync/setup")
|
||||
public class RemoteSynchronizationSetupController {
|
||||
|
||||
@Autowired
|
||||
private RemoteSynchronizationSetupService remoteSynchronizationSetupService;
|
||||
|
||||
|
||||
@RequestMapping(value = "publications/retrieve", method = RequestMethod.GET)
|
||||
public ServiceRestResponse retrievePublications() throws Exception {
|
||||
return ServiceRestResponse.createPositiveResponse(remoteSynchronizationSetupService.retrievePublications());
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = "publications/insert-group", method = RequestMethod.POST)
|
||||
public ServiceRestResponse insertPublicationGroup(@RequestBody InsertPublicationGroupRequestDTO request) throws Exception {
|
||||
return ServiceRestResponse.createPositiveResponse(remoteSynchronizationSetupService.addPublicationGroup(request.getDescription()));
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = "publications/{groupId}/insert", method = RequestMethod.POST)
|
||||
public ServiceRestResponse insertPublications(@PathVariable long groupId, @RequestBody PublicationDTO publicationToInsert) throws Exception {
|
||||
InsertPublicationItemResponseDTO response = new InsertPublicationItemResponseDTO()
|
||||
.setId(remoteSynchronizationSetupService.addPublicationItem(groupId, publicationToInsert));
|
||||
|
||||
return ServiceRestResponse.createPositiveResponse(response);
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = "publications/{groupId}/delete-group", method = RequestMethod.POST)
|
||||
public ServiceRestResponse deletePublicationGroup(@PathVariable long groupId) throws Exception {
|
||||
remoteSynchronizationSetupService.deletePublicationsGroup(groupId);
|
||||
return ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = "publications/{publicationId}/delete", method = RequestMethod.POST)
|
||||
public ServiceRestResponse deletePublication(@PathVariable long publicationId) throws Exception {
|
||||
remoteSynchronizationSetupService.deletePublications(Collections.singletonList(publicationId));
|
||||
return ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
|
||||
|
||||
@RequestMapping(value = "publications/{publicationId}/edit", method = RequestMethod.POST)
|
||||
public ServiceRestResponse editPublication(@PathVariable long publicationId, @RequestBody PublicationDTO publicationToEdit) throws Exception {
|
||||
remoteSynchronizationSetupService.editPublication(publicationId, publicationToEdit);
|
||||
return ServiceRestResponse.createPositiveResponse();
|
||||
}
|
||||
|
||||
|
||||
|
||||
@RequestMapping(value = "subscriptions/insert", method = RequestMethod.POST)
|
||||
public ServiceRestResponse insertSubscription(@RequestBody SubscriptionDTO subscriptionToInsert) throws Exception {
|
||||
InsertSubscriptionResponseDTO response = new InsertSubscriptionResponseDTO()
|
||||
.setId(remoteSynchronizationSetupService.addSubscription(subscriptionToInsert));
|
||||
|
||||
return ServiceRestResponse.createPositiveResponse(response);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package it.integry.ems.sync.controller;
|
||||
|
||||
import it.integry.ems.response.ServiceRestResponse;
|
||||
import it.integry.ems.sync.service.RemoteSynchronizationTransactionsService;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@RestController
|
||||
@Scope("request")
|
||||
@RequestMapping("system/remote-transaction")
|
||||
public class RemoteSynchronizationTransactionsController {
|
||||
|
||||
@Autowired
|
||||
private RemoteSynchronizationTransactionsService remoteSynchronizationTransactionsService;
|
||||
|
||||
|
||||
@RequestMapping(value = "{publicationId}/retrieve", method = RequestMethod.GET)
|
||||
public ServiceRestResponse retrieve(@PathVariable long publicationId,
|
||||
@RequestParam(required = false) Long lastRetrievedTransactionId,
|
||||
@RequestParam(required = false, defaultValue = "-1") int limit) throws Exception {
|
||||
return ServiceRestResponse.createPositiveResponse(
|
||||
remoteSynchronizationTransactionsService.retrieveTransactions(publicationId, lastRetrievedTransactionId, limit));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
import it.integry.ems.datasource.DataSource;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
|
||||
public class ExportHistoryGroupDTO {
|
||||
|
||||
private DataSource dataSource;
|
||||
private long groupId;
|
||||
private LocalDateTime startTime;
|
||||
private LocalDateTime endTime;
|
||||
private boolean completedRead;
|
||||
private long totalItemCount;
|
||||
private long processedItemCount;
|
||||
private long syncronizedItemCount;
|
||||
private List<ExportHistoryItemDTO> items = new ArrayList<>();
|
||||
|
||||
private final Queue<Map.Entry<String, String>> toProcessQueue = new ConcurrentLinkedQueue<>();
|
||||
|
||||
|
||||
public long getGroupId() {
|
||||
return groupId;
|
||||
}
|
||||
|
||||
public ExportHistoryGroupDTO setGroupId(long groupId) {
|
||||
this.groupId = groupId;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<ExportHistoryItemDTO> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public ExportHistoryGroupDTO setItems(List<ExportHistoryItemDTO> items) {
|
||||
this.items = items;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public Queue<Map.Entry<String, String>> getToProcessQueue() {
|
||||
return toProcessQueue;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
public ExportHistoryGroupDTO setStartTime(LocalDateTime startTime) {
|
||||
this.startTime = startTime;
|
||||
return this;
|
||||
}
|
||||
|
||||
public DataSource getDataSource() {
|
||||
return dataSource;
|
||||
}
|
||||
|
||||
public ExportHistoryGroupDTO setDataSource(DataSource dataSource) {
|
||||
this.dataSource = dataSource;
|
||||
return this;
|
||||
}
|
||||
|
||||
public long getTotalItemCount() {
|
||||
return totalItemCount;
|
||||
}
|
||||
|
||||
public ExportHistoryGroupDTO setTotalItemCount(long totalItemCount) {
|
||||
this.totalItemCount = totalItemCount;
|
||||
return this;
|
||||
}
|
||||
|
||||
public long getProcessedItemCount() {
|
||||
return processedItemCount;
|
||||
}
|
||||
|
||||
public ExportHistoryGroupDTO setProcessedItemCount(long processedItemCount) {
|
||||
this.processedItemCount = processedItemCount;
|
||||
return this;
|
||||
}
|
||||
|
||||
public long getSyncronizedItemCount() {
|
||||
return syncronizedItemCount;
|
||||
}
|
||||
|
||||
public ExportHistoryGroupDTO setSyncronizedItemCount(long syncronizedItemCount) {
|
||||
this.syncronizedItemCount = syncronizedItemCount;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isCompletedRead() {
|
||||
return completedRead;
|
||||
}
|
||||
|
||||
public ExportHistoryGroupDTO setCompletedRead(boolean completedRead) {
|
||||
this.completedRead = completedRead;
|
||||
return this;
|
||||
}
|
||||
|
||||
public LocalDateTime getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public ExportHistoryGroupDTO setEndTime(LocalDateTime endTime) {
|
||||
this.endTime = endTime;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class ExportHistoryItemDTO {
|
||||
|
||||
private PublicationDTO publication;
|
||||
private LocalDateTime startDate;
|
||||
|
||||
|
||||
public PublicationDTO getPublication() {
|
||||
return publication;
|
||||
}
|
||||
|
||||
public ExportHistoryItemDTO setPublication(PublicationDTO publication) {
|
||||
this.publication = publication;
|
||||
return this;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartDate() {
|
||||
return startDate;
|
||||
}
|
||||
|
||||
public ExportHistoryItemDTO setStartDate(LocalDateTime startDate) {
|
||||
this.startDate = startDate;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class ExportHistoryStatusDTO {
|
||||
|
||||
private long publicationGroupId;
|
||||
private long processedCount;
|
||||
private long totalCount;
|
||||
private LocalDateTime startedAt;
|
||||
private LocalDateTime estimatedEnd;
|
||||
private int speedPerMinute;
|
||||
|
||||
|
||||
public long getPublicationGroupId() {
|
||||
return publicationGroupId;
|
||||
}
|
||||
|
||||
public ExportHistoryStatusDTO setPublicationGroupId(long publicationGroupId) {
|
||||
this.publicationGroupId = publicationGroupId;
|
||||
return this;
|
||||
}
|
||||
|
||||
public long getProcessedCount() {
|
||||
return processedCount;
|
||||
}
|
||||
|
||||
public ExportHistoryStatusDTO setProcessedCount(long processedCount) {
|
||||
this.processedCount = processedCount;
|
||||
return this;
|
||||
}
|
||||
|
||||
public long getTotalCount() {
|
||||
return totalCount;
|
||||
}
|
||||
|
||||
public ExportHistoryStatusDTO setTotalCount(long totalCount) {
|
||||
this.totalCount = totalCount;
|
||||
return this;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartedAt() {
|
||||
return startedAt;
|
||||
}
|
||||
|
||||
public ExportHistoryStatusDTO setStartedAt(LocalDateTime startedAt) {
|
||||
this.startedAt = startedAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
public LocalDateTime getEstimatedEnd() {
|
||||
return estimatedEnd;
|
||||
}
|
||||
|
||||
public ExportHistoryStatusDTO setEstimatedEnd(LocalDateTime estimatedEnd) {
|
||||
this.estimatedEnd = estimatedEnd;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getSpeedPerMinute() {
|
||||
return speedPerMinute;
|
||||
}
|
||||
|
||||
public ExportHistoryStatusDTO setSpeedPerMinute(int speedPerMinute) {
|
||||
this.speedPerMinute = speedPerMinute;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
public class InsertPublicationGroupRequestDTO {
|
||||
|
||||
private String description;
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public InsertPublicationGroupRequestDTO setDescription(String description) {
|
||||
this.description = description;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
public class InsertPublicationGroupResponseDTO {
|
||||
|
||||
private long id;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public InsertPublicationGroupResponseDTO setId(long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
public class InsertPublicationItemResponseDTO {
|
||||
|
||||
private long id;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public InsertPublicationItemResponseDTO setId(long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
public class InsertSubscriptionResponseDTO {
|
||||
|
||||
private long id;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public InsertSubscriptionResponseDTO setId(long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
import it.integry.ems_model.entity.StbPublicationsDetail;
|
||||
|
||||
public class PublicationDTO {
|
||||
|
||||
private long id;
|
||||
private String entityName;
|
||||
private String whereCondSql;
|
||||
private String recalcColumns;
|
||||
private Boolean active;
|
||||
private Boolean exportHistory;
|
||||
private Boolean readyToTransmit;
|
||||
private String whereCond;
|
||||
|
||||
|
||||
public static PublicationDTO fromStbPublicationDetail(StbPublicationsDetail stbPublicationsDetail) {
|
||||
return new PublicationDTO()
|
||||
.setActive(stbPublicationsDetail.isActive())
|
||||
.setExportHistory(stbPublicationsDetail.isExportHistory())
|
||||
.setReadyToTransmit(stbPublicationsDetail.isReadyToTransmit())
|
||||
.setId(stbPublicationsDetail.getId())
|
||||
.setRecalcColumns(stbPublicationsDetail.getRecalcColumnsField())
|
||||
.setEntityName(stbPublicationsDetail.getEntityName())
|
||||
.setWhereCond(stbPublicationsDetail.getWhereCondField())
|
||||
.setWhereCondSql(stbPublicationsDetail.getWhereCondSql());
|
||||
}
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public PublicationDTO setId(long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEntityName() {
|
||||
return entityName;
|
||||
}
|
||||
|
||||
public PublicationDTO setEntityName(String entityName) {
|
||||
this.entityName = entityName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getWhereCondSql() {
|
||||
return whereCondSql;
|
||||
}
|
||||
|
||||
public PublicationDTO setWhereCondSql(String whereCondSql) {
|
||||
this.whereCondSql = whereCondSql;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getRecalcColumns() {
|
||||
return recalcColumns;
|
||||
}
|
||||
|
||||
public PublicationDTO setRecalcColumns(String recalcColumns) {
|
||||
this.recalcColumns = recalcColumns;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Boolean getActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public PublicationDTO setActive(Boolean active) {
|
||||
this.active = active;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Boolean getExportHistory() {
|
||||
return exportHistory;
|
||||
}
|
||||
|
||||
public PublicationDTO setExportHistory(Boolean exportHistory) {
|
||||
this.exportHistory = exportHistory;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Boolean getReadyToTransmit() {
|
||||
return readyToTransmit;
|
||||
}
|
||||
|
||||
public PublicationDTO setReadyToTransmit(Boolean readyToTransmit) {
|
||||
this.readyToTransmit = readyToTransmit;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getWhereCond() {
|
||||
return whereCond;
|
||||
}
|
||||
|
||||
public PublicationDTO setWhereCond(String whereCond) {
|
||||
this.whereCond = whereCond;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class PublicationGroupDTO {
|
||||
|
||||
private long id;
|
||||
private String description;
|
||||
|
||||
private boolean canStartExport;
|
||||
private boolean canBeDeleted;
|
||||
|
||||
private List<PublicationDTO> publications = new ArrayList<>();
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public PublicationGroupDTO setId(long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public PublicationGroupDTO setDescription(String description) {
|
||||
this.description = description;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isCanStartExport() {
|
||||
return canStartExport;
|
||||
}
|
||||
|
||||
public PublicationGroupDTO setCanStartExport(boolean canStartExport) {
|
||||
this.canStartExport = canStartExport;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isCanBeDeleted() {
|
||||
return canBeDeleted;
|
||||
}
|
||||
|
||||
public PublicationGroupDTO setCanBeDeleted(boolean canBeDeleted) {
|
||||
this.canBeDeleted = canBeDeleted;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<PublicationDTO> getPublications() {
|
||||
return publications;
|
||||
}
|
||||
|
||||
public PublicationGroupDTO setPublications(List<PublicationDTO> publications) {
|
||||
this.publications = publications;
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
import it.integry.ems_model.entity.StbRemoteSubscription;
|
||||
|
||||
public class SubscriptionDTO {
|
||||
|
||||
private Long id;
|
||||
private long publicationId;
|
||||
private String publicationDescription;
|
||||
private String endpointProtocol;
|
||||
private String endpointHost;
|
||||
private int endpointPort;
|
||||
private String username;
|
||||
private String password;
|
||||
private String profileDb;
|
||||
private boolean active;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setId(Long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public long getPublicationId() {
|
||||
return publicationId;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setPublicationId(long publicationId) {
|
||||
this.publicationId = publicationId;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPublicationDescription() {
|
||||
return publicationDescription;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setPublicationDescription(String publicationDescription) {
|
||||
this.publicationDescription = publicationDescription;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEndpointProtocol() {
|
||||
return endpointProtocol;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setEndpointProtocol(String endpointProtocol) {
|
||||
this.endpointProtocol = endpointProtocol;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEndpointHost() {
|
||||
return endpointHost;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setEndpointHost(String endpointHost) {
|
||||
this.endpointHost = endpointHost;
|
||||
return this;
|
||||
}
|
||||
|
||||
public int getEndpointPort() {
|
||||
return endpointPort;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setEndpointPort(int endpointPort) {
|
||||
this.endpointPort = endpointPort;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setUsername(String username) {
|
||||
this.username = username;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setPassword(String password) {
|
||||
this.password = password;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getProfileDb() {
|
||||
return profileDb;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setProfileDb(String profileDb) {
|
||||
this.profileDb = profileDb;
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isActive() {
|
||||
return active;
|
||||
}
|
||||
|
||||
public SubscriptionDTO setActive(boolean active) {
|
||||
this.active = active;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public String getEndpointUrl() {
|
||||
return endpointProtocol.toLowerCase() + "://" + endpointHost + ":" + endpointPort;
|
||||
}
|
||||
|
||||
|
||||
public static SubscriptionDTO fromEntity(StbRemoteSubscription stbRemoteSubscription) {
|
||||
return new SubscriptionDTO()
|
||||
.setId(stbRemoteSubscription.getId())
|
||||
.setPublicationId(stbRemoteSubscription.getPublicationId())
|
||||
.setPublicationDescription(stbRemoteSubscription.getPublicationDescription())
|
||||
.setEndpointProtocol(stbRemoteSubscription.getEndpointProtocol())
|
||||
.setEndpointHost(stbRemoteSubscription.getEndpointHost())
|
||||
.setEndpointPort(stbRemoteSubscription.getEndpointPort())
|
||||
.setUsername(stbRemoteSubscription.getUsername())
|
||||
.setPassword(stbRemoteSubscription.getPassword())
|
||||
.setProfileDb(stbRemoteSubscription.getProfileDb())
|
||||
.setActive(stbRemoteSubscription.isActive());
|
||||
}
|
||||
|
||||
public StbRemoteSubscription toEntity() {
|
||||
return new StbRemoteSubscription()
|
||||
.setPublicationId(getPublicationId())
|
||||
.setPublicationDescription(getPublicationDescription())
|
||||
.setEndpointProtocol(getEndpointProtocol())
|
||||
.setEndpointHost(getEndpointHost())
|
||||
.setEndpointPort(getEndpointPort())
|
||||
.setProfileDb(getProfileDb())
|
||||
.setUsernameField(getUsername())
|
||||
.setPassword(getPassword())
|
||||
.setActive(isActive());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
public class TransactionDTO {
|
||||
|
||||
private long publicationId;
|
||||
private long transactionId;
|
||||
private LocalDateTime transactionDate;
|
||||
private String username;
|
||||
private String entityName;
|
||||
private String transactionJson;
|
||||
|
||||
public long getPublicationId() {
|
||||
return publicationId;
|
||||
}
|
||||
|
||||
public TransactionDTO setPublicationId(long publicationId) {
|
||||
this.publicationId = publicationId;
|
||||
return this;
|
||||
}
|
||||
|
||||
public long getTransactionId() {
|
||||
return transactionId;
|
||||
}
|
||||
|
||||
public TransactionDTO setTransactionId(long transactionId) {
|
||||
this.transactionId = transactionId;
|
||||
return this;
|
||||
}
|
||||
|
||||
public LocalDateTime getTransactionDate() {
|
||||
return transactionDate;
|
||||
}
|
||||
|
||||
public TransactionDTO setTransactionDate(LocalDateTime transactionDate) {
|
||||
this.transactionDate = transactionDate;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public TransactionDTO setUsername(String username) {
|
||||
this.username = username;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEntityName() {
|
||||
return entityName;
|
||||
}
|
||||
|
||||
public TransactionDTO setEntityName(String entityName) {
|
||||
this.entityName = entityName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getTransactionJson() {
|
||||
return transactionJson;
|
||||
}
|
||||
|
||||
public TransactionDTO setTransactionJson(String transactionJson) {
|
||||
this.transactionJson = transactionJson;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package it.integry.ems.sync.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TransactionGroupDTO {
|
||||
|
||||
private long id;
|
||||
|
||||
private List<TransactionDTO> items;
|
||||
|
||||
public long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public TransactionGroupDTO setId(long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<TransactionDTO> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public TransactionGroupDTO setItems(List<TransactionDTO> items) {
|
||||
this.items = items;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
package it.integry.ems.sync.service;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import it.integry.ems.json.JSONObjectMapper;
|
||||
import it.integry.ems.response.EsitoType;
|
||||
import it.integry.ems.response.ServiceRestResponse;
|
||||
import it.integry.ems.service.EntityProcessor;
|
||||
import it.integry.ems.service.HttpRestWrapper;
|
||||
import it.integry.ems.sync.AsyncHistoryManager;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.sync.dto.ExportHistoryStatusDTO;
|
||||
import it.integry.ems.sync.dto.PublicationDTO;
|
||||
import it.integry.ems.sync.dto.TransactionDTO;
|
||||
import it.integry.ems.sync.dto.TransactionGroupDTO;
|
||||
import it.integry.ems.utility.UtilityEntity;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.base.EntityPropertyHolder;
|
||||
import it.integry.ems_model.entity.StbPublicationsDetail;
|
||||
import it.integry.ems_model.entity.StbRemoteSubscription;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.Query;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
@Service
|
||||
@Scope(value = "request")
|
||||
public class RemoteSynchronizationService {
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
@Autowired
|
||||
private MultiDBTransactionManager multiDBTransactionManager;
|
||||
|
||||
@Autowired
|
||||
private AsyncHistoryManager asyncHistoryManager;
|
||||
|
||||
@Autowired
|
||||
private EntityPropertyHolder entityPropertyHolder;
|
||||
|
||||
@Autowired
|
||||
private EntityProcessor entityProcessor;
|
||||
|
||||
@Autowired
|
||||
private JSONObjectMapper jsonObjectMapper;
|
||||
|
||||
public void startPublication(long groupId) throws Exception {
|
||||
String sql = Query.format("SELECT * FROM " + StbPublicationsDetail.ENTITY + " WHERE stb_publication_id = %s AND export_history = %s AND ready_to_transmit = 0", groupId, 1);
|
||||
|
||||
final List<StbPublicationsDetail> stbPublicationsDetails = UtilityDB.executeSimpleQueryDTO(multiDBTransactionManager.getPrimaryConnection(), sql, StbPublicationsDetail.class);
|
||||
|
||||
if (stbPublicationsDetails == null)
|
||||
throw new Exception("Non è stata trovata alcuna pubblicazione da poter avviare (ID: " + groupId + ")");
|
||||
|
||||
for (StbPublicationsDetail stbPublicationsDetail : stbPublicationsDetails) {
|
||||
asyncHistoryManager.addToExportQueue(multiDBTransactionManager.getPrimaryDatasource(),
|
||||
groupId,
|
||||
PublicationDTO.fromStbPublicationDetail(stbPublicationsDetail));
|
||||
}
|
||||
}
|
||||
|
||||
public List<ExportHistoryStatusDTO> getPublicationStatus() {
|
||||
return asyncHistoryManager.getStatus();
|
||||
}
|
||||
|
||||
public void runSubscription(long subscriptionId) throws Exception {
|
||||
String sql = Query.format("SELECT * FROM " + StbRemoteSubscription.ENTITY +
|
||||
" WHERE id = %s AND active = 1", subscriptionId);
|
||||
|
||||
final StbRemoteSubscription stbRemoteSubscription =
|
||||
UtilityDB.executeSimpleQueryOnlyFirstRowDTO(multiDBTransactionManager.getPrimaryConnection(), sql, StbRemoteSubscription.class);
|
||||
|
||||
if (stbRemoteSubscription == null)
|
||||
throw new Exception("Non è stata trovata alcuna sottoscrizione da poter avviare con l'ID " + subscriptionId);
|
||||
|
||||
internalSubscriptionRun(stbRemoteSubscription);
|
||||
}
|
||||
|
||||
|
||||
private void internalSubscriptionRun(StbRemoteSubscription subscription) throws Exception {
|
||||
boolean shouldStop = false;
|
||||
|
||||
while (!shouldStop) {
|
||||
List<TransactionGroupDTO> downloadedTransactions = downloadTransactions(subscription);
|
||||
|
||||
if (downloadedTransactions == null || downloadedTransactions.isEmpty()) {
|
||||
shouldStop = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
long lastImportedId = importTransactions(subscription, downloadedTransactions);
|
||||
subscription.setLastTransactionIdImported(lastImportedId);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private void internalSubscriptionRunParallel(StbRemoteSubscription subscription) throws Exception {
|
||||
AtomicBoolean shouldStop = new AtomicBoolean(false);
|
||||
|
||||
ConcurrentLinkedQueue<TransactionGroupDTO> queue = new ConcurrentLinkedQueue<>();
|
||||
|
||||
new Thread(() -> {
|
||||
|
||||
while (!shouldStop.get()) {
|
||||
try {
|
||||
if (queue.size() > 1000) {
|
||||
Thread.sleep(3 * 1000);
|
||||
continue;
|
||||
}
|
||||
|
||||
List<TransactionGroupDTO> downloadedTransactions = downloadTransactions(subscription);
|
||||
|
||||
|
||||
if (downloadedTransactions == null || downloadedTransactions.isEmpty()) {
|
||||
shouldStop.set(true);
|
||||
continue;
|
||||
}
|
||||
|
||||
queue.addAll(downloadedTransactions);
|
||||
|
||||
final Long maxId = downloadedTransactions.stream()
|
||||
.flatMap(x -> x.getItems().stream())
|
||||
.map(TransactionDTO::getTransactionId)
|
||||
.max(Long::compare)
|
||||
.get();
|
||||
subscription.setLastTransactionIdImported(maxId);
|
||||
|
||||
} catch (Exception e) {
|
||||
shouldStop.set(true);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
|
||||
while (!shouldStop.get()) {
|
||||
|
||||
if (queue.isEmpty()) {
|
||||
Thread.sleep(2 * 1000);
|
||||
continue;
|
||||
}
|
||||
|
||||
while (!queue.isEmpty()) {
|
||||
try {
|
||||
importTransactionGroup(subscription, queue.poll());
|
||||
} catch (Exception ex) {
|
||||
shouldStop.set(true);
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
while (!shouldStop.get()) {
|
||||
Thread.sleep(5 * 1000);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
private List<TransactionGroupDTO> downloadTransactions(StbRemoteSubscription subscription) throws Exception {
|
||||
String endpoint = subscription.getEndpointUrl();
|
||||
HashMap<String, String> queryParams = new HashMap<String, String>() {{
|
||||
put("profileDb", subscription.getProfileDb());
|
||||
put("lastRetrievedTransactionId", subscription.getLastTransactionIdImported() == null ? null : String.valueOf(subscription.getLastTransactionIdImported()));
|
||||
put("limit", String.valueOf(500));
|
||||
}};
|
||||
|
||||
String retrieveTransactionsUrl = endpoint + "/ems-api/system/remote-transaction/" + subscription.getPublicationId() + "/retrieve";
|
||||
|
||||
StringBuilder responseBody = new StringBuilder();
|
||||
int status = HttpRestWrapper.callGenericGet(retrieveTransactionsUrl, subscription.getUsername(), subscription.getPassword(), responseBody, queryParams);
|
||||
|
||||
if (status != 200)
|
||||
throw new Exception("Errore durante l'aggiornamento della subscription \"" + subscription.getPublicationDescription() + "\"," +
|
||||
" l'endpoint " + endpoint + " ha generato lo status code " + status);
|
||||
|
||||
ServiceRestResponse response = jsonObjectMapper.readValue(responseBody.toString(), ServiceRestResponse.class);
|
||||
|
||||
if (response.getEsito() != EsitoType.OK)
|
||||
throw new Exception("Errore durante l'aggiornamento della subscription \"" + subscription.getPublicationDescription() + "\"." +
|
||||
" L'endpoint " + endpoint + " ha generato esito KO con il seguente messaggio: " + response.getErrorMessage());
|
||||
|
||||
|
||||
return response.getDTO(new TypeReference<List<TransactionGroupDTO>>() {
|
||||
});
|
||||
}
|
||||
|
||||
private long importTransactions(StbRemoteSubscription subscription, List<TransactionGroupDTO> transactions) throws Exception {
|
||||
long idToReturn = -1;
|
||||
|
||||
for (TransactionGroupDTO transactionGroup : transactions) {
|
||||
idToReturn = importTransactionGroup(subscription, transactionGroup);
|
||||
}
|
||||
|
||||
return idToReturn;
|
||||
}
|
||||
|
||||
private long importTransactionGroup(StbRemoteSubscription subscription, TransactionGroupDTO transactionGroup) throws Exception {
|
||||
StbRemoteSubscription cloneSubscriptionItem = (StbRemoteSubscription) subscription.deepClone();
|
||||
List<EntityBase> entities = new ArrayList<>();
|
||||
|
||||
for (TransactionDTO transaction : transactionGroup.getItems()) {
|
||||
final String entityJson = new String(Base64.getDecoder().decode(transaction.getTransactionJson()));
|
||||
final EntityBase entityBase = jsonObjectMapper.readValue(entityJson, EntityBase.class);
|
||||
entities.add(entityBase);
|
||||
}
|
||||
|
||||
cloneSubscriptionItem.setLastTransactionIdImported(
|
||||
transactionGroup.getItems().stream()
|
||||
.map(TransactionDTO::getTransactionId)
|
||||
.max(Long::compare).get());
|
||||
|
||||
cloneSubscriptionItem.setOperation(OperationType.UPDATE);
|
||||
entities.add(cloneSubscriptionItem);
|
||||
|
||||
entities = entityProcessor.processEntityList(entities,
|
||||
null, false, true,
|
||||
false, multiDBTransactionManager,
|
||||
false, true);
|
||||
|
||||
UtilityEntity.throwEntitiesException(entities);
|
||||
|
||||
return cloneSubscriptionItem.getLastTransactionIdImported();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package it.integry.ems.sync.service;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import it.integry.ems.exception.PrimaryDatabaseNotPresentException;
|
||||
import it.integry.ems.json.JSONObjectMapper;
|
||||
import it.integry.ems.response.ServiceRestResponse;
|
||||
import it.integry.ems.service.EntityProcessor;
|
||||
import it.integry.ems.service.HttpRestWrapper;
|
||||
import it.integry.ems.sync.AsyncHistoryManager;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.sync.dto.ExportHistoryStatusDTO;
|
||||
import it.integry.ems.sync.dto.PublicationDTO;
|
||||
import it.integry.ems.sync.dto.PublicationGroupDTO;
|
||||
import it.integry.ems.sync.dto.SubscriptionDTO;
|
||||
import it.integry.ems.utility.UtilityEntity;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.entity.StbPublications;
|
||||
import it.integry.ems_model.entity.StbPublicationsDetail;
|
||||
import it.integry.ems_model.entity.StbRemoteSubscription;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityQuery;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.io.IOException;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static java.util.stream.Collectors.groupingBy;
|
||||
import static java.util.stream.Collectors.toList;
|
||||
|
||||
@Service
|
||||
@Scope(value = "request")
|
||||
public class RemoteSynchronizationSetupService {
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
@Autowired
|
||||
private MultiDBTransactionManager multiDBTransactionManager;
|
||||
|
||||
@Autowired
|
||||
private EntityProcessor entityProcessor;
|
||||
|
||||
@Autowired
|
||||
private AsyncHistoryManager asyncHistoryManager;
|
||||
|
||||
@Autowired
|
||||
private JSONObjectMapper jsonObjectMapper;
|
||||
|
||||
public List<PublicationGroupDTO> retrievePublications() throws Exception {
|
||||
|
||||
List<StbPublications> stbPublicationsToRetrieve = UtilityDB.executeSimpleQueryDTO(multiDBTransactionManager.getPrimaryConnection(),
|
||||
"SELECT * FROM " + StbPublications.ENTITY, StbPublications.class);
|
||||
if (stbPublicationsToRetrieve == null) return null;
|
||||
|
||||
List<StbPublicationsDetail> stbPublicationsDetails =
|
||||
UtilityDB.executeSimpleQueryDTO(multiDBTransactionManager.getPrimaryConnection(),
|
||||
"SELECT * FROM " + StbPublicationsDetail.ENTITY, StbPublicationsDetail.class);
|
||||
if (stbPublicationsDetails == null) stbPublicationsDetails = new ArrayList<>();
|
||||
|
||||
List<PublicationGroupDTO> publicationGroups = new ArrayList<>();
|
||||
|
||||
final List<ExportHistoryStatusDTO> currentExportStatus = asyncHistoryManager.getStatus();
|
||||
|
||||
for (StbPublications stbPublication : stbPublicationsToRetrieve) {
|
||||
|
||||
final PublicationGroupDTO publicationGroupDTO = new PublicationGroupDTO()
|
||||
.setId(stbPublication.getId())
|
||||
.setDescription(stbPublication.getPublicationDescription());
|
||||
publicationGroups.add(publicationGroupDTO);
|
||||
|
||||
final List<PublicationDTO> publications = stbPublicationsDetails.stream()
|
||||
.filter(x -> x.getStbPublicationId() == stbPublication.getId())
|
||||
.map(PublicationDTO::fromStbPublicationDetail)
|
||||
.collect(toList());
|
||||
publicationGroupDTO.setPublications(publications);
|
||||
|
||||
boolean atLeastOneActiveToExport = publications.stream().anyMatch(publicationDTO -> publicationDTO.getExportHistory() && publicationDTO.getActive() && !publicationDTO.getReadyToTransmit());
|
||||
boolean alreadyExporting = currentExportStatus.stream().anyMatch(x -> x.getPublicationGroupId() == publicationGroupDTO.getId());
|
||||
|
||||
publicationGroupDTO.setCanStartExport(atLeastOneActiveToExport && !alreadyExporting);
|
||||
publicationGroupDTO.setCanBeDeleted(!alreadyExporting);
|
||||
}
|
||||
|
||||
return publicationGroups;
|
||||
}
|
||||
|
||||
|
||||
public long addPublicationGroup(String description) throws Exception {
|
||||
StbPublications stbPublications = new StbPublications()
|
||||
.setPublicationDescription(description);
|
||||
stbPublications.setOperation(OperationType.INSERT);
|
||||
|
||||
entityProcessor.processEntity(stbPublications, multiDBTransactionManager);
|
||||
|
||||
return stbPublications.getId();
|
||||
}
|
||||
|
||||
|
||||
public long addPublicationItem(long groupId, @NotNull PublicationDTO publicationToInsert) throws Exception {
|
||||
if (checkIfPublicationExists(groupId, publicationToInsert))
|
||||
throw new Exception("Esiste già una pubblicazione per " + publicationToInsert.getEntityName() + " con gli stessi parametri");
|
||||
|
||||
final StbPublicationsDetail stbPublicationsDetail = new StbPublicationsDetail()
|
||||
.setStbPublicationId(groupId)
|
||||
.setEntityName(publicationToInsert.getEntityName().toUpperCase())
|
||||
.setWhereCondSql(publicationToInsert.getWhereCondSql())
|
||||
.setRecalcColumns(publicationToInsert.getRecalcColumns())
|
||||
.setActive(publicationToInsert.getActive())
|
||||
.setWhereCondField(publicationToInsert.getWhereCond())
|
||||
.setExportHistory(publicationToInsert.getExportHistory())
|
||||
.setReadyToTransmit(!(publicationToInsert.getExportHistory() != null && publicationToInsert.getExportHistory()));
|
||||
stbPublicationsDetail.setOperation(OperationType.INSERT);
|
||||
|
||||
StbPublications stbPublications = new StbPublications()
|
||||
.setId(groupId);
|
||||
stbPublications.setOperation(OperationType.NO_OP);
|
||||
stbPublications.getStbPublicationsDetails().add(stbPublicationsDetail);
|
||||
|
||||
entityProcessor.processEntity(stbPublications, multiDBTransactionManager);
|
||||
|
||||
return stbPublications.getStbPublicationsDetails().get(0).getId();
|
||||
}
|
||||
|
||||
public void addPublications(long groupId, @NotNull List<PublicationDTO> publications) throws Exception {
|
||||
final List<StbPublicationsDetail> stbPublicationsToInsert = publications.stream()
|
||||
.map(x -> {
|
||||
StbPublicationsDetail stbPublicationsDetail = new StbPublicationsDetail()
|
||||
.setStbPublicationId(groupId)
|
||||
.setEntityName(x.getEntityName())
|
||||
.setWhereCondSql(x.getWhereCondSql())
|
||||
.setRecalcColumns(x.getRecalcColumns())
|
||||
.setActive(x.getActive())
|
||||
.setWhereCondField(x.getWhereCond());
|
||||
stbPublicationsDetail.setOperation(OperationType.INSERT);
|
||||
return stbPublicationsDetail;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
StbPublications stbPublications = new StbPublications()
|
||||
.setId(groupId)
|
||||
.setStbPublicationsDetails(stbPublicationsToInsert);
|
||||
stbPublications.setOperation(OperationType.NO_OP);
|
||||
|
||||
final List<EntityBase> savedEntities = entityProcessor.processEntity(stbPublications, multiDBTransactionManager);
|
||||
|
||||
UtilityEntity.throwEntitiesException(savedEntities);
|
||||
}
|
||||
|
||||
public void deletePublications(@NotNull List<Long> publicationsId) throws Exception {
|
||||
List<StbPublicationsDetail> stbPubblicationsDetail = publicationsId.stream()
|
||||
.map(x -> {
|
||||
final StbPublicationsDetail stbPublicationsDetail = new StbPublicationsDetail()
|
||||
.setId(x);
|
||||
stbPublicationsDetail.setOperation(OperationType.SELECT_OBJECT);
|
||||
return stbPublicationsDetail;
|
||||
})
|
||||
.collect(toList());
|
||||
final List<EntityBase> entityBases = entityProcessor.processEntityList(stbPubblicationsDetail, true);
|
||||
|
||||
stbPubblicationsDetail = UtilityEntity.toCustomEntity(entityBases);
|
||||
|
||||
final Map<Long, List<StbPublicationsDetail>> collect = stbPubblicationsDetail.stream()
|
||||
.collect(groupingBy(StbPublicationsDetail::getStbPublicationId));
|
||||
|
||||
final List<StbPublications> stbPublications = new ArrayList<>();
|
||||
collect.keySet().forEach(x -> {
|
||||
List<StbPublicationsDetail> details = collect.get(x);
|
||||
details.forEach(y -> y.setOperation(OperationType.DELETE));
|
||||
|
||||
StbPublications stbPublication = new StbPublications()
|
||||
.setId(x)
|
||||
.setStbPublicationsDetails(details);
|
||||
stbPublication.setOperation(OperationType.NO_OP);
|
||||
stbPublications.add(stbPublication);
|
||||
});
|
||||
|
||||
final List<EntityBase> savedEntities = entityProcessor.processEntityList(stbPublications, multiDBTransactionManager, true);
|
||||
UtilityEntity.throwEntitiesException(savedEntities);
|
||||
}
|
||||
|
||||
public void editPublication(long publicationId, PublicationDTO publicationDTO) throws Exception {
|
||||
StbPublicationsDetail stbPublicationsDetail = new StbPublicationsDetail()
|
||||
.setId(publicationId);
|
||||
stbPublicationsDetail.setOperation(OperationType.SELECT_OBJECT);
|
||||
|
||||
stbPublicationsDetail = entityProcessor.processEntity(stbPublicationsDetail, multiDBTransactionManager);
|
||||
|
||||
if (publicationDTO.getExportHistory() != null && !stbPublicationsDetail.isReadyToTransmit())
|
||||
stbPublicationsDetail.setExportHistory(publicationDTO.getExportHistory());
|
||||
|
||||
if (publicationDTO.getActive() != null)
|
||||
stbPublicationsDetail.setActive(publicationDTO.getActive());
|
||||
|
||||
if (publicationDTO.getEntityName() != null)
|
||||
stbPublicationsDetail.setEntityName(publicationDTO.getEntityName());
|
||||
|
||||
if (publicationDTO.getRecalcColumns() != null)
|
||||
stbPublicationsDetail.setRecalcColumns(publicationDTO.getRecalcColumns());
|
||||
|
||||
if (publicationDTO.getWhereCond() != null)
|
||||
stbPublicationsDetail.setWhereCondField(publicationDTO.getWhereCond());
|
||||
|
||||
if (publicationDTO.getWhereCondSql() != null)
|
||||
stbPublicationsDetail.setWhereCondSql(publicationDTO.getWhereCondSql());
|
||||
|
||||
stbPublicationsDetail.setOperation(OperationType.UPDATE);
|
||||
|
||||
StbPublications stbPublication = new StbPublications()
|
||||
.setId(stbPublicationsDetail.getStbPublicationId());
|
||||
stbPublication.getStbPublicationsDetails().add(stbPublicationsDetail);
|
||||
stbPublication.setOperation(OperationType.NO_OP);
|
||||
|
||||
entityProcessor.processEntity(stbPublication, multiDBTransactionManager);
|
||||
}
|
||||
|
||||
public void deletePublicationsGroup(long publicationGroup) throws Exception {
|
||||
StbPublications tmpStbPublications = new StbPublications()
|
||||
.setId(publicationGroup);
|
||||
tmpStbPublications.setOperation(OperationType.DELETE);
|
||||
|
||||
entityProcessor.processEntity(tmpStbPublications, multiDBTransactionManager);
|
||||
}
|
||||
|
||||
|
||||
private boolean checkIfPublicationExists(long groupId, PublicationDTO publication) throws SQLException, IOException, PrimaryDatabaseNotPresentException {
|
||||
HashMap<String, Object> searchParams = new HashMap<>();
|
||||
searchParams.put("entity_name", publication.getEntityName());
|
||||
searchParams.put("where_cond_sql", publication.getWhereCondSql());
|
||||
searchParams.put("recalc_columns", publication.getRecalcColumns());
|
||||
searchParams.put("where_cond", publication.getWhereCond());
|
||||
searchParams.put("stb_publication_id", groupId);
|
||||
|
||||
String sql = "SELECT CAST(COUNT(*) AS BIT) AS exist " +
|
||||
"FROM " + StbPublicationsDetail.ENTITY + " " +
|
||||
"WHERE " + UtilityQuery.concatFieldsInWhereCond(searchParams);
|
||||
|
||||
return UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(multiDBTransactionManager.getPrimaryConnection(), sql);
|
||||
}
|
||||
|
||||
public long addSubscription(SubscriptionDTO subscriptionToInsert) throws Exception {
|
||||
|
||||
String endpointRetrieve = subscriptionToInsert.getEndpointUrl() + "/ems-api/system/remote-sync/setup/publications/retrieve";
|
||||
HashMap<String, String> queryParams = new HashMap<String, String>() {{
|
||||
put("profileDb", subscriptionToInsert.getProfileDb());
|
||||
}};
|
||||
|
||||
StringBuilder responseString = new StringBuilder();
|
||||
int retrieveStatus = HttpRestWrapper.callGenericGet(endpointRetrieve,
|
||||
subscriptionToInsert.getUsername(), subscriptionToInsert.getPassword(), responseString, queryParams);
|
||||
|
||||
if (retrieveStatus != 200)
|
||||
throw new Exception("Impossibile stabilire una connessione con l'endpoint " + subscriptionToInsert.getEndpointUrl() + ". [STATUS CODE: " + retrieveStatus + "]");
|
||||
|
||||
final ServiceRestResponse publicationResponse = jsonObjectMapper.readValue(responseString.toString(), ServiceRestResponse.class);
|
||||
final List<PublicationGroupDTO> availablePublications = publicationResponse.getDTO(new TypeReference<List<PublicationGroupDTO>>() {
|
||||
});
|
||||
|
||||
final PublicationGroupDTO publicationGroupDTO = availablePublications.stream().filter(x -> x.getId() == subscriptionToInsert.getPublicationId())
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
if (publicationGroupDTO == null)
|
||||
throw new Exception("Non è stata trovata alcuna pubblicazione con ID " + subscriptionToInsert.getPublicationId() + " sull'endpoint " + subscriptionToInsert.getEndpointUrl());
|
||||
|
||||
subscriptionToInsert.setPublicationDescription(publicationGroupDTO.getDescription());
|
||||
|
||||
final StbRemoteSubscription stbRemoteSubscription = subscriptionToInsert.toEntity();
|
||||
stbRemoteSubscription.setOperation(OperationType.INSERT);
|
||||
|
||||
entityProcessor.processEntity(stbRemoteSubscription, multiDBTransactionManager);
|
||||
|
||||
return stbRemoteSubscription.getId();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package it.integry.ems.sync.service;
|
||||
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.sync.dto.TransactionDTO;
|
||||
import it.integry.ems.sync.dto.TransactionGroupDTO;
|
||||
import it.integry.ems_model.entity.StbPublicationsDetail;
|
||||
import it.integry.ems_model.entity.StbTransactionLog;
|
||||
import it.integry.ems_model.utility.Query;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityQuery;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Scope;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static java.util.stream.Collectors.groupingBy;
|
||||
|
||||
@Service
|
||||
@Scope("request")
|
||||
public class RemoteSynchronizationTransactionsService {
|
||||
|
||||
|
||||
@Autowired
|
||||
private MultiDBTransactionManager multiDBTransactionManager;
|
||||
|
||||
|
||||
public List<TransactionGroupDTO> retrieveTransactions(long publicationId, Long lastRetrievedTransactionId, int limit) throws Exception {
|
||||
|
||||
String sql = Query.format("SELECT * FROM " + StbPublicationsDetail.ENTITY + " WHERE stb_publication_id = %s AND ready_to_transmit = 1", publicationId);
|
||||
final StbPublicationsDetail stbPublicationsDetails = UtilityDB.executeSimpleQueryOnlyFirstRowDTO(multiDBTransactionManager.getPrimaryConnection(), sql, StbPublicationsDetail.class);
|
||||
|
||||
if (stbPublicationsDetails == null)
|
||||
return null;
|
||||
|
||||
List<Long> availableGroupIds = UtilityDB.executeSimpleQueryOnlyFirstColumn(multiDBTransactionManager.getPrimaryConnection(),
|
||||
"SELECT DISTINCT group_id\n" +
|
||||
"FROM " + StbTransactionLog.ENTITY + "\n" +
|
||||
"WHERE publication_group_id = " + UtilityDB.valueToString(publicationId) + "\n" +
|
||||
(lastRetrievedTransactionId != null ? "AND id > " + UtilityDB.valueToString(lastRetrievedTransactionId) + "\n" : "") +
|
||||
"ORDER BY group_id");
|
||||
|
||||
if (availableGroupIds == null || availableGroupIds.isEmpty())
|
||||
return null;
|
||||
|
||||
availableGroupIds = availableGroupIds.subList(0, Math.min(limit > 0 ? limit : 100, availableGroupIds.size()));
|
||||
|
||||
List<StbTransactionLog> transactions = UtilityDB.executeSimpleQueryDTO(multiDBTransactionManager.getPrimaryConnection(),
|
||||
"SELECT * FROM " + StbTransactionLog.ENTITY + "\n" +
|
||||
"WHERE group_id IN (" + UtilityQuery.concatLongFieldsWithSeparator(availableGroupIds, ",") + ")\n" +
|
||||
"AND publication_group_id = " + UtilityDB.valueToString(publicationId) + "\n" +
|
||||
"ORDER BY id",
|
||||
StbTransactionLog.class);
|
||||
|
||||
|
||||
if (transactions == null || transactions.isEmpty())
|
||||
return null;
|
||||
|
||||
final Map<Long, List<StbTransactionLog>> collect = transactions.stream().collect(groupingBy(StbTransactionLog::getGroupId));
|
||||
final List<TransactionGroupDTO> transactionGroups = new ArrayList<>();
|
||||
|
||||
for (Long groupId : collect.keySet().stream().sorted().collect(Collectors.toList())) {
|
||||
transactionGroups.add(new TransactionGroupDTO()
|
||||
.setId(groupId)
|
||||
.setItems(collect.get(groupId).stream()
|
||||
.sorted(Comparator.comparingLong(StbTransactionLog::getId))
|
||||
.map(x -> new TransactionDTO()
|
||||
.setTransactionId(x.getId())
|
||||
.setPublicationId(x.getPublicationGroupId())
|
||||
.setTransactionDate(x.getCreatedAt())
|
||||
.setEntityName(x.getEntities())
|
||||
.setTransactionJson(Base64.getEncoder().encodeToString(x.getEntitiesJson().getBytes()))
|
||||
.setUsername(x.getUserName()))
|
||||
.collect(Collectors.toList())));
|
||||
}
|
||||
|
||||
return transactionGroups;
|
||||
}
|
||||
}
|
||||
@@ -26,17 +26,18 @@ public class GlobalExceptionHandler {
|
||||
return ServiceRestResponse.createNegativeResponse(ex);
|
||||
}
|
||||
|
||||
@ExceptionHandler({SystemNotInitializedException.class})
|
||||
public @ResponseBody
|
||||
ServiceRestResponse handleSystemNotInitializedException(HttpServletRequest request, HttpServletResponse response, SystemNotInitializedException ex) {
|
||||
response.setStatus(ex.getStatusCode());
|
||||
return ServiceRestResponse.createNegativeResponse(ex);
|
||||
}
|
||||
|
||||
@ExceptionHandler({Exception.class})
|
||||
public @ResponseBody
|
||||
ServiceRestResponse handleException(HttpServletRequest request, HttpServletResponse response, Exception ex) {
|
||||
if (ex instanceof RuntimeException) {
|
||||
if (ex.getCause() instanceof SystemNotInitializedException)
|
||||
response.setStatus(((SystemNotInitializedException) ex.getCause()).getStatusCode());
|
||||
}
|
||||
|
||||
if (!(ex instanceof RuntimeException && ex.getCause() instanceof SystemNotInitializedException))
|
||||
logger.error(request.getRequestURI(), ex);
|
||||
|
||||
ex.printStackTrace();
|
||||
logger.error(request.getRequestURI(), ex);
|
||||
return ServiceRestResponse.createNegativeResponse(ex);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
@Scope("request")
|
||||
@@ -38,7 +37,7 @@ public class SystemRequisiteCheckInterceptor extends HandlerInterceptorAdapter {
|
||||
|
||||
public boolean preHandle(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response, Object handler) {
|
||||
HttpServletResponse response, Object handler) throws SystemNotInitializedException {
|
||||
|
||||
try {
|
||||
String serviceName = request.getServletPath();
|
||||
@@ -52,7 +51,7 @@ public class SystemRequisiteCheckInterceptor extends HandlerInterceptorAdapter {
|
||||
!serviceName.contains("index.html") &&
|
||||
!serviceName.contains("favicon.ico") &&
|
||||
|
||||
!serviceName.contains("system/login")&&
|
||||
!serviceName.contains("system/login") &&
|
||||
!serviceName.contains("system/migration")) {
|
||||
|
||||
if (!emsCoreContext.isContextInitialized()) {
|
||||
@@ -77,19 +76,16 @@ public class SystemRequisiteCheckInterceptor extends HandlerInterceptorAdapter {
|
||||
if (foundName != null) {
|
||||
|
||||
if (emsDBConst.getConsts(foundName).getApplicationDbName() == null) {
|
||||
response.sendError(551, "Application Name not initialized");
|
||||
return false;
|
||||
throw new SystemNotInitializedException(553, "Application Name not initialized");
|
||||
}
|
||||
if (emsDBConst.getConsts(foundName).getNomeAzienda() == null) {
|
||||
response.sendError(551, "Nome azienda not initialized");
|
||||
return false;
|
||||
throw new SystemNotInitializedException(554, "Nome azienda not initialized");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
} catch (SystemNotInitializedException snie) {
|
||||
throw snie;
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ public class UtilityEntity {
|
||||
}
|
||||
|
||||
|
||||
public static <T extends EntityBase> List<T> toCustomEntity(List<EntityBase> entities) {
|
||||
public static <T extends EntityBase> List<T> toCustomEntity(List<? extends EntityBase> entities) {
|
||||
List<T> respList = new ArrayList<T>();
|
||||
|
||||
for (EntityBase entity : entities) {
|
||||
@@ -108,4 +108,11 @@ public class UtilityEntity {
|
||||
return StringUtils.join(fieldsPK, "~");
|
||||
}
|
||||
|
||||
|
||||
public <T extends EntityBase> String calculateWhereCond(T entity, boolean onlyPK) {
|
||||
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.itextpdf.text.PageSize;
|
||||
import com.itextpdf.text.pdf.PdfPTable;
|
||||
import com.itextpdf.text.pdf.PdfWriter;
|
||||
import com.itextpdf.tool.xml.XMLWorkerHelper;
|
||||
import it.integry.ems.Import.dto.ImportRequestDTO;
|
||||
import it.integry.ems.sync.MultiDBTransaction.MultiDBTransactionManager;
|
||||
import it.integry.ems.utility.enums.DigitalSignatureType;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
@@ -12,6 +13,7 @@ import it.integry.ems_model.utility.UtilityString;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.bouncycastle.cms.CMSSignedData;
|
||||
@@ -31,6 +33,7 @@ import java.nio.file.*;
|
||||
import java.nio.file.attribute.BasicFileAttributes;
|
||||
import java.security.Security;
|
||||
import java.sql.Connection;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.*;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
@@ -413,4 +416,21 @@ public class UtilityFile {
|
||||
}
|
||||
return cleanName.toString();
|
||||
}
|
||||
|
||||
public static void moveFile(@NotNull String path, @NotNull String newPath, @NotNull String fileName, String newFileName) throws Exception {
|
||||
if (!path.endsWith("\\") || !path.endsWith("/"))
|
||||
path = path + File.separator;
|
||||
|
||||
if (!newPath.endsWith("\\") || !newPath.endsWith("/"))
|
||||
newPath = newPath + File.separator;
|
||||
|
||||
if (newFileName == null)
|
||||
newFileName = fileName;
|
||||
|
||||
try {
|
||||
FileUtils.moveFile(new File(path + fileName), new File(newPath + newFileName));
|
||||
} catch (Exception e) {
|
||||
throw new Exception("Impossibile spostare il file");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,13 +7,10 @@ import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo.As;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonTypeResolver;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import com.google.common.base.Joiner;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonParser;
|
||||
import com.microsoft.sqlserver.jdbc.SQLServerConnection;
|
||||
import com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement;
|
||||
import it.integry.common.var.CommonConstants;
|
||||
import it.integry.common.var.EmsDBConst;
|
||||
import it.integry.ems.object_storage.minio.MinIOService;
|
||||
@@ -31,7 +28,6 @@ import it.integry.ems_model.config.EmsRestConstants;
|
||||
import it.integry.ems_model.db.ResultSetMapper;
|
||||
import it.integry.ems_model.exception.*;
|
||||
import it.integry.ems_model.resolver.PropertyTypeResolver;
|
||||
import it.integry.ems_model.resolver.ResultSetSerializer;
|
||||
import it.integry.ems_model.resolver.SqlFieldHolder;
|
||||
import it.integry.ems_model.rulescompleting.DroolsDataCompleting;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
@@ -51,7 +47,6 @@ import org.xmlpull.v1.XmlPullParserException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.Serializable;
|
||||
import java.io.StringWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
@@ -65,6 +60,7 @@ import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.*;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@JsonFilter("jsonEntityFilter")
|
||||
//@JsonDeserialize(using = CustomPropertyTypeDeserializerNew.class)
|
||||
@@ -119,7 +115,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
|
||||
//ID del gruppo di transazioni per le Sync OFFLINE
|
||||
@JsonIgnore
|
||||
private Integer transactionGroupId = null;
|
||||
private Long transactionGroupId = null;
|
||||
|
||||
@JsonIgnore
|
||||
private int queryTimeoutSeconds = 60 * 30;
|
||||
@@ -137,19 +133,20 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
this.type = null;
|
||||
}
|
||||
|
||||
List<Field> fields = getEntityHolder().getFields(this.getClass());
|
||||
for (Field field : fields) {
|
||||
if (field.getAnnotation(EntityChild.class) != null) {
|
||||
field.setAccessible(true);
|
||||
try {
|
||||
Object object = field.get(this);
|
||||
if (object == null && field.getType().isAssignableFrom(List.class)) {
|
||||
object = new ArrayList();
|
||||
field.set(this, object);
|
||||
}
|
||||
} catch (IllegalAccessException ex) {
|
||||
logger.error(ex);
|
||||
List<Field> entityChildFields = getEntityHolder().getEntityChildFields(this.getClass());
|
||||
|
||||
if (entityChildFields == null) return;
|
||||
|
||||
for (Field field : entityChildFields) {
|
||||
field.setAccessible(true);
|
||||
try {
|
||||
Object object = field.get(this);
|
||||
if (object == null && field.getType().isAssignableFrom(List.class)) {
|
||||
object = new ArrayList();
|
||||
field.set(this, object);
|
||||
}
|
||||
} catch (IllegalAccessException ex) {
|
||||
logger.error(ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -419,10 +416,13 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
this.exception = exception;
|
||||
}
|
||||
|
||||
public Object select(Connection connection) throws Exception {
|
||||
public List<? extends EntityBase> select(Connection connection) throws Exception {
|
||||
return select(connection, null);
|
||||
}
|
||||
|
||||
public List<? extends EntityBase> select(Connection connection, String whereCond) throws Exception {
|
||||
String query = "";
|
||||
if (nativeSql != null) {
|
||||
|
||||
String columnList;
|
||||
|
||||
int sIdx = nativeSql.toUpperCase().indexOf("SELECT DISTINCT");
|
||||
@@ -448,56 +448,34 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
if ("*".equals(fields)) {
|
||||
columnList = getEntityHolder().getColumnList(this.getClass(), this.getTableName());
|
||||
} else {
|
||||
List<String> colList = new ArrayList<String>();
|
||||
|
||||
for (String sqlFieldName : fields.split(",")) {
|
||||
Field f = getEntityHolder().getFieldBySql("", sqlFieldName);
|
||||
sqlFieldName += " as " + f.getName();
|
||||
colList.add(sqlFieldName);
|
||||
}
|
||||
List<String> colList = new ArrayList<>(Arrays.asList(fields.split(",")));
|
||||
columnList = StringUtils.join(colList, ", ");
|
||||
}
|
||||
|
||||
query = "SELECT " + columnList + ", '" + table + "' as type FROM " + table;
|
||||
query = UtilityDB.addwhereCond(query, where, false);
|
||||
} else {
|
||||
String wherePK = getEntityHolder().getWherePK(this);
|
||||
String wherePK;
|
||||
|
||||
if ((getOperation() == OperationType.SUBSTITUTE || getOperation() == OperationType.DELETE_THEN_INSERT) && getOldPk() != null) {
|
||||
wherePK = getWhereCondOldPk();
|
||||
} else {
|
||||
wherePK = getEntityHolder().getWherePK(this);
|
||||
}
|
||||
|
||||
String columnList = getEntityHolder().getColumnList(this.getClass(), this.getTableName());
|
||||
if (!UtilityString.isNullOrEmpty(wherePK))
|
||||
query = "SELECT " + columnList + ", '" + getTableName() + "' as type FROM " + getTableName() + " WHERE " + wherePK;
|
||||
else return null;
|
||||
|
||||
if (!UtilityString.isNullOrEmpty(wherePK)) {
|
||||
query = "SELECT " + columnList + ", '" + getTableName() + "' as type FROM " + getTableName();
|
||||
query += " WHERE " + wherePK;
|
||||
|
||||
if (!UtilityString.isNullOrEmpty(whereCond))
|
||||
query += " AND " + whereCond;
|
||||
|
||||
} else return null;
|
||||
}
|
||||
|
||||
return selectRawData(connection, query);
|
||||
}
|
||||
|
||||
private Object selectRawData(Connection connection, String query) throws Exception {
|
||||
SimpleModule module = new SimpleModule();
|
||||
module.addSerializer(new ResultSetSerializer());
|
||||
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.registerModule(module);
|
||||
PreparedStatement ps = connection.prepareStatement(query);
|
||||
ps.setQueryTimeout(queryTimeoutSeconds);
|
||||
ResultSet resultset = ps.executeQuery();
|
||||
|
||||
// Use the DataBind Api here
|
||||
ObjectNode objectNode = objectMapper.createObjectNode();
|
||||
|
||||
// put the resultset in a containing structure
|
||||
objectNode.putPOJO("results", resultset);
|
||||
// generate all
|
||||
StringWriter writer = new StringWriter();
|
||||
objectMapper.writeValue(writer, objectNode.get("results"));
|
||||
//chiusura resultset
|
||||
resultset.close();
|
||||
ps.close();
|
||||
|
||||
String json = writer.toString();
|
||||
JsonArray array = new JsonParser().parse(json).getAsJsonArray();
|
||||
if (array.size() == 0) return null;
|
||||
|
||||
return json;
|
||||
return UtilityDB.executeSimpleQueryDTO(connection, query, this.getClass());
|
||||
}
|
||||
|
||||
private boolean checkPkValueNull(EntityBase entityBase) throws IllegalAccessException {
|
||||
@@ -539,7 +517,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
return entityDB;
|
||||
}
|
||||
|
||||
public List<EntityBase> selectEntityRowList(Connection connection, EntityBase entity, Class<? extends EntityBase> rowClass, String tableName, String whereConds) throws IOException, FieldMissingException, IllegalAccessException, SQLException, DataConverterNotFoundException, InstantiationException {
|
||||
public List<? extends EntityBase> selectEntityRowList(Connection connection, EntityBase entity, Class<? extends EntityBase> rowClass, String tableName, String whereConds) throws IOException, FieldMissingException, IllegalAccessException, SQLException, DataConverterNotFoundException, InstantiationException {
|
||||
|
||||
if (!UtilityString.isNullOrEmpty(whereConds)) {
|
||||
whereConds = " AND " + whereConds;
|
||||
@@ -550,6 +528,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
String query;
|
||||
String wherePK;
|
||||
|
||||
|
||||
if ((entity.getOperation() == OperationType.SUBSTITUTE || entity.getOperation() == OperationType.DELETE_THEN_INSERT) && entity.getOldPk() != null) {
|
||||
wherePK = entity.getWhereCondOldPk();
|
||||
} else {
|
||||
@@ -895,6 +874,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkPreSave() throws Exception {
|
||||
|
||||
}
|
||||
@@ -946,11 +926,10 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
managePriorityPost();
|
||||
|
||||
if (this.getClass().getAnnotation(Master.class) != null) {
|
||||
String publicationId = AsyncManager.getPublicationIdIfExists(dbName, this);
|
||||
long publicationId = AsyncManager.getPublicationIdIfExists(dbName, this);
|
||||
|
||||
if (publicationId != null) {
|
||||
if (transactionGroupId == null) transactionGroupId = AsyncManager.getNextTransactionGroupId(connection);
|
||||
AsyncManager.saveNewTransaction(connection, this, transactionGroupId);
|
||||
if (publicationId > 0) {
|
||||
transactionGroupId = AsyncManager.saveNewTransaction(connection, dbName, this, publicationId, transactionGroupId);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1364,47 +1343,100 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
|
||||
List<Field> fields = getEntityHolder().getFields(this.getClass());
|
||||
|
||||
|
||||
List<String> campi = new ArrayList<>();
|
||||
List<String> valori = new ArrayList<>();
|
||||
List<Object> originalValues = new ArrayList<>();
|
||||
|
||||
Map<Integer, Object> mapLob = getFieldToQuery(fields, campi, valori);
|
||||
Map<Integer, Object> mapLob = getFieldToQuery(fields, campi, valori, originalValues);
|
||||
|
||||
if (campi.size() != 0) {
|
||||
String sql = "INSERT INTO " + getTableName() + "(" + StringUtils.join(campi, ",") + ") " + "VALUES (" + StringUtils.join(valori, ",") + ")";
|
||||
if (!campi.isEmpty()) {
|
||||
|
||||
boolean containsIdentity;
|
||||
|
||||
boolean containsIdentity = mapLob.containsKey(-1);
|
||||
String identityFieldName = null;
|
||||
if (containsIdentity = mapLob.containsKey(-1)) {
|
||||
|
||||
if (containsIdentity) {
|
||||
identityFieldName = (String) mapLob.get(-1);
|
||||
mapLob.remove(-1);
|
||||
}
|
||||
|
||||
if (logger.isTraceEnabled()) {
|
||||
logger.trace("QUERY: " + sql);
|
||||
}
|
||||
try {
|
||||
PreparedStatement pstm = connection.prepareStatement(sql, containsIdentity ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
|
||||
setupBinaryParams(mapLob, pstm);
|
||||
long insertedIdentity = -1;
|
||||
|
||||
int insertedRowCount = pstm.executeUpdate();
|
||||
pstm.setQueryTimeout(queryTimeoutSeconds);
|
||||
if (connection instanceof SQLServerConnection) {
|
||||
SQLServerConnection sqlServerConnection = (SQLServerConnection) connection;
|
||||
|
||||
if (insertedRowCount > 0 && containsIdentity) {
|
||||
ResultSet rs = pstm.getGeneratedKeys();
|
||||
if (rs.next()) {
|
||||
Long identity = rs.getLong(1);
|
||||
StringBuilder insertSQL = new StringBuilder("INSERT INTO ")
|
||||
.append(getTableName())
|
||||
.append(" (")
|
||||
.append(StringUtils.join(campi, ","))
|
||||
.append(") VALUES (");
|
||||
|
||||
// Field identityField = getClass().getDeclaredField(SqlFieldHolder.getSqlValue(identityFieldName,));
|
||||
Field identityField = getEntityHolder().getFieldBySql(getClass().getSimpleName(), identityFieldName);
|
||||
identityField.setAccessible(true);
|
||||
identityField.set(this, identity);
|
||||
}
|
||||
for (int i = 0; i < campi.size(); i++) {
|
||||
insertSQL.append(" ?");
|
||||
|
||||
if (i < campi.size() - 1)
|
||||
insertSQL.append(",");
|
||||
}
|
||||
|
||||
pstm.close();
|
||||
} catch (SQLException e) {
|
||||
throw new EntityException(e, this, sql);
|
||||
insertSQL.append(")");
|
||||
|
||||
try (SQLServerPreparedStatement insertBulkPs =
|
||||
(SQLServerPreparedStatement) sqlServerConnection.prepareStatement(
|
||||
insertSQL.toString(),
|
||||
containsIdentity ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS)) {
|
||||
|
||||
for (int i = 1; i <= originalValues.size(); i++) {
|
||||
insertBulkPs.setObject(i, SqlFieldHolder.getSqlValueFieldAsObject(originalValues.get(i - 1), true));
|
||||
}
|
||||
|
||||
long insertedRowCount = insertBulkPs.executeLargeUpdate();
|
||||
if (insertedRowCount > 0 && containsIdentity) {
|
||||
ResultSet rs = insertBulkPs.getGeneratedKeys();
|
||||
if (rs.next()) {
|
||||
insertedIdentity = rs.getLong(1);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
} else {
|
||||
String sql = "INSERT INTO " + getTableName() + "(" + StringUtils.join(campi, ",") + ") " + "VALUES (" + StringUtils.join(valori, ",") + ")";
|
||||
|
||||
if (logger.isTraceEnabled()) {
|
||||
logger.trace("QUERY: " + sql);
|
||||
}
|
||||
|
||||
try {
|
||||
PreparedStatement pstm = connection.prepareStatement(sql, containsIdentity ? Statement.RETURN_GENERATED_KEYS : Statement.NO_GENERATED_KEYS);
|
||||
setupBinaryParams(mapLob, pstm);
|
||||
|
||||
int insertedRowCount = pstm.executeUpdate();
|
||||
pstm.setQueryTimeout(queryTimeoutSeconds);
|
||||
|
||||
if (insertedRowCount > 0 && containsIdentity) {
|
||||
try (ResultSet rs = pstm.getGeneratedKeys()) {
|
||||
if (rs.next())
|
||||
insertedIdentity = rs.getLong(1);
|
||||
}
|
||||
}
|
||||
|
||||
pstm.close();
|
||||
} catch (SQLException e) {
|
||||
throw new EntityException(e, this, sql);
|
||||
}
|
||||
}
|
||||
|
||||
if (containsIdentity) {
|
||||
if(insertedIdentity < 0)
|
||||
throw new Exception("Impossibile leggere il campo identity anche se è richiesto");
|
||||
|
||||
Field identityField = getEntityHolder().getFieldBySql(getClass().getSimpleName(), identityFieldName);
|
||||
identityField.setAccessible(true);
|
||||
identityField.set(this, insertedIdentity);
|
||||
}
|
||||
|
||||
} else {
|
||||
throw new Exception("Nessun campo valorizzato per la entity " + getTableName() + " (Controllare metodi get/set della entity)");
|
||||
}
|
||||
@@ -1475,7 +1507,9 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
}
|
||||
|
||||
public void setParentPKAndImportFromParent(EntityBase parent, Boolean isChild) throws InvocationTargetException, IllegalAccessException {
|
||||
List<Field> pkField = Stream.of(parent.getClass().getDeclaredFields()).filter(x -> x.isAnnotationPresent(PK.class) && x.isAnnotationPresent(SqlField.class)).toList();
|
||||
List<Field> pkField = Arrays.stream(parent.getClass().getDeclaredFields())
|
||||
.filter(x -> x.isAnnotationPresent(PK.class) && x.isAnnotationPresent(SqlField.class) && !x.isAnnotationPresent(Identity.class))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
for (Field field : pkField) {
|
||||
field.setAccessible(true);
|
||||
@@ -1541,9 +1575,9 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
HashMap<String, Object> j = (HashMap<String, Object>) parent.getOldPk().clone();
|
||||
if (this.getOldPk() != null) {
|
||||
Set<Entry<String, Object>> map = this.getOldPk().entrySet();
|
||||
Iterator<Entry<String, Object>> iterator = map.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
String propName = iterator.next().getKey();
|
||||
|
||||
for (Entry<String, Object> stringObjectEntry : map) {
|
||||
String propName = stringObjectEntry.getKey();
|
||||
Object element = this.getOldPk().get(propName);
|
||||
j.put(propName, element);
|
||||
}
|
||||
@@ -1613,16 +1647,6 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
public void deleteAllEntities(Connection conn, EntityBase parent) throws Exception {
|
||||
String whereCondDel = parent.getWhereCondDelete();
|
||||
deleteAllEntities(conn, whereCondDel);
|
||||
// String sql = "DELETE " + getTableName() + " WHERE " + whereCondDel;
|
||||
//
|
||||
// if (logger.isTraceEnabled()) {
|
||||
// logger.trace("QUERY: " + sql);
|
||||
// }
|
||||
//
|
||||
// PreparedStatement pstm = conn.prepareStatement(sql);
|
||||
// pstm.setQueryTimeout(queryTimeoutSeconds);
|
||||
// pstm.executeUpdate();
|
||||
// pstm.close();
|
||||
}
|
||||
|
||||
private String getWhereCondDelete() throws Exception {
|
||||
@@ -1675,7 +1699,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
|
||||
Object obj = field.get(parent);
|
||||
if (obj != null) {
|
||||
Object dato = SqlFieldHolder.getSqlValueField(obj);
|
||||
Object dato = SqlFieldHolder.getSqlValueFieldAsString(obj);
|
||||
where.add(sqlColumn + " = " + dato);
|
||||
} else if (this.getOperation() != OperationType.DELETE) {
|
||||
where.add(sqlColumn + " IS null ");
|
||||
@@ -1764,9 +1788,9 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
String whereCondOldPk = null;
|
||||
if (this.getOldPk() != null) {
|
||||
Set<Entry<String, Object>> map = this.getOldPk().entrySet();
|
||||
Iterator<Entry<String, Object>> iterator = map.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
final String campo = iterator.next().getKey();
|
||||
|
||||
for (Entry<String, Object> stringObjectEntry : map) {
|
||||
final String campo = stringObjectEntry.getKey();
|
||||
Optional<Field> fieldOptional = Stream.of(fields).filter(field -> field.getName().equalsIgnoreCase(campo) && field.getAnnotation(SqlField.class) != null).findFirst();
|
||||
|
||||
if (fieldOptional.isEmpty()) {
|
||||
@@ -1786,7 +1810,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
if ((fieldOptional.get().getType() == Date.class || fieldOptional.get().getType() == Timestamp.class) && valore instanceof String) {
|
||||
valore = UtilityString.parseDate(valore.toString());
|
||||
}
|
||||
Object valueSql = SqlFieldHolder.getSqlValueField(valore);
|
||||
Object valueSql = SqlFieldHolder.getSqlValueFieldAsString(valore);
|
||||
where.add(sqlField + " = " + valueSql);
|
||||
}
|
||||
}
|
||||
@@ -1796,7 +1820,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
return whereCondOldPk;
|
||||
}
|
||||
|
||||
private Map<Integer, Object> getFieldToQuery(List<Field> fields, List<String> campi, List<String> valori) throws Exception {
|
||||
private Map<Integer, Object> getFieldToQuery(List<Field> fields, List<String> campi, List<String> valori, List<Object> originalValues) throws Exception {
|
||||
|
||||
Map<Integer, Object> map = new HashMap<Integer, Object>();
|
||||
Integer counter = 1;
|
||||
@@ -1823,7 +1847,8 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
|
||||
if (!UtilityString.isNullOrEmpty(refUuid)) {
|
||||
campi.add("ref_uuid" + (objectStorage.suffix() > 0 ? objectStorage.suffix() : ""));
|
||||
valori.add(SqlFieldHolder.getSqlValueField(refUuid).toString());
|
||||
valori.add(SqlFieldHolder.getSqlValueFieldAsString(refUuid).toString());
|
||||
originalValues.add(refUuid);
|
||||
}
|
||||
|
||||
if (!SettingsModel.getInstance().getMinioConfiguration().isEnableOldSave()) continue;
|
||||
@@ -1865,17 +1890,20 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
if (field.getAnnotation(it.integry.ems_model.annotation.Clob.class) != null) {
|
||||
setupClobData(counter, map, obj);
|
||||
valori.add("?");
|
||||
originalValues.add(obj);
|
||||
campi.add(SqlFieldHolder.getSqlValue(sqlField.value(), field));
|
||||
|
||||
counter++;
|
||||
} else if (field.getAnnotation(it.integry.ems_model.annotation.Blob.class) != null) {
|
||||
setupBlobData(counter, map, obj);
|
||||
valori.add("?");
|
||||
originalValues.add(obj);
|
||||
campi.add(SqlFieldHolder.getSqlValue(sqlField.value(), field));
|
||||
|
||||
counter++;
|
||||
} else {
|
||||
String value = SqlFieldHolder.getSqlValueField(obj == null ? defaultVal : obj, sqlField.trimSpaces()).toString();
|
||||
Object originalValue = obj == null ? defaultVal : obj;
|
||||
String value = SqlFieldHolder.getSqlValueFieldAsString(originalValue, sqlField.trimSpaces());
|
||||
|
||||
if (obj instanceof String) {
|
||||
value = value.replaceAll("\r", "' + CHAR(13) + '").replaceAll("\n", "' + CHAR(10) + '");
|
||||
@@ -1884,6 +1912,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
}
|
||||
|
||||
valori.add(value);
|
||||
originalValues.add(originalValue);
|
||||
campi.add(SqlFieldHolder.getSqlValue(sqlField.value(), field));
|
||||
}
|
||||
}
|
||||
@@ -1915,7 +1944,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
else if (obj instanceof byte[]) refUuid = minIOService.uploadObject((byte[]) obj, connection);
|
||||
|
||||
|
||||
campi.add("ref_uuid" + (objectStorage.suffix() > 0 ? objectStorage.suffix() : "") + " = " + SqlFieldHolder.getSqlValueField(refUuid));
|
||||
campi.add("ref_uuid" + (objectStorage.suffix() > 0 ? objectStorage.suffix() : "") + " = " + SqlFieldHolder.getSqlValueFieldAsString(refUuid));
|
||||
|
||||
|
||||
if (!SettingsModel.getInstance().getMinioConfiguration().isEnableOldSave()) continue;
|
||||
@@ -1926,7 +1955,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
if ((sqlField = field.getAnnotation(SqlField.class)) != null && !field.getName().startsWith("refUuid")) {
|
||||
PK pk = field.getAnnotation(PK.class);
|
||||
SqlField sqlProp = field.getAnnotation(SqlField.class);
|
||||
Object dato = SqlFieldHolder.getSqlValueField(obj, sqlProp.trimSpaces());
|
||||
Object dato = SqlFieldHolder.getSqlValueFieldAsString(obj, sqlProp.trimSpaces());
|
||||
String sqlVal = SqlFieldHolder.getSqlValue(sqlField.value(), field);
|
||||
|
||||
if (pk != null) {
|
||||
@@ -2018,11 +2047,11 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
public Integer getTransactionGroupId() {
|
||||
public Long getTransactionGroupId() {
|
||||
return transactionGroupId;
|
||||
}
|
||||
|
||||
public void setTransactionGroupId(Integer transactionGroupId) {
|
||||
public void setTransactionGroupId(Long transactionGroupId) {
|
||||
this.transactionGroupId = transactionGroupId;
|
||||
}
|
||||
|
||||
@@ -2035,8 +2064,7 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
try {
|
||||
field.setAccessible(true);
|
||||
idRiga = (Integer) field.get(entityBase);
|
||||
} catch (Exception e) {
|
||||
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
return idRiga;
|
||||
}
|
||||
@@ -2082,7 +2110,9 @@ public abstract class EntityBase implements Serializable, Cloneable, EntityInter
|
||||
public void resetIdentiy(Connection connection) throws Exception {
|
||||
Field[] fields = this.getClass().getDeclaredFields();
|
||||
|
||||
Optional<Field> identityField = Stream.of(fields).filter(x -> x.isAnnotationPresent(Identity.class) && x.isAnnotationPresent(SqlField.class)).findFirst();
|
||||
Optional<Field> identityField = Stream.of(fields)
|
||||
.filter(x -> x.isAnnotationPresent(Identity.class) && x.isAnnotationPresent(SqlField.class))
|
||||
.findFirst();
|
||||
|
||||
if (identityField.isPresent()) {
|
||||
String tableName = this.getTableName();
|
||||
|
||||
@@ -25,7 +25,7 @@ public interface EntityInterface {
|
||||
|
||||
void applyDefault() throws IllegalAccessException, IOException;
|
||||
|
||||
Object select(Connection connection) throws Exception;
|
||||
List<? extends EntityBase> select(Connection connection) throws Exception;
|
||||
|
||||
OperationType getOperation();
|
||||
|
||||
@@ -83,9 +83,9 @@ public interface EntityInterface {
|
||||
|
||||
EntityException getException();
|
||||
|
||||
Integer getTransactionGroupId();
|
||||
Long getTransactionGroupId();
|
||||
|
||||
void setTransactionGroupId(Integer transactionGroupId);
|
||||
void setTransactionGroupId(Long transactionGroupId);
|
||||
|
||||
void resetTransactionGroupId();
|
||||
|
||||
|
||||
@@ -5,10 +5,8 @@ import com.google.common.collect.BiMap;
|
||||
import com.google.common.collect.HashBiMap;
|
||||
import it.integry.ems.dto.EntityHierarchyDTO;
|
||||
import it.integry.ems.object_storage.minio.MinIOService;
|
||||
import it.integry.ems.object_storage.minio.sdk.errors.MinioException;
|
||||
import it.integry.ems.settings.Model.SettingsModel;
|
||||
import it.integry.ems_model.annotation.*;
|
||||
import it.integry.ems_model.exception.*;
|
||||
import it.integry.ems_model.resolver.SqlFieldHolder;
|
||||
import it.integry.ems_model.rulescompleting.DroolsDataCompleting;
|
||||
import it.integry.ems_model.types.LatLng;
|
||||
@@ -22,15 +20,13 @@ import org.reflections.Reflections;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.context.ContextLoader;
|
||||
import org.xmlpull.v1.XmlPullParserException;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.*;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@@ -40,6 +36,7 @@ public class EntityPropertyHolder {
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
private List<EntityHierarchyDTO> entityHierarchyMap;
|
||||
|
||||
private final HashMap<String, Class<?>> entityNameMap = new HashMap<>();
|
||||
private final HashMap<String, Object> classMap = new HashMap<>();
|
||||
@@ -59,8 +56,48 @@ public class EntityPropertyHolder {
|
||||
return entityNameMap.getOrDefault(entityName, null);
|
||||
}
|
||||
|
||||
public Class<? extends EntityBase> getEntityClassFromTableName(String tableName) {
|
||||
List<EntityHierarchyDTO> tempList = new ArrayList<>(entityHierarchyMap);
|
||||
tempList.addAll(tempList.stream().flatMap(x -> x.getChildren().stream()).collect(Collectors.toList()));
|
||||
|
||||
return tempList.stream()
|
||||
.filter(x -> x.getTableName().equalsIgnoreCase(tableName))
|
||||
.map(EntityHierarchyDTO::getClazz)
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
public List<EntityHierarchyDTO> getEntityHierarchyMap() {
|
||||
return entityHierarchyMap;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void scanEntityFields() {
|
||||
public void init() {
|
||||
scanEntityFields();
|
||||
entityHierarchyMap = scanEntityMapping();
|
||||
}
|
||||
|
||||
public List<EntityHierarchyDTO> scanEntityMapping() {
|
||||
Reflections reflections = new Reflections("it.integry.ems_model.entity");
|
||||
List<EntityHierarchyDTO> mapping = new ArrayList<>();
|
||||
Set<Class<? extends EntityBase>> classes = reflections.getSubTypesOf(EntityBase.class);
|
||||
|
||||
for (Class<? extends EntityBase> entity : classes) {
|
||||
if(!entity.isAnnotationPresent(Table.class)) continue;
|
||||
|
||||
EntityHierarchyDTO dto = new EntityHierarchyDTO();
|
||||
dto.setClazz(entity);
|
||||
dto.setEntityName(entity.getSimpleName());
|
||||
dto.setTableName(entity.getAnnotation(Table.class).value());
|
||||
dto.setChildren(getEntityChildren(entity));
|
||||
dto.setMaster(entity.isAnnotationPresent(Master.class));
|
||||
|
||||
mapping.add(dto);
|
||||
}
|
||||
return mapping;
|
||||
}
|
||||
|
||||
|
||||
private void scanEntityFields() {
|
||||
Reflections reflections = new Reflections("it.integry.ems_model.entity");
|
||||
|
||||
List<Class<?>> clssList = new ArrayList<>(Stream.of(reflections.getSubTypesOf(EntityBase.class))
|
||||
@@ -172,21 +209,18 @@ public class EntityPropertyHolder {
|
||||
}
|
||||
}
|
||||
|
||||
public Boolean isEntityChild(Class<? extends EntityBase> clazz, String childName) {
|
||||
Boolean isChild = false;
|
||||
List<Field> children = getEntityChildField(clazz);
|
||||
|
||||
for (Field child : children) {
|
||||
if (child.getName().equals(childName)) {
|
||||
isChild = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return isChild;
|
||||
public List<Field> getEntityChildFields(Class<? extends EntityBase> clazz) {
|
||||
return this.entityHierarchyMap.stream()
|
||||
.filter(x -> x.getClazz().equals(clazz))
|
||||
.map(EntityHierarchyDTO::getChildren)
|
||||
.flatMap(Collection::stream)
|
||||
.map(EntityHierarchyDTO::getField)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<EntityBase> getEntityChain(List<? extends EntityBase> entityList, Connection conn, EntityBase testata) throws MergeEntityDBToObjectException, SQLException, MinioException, XmlPullParserException, IOException, NoSuchAlgorithmException, InvalidKeyException, FieldMissingException, IllegalAccessException, ConverterNotConfiguredException, DataConverterNotFoundException, NoSuchFieldException, InstantiationException, RulesNotCompiledException, InvocationTargetException {
|
||||
|
||||
public List<EntityBase> getEntityChain(List<? extends EntityBase> entityList, Connection conn, EntityBase testata) throws Exception {
|
||||
List<EntityBase> chain = new ArrayList<EntityBase>();
|
||||
|
||||
int lastNullIdx = 0;
|
||||
@@ -220,7 +254,7 @@ public class EntityPropertyHolder {
|
||||
if (object instanceof List) {
|
||||
List<EntityBase> list = ((List<EntityBase>) object);
|
||||
|
||||
List<EntityBase> listRowDB = UtilityDB.reloadOnlyDbRow(conn, entityInsert, list, field);
|
||||
List<? extends EntityBase> listRowDB = UtilityDB.reloadOnlyDbRow(conn, entityInsert, list, field);
|
||||
if (listRowDB != null) {
|
||||
for (EntityBase entDB : listRowDB) {
|
||||
EntityBase cloningDB = (EntityBase) entDB.clone();
|
||||
@@ -259,7 +293,7 @@ public class EntityPropertyHolder {
|
||||
return chain;
|
||||
}
|
||||
|
||||
public List<EntityBase> getEntityChain(List<? extends EntityBase> entityList, Connection conn) throws MergeEntityDBToObjectException, SQLException, IOException, NoSuchAlgorithmException, InvalidKeyException, NoSuchFieldException, IllegalAccessException, ConverterNotConfiguredException, DataConverterNotFoundException, MinioException, XmlPullParserException, FieldMissingException, InstantiationException, RulesNotCompiledException, InvocationTargetException {
|
||||
public List<EntityBase> getEntityChain(List<? extends EntityBase> entityList, Connection conn) throws Exception {
|
||||
return getEntityChain(entityList, conn, null);
|
||||
}
|
||||
|
||||
@@ -315,8 +349,12 @@ public class EntityPropertyHolder {
|
||||
pkIdentityNull = true;
|
||||
}
|
||||
} else {
|
||||
Object dato = SqlFieldHolder.getSqlValueField(obj);
|
||||
where.add(SqlFieldHolder.getSqlValue(colName, field) + " = " + dato);
|
||||
if (identity != null && (field.getType().isPrimitive() && ((long) obj) == 0)) {
|
||||
pkIdentityNull = true;
|
||||
} else {
|
||||
Object dato = SqlFieldHolder.getSqlValueFieldAsString(obj);
|
||||
where.add(SqlFieldHolder.getSqlValue(colName, field) + " = " + dato);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -335,7 +373,7 @@ public class EntityPropertyHolder {
|
||||
if (obj == null) {
|
||||
whereUnique.add(SqlFieldHolder.getSqlValue(colName, field) + " IS NULL");
|
||||
} else {
|
||||
Object dato = SqlFieldHolder.getSqlValueField(obj);
|
||||
Object dato = SqlFieldHolder.getSqlValueFieldAsString(obj);
|
||||
whereUnique.add(SqlFieldHolder.getSqlValue(colName, field) + " = " + dato);
|
||||
}
|
||||
}
|
||||
@@ -345,6 +383,10 @@ public class EntityPropertyHolder {
|
||||
String whereUniqueStr = StringUtils.join(whereUnique, " AND ");
|
||||
if (!UtilityString.isNullOrEmpty(whereUniqueStr))
|
||||
whereStr += "OR (" + whereUniqueStr + ")";
|
||||
|
||||
if (whereStr.equalsIgnoreCase("()"))
|
||||
whereStr = "(1 = 1)";
|
||||
|
||||
return whereStr;
|
||||
}
|
||||
|
||||
@@ -359,7 +401,7 @@ public class EntityPropertyHolder {
|
||||
SqlField sqlField;
|
||||
if ((sqlField = field.getAnnotation(SqlField.class)) != null) {
|
||||
if (obj != null) {
|
||||
Object dato = SqlFieldHolder.getSqlValueField(obj);
|
||||
Object dato = SqlFieldHolder.getSqlValueFieldAsString(obj);
|
||||
where.add(SqlFieldHolder.getSqlValue(sqlField.value(), field) + " = " + dato);
|
||||
}
|
||||
}
|
||||
@@ -368,7 +410,7 @@ public class EntityPropertyHolder {
|
||||
}
|
||||
|
||||
public String getColumnList(Class clazz, String tableName) {
|
||||
return getColumnList(clazz, false, tableName, true);
|
||||
return getColumnList(clazz, true, tableName, true);
|
||||
}
|
||||
|
||||
public String getColumnList(Class clazz, boolean isSql, String tableName, boolean includeForcedRecalc) {
|
||||
@@ -444,22 +486,6 @@ public class EntityPropertyHolder {
|
||||
return null;
|
||||
}
|
||||
|
||||
public List<EntityHierarchyDTO> getEntityMapping() {
|
||||
Reflections reflections = new Reflections("it.integry.ems_model.entity");
|
||||
List<EntityHierarchyDTO> mapping = new ArrayList<>();
|
||||
Set<Class<? extends EntityBase>> classes = reflections.getSubTypesOf(EntityBase.class);
|
||||
for (Class<? extends EntityBase> entity : classes) {
|
||||
if (entity.isAnnotationPresent(Master.class)) {
|
||||
EntityHierarchyDTO dto = new EntityHierarchyDTO();
|
||||
dto.setEntityName(entity.getSimpleName());
|
||||
dto.setTableName(entity.getAnnotation(Table.class).value());
|
||||
dto.setChildren(getEntityChildren(entity));
|
||||
mapping.add(dto);
|
||||
}
|
||||
}
|
||||
return mapping;
|
||||
}
|
||||
|
||||
public List<EntityHierarchyDTO> getEntityChildren(Class<? extends EntityBase> entity) {
|
||||
List<EntityHierarchyDTO> children = new ArrayList<>();
|
||||
Field[] fields = entity.getDeclaredFields();
|
||||
@@ -478,14 +504,16 @@ public class EntityPropertyHolder {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (childEntity.equals(entity)) {
|
||||
//ignoro le entity autoreferenziate
|
||||
continue;
|
||||
}
|
||||
EntityHierarchyDTO dto = new EntityHierarchyDTO();
|
||||
dto.setClazz(childEntity);
|
||||
dto.setEntityName(childEntity.getSimpleName());
|
||||
dto.setTableName(childEntity.getAnnotation(Table.class).value());
|
||||
dto.setChildren(getEntityChildren(childEntity));
|
||||
|
||||
if (!childEntity.equals(entity))
|
||||
//Prendo i fields solo delle entity non autoreferenziate
|
||||
dto.setChildren(getEntityChildren(childEntity));
|
||||
|
||||
dto.setField(field);
|
||||
children.add(dto);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -789,7 +789,7 @@ public class ProductionBusinessLogic {
|
||||
for (int a = 0; a < elencoFasiAss.length; a++) {
|
||||
datiDist.setIdRigaStep(datiDist.getIdRigaStep() + 1);
|
||||
|
||||
if (pesoInQtaLav){
|
||||
if (pesoInQtaLav) {
|
||||
qtaLav = qtaProd.divide(rapConv, EmsRestConstants.cifreDecMax, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
@@ -1198,8 +1198,8 @@ public class ProductionBusinessLogic {
|
||||
userName = userNameLav;
|
||||
}
|
||||
|
||||
// Verifica se l'articolo prevede l'obbligo del codice di commessa, in tal caso si blocca la procedura
|
||||
// il campo COD_JCOM_REQUIRED può contenere o S/N se qualciasi produzione deve avere la specifica della commessa,
|
||||
// Verifica se l'articolo prevede l'obbligo del codice di commessa, in tal caso si blocca la procedura.
|
||||
// Il campo COD_JCOM_REQUIRED può contenere o S/N se qualsiasi produzione deve avere la specifica della commessa,
|
||||
// oppure la specifica di una etichetta (Disegni) sui quali prodotti è necessario specificare la commessa
|
||||
String codJcomRequired = UtilityString.isNull(setupOrdProdGest.get("COD_JCOM_REQUIRED"), "");
|
||||
|
||||
@@ -1223,6 +1223,7 @@ public class ProductionBusinessLogic {
|
||||
|
||||
count = UtilityDB.executeSimpleQueryOnlyFirstRowFirstColumn(conn, sql);
|
||||
}
|
||||
|
||||
if (count != 0 && (codJcom == null || codJcom.equals(EmsRestConstants.NULL))) {
|
||||
throw new Exception("Il prodotto " + codProd + " prevede il codice commessa obbligatoriamente, impossibile procedere alla generazione dell'ordine di produzione");
|
||||
}
|
||||
|
||||
@@ -150,10 +150,6 @@ public class EmsRestConstants {
|
||||
public static final String PATH_EXPORT_PRODOTTI_CQ = PATH + "exportProdottiCQ";
|
||||
public static final String PATH_IMPORT_ORDINI_CQ = PATH + "importOrdiniCQ";
|
||||
public static final String PATH_SELECT_RAW_DATA = PATH + "selectRawData";
|
||||
public static final String PATH_ASYNC_BASE_ROUTE = PATH + "async_v2";
|
||||
public static final String PATH_ASYNC_START = PATH + "start";
|
||||
public static final String PATH_ASYNC_RETRIEVE_TRANSACTIONS = PATH + "retrieveTransactions";
|
||||
public static final String PATH_ASYNC_UPDATE_TRANSACTION_IMPORT_ID = PATH + "updateTransactionImportID";
|
||||
public static final String PATH_ACCETTAZIONE = PATH + "accettazione";
|
||||
public static final String PATH_PICKING = PATH + "picking";
|
||||
public static final String PATH_PICKING_ORDINE = PATH + "pickingOrdine";
|
||||
@@ -295,6 +291,7 @@ public class EmsRestConstants {
|
||||
public static final String PATH_DELETE_ACTIVITY = PATH + "activity/delete";
|
||||
public static final String PATH_GET_COMMESSA_FROM_USERNAME = PATH + "activity/getCommessaFromUsername";
|
||||
public static final String PATH_GET_ACTIVITY_HISTORY = PATH + "activity/getActivityHistory";
|
||||
public static final String PATH_SET_ACTIVITY_SOLVED = PATH + "activity/activitySolved";
|
||||
//SteUP
|
||||
public static final String PATH_LOGIN_STEUP = PATH + "login";
|
||||
public static final String PATH_LOGINAZIENDA_STEUP = PATH + "loginAzienda";
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
package it.integry.ems_model.db;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.microsoft.sqlserver.jdbc.SQLServerResultSet;
|
||||
import it.integry.ems.expansion.RunnableArgs;
|
||||
import it.integry.ems.expansion.RunnableArgsWithReturn;
|
||||
import it.integry.ems.utility.UtilityDebug;
|
||||
import it.integry.ems_model.ImportExport.Interfaces.IExportFormat;
|
||||
import it.integry.ems_model.ImportExport.Interfaces.IImportFormat;
|
||||
import it.integry.ems_model.annotation.Clob;
|
||||
import it.integry.ems_model.annotation.MapToTable;
|
||||
import it.integry.ems_model.annotation.SqlField;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.exception.DataConverterNotFoundException;
|
||||
import it.integry.ems_model.resolver.SqlFieldHolder;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Type;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.util.*;
|
||||
|
||||
public class AsyncResultSetMapper {
|
||||
|
||||
|
||||
private final Logger logger = LogManager.getLogger();
|
||||
|
||||
|
||||
@NotNull
|
||||
public static List<HashMap<String, Object>> mapResultSetToHashMap(ResultSet rs) throws SQLException {
|
||||
ResultSetMetaData md = rs.getMetaData();
|
||||
int columns = md.getColumnCount();
|
||||
List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
|
||||
while (rs.next()) {
|
||||
HashMap<String, Object> row = new HashMap<String, Object>(columns);
|
||||
for (int i = 1; i <= columns; ++i) {
|
||||
row.put(md.getColumnName(i), rs.getObject(i));
|
||||
}
|
||||
list.add(row);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static Map.Entry<String[], List<Object[]>> mapResultSetToArray(ResultSet rs) throws SQLException {
|
||||
ResultSetMetaData md = rs.getMetaData();
|
||||
int columns = md.getColumnCount();
|
||||
|
||||
String[] columnNames = new String[columns];
|
||||
for (int i = 1; i <= columns; ++i) {
|
||||
columnNames[i - 1] = md.getColumnName(i).toLowerCase();
|
||||
}
|
||||
|
||||
List<Object[]> rowsValues = new ArrayList<>();
|
||||
|
||||
while (rs.next()) {
|
||||
Object[] singleRowValues = new Object[columns];
|
||||
|
||||
for (int i = 1; i <= columns; ++i) {
|
||||
singleRowValues[i - 1] = rs.getObject(i);
|
||||
}
|
||||
|
||||
rowsValues.add(singleRowValues);
|
||||
}
|
||||
|
||||
rs.close();
|
||||
return new AbstractMap.SimpleEntry<>(columnNames, rowsValues);
|
||||
}
|
||||
|
||||
public <T> void mapResultSetToList(SQLServerResultSet rs, Class<T> outputClass, RunnableArgs<T> onElementRetrieved) throws SQLException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
mapResultSetToList(rs, outputClass, null, true, onElementRetrieved);
|
||||
}
|
||||
|
||||
public <T> void mapResultSetToList(SQLServerResultSet rs, Class<T> outputClass, OperationType operation, RunnableArgs<T> onElementRetrieved)
|
||||
throws SQLException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
mapResultSetToList(rs, outputClass, operation, true, onElementRetrieved);
|
||||
}
|
||||
|
||||
public <T> void mapResultSetToList(SQLServerResultSet rs, Class<T> outputClass, OperationType operation, Boolean onlyPKMaster, RunnableArgs<T> onElementRetrieved) throws SQLException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
if (rs != null) {
|
||||
|
||||
Field[] fields;
|
||||
if (IExportFormat.class.isAssignableFrom(outputClass) || IImportFormat.class.isAssignableFrom(outputClass)) {
|
||||
fields = outputClass.getSuperclass().getDeclaredFields();
|
||||
} else {
|
||||
fields = outputClass.getDeclaredFields();
|
||||
}
|
||||
|
||||
internalMappingList(rs, outputClass, fields, onElementRetrieved);
|
||||
|
||||
// if (outputList != null && !outputList.isEmpty() && EntityBase.class.isAssignableFrom(outputClass)) {
|
||||
// for (T bean : outputList) {
|
||||
// if (operation != null) {
|
||||
// ((EntityBase) bean).setOperation(operation);
|
||||
// }
|
||||
//
|
||||
// if (onlyPKMaster != null) {
|
||||
// ((EntityBase) bean).setOnlyPkMaster(onlyPKMaster);
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
// return outputList != null && !outputList.isEmpty() ? outputList : null;
|
||||
}
|
||||
|
||||
private <T> void internalMappingList(SQLServerResultSet resultSet, Class<T> outputClass, Field[] fields, RunnableArgs<T> onElementRetrieved) throws SQLException, DataConverterNotFoundException, InstantiationException, IllegalAccessException {
|
||||
final HashMap<Integer, RunnableArgsWithReturn<Object, Object>> columnToConverterMap = new HashMap<>();
|
||||
final HashMap<Integer, Field> columnToFieldMap = new HashMap<>();
|
||||
|
||||
final ResultSetMetaData metaData = resultSet.getMetaData();
|
||||
|
||||
for (int i = 0; i < metaData.getColumnCount(); i++) {
|
||||
String columnName = metaData.getColumnName(i + 1).toLowerCase();
|
||||
|
||||
final Field field = Arrays.stream(fields)
|
||||
.filter(x -> x.isAnnotationPresent(SqlField.class) && x.getAnnotation(SqlField.class).value().equalsIgnoreCase(columnName))
|
||||
.findFirst().orElse(null);
|
||||
|
||||
if (field == null)
|
||||
continue;
|
||||
|
||||
field.setAccessible(true);
|
||||
|
||||
final int columnType = metaData.getColumnType(i + 1);
|
||||
final RunnableArgsWithReturn<Object, Object> converter = SqlFieldHolder.getConverter(UtilityDB.sqlTypeToJavaClass(columnType), field.getType());
|
||||
|
||||
columnToConverterMap.put(i + 1, converter);
|
||||
columnToFieldMap.put(i + 1, field);
|
||||
}
|
||||
|
||||
while (resultSet.next()) {
|
||||
final T outputObject = outputClass.newInstance();
|
||||
|
||||
for (Integer columnIndex : columnToConverterMap.keySet()) {
|
||||
Object obj = resultSet.getObject(columnIndex);
|
||||
Object convertedObject = columnToConverterMap.get(columnIndex).run(obj);
|
||||
columnToFieldMap.get(columnIndex).set(outputObject, convertedObject);
|
||||
}
|
||||
|
||||
onElementRetrieved.run(outputObject);
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
// final Map.Entry<String[], List<Object[]>> listPair = mapResultSetToArray(resultSet);
|
||||
//
|
||||
// List<String> columnNames = Arrays.asList(listPair.getKey());
|
||||
// List<Object[]> columnValuesList = listPair.getValue();
|
||||
//
|
||||
// if (columnValuesList == null || columnValuesList.isEmpty())
|
||||
// return null;
|
||||
//
|
||||
// List<Field> fieldsWithAnnotations = Stream.of(fields)
|
||||
// .filter(x -> x.isAnnotationPresent(SqlField.class) || x.isAnnotationPresent(JsonProperty.class) || x.isAnnotationPresent(MapToTable.class))
|
||||
// .toList();
|
||||
//
|
||||
// if (fieldsWithAnnotations.isEmpty()) {
|
||||
// System.out.println("Attenzione nella classe non sono presenti elementi con le seguenti annotazioni @SqlField, @JsonProperty, @MapToTable. Nessun campo sarà mappato nella classe");
|
||||
// }
|
||||
//
|
||||
//
|
||||
// final List<ResultSetMappingField> resultSetMappingFields = scanResultSetFields(fields, columnNames, columnTypesFromResultSet);
|
||||
// final HashMap<Field, List<ResultSetMappingField>> entityChildsResultSetMappingField = new HashMap<>();
|
||||
//
|
||||
// //Searching entities
|
||||
// List<Field> entityFields = fieldsWithAnnotations.stream()
|
||||
// .filter(x -> EntityBase.class.isAssignableFrom(x.getType()))
|
||||
// .collect(Collectors.toList());
|
||||
//
|
||||
// for (Field entityField : entityFields) {
|
||||
// Field[] entityChildFields = entityField.getType().getDeclaredFields();
|
||||
// entityChildsResultSetMappingField.put(entityField, scanResultSetFields(entityChildFields, columnNames, columnTypesFromResultSet));
|
||||
// }
|
||||
//
|
||||
//
|
||||
//
|
||||
// for (int i = 0; i < listPair.getValue().size(); i++) {
|
||||
// T bean = outputClass.newInstance();
|
||||
// Object[] columnValues = columnValuesList.get(i);
|
||||
//
|
||||
// for (ResultSetMappingField resultSetMappingField : resultSetMappingFields) {
|
||||
// Object columnValue = columnValues[resultSetMappingField.getColumnIndex()];
|
||||
//
|
||||
// if (resultSetMappingField.getConverter() != null && columnValue != null) {
|
||||
// columnValue = resultSetMappingField.getConverter().run(columnValue);
|
||||
// resultSetMappingField.getField().set(bean, columnValue);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// for (Field entityChildResultSetMappingField : entityChildsResultSetMappingField.keySet()) {
|
||||
// EntityBase entityChildBean = (EntityBase) entityChildResultSetMappingField.getType().newInstance();
|
||||
// entityChildBean.setOperation(OperationType.SELECT_OBJECT);
|
||||
// entityChildResultSetMappingField.set(bean, entityChildBean);
|
||||
//
|
||||
// List<ResultSetMappingField> entityChildResultSetMappingFieldList = entityChildsResultSetMappingField.get(entityChildResultSetMappingField);
|
||||
//
|
||||
// for (ResultSetMappingField entityChildResultSetMapping : entityChildResultSetMappingFieldList) {
|
||||
// Object columnValue = columnValues[entityChildResultSetMapping.getColumnIndex()];
|
||||
//
|
||||
// if (entityChildResultSetMapping.getConverter() != null && columnValue != null) {
|
||||
// columnValue = entityChildResultSetMapping.getConverter().run(columnValue);
|
||||
// entityChildResultSetMapping.getField().set(entityChildBean, columnValue);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// values.add(bean);
|
||||
// }
|
||||
//
|
||||
// return values;
|
||||
}
|
||||
|
||||
|
||||
private List<ResultSetMappingField> scanResultSetFields(Field[] fields, List<String> columnNames, HashMap<String, Type> sqlTypes) throws DataConverterNotFoundException {
|
||||
final List<ResultSetMappingField> resultSetMappingFields = new ArrayList<>();
|
||||
|
||||
for (Field field : fields) {
|
||||
field.setAccessible(true);
|
||||
|
||||
if (!field.isAnnotationPresent(SqlField.class) && !field.isAnnotationPresent(JsonProperty.class) && !field.isAnnotationPresent(MapToTable.class)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String columnName;
|
||||
if (field.isAnnotationPresent(SqlField.class)) {
|
||||
SqlField column = field.getAnnotation(SqlField.class);
|
||||
columnName = !UtilityString.isNullOrEmpty(column.value()) ? column.value() : field.getName();
|
||||
|
||||
} else if (field.isAnnotationPresent(MapToTable.class)) {
|
||||
columnName = field.getAnnotation(MapToTable.class).value();
|
||||
|
||||
} else if (field.isAnnotationPresent(JsonProperty.class)) {
|
||||
columnName = field.getAnnotation(JsonProperty.class).value();
|
||||
} else continue;
|
||||
|
||||
if (EntityBase.class.isAssignableFrom(field.getType()))
|
||||
continue;
|
||||
|
||||
columnName = columnName.toLowerCase();
|
||||
|
||||
Type sqlType = sqlTypes.get(columnName);
|
||||
Type entityType = field.getGenericType();
|
||||
|
||||
if (sqlType == null)
|
||||
continue;
|
||||
|
||||
|
||||
RunnableArgsWithReturn<Object, Object> converter;
|
||||
if (field.isAnnotationPresent(Clob.class)) {
|
||||
converter = data -> Base64.encodeBase64String(data.toString().getBytes());
|
||||
} else
|
||||
converter = SqlFieldHolder.getConverter(sqlType, entityType);
|
||||
|
||||
if (converter == null) {
|
||||
if (UtilityDebug.isDebugExecution() || UtilityDebug.isIntegryServer())
|
||||
throw new DataConverterNotFoundException(columnName, sqlType.getTypeName(), entityType.getTypeName());
|
||||
|
||||
logger.warn(String.format("Converter non trovato per colonna %s, sqlType %s -> dtoType %s", columnName, sqlType.getTypeName(), entityType.getTypeName()));
|
||||
}
|
||||
|
||||
resultSetMappingFields.add(new ResultSetMappingField()
|
||||
.setField(field)
|
||||
.setColumnName(columnName)
|
||||
.setFieldName(field.getName())
|
||||
.setConverter(converter)
|
||||
.setColumnIndex(columnNames.indexOf(columnName)));
|
||||
}
|
||||
|
||||
return resultSetMappingFields;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -7,14 +7,16 @@ import it.integry.ems_model.annotation.PK;
|
||||
import it.integry.ems_model.annotation.SqlField;
|
||||
import it.integry.ems_model.annotation.Table;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.db.ResultSetMapper;
|
||||
import it.integry.ems_model.utility.UtilityDB;
|
||||
import org.kie.api.definition.type.PropertyReactive;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.*;
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import it.integry.ems_model.annotation.FK;
|
||||
|
||||
@Master
|
||||
@PropertyReactive
|
||||
@@ -123,6 +125,9 @@ public class Azienda extends EntityBase {
|
||||
@SqlField(value = "last_upg_sp", maxLength = 40, nullable = true)
|
||||
private String lastUpgSp;
|
||||
|
||||
@SqlField(value = "last_upg_db_menu", maxLength = 10, nullable = false)
|
||||
private String lastUpgDbMenu;
|
||||
|
||||
@SqlField(value = "sito_web", maxLength = 255, nullable = true)
|
||||
private String sitoWeb;
|
||||
|
||||
@@ -559,6 +564,15 @@ public class Azienda extends EntityBase {
|
||||
this.lastUpgSp = lastUpgSp;
|
||||
}
|
||||
|
||||
public String getLastUpgDbMenu() {
|
||||
return lastUpgDbMenu;
|
||||
}
|
||||
|
||||
public Azienda setLastUpgDbMenu(String lastUpgDbMenu) {
|
||||
this.lastUpgDbMenu = lastUpgDbMenu;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getSitoWeb() {
|
||||
return sitoWeb;
|
||||
}
|
||||
|
||||
@@ -504,13 +504,17 @@ public class CtbMovr extends EntityBase {
|
||||
@Override
|
||||
public void checkPreSave() throws Exception {
|
||||
// TODO -MINA Valutare completamento ctb_movr_coan
|
||||
for (CtbMovrCoan ctbMovrCoan : getCtbMovrCoan()) {
|
||||
ctbMovrCoan.setIdRiga(getIdRiga());
|
||||
if (getCtbMovrCoan() != null ) {
|
||||
for (CtbMovrCoan ctbMovrCoan : getCtbMovrCoan()) {
|
||||
ctbMovrCoan.setIdRiga(getIdRiga());
|
||||
}
|
||||
}
|
||||
for (CtbParr ctbParr : getCtbParr()) {
|
||||
ctbParr.setIdRiga(getIdRiga());
|
||||
if (getCtbParr() != null ) {
|
||||
for (CtbParr ctbParr : getCtbParr()) {
|
||||
ctbParr.setIdRiga(getIdRiga());
|
||||
}
|
||||
}
|
||||
if (getCtbScad() != null ){
|
||||
if (getCtbScad() != null ) {
|
||||
for (CtbScad ctbScad : getCtbScad()) {
|
||||
ctbScad.setIdRigaMov(getIdRiga());
|
||||
}
|
||||
@@ -519,14 +523,18 @@ public class CtbMovr extends EntityBase {
|
||||
|
||||
@Override
|
||||
protected void insertChilds() throws Exception {
|
||||
for (CtbMovrCoan ctbMovrCoan : getCtbMovrCoan()) {
|
||||
ctbMovrCoan.manageWithParentConnection(connection, ctbMovrCoan.getOperation(), dataCompleting, entityHolder);
|
||||
}
|
||||
for (CtbParr ctbParr : getCtbParr()) {
|
||||
if (!UtilityString.isNullOrEmpty(ctbParr.getDesAgg()) && ctbParr.getDesAgg().length() > 40) {
|
||||
ctbParr.setDesAgg(ctbParr.getDesAgg().substring(0, 39));
|
||||
if ( getCtbMovrCoan() != null ) {
|
||||
for (CtbMovrCoan ctbMovrCoan : getCtbMovrCoan()) {
|
||||
ctbMovrCoan.manageWithParentConnection(connection, ctbMovrCoan.getOperation(), dataCompleting, entityHolder);
|
||||
}
|
||||
}
|
||||
if ( getCtbParr() != null ) {
|
||||
for (CtbParr ctbParr : getCtbParr()) {
|
||||
if (!UtilityString.isNullOrEmpty(ctbParr.getDesAgg()) && ctbParr.getDesAgg().length() > 40) {
|
||||
ctbParr.setDesAgg(ctbParr.getDesAgg().substring(0, 39));
|
||||
}
|
||||
ctbParr.manageWithParentConnection(connection, ctbParr.getOperation(), dataCompleting, entityHolder);
|
||||
}
|
||||
ctbParr.manageWithParentConnection(connection, ctbParr.getOperation(), dataCompleting, entityHolder);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -86,6 +86,8 @@ public class CtbParr extends EntityBase {
|
||||
|
||||
private Integer tipoPartita;
|
||||
|
||||
private BigDecimal cambioDiviScad;
|
||||
|
||||
@Priority(value = 101, copyPk = false)
|
||||
private List<CtbScad> ctbScad;
|
||||
|
||||
@@ -258,6 +260,16 @@ public class CtbParr extends EntityBase {
|
||||
this.tipoPartita = tipoPartita;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BigDecimal getCambioDiviScad() {
|
||||
return cambioDiviScad;
|
||||
}
|
||||
|
||||
public CtbParr setCambioDiviScad(BigDecimal cambioDiviScad) {
|
||||
this.cambioDiviScad = cambioDiviScad;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<CtbScad> getCtbScad() {
|
||||
return ctbScad;
|
||||
}
|
||||
|
||||
@@ -114,6 +114,7 @@ public class CtbPart extends EntityBase {
|
||||
@SqlField(value = "flag_verificata", maxLength = 1, nullable = false, defaultObjectValue = "N")
|
||||
private String flagVerificata;
|
||||
|
||||
@ImportFromParent
|
||||
@SqlField(value = "num_doc_forn", maxLength = 40, nullable = true)
|
||||
private String numDocForn;
|
||||
|
||||
|
||||
@@ -376,10 +376,12 @@ public class CtbScad extends EntityBase {
|
||||
|
||||
@Override
|
||||
protected void insertChilds() throws Exception {
|
||||
for (CrlScadParr crlScadParr: getCrlScadParr()) {
|
||||
if ( crlScadParr.getIdRigaScad() == null ) crlScadParr.setIdRigaScad(getIdRiga());
|
||||
if ( crlScadParr.getIdRigaMov() == null ) crlScadParr.setIdRigaMov(getIdRigaMov());
|
||||
crlScadParr.manageWithParentConnection(connection, crlScadParr.getOperation(), dataCompleting, entityHolder);
|
||||
if ( getCrlScadParr() != null ) {
|
||||
for (CrlScadParr crlScadParr : getCrlScadParr()) {
|
||||
if (crlScadParr.getIdRigaScad() == null) crlScadParr.setIdRigaScad(getIdRiga());
|
||||
if (crlScadParr.getIdRigaMov() == null) crlScadParr.setIdRigaMov(getIdRigaMov());
|
||||
crlScadParr.manageWithParentConnection(connection, crlScadParr.getOperation(), dataCompleting, entityHolder);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -316,6 +316,9 @@ public class DtbDoct extends DtbBaseDocT {
|
||||
|
||||
@SqlField(value = "cod_lingua", nullable = true)
|
||||
private String codLingua;
|
||||
|
||||
@SqlField(value = "id_lotto", nullable = true)
|
||||
private Integer idLotto;
|
||||
@JsonProperty(value = "explodeKit")
|
||||
private String explodeKit;
|
||||
|
||||
@@ -1206,6 +1209,14 @@ public class DtbDoct extends DtbBaseDocT {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Integer getIdLotto() {
|
||||
return idLotto;
|
||||
}
|
||||
|
||||
public void setIdLotto(Integer idLotto) {
|
||||
this.idLotto = idLotto;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExplodeKit() {
|
||||
return explodeKit;
|
||||
|
||||
@@ -57,6 +57,12 @@ public class DtbFatturePassive extends EntityBase {
|
||||
@EntityChild
|
||||
private List<DtbFatturePassiveScad> dtbFatturePassiveScad;
|
||||
|
||||
@EntityChild
|
||||
private List<DtbFatturePassiveIva> dtbFatturePassiveIva;
|
||||
|
||||
@EntityChild
|
||||
private List<DtbFatturePassiveDdt> dtbFatturePassiveDdt;
|
||||
|
||||
public String getIdAttach() {
|
||||
return idAttach;
|
||||
}
|
||||
@@ -150,6 +156,26 @@ public class DtbFatturePassive extends EntityBase {
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<DtbFatturePassiveIva> getDtbFatturePassiveIva() {
|
||||
if (dtbFatturePassiveIva == null) dtbFatturePassiveIva = new ArrayList<>();
|
||||
return dtbFatturePassiveIva;
|
||||
}
|
||||
|
||||
public DtbFatturePassive setDtbFatturePassiveIva(List<DtbFatturePassiveIva> dtbFatturePassiveIva) {
|
||||
this.dtbFatturePassiveIva = dtbFatturePassiveIva;
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<DtbFatturePassiveDdt> getDtbFatturePassiveDdt() {
|
||||
if (dtbFatturePassiveDdt == null) dtbFatturePassiveDdt = new ArrayList<>();
|
||||
return dtbFatturePassiveDdt;
|
||||
}
|
||||
|
||||
public DtbFatturePassive setDtbFatturePassiveDdt(List<DtbFatturePassiveDdt> dtbFatturePassiveDdt) {
|
||||
this.dtbFatturePassiveDdt = dtbFatturePassiveDdt;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkPreSave() throws Exception {
|
||||
}
|
||||
@@ -159,6 +185,14 @@ public class DtbFatturePassive extends EntityBase {
|
||||
for (DtbFatturePassiveScad dtbFatturePassiveScad : getDtbFatturePassiveScad()) {
|
||||
dtbFatturePassiveScad.manageWithParentConnection(connection, dtbFatturePassiveScad.getOperation(), dataCompleting, entityHolder);
|
||||
}
|
||||
|
||||
for (DtbFatturePassiveIva dtbFatturePassiveIva : getDtbFatturePassiveIva()){
|
||||
dtbFatturePassiveIva.manageWithParentConnection(connection, dtbFatturePassiveIva.getOperation(), dataCompleting, entityHolder);
|
||||
}
|
||||
|
||||
for (DtbFatturePassiveDdt dtbFatturePassiveDdt : getDtbFatturePassiveDdt()){
|
||||
dtbFatturePassiveDdt.manageWithParentConnection(connection, dtbFatturePassiveDdt.getOperation(), dataCompleting, entityHolder);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -176,5 +210,11 @@ public class DtbFatturePassive extends EntityBase {
|
||||
for (StbFilesAttached stbFilesAttached : listAllegati) {
|
||||
stbFilesAttached.manageWithParentConnection(connection, dtbFatturePassiveScad.getOperation(), dataCompleting, entityHolder);
|
||||
}
|
||||
|
||||
DtbFatturePassiveIva dtbFatturePassiveIva = new DtbFatturePassiveIva();
|
||||
dtbFatturePassiveIva.deleteAllEntities(connection, this);
|
||||
|
||||
DtbFatturePassiveDdt dtbFatturePassiveDdt = new DtbFatturePassiveDdt();
|
||||
dtbFatturePassiveDdt.deleteAllEntities(connection, this);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package it.integry.ems_model.entity;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
import it.integry.ems_model.annotation.*;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import org.kie.api.definition.type.PropertyReactive;
|
||||
|
||||
import java.util.Date;
|
||||
|
||||
@PropertyReactive
|
||||
@Table(DtbFatturePassiveDdt.ENTITY)
|
||||
@JsonTypeName(DtbFatturePassiveDdt.ENTITY)
|
||||
public class DtbFatturePassiveDdt extends EntityBase {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public static final String ENTITY = "dtb_fatture_passive_ddt";
|
||||
|
||||
@Identity
|
||||
@PK
|
||||
@SqlField(value = "id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@ImportFromParent
|
||||
@SqlField(value = "id_attach", maxLength = 40, nullable = false)
|
||||
private String idAttach;
|
||||
|
||||
@SqlField(value = "numero", maxLength = 15, nullable = false)
|
||||
private String numero;
|
||||
|
||||
@SqlField(value = "data", nullable = false)
|
||||
private Date data;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public DtbFatturePassiveDdt setId(Long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getIdAttach() {
|
||||
return idAttach;
|
||||
}
|
||||
|
||||
public DtbFatturePassiveDdt setIdAttach(String idAttach) {
|
||||
this.idAttach = idAttach;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getNumero() {
|
||||
return numero;
|
||||
}
|
||||
|
||||
public DtbFatturePassiveDdt setNumero(String numero) {
|
||||
this.numero = numero;
|
||||
return this;
|
||||
}
|
||||
|
||||
public Date getData() {
|
||||
return data;
|
||||
}
|
||||
|
||||
public DtbFatturePassiveDdt setData(Date data) {
|
||||
this.data = data;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkPreSave() throws Exception {}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package it.integry.ems_model.entity;
|
||||
|
||||
import it.integry.ems_model.annotation.*;
|
||||
import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.types.OperationType;
|
||||
import org.kie.api.definition.type.PropertyReactive;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeName;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@PropertyReactive
|
||||
@Table(DtbFatturePassiveIva.ENTITY)
|
||||
@JsonTypeName(DtbFatturePassiveIva.ENTITY)
|
||||
public class DtbFatturePassiveIva extends EntityBase {
|
||||
private static final long serialVersionUID = 1L;
|
||||
public static final String ENTITY = "dtb_fatture_passive_iva";
|
||||
|
||||
@Identity
|
||||
@PK
|
||||
@SqlField(value = "id", nullable = false)
|
||||
private Long id;
|
||||
|
||||
@ImportFromParent
|
||||
@SqlField(value = "id_attach", maxLength = 40, nullable = false)
|
||||
private String idAttach;
|
||||
|
||||
@SqlField(value = "perc_iva", defaultObjectValue="0", nullable = false)
|
||||
private BigDecimal percIva;
|
||||
|
||||
@SqlField(value = "imponibile", defaultObjectValue="0", nullable = false)
|
||||
private BigDecimal imponibile;
|
||||
|
||||
@SqlField(value = "imposta", defaultObjectValue="0", nullable = false)
|
||||
private BigDecimal imposta;
|
||||
|
||||
@SqlField(value = "natura", maxLength = 5)
|
||||
private String natura;
|
||||
|
||||
@SqlField(value = "esigibilita", maxLength = 1)
|
||||
private String esigibilita;
|
||||
|
||||
public Long getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public DtbFatturePassiveIva setId(Long id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getIdAttach() {
|
||||
return idAttach;
|
||||
}
|
||||
|
||||
public DtbFatturePassiveIva setIdAttach(String idAttach) {
|
||||
this.idAttach = idAttach;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BigDecimal getPercIva() {
|
||||
return percIva;
|
||||
}
|
||||
|
||||
public DtbFatturePassiveIva setPercIva(BigDecimal percIva) {
|
||||
this.percIva = percIva;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BigDecimal getImponibile() {
|
||||
return imponibile;
|
||||
}
|
||||
|
||||
public DtbFatturePassiveIva setImponibile(BigDecimal imponibile) {
|
||||
this.imponibile = imponibile;
|
||||
return this;
|
||||
}
|
||||
|
||||
public BigDecimal getImposta() {
|
||||
return imposta;
|
||||
}
|
||||
|
||||
public DtbFatturePassiveIva setImposta(BigDecimal imposta) {
|
||||
this.imposta = imposta;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getNatura() {
|
||||
return natura;
|
||||
}
|
||||
|
||||
public DtbFatturePassiveIva setNatura(String natura) {
|
||||
this.natura = natura;
|
||||
return this;
|
||||
}
|
||||
|
||||
public String getEsigibilita() {
|
||||
return esigibilita;
|
||||
}
|
||||
|
||||
public DtbFatturePassiveIva setEsigibilita(String esigibilita) {
|
||||
this.esigibilita = esigibilita;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkPreSave() throws Exception {}
|
||||
|
||||
}
|
||||
@@ -454,6 +454,7 @@ public class DtbOrdt extends DtbDocOrdT {
|
||||
|
||||
private VtbDest vtbDest;
|
||||
|
||||
private Boolean flagScollegaPartitaMag = false;
|
||||
public DtbOrdt() {
|
||||
super();
|
||||
}
|
||||
@@ -1720,6 +1721,14 @@ public class DtbOrdt extends DtbDocOrdT {
|
||||
return this;
|
||||
}
|
||||
|
||||
public Boolean getFlagScollegaPartitaMag() {
|
||||
return flagScollegaPartitaMag;
|
||||
}
|
||||
|
||||
public void setFlagScollegaPartitaMag(Boolean flagScollegaPartitaMag) {
|
||||
this.flagScollegaPartitaMag = flagScollegaPartitaMag;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void checkPreSave() throws Exception {
|
||||
switch (getOperation()) {
|
||||
|
||||
@@ -30,7 +30,7 @@ public class JrlCiclDisegni extends EntityBase {
|
||||
private BigDecimal qta;
|
||||
|
||||
@SqlField(value = "riga_ord", nullable = false, defaultObjectValue = "0")
|
||||
private Integer rigaOrd;
|
||||
private BigDecimal rigaOrd;
|
||||
|
||||
public JrlCiclDisegni() {
|
||||
super();
|
||||
@@ -60,11 +60,11 @@ public class JrlCiclDisegni extends EntityBase {
|
||||
this.qta = qta;
|
||||
}
|
||||
|
||||
public Integer getRigaOrd() {
|
||||
public BigDecimal getRigaOrd() {
|
||||
return rigaOrd;
|
||||
}
|
||||
|
||||
public void setRigaOrd(Integer rigaOrd) {
|
||||
public void setRigaOrd(BigDecimal rigaOrd) {
|
||||
this.rigaOrd = rigaOrd;
|
||||
}
|
||||
|
||||
|
||||
@@ -9,9 +9,9 @@ import it.integry.ems_model.base.EntityBase;
|
||||
import it.integry.ems_model.entity._enum.IBaseEnum;
|
||||
import it.integry.ems_model.utility.UtilityString;
|
||||
import org.kie.api.definition.type.PropertyReactive;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
@PropertyReactive
|
||||
@Table(MtbColr.ENTITY)
|
||||
@@ -561,7 +561,7 @@ public class MtbColr extends EntityBase {
|
||||
}
|
||||
|
||||
protected void insertChilds() throws Exception {
|
||||
if ( getMtbColrInfoProd() != null ) {
|
||||
if (getMtbColrInfoProd() != null) {
|
||||
getMtbColrInfoProd().setRiga(riga);
|
||||
getMtbColrInfoProd().manageWithParentConnection(connection, getMtbColrInfoProd().getOperation(), dataCompleting, entityHolder);
|
||||
}
|
||||
@@ -579,18 +579,18 @@ public class MtbColr extends EntityBase {
|
||||
}
|
||||
|
||||
|
||||
public enum Causale implements IBaseEnum {
|
||||
public enum Causale implements IBaseEnum<Causale> {
|
||||
|
||||
DEFAULT(0), RETTIFICA(1), VERSAMENTO(2);
|
||||
DEFAULT((short) 0), RETTIFICA((short) 1), VERSAMENTO((short) 2);
|
||||
|
||||
private final int value;
|
||||
private final short value;
|
||||
|
||||
Causale(int value) {
|
||||
Causale(short value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public static Causale from(Object value) {
|
||||
int castValue = (int) value;
|
||||
short castValue = (short) value;
|
||||
for (Causale b : Causale.values()) {
|
||||
if (b.value == castValue)
|
||||
return b;
|
||||
@@ -599,7 +599,7 @@ public class MtbColr extends EntityBase {
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public int getValue() {
|
||||
public short getValue() {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
@@ -609,7 +609,7 @@ public class MtbColr extends EntityBase {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object fromInternal(Object val) {
|
||||
public Causale fromInternal(Object val) {
|
||||
return from(val);
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user