From 7a3f9bd79c8fec7717490995085a969ac25696ff Mon Sep 17 00:00:00 2001 From: Frederic Bregier Date: Thu, 18 Jul 2019 11:25:58 +0200 Subject: [PATCH 1/3] Add Junit to v3.1.0 --- .gitignore | 74 +- pom.xml | 25 +- .../client/AbstractBusinessRequest.java | 7 + .../waarp/openr66/client/DirectTransfer.java | 16 + .../client/MultipleDirectTransfer.java | 13 + .../client/MultipleSubmitTransfer.java | 16 + .../dao/database/h2/H2TransferDAO.java | 2 +- .../openr66/database/data/DbHostAuth.java | 6 - .../protocol/configuration/Configuration.java | 8 + .../http/restv2/RestServiceInitializer.java | 2 +- .../localhandler/TransferActions.java | 4 +- .../openr66/server/ServerInitDatabase.java | 45 + .../{java => resources}/messages.properties | 0 .../messages_en.properties | 0 .../messages_fr.properties | 0 .../restmessages.properties | 0 .../restmessages_en.properties | 0 .../restmessages_fr.properties | 0 src/test/java/.gitkeep | 0 .../openr66/dao/database/DBAllDAOTest.java | 972 +++++++++ .../openr66/dao/database/DBBusinessDAOIT.java | 189 -- .../openr66/dao/database/DBHostDAOIT.java | 199 -- .../openr66/dao/database/DBLimitDAOIT.java | 193 -- .../dao/database/DBMultipleMonitorDAOIT.java | 179 -- .../openr66/dao/database/DBRuleDAOIT.java | 210 -- .../openr66/dao/database/DBTransferDAOIT.java | 192 -- .../openr66/dao/database/ScriptRunner.java | 456 ++-- .../openr66/dao/database/h2/DbH2DAOTest.java | 61 + .../mariadb/DBBusinessMariaDBDAOIT.java | 39 - .../database/mariadb/DBHostMariaDBDAOIT.java | 39 - .../database/mariadb/DBLimitMariaDBDAOIT.java | 39 - .../DBMultipleMonitorMariaDBDAOIT.java | 39 - .../database/mariadb/DBRuleMariaDBDAOIT.java | 39 - .../mariadb/DBTransferMariaDBDAOIT.java | 48 - .../database/mariadb/DbMariadbDAOTest.java | 66 + .../database/mySQL/DBBusinessMySQLDAOIT.java | 39 - .../dao/database/mySQL/DBHostMySQLDAOIT.java | 39 - .../dao/database/mySQL/DBLimitMySQLDAOIT.java | 39 - .../mySQL/DBMultipleMonitorMySQLDAOIT.java | 39 - .../database/mySQL/DBMySQLDAOTransfer.java | 66 + .../dao/database/mySQL/DBRuleMySQLDAOIT.java | 39 - .../database/mySQL/DBTransferMySQLDAOIT.java | 47 - .../oracle/DBBusinessOracleDBDAOIT.java | 39 - .../database/oracle/DBHostOracleDBDAOIT.java | 39 - .../database/oracle/DBLimitOracleDBDAOIT.java | 39 - .../DBMultipleMonitorOracleDBDAOIT.java | 39 - .../database/oracle/DBOracleDBDAOTest.java | 66 + .../database/oracle/DBRuleOracleDBDAOIT.java | 39 - .../oracle/DBTransferOracleDBDAOIT.java | 47 - .../postgres/DBBusinessPostgreSQLDAOIT.java | 39 - .../postgres/DBHostPostgreSQLDAOIT.java | 39 - .../postgres/DBLimitPostgreSQLDAOIT.java | 39 - .../DBMultipleMonitorPostgreSQLDAOIT.java | 39 - .../postgres/DBPostgreSQLDAOTest.java | 65 + .../postgres/DBRulePostgreSQLDAOIT.java | 39 - .../postgres/DBTransferPostgreSQLDAOIT.java | 47 - .../http/rest/test/HttpTestR66PseudoMain.java | 143 +- .../rest/test/HttpTestResponseHandler.java | 489 +++-- .../test/HttpTestRestClientInitializer.java | 73 +- .../http/rest/test/HttpTestRestR66Client.java | 1928 +++++++++-------- .../openr66/protocol/junit/AllTasksTest.java | 68 + .../protocol/junit/NetworkClientTest.java | 1238 +++++++++++ .../junit/NetworkTransactionTest.java | 48 + .../openr66/protocol/junit/TestAbstract.java | 260 +++ .../protocol/junit/TestAbstractMinimal.java | 96 + .../protocol/junit/WaarpLoggerListener.java | 258 +++ .../json/TransferRequestJsonPacketTest.java | 135 +- .../NetworkTransactionTest.java | 27 - .../protocol/test/TestBusinessRequest.java | 269 +-- .../protocol/test/TestJsonGenerator.java | 131 -- .../test/TestProgressBarTransfer.java | 310 +-- .../protocol/test/TestRecvThroughClient.java | 230 +- .../protocol/test/TestSendThroughClient.java | 375 ++-- .../protocol/test/TestSendThroughForward.java | 408 ++-- .../protocol/test/TestSubmitTransfer.java | 185 +- .../openr66/protocol/test/TestTasks.java | 357 ++- .../test/TestThriftClientExample.java | 245 ++- .../protocol/test/TestTransaction.java | 237 +- .../protocol/test/TestTransferNoDb.java | 287 ++- .../openr66/protocol/test/package-info.java | 22 +- src/test/resources/Linux/config/OPENR66-MIB | 867 ++++++++ .../Linux/config/OpenR66-authent-A.xml | 52 + .../resources/Linux/config/certs/client1.cer | Bin 0 -> 937 bytes .../resources/Linux/config/certs/client1.der | Bin 0 -> 1218 bytes .../resources/Linux/config/certs/client2.cer | Bin 0 -> 937 bytes .../resources/Linux/config/certs/client2.der | Bin 0 -> 1219 bytes .../resources/Linux/config/certs/client3.cer | Bin 0 -> 937 bytes .../resources/Linux/config/certs/client3.der | Bin 0 -> 1219 bytes .../resources/Linux/config/certs/key.sha256 | 1 + .../Linux/config/certs/servercert.cer | Bin 0 -> 937 bytes .../Linux/config/certs/serverpriv.der | Bin 0 -> 1218 bytes .../resources/Linux/config/certs/test-key.des | 1 + .../Linux/config/certs/test-passwd-http.ggp | 1 + .../Linux/config/certs/test-passwd.ggp | 1 + .../Linux/config/certs/test-passwd2.ggp | 1 + .../Linux/config/certs/test-passwd3.ggp | 1 + .../resources/Linux/config/certs/testcert.jks | Bin 0 -> 3907 bytes .../Linux/config/certs/testclient.jks | Bin 0 -> 1003 bytes .../Linux/config/certs/testclient1.jks | Bin 0 -> 2291 bytes .../Linux/config/certs/testclient2.jks | Bin 0 -> 2292 bytes .../Linux/config/certs/testclient3.jks | Bin 0 -> 2292 bytes .../Linux/config/certs/testsslclient.jks | Bin 0 -> 609 bytes .../Linux/config/certs/testsslnocert.jks | Bin 0 -> 2293 bytes .../resources/Linux/config/config-clientA.xml | 41 + .../resources/Linux/config/config-clientB.xml | 40 + .../Linux/config/config-clientNoDB.xml | 36 + .../Linux/config/config-clientNoDB_B.xml | 38 + .../Linux/config/config-clientSubmitA.xml | 23 + .../config-clienttest-spooled-multiple.xml | 94 + .../Linux/config/config-clienttest.xml | 33 + .../Linux/config/config-serverA-minimal.xml | 101 + .../resources/Linux/config/config-serverA.xml | 121 ++ .../resources/Linux/config/config-serverB.xml | 79 + .../Linux/config/config-serverInitA.xml | 56 + .../Linux/config/config-serverInitB.xml | 58 + .../Linux/config/dummyBootCounter.agent | Bin 0 -> 11983 bytes .../resources/Linux/config/dummyConf.agent | Bin 0 -> 10 bytes .../resources/Linux/config/limitConfiga.xml | 15 + .../resources/Linux/config/logback-client.xml | 35 + .../Linux/config/logback-clientDebug.xml | 35 + .../Linux/config/logback-service.xml | 34 + src/test/resources/Linux/config/logback.xml | 34 + .../Linux/config/rulerecv-any.rule.xml | 86 + .../resources/Linux/config/rulerecv.rule.xml | 70 + .../Linux/config/rulerecvthrough-any.rule.xml | 66 + .../Linux/config/rulesend-any.rule.xml | 66 + .../resources/Linux/config/rulesend.rule.xml | 75 + .../Linux/config/rulesendthrough-any.rule.xml | 66 + .../resources/Linux/config/snmpconfig.xml | 99 + src/test/resources/h2/clean.sql | 8 + src/test/resources/h2/create.sql | 130 ++ src/test/resources/h2/populate.sql | 62 + src/test/resources/logback-test.xml | 24 +- src/test/resources/mariadb/clean.sql | 7 + src/test/resources/mariadb/create.sql | 116 + src/test/resources/mariadb/populate.sql | 62 + src/test/resources/mysql/create.sql | 4 +- src/test/resources/oracle/clean.sql | 1 + src/test/resources/oracle/create.sql | 13 +- src/test/resources/postgresql/clean.sql | 12 +- 140 files changed, 9597 insertions(+), 5088 deletions(-) rename src/main/{java => resources}/messages.properties (100%) rename src/main/{java => resources}/messages_en.properties (100%) rename src/main/{java => resources}/messages_fr.properties (100%) rename src/main/{java => resources}/restmessages.properties (100%) rename src/main/{java => resources}/restmessages_en.properties (100%) rename src/main/{java => resources}/restmessages_fr.properties (100%) create mode 100644 src/test/java/.gitkeep create mode 100644 src/test/java/org/waarp/openr66/dao/database/DBAllDAOTest.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/DBBusinessDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/DBHostDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/DBLimitDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/DBMultipleMonitorDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/DBRuleDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/DBTransferDAOIT.java create mode 100644 src/test/java/org/waarp/openr66/dao/database/h2/DbH2DAOTest.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mariadb/DBBusinessMariaDBDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mariadb/DBHostMariaDBDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mariadb/DBLimitMariaDBDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mariadb/DBMultipleMonitorMariaDBDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mariadb/DBRuleMariaDBDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mariadb/DBTransferMariaDBDAOIT.java create mode 100644 src/test/java/org/waarp/openr66/dao/database/mariadb/DbMariadbDAOTest.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mySQL/DBBusinessMySQLDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mySQL/DBHostMySQLDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mySQL/DBLimitMySQLDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mySQL/DBMultipleMonitorMySQLDAOIT.java create mode 100644 src/test/java/org/waarp/openr66/dao/database/mySQL/DBMySQLDAOTransfer.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mySQL/DBRuleMySQLDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/mySQL/DBTransferMySQLDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/oracle/DBBusinessOracleDBDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/oracle/DBHostOracleDBDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/oracle/DBLimitOracleDBDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/oracle/DBMultipleMonitorOracleDBDAOIT.java create mode 100644 src/test/java/org/waarp/openr66/dao/database/oracle/DBOracleDBDAOTest.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/oracle/DBRuleOracleDBDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/oracle/DBTransferOracleDBDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/postgres/DBBusinessPostgreSQLDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/postgres/DBHostPostgreSQLDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/postgres/DBLimitPostgreSQLDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/postgres/DBMultipleMonitorPostgreSQLDAOIT.java create mode 100644 src/test/java/org/waarp/openr66/dao/database/postgres/DBPostgreSQLDAOTest.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/postgres/DBRulePostgreSQLDAOIT.java delete mode 100644 src/test/java/org/waarp/openr66/dao/database/postgres/DBTransferPostgreSQLDAOIT.java create mode 100644 src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java create mode 100644 src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java create mode 100644 src/test/java/org/waarp/openr66/protocol/junit/NetworkTransactionTest.java create mode 100644 src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java create mode 100644 src/test/java/org/waarp/openr66/protocol/junit/TestAbstractMinimal.java create mode 100644 src/test/java/org/waarp/openr66/protocol/junit/WaarpLoggerListener.java delete mode 100644 src/test/java/org/waarp/openr66/protocol/networkhandler/NetworkTransactionTest.java delete mode 100644 src/test/java/org/waarp/openr66/protocol/test/TestJsonGenerator.java create mode 100755 src/test/resources/Linux/config/OPENR66-MIB create mode 100755 src/test/resources/Linux/config/OpenR66-authent-A.xml create mode 100755 src/test/resources/Linux/config/certs/client1.cer create mode 100755 src/test/resources/Linux/config/certs/client1.der create mode 100755 src/test/resources/Linux/config/certs/client2.cer create mode 100755 src/test/resources/Linux/config/certs/client2.der create mode 100755 src/test/resources/Linux/config/certs/client3.cer create mode 100755 src/test/resources/Linux/config/certs/client3.der create mode 100755 src/test/resources/Linux/config/certs/key.sha256 create mode 100755 src/test/resources/Linux/config/certs/servercert.cer create mode 100755 src/test/resources/Linux/config/certs/serverpriv.der create mode 100755 src/test/resources/Linux/config/certs/test-key.des create mode 100755 src/test/resources/Linux/config/certs/test-passwd-http.ggp create mode 100755 src/test/resources/Linux/config/certs/test-passwd.ggp create mode 100755 src/test/resources/Linux/config/certs/test-passwd2.ggp create mode 100755 src/test/resources/Linux/config/certs/test-passwd3.ggp create mode 100755 src/test/resources/Linux/config/certs/testcert.jks create mode 100755 src/test/resources/Linux/config/certs/testclient.jks create mode 100755 src/test/resources/Linux/config/certs/testclient1.jks create mode 100755 src/test/resources/Linux/config/certs/testclient2.jks create mode 100755 src/test/resources/Linux/config/certs/testclient3.jks create mode 100755 src/test/resources/Linux/config/certs/testsslclient.jks create mode 100755 src/test/resources/Linux/config/certs/testsslnocert.jks create mode 100755 src/test/resources/Linux/config/config-clientA.xml create mode 100755 src/test/resources/Linux/config/config-clientB.xml create mode 100755 src/test/resources/Linux/config/config-clientNoDB.xml create mode 100755 src/test/resources/Linux/config/config-clientNoDB_B.xml create mode 100755 src/test/resources/Linux/config/config-clientSubmitA.xml create mode 100755 src/test/resources/Linux/config/config-clienttest-spooled-multiple.xml create mode 100755 src/test/resources/Linux/config/config-clienttest.xml create mode 100755 src/test/resources/Linux/config/config-serverA-minimal.xml create mode 100755 src/test/resources/Linux/config/config-serverA.xml create mode 100755 src/test/resources/Linux/config/config-serverB.xml create mode 100755 src/test/resources/Linux/config/config-serverInitA.xml create mode 100755 src/test/resources/Linux/config/config-serverInitB.xml create mode 100644 src/test/resources/Linux/config/dummyBootCounter.agent create mode 100644 src/test/resources/Linux/config/dummyConf.agent create mode 100755 src/test/resources/Linux/config/limitConfiga.xml create mode 100755 src/test/resources/Linux/config/logback-client.xml create mode 100755 src/test/resources/Linux/config/logback-clientDebug.xml create mode 100755 src/test/resources/Linux/config/logback-service.xml create mode 100755 src/test/resources/Linux/config/logback.xml create mode 100755 src/test/resources/Linux/config/rulerecv-any.rule.xml create mode 100755 src/test/resources/Linux/config/rulerecv.rule.xml create mode 100755 src/test/resources/Linux/config/rulerecvthrough-any.rule.xml create mode 100755 src/test/resources/Linux/config/rulesend-any.rule.xml create mode 100755 src/test/resources/Linux/config/rulesend.rule.xml create mode 100755 src/test/resources/Linux/config/rulesendthrough-any.rule.xml create mode 100755 src/test/resources/Linux/config/snmpconfig.xml create mode 100644 src/test/resources/h2/clean.sql create mode 100644 src/test/resources/h2/create.sql create mode 100644 src/test/resources/h2/populate.sql create mode 100644 src/test/resources/mariadb/clean.sql create mode 100644 src/test/resources/mariadb/create.sql create mode 100644 src/test/resources/mariadb/populate.sql diff --git a/.gitignore b/.gitignore index e53798096..bc42b324e 100644 --- a/.gitignore +++ b/.gitignore @@ -17,11 +17,6 @@ local.properties .loadpath .pmd -############ -## Intellij -############ -.idea - # External tool builders .externalToolBuilders/ @@ -34,19 +29,34 @@ local.properties # PDT-specific .buildpath - -################# -# Intellij -################# -.idea -src/main/java/resources/ - ################# ## Java ################# +# Compiled class file *.class *.jardesc +# Log file +*.log + +# BlueJ files +*.ctxt + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.nar +*.ear +*.zip +*.tar.gz +*.rar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + ################# ## Visual Studio ################# @@ -144,3 +154,43 @@ Thumbs.db Desktop.ini runtime.properties + +############### +## Intellij +############### +# User-specific stuff +.idea/ + +# Gradle and Maven with auto-import +# When using Gradle or Maven with auto-import, you should exclude module files, +# since they will be recreated, and may cause churn. Uncomment if using +# auto-import. +.idea/modules.xml +.idea/*.iml +.idea/modules +*.iml +*.ipr + +# CMake +cmake-build-*/ + +# File-based project format +*.iws + +# IntelliJ +out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties +fabric.properties + +*.log + diff --git a/pom.xml b/pom.xml index 78aac5990..e3c745ba7 100644 --- a/pom.xml +++ b/pom.xml @@ -75,7 +75,7 @@ Waarp WaarpCommon - 3.0.12 + 3.1.0 xml-apis @@ -98,7 +98,7 @@ com.h2database h2 - 1.4.197 + 1.4.199 true @@ -115,13 +115,13 @@ Waarp WaarpExec - 3.0.4 + 3.0.5 true Waarp WaarpSnmp - 3.0.6 + 3.0.7 true @@ -137,7 +137,7 @@ Waarp WaarpThrift - 3.0.6 + 3.0.7 true @@ -149,7 +149,7 @@ org.postgresql postgresql - 42.2.5.jre6 + 42.2.6.jre6 true @@ -167,12 +167,12 @@ Waarp WaarpGatewayKernel - 3.0.10 + 3.1.0 Waarp WaarpFtpClient - 3.0.6 + 3.0.7 junit @@ -230,6 +230,13 @@ netty-http 1.2.0 + + org.apache.ant + ant + 1.10.6 + test + + @@ -253,7 +260,7 @@ 1.6 1.6 true - true + true diff --git a/src/main/java/org/waarp/openr66/client/AbstractBusinessRequest.java b/src/main/java/org/waarp/openr66/client/AbstractBusinessRequest.java index e855d12bf..1310d1b39 100644 --- a/src/main/java/org/waarp/openr66/client/AbstractBusinessRequest.java +++ b/src/main/java/org/waarp/openr66/client/AbstractBusinessRequest.java @@ -22,6 +22,7 @@ import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; import org.waarp.openr66.client.utils.OutputFormat; import org.waarp.openr66.configuration.FileBasedConfiguration; import org.waarp.openr66.context.ErrorCode; @@ -149,6 +150,9 @@ public static void main(String[] args) { if (DbConstant.admin != null && DbConstant.admin.isActive()) { DbConstant.admin.close(); } + if (DetectionUtils.isJunit()) { + return; + } ChannelUtils.stopLogger(); System.exit(2); } @@ -181,6 +185,9 @@ public static void main(String[] args) { " " + rhost + "" + " " + future.getCause() + "" + " delay: " + delay); + if (DetectionUtils.isJunit()) { + return; + } networkTransaction.closeAll(); System.exit(ErrorCode.Unknown.ordinal()); } diff --git a/src/main/java/org/waarp/openr66/client/DirectTransfer.java b/src/main/java/org/waarp/openr66/client/DirectTransfer.java index 2a080e7e3..216d86404 100644 --- a/src/main/java/org/waarp/openr66/client/DirectTransfer.java +++ b/src/main/java/org/waarp/openr66/client/DirectTransfer.java @@ -20,6 +20,7 @@ import org.waarp.common.database.exception.WaarpDatabaseException; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; import org.waarp.openr66.client.utils.OutputFormat; import org.waarp.openr66.client.utils.OutputFormat.FIELDS; import org.waarp.openr66.commander.ClientRunner; @@ -139,6 +140,9 @@ public static void main(String[] args) { if (DbConstant.admin != null && DbConstant.admin.isActive()) { DbConstant.admin.close(); } + if (DetectionUtils.isJunit()) { + return; + } ChannelUtils.stopLogger(); System.exit(2); } @@ -191,6 +195,9 @@ public static void main(String[] args) { e); } } + if (DetectionUtils.isJunit()) { + return; + } networkTransaction.closeAll(); System.exit(0); } else { @@ -203,6 +210,9 @@ public static void main(String[] args) { if (!OutputFormat.isQuiet()) { outputFormat.sysout(); } + if (DetectionUtils.isJunit()) { + return; + } networkTransaction.closeAll(); System.exit(ErrorCode.Unknown.ordinal()); } @@ -226,6 +236,9 @@ public static void main(String[] args) { if (!OutputFormat.isQuiet()) { outputFormat.sysout(); } + if (DetectionUtils.isJunit()) { + return; + } networkTransaction.closeAll(); System.exit(result.getCode().ordinal()); } @@ -233,6 +246,9 @@ public static void main(String[] args) { logger.error("Exception", e); } finally { logger.debug("finish transfer: " + future.isDone() + ":" + future.isSuccess()); + if (DetectionUtils.isJunit()) { + return; + } networkTransaction.closeAll(); // In case something wrong append if (future.isDone() && future.isSuccess()) { diff --git a/src/main/java/org/waarp/openr66/client/MultipleDirectTransfer.java b/src/main/java/org/waarp/openr66/client/MultipleDirectTransfer.java index 89af357bc..a34dc4978 100644 --- a/src/main/java/org/waarp/openr66/client/MultipleDirectTransfer.java +++ b/src/main/java/org/waarp/openr66/client/MultipleDirectTransfer.java @@ -25,6 +25,7 @@ import org.waarp.common.database.exception.WaarpDatabaseException; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; import org.waarp.openr66.client.utils.OutputFormat; import org.waarp.openr66.client.utils.OutputFormat.FIELDS; import org.waarp.openr66.context.ErrorCode; @@ -224,6 +225,9 @@ public void run() { logger.error(outputFormat.loggerOut(), future.getCause()); outputFormat.setValue(FIELDS.error.name(), future.getCause().getMessage()); outputFormat.sysout(); + if (DetectionUtils.isJunit()) { + return; + } networkTransaction.closeAll(); System.exit(ErrorCode.Unknown.ordinal()); } @@ -283,6 +287,9 @@ public static void main(String[] args) { if (DbConstant.admin != null && DbConstant.admin.isActive()) { DbConstant.admin.close(); } + if (DetectionUtils.isJunit()) { + return; + } ChannelUtils.stopLogger(); System.exit(2); } @@ -342,12 +349,18 @@ public static void main(String[] args) { result.sysout(); } } + if (DetectionUtils.isJunit()) { + return; + } networkTransaction.closeAll(); System.exit(multipleDirectTransfer.getErrorMultiple()); } } catch (Throwable e) { logger.error("Exception", e); } finally { + if (DetectionUtils.isJunit()) { + return; + } networkTransaction.closeAll(); System.exit(0); } diff --git a/src/main/java/org/waarp/openr66/client/MultipleSubmitTransfer.java b/src/main/java/org/waarp/openr66/client/MultipleSubmitTransfer.java index 8f5755cfb..722ffed14 100644 --- a/src/main/java/org/waarp/openr66/client/MultipleSubmitTransfer.java +++ b/src/main/java/org/waarp/openr66/client/MultipleSubmitTransfer.java @@ -24,6 +24,7 @@ import org.waarp.common.database.exception.WaarpDatabaseException; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; import org.waarp.openr66.client.utils.OutputFormat; import org.waarp.openr66.client.utils.OutputFormat.FIELDS; import org.waarp.openr66.context.R66Result; @@ -83,11 +84,17 @@ public void run() { dbrule = new DbRule(rulename); } catch (WaarpDatabaseException e) { logger.error(Messages.getString("SubmitTransfer.2") + rule); //$NON-NLS-1$ + if (DetectionUtils.isJunit()) { + return; + } ChannelUtils.stopLogger(); System.exit(2); } if (!submit && dbrule.isRecvMode() && networkTransaction == null) { logger.error(Messages.getString("Configuration.WrongInit") + " => -client argument is missing"); //$NON-NLS-1$ + if (DetectionUtils.isJunit()) { + return; + } ChannelUtils.stopLogger(); System.exit(2); } @@ -197,6 +204,9 @@ public static void main(String[] args) { if (DbConstant.admin != null && DbConstant.admin.isActive()) { DbConstant.admin.close(); } + if (DetectionUtils.isJunit()) { + return; + } ChannelUtils.stopLogger(); System.exit(1); } @@ -239,6 +249,9 @@ public static void main(String[] args) { networkTransaction = null; } DbConstant.admin.close(); + if (DetectionUtils.isJunit()) { + return; + } ChannelUtils.stopLogger(); System.exit(0); } else { @@ -263,6 +276,9 @@ public static void main(String[] args) { networkTransaction = null; } DbConstant.admin.close(); + if (DetectionUtils.isJunit()) { + return; + } ChannelUtils.stopLogger(); System.exit(transaction.getErrorMultiple()); } diff --git a/src/main/java/org/waarp/openr66/dao/database/h2/H2TransferDAO.java b/src/main/java/org/waarp/openr66/dao/database/h2/H2TransferDAO.java index 541c79281..32bd9cff0 100644 --- a/src/main/java/org/waarp/openr66/dao/database/h2/H2TransferDAO.java +++ b/src/main/java/org/waarp/openr66/dao/database/h2/H2TransferDAO.java @@ -10,7 +10,7 @@ public class H2TransferDAO extends DBTransferDAO { - protected static String SQL_GET_ID = "SELECT NEXTVAL(runseq)"; + protected static String SQL_GET_ID = "SELECT NEXTVAL('RUNSEQ')"; public H2TransferDAO(Connection con) throws DAOException { super(con); diff --git a/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java b/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java index debcedac4..e840e3b43 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java +++ b/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java @@ -215,7 +215,6 @@ protected void setPrimaryKey() { primaryKey[0].setValue(host.getHostid()); } /** - * @param dbSession * @param hostid * @param address * @param port @@ -282,7 +281,6 @@ public void setFromJson(ObjectNode node, boolean ignorePrimaryKey) throws WaarpD } /** - * @param dbSession * @param hostid * @throws WaarpDatabaseException */ @@ -310,7 +308,6 @@ public DbHostAuth(String hostid) throws WaarpDatabaseException { /** * Delete all entries (used when purge and reload) * - * @param dbSession * @return the previous existing array of DbRule * @throws WaarpDatabaseException */ @@ -421,8 +418,6 @@ private DbHostAuth() { /** * Get All DbHostAuth from database or from internal hashMap in case of no database support * - * @param dbSession - * may be null * @return the array of DbHostAuth * @throws WaarpDatabaseNoConnectionException * @throws WaarpDatabaseSqlException @@ -866,7 +861,6 @@ public String toSpecializedHtml(R66Session session, String body, boolean crypted /** * - * @param session * @return True if any of the server has the isProxified property */ public static boolean hasProxifiedHosts() { diff --git a/src/main/java/org/waarp/openr66/protocol/configuration/Configuration.java b/src/main/java/org/waarp/openr66/protocol/configuration/Configuration.java index 2590ea2e1..c4393d0ea 100644 --- a/src/main/java/org/waarp/openr66/protocol/configuration/Configuration.java +++ b/src/main/java/org/waarp/openr66/protocol/configuration/Configuration.java @@ -59,6 +59,7 @@ import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.role.RoleDefault; +import org.waarp.common.utility.DetectionUtils; import org.waarp.common.utility.SystemPropertyUtil; import org.waarp.common.utility.WaarpNettyUtil; import org.waarp.common.utility.WaarpShutdownHook; @@ -714,6 +715,9 @@ public void serverStartup() throws WaarpDatabaseNoConnectionException, logger.debug("Use NoSSL: " + isUseNOSSL() + " Use SSL: " + isUseSSL()); if ((!isUseNOSSL()) && (!isUseSSL())) { logger.error(Messages.getString("Configuration.NoSSL")); //$NON-NLS-1$ + if (DetectionUtils.isJunit()) { + return; + } System.exit(-1); } pipelineInit(); @@ -872,6 +876,10 @@ public void startMonitoring() throws WaarpDatabaseSqlException { } } + public void startJunitRestSupport(RestConfiguration config) { + HttpRestR66Handler.initializeService(config); + } + public InternalRunner getInternalRunner() { return internalRunner; } diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/RestServiceInitializer.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/RestServiceInitializer.java index 1fc2375df..8458ce068 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/RestServiceInitializer.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/RestServiceInitializer.java @@ -219,7 +219,7 @@ public static void stopRestService() { if (restService != null) { try { restService.stop(); - } catch (Exception e) { + } catch (Throwable e) { logger.error("Exception caught during RESTv2 service shutdown", e); } } else { diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/TransferActions.java b/src/main/java/org/waarp/openr66/protocol/localhandler/TransferActions.java index 411690ed4..5944a4d7a 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/TransferActions.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/TransferActions.java @@ -721,7 +721,7 @@ public void data(Channel channel, DataPacket packet) logger.error( Messages.getString("LocalServerHandler.17"), packet, localChannelReference.getPartner().getDigestAlgo().name); //$NON-NLS-1$ errorToSend("Transfer in error due to bad Hash on data packet (" - + localChannelReference.getPartner().getDigestAlgo().name + ")", + + localChannelReference.getPartner().getDigestAlgo().name+ ")", ErrorCode.MD5Error, channel, 21); packet.clear(); return; @@ -849,7 +849,7 @@ public void endTransfer(Channel channel, EndTransferPacket packet) //session.getRunner().setRankAtStartup(0); R66Result result = new R66Result(new OpenR66RunnerErrorException( Messages.getString("LocalServerHandler.19") + //$NON-NLS-1$ - localChannelReference.getPartner().getDigestAlgo().name + ")"), + localChannelReference.getPartner().getDigestAlgo().name+ ")"), session, true, ErrorCode.MD5Error, session.getRunner()); try { session.setFinalizeTransfer(false, result); diff --git a/src/main/java/org/waarp/openr66/server/ServerInitDatabase.java b/src/main/java/org/waarp/openr66/server/ServerInitDatabase.java index c76dafb1c..ff3586993 100644 --- a/src/main/java/org/waarp/openr66/server/ServerInitDatabase.java +++ b/src/main/java/org/waarp/openr66/server/ServerInitDatabase.java @@ -27,6 +27,7 @@ import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; import org.waarp.openr66.configuration.AuthenticationFileBasedConfiguration; import org.waarp.openr66.configuration.FileBasedConfiguration; import org.waarp.openr66.configuration.RuleFileBasedConfiguration; @@ -112,6 +113,9 @@ public static void main(String[] args) { if (DbConstant.admin != null && DbConstant.admin.isActive()) { DbConstant.admin.close(); } + if (DetectionUtils.isJunit()) { + return; + } ChannelUtils.stopLogger(); System.exit(2); } @@ -121,6 +125,10 @@ public static void main(String[] args) { Configuration.configuration, args[0], database)) { System.err.format(Messages.getString( "Configuration.NeedCorrectConfig")); + System.err.println(); + if (DetectionUtils.isJunit()) { + return; + } ChannelUtils.stopLogger(); System.exit(2); } @@ -128,66 +136,95 @@ public static void main(String[] args) { // Init database System.out.format(Messages.getString( "ServerInitDatabase.Create.Start")); + System.out.println(); initdb(); System.out.format(Messages.getString( "ServerInitDatabase.Create.Done")); + System.out.println(); } if (upgradeDb) { // try to upgrade DB schema System.out.format(Messages.getString( "ServerInitDatabase.Upgrade.Start")); + System.out.println(); // TODO Split check for update and upgrade actions if (!upgradedb()) { System.err.println(Messages.getString( "ServerInitDatabase.SchemaNotUptodate")); + System.err.println(); + if (DetectionUtils.isJunit()) { + return; + } System.exit(1); } System.out.format(Messages.getString( "ServerInitDatabase.Upgrade.Done")); + System.out.println(); } if (sdirconfig != null) { // load Rules System.out.format(Messages.getString( "ServerInitDatabase.LoadRule.Start"), sdirconfig); + System.out.println(); File dirConfig = new File(sdirconfig); if (dirConfig.isDirectory()) { if (!loadRules(dirConfig)) { System.out.format(Messages.getString( "ServerInitDatabase.LoadRule.Failed")); + if (DetectionUtils.isJunit()) { + return; + } System.exit(1); } } else { System.err.format(Messages.getString( "ServerInitDatabase.LoadRule.NoDirectory"), sdirconfig); + System.err.println(); + if (DetectionUtils.isJunit()) { + return; + } System.exit(1); } System.out.format(Messages.getString( "ServerInitDatabase.LoadRule.Done")); + System.out.println(); } if (shostauth != null) { // Load Host Authentications System.out.format(Messages.getString( "ServerInitDatabase.LoadAuth.Start"), shostauth); + System.out.println(); if (!loadHostAuth(shostauth)) { System.err.format(Messages.getString( "ServerInitDatabase.LoadAuth.Failed")); + System.err.println(); + if (DetectionUtils.isJunit()) { + return; + } System.exit(1); } System.out.format(Messages.getString( "ServerInitDatabase.LoadAuth.Done")); + System.out.println(); } if (slimitconfig != null) { // Load configuration System.out.format(Messages.getString( "ServerInitDatabase.LoadLimit.Start"), slimitconfig); + System.out.println(); if (!FileBasedConfiguration.setConfigurationLoadLimitFromXml( Configuration.configuration, slimitconfig)) { System.err.format(Messages.getString( "ServerInitDatabase.LoadLimit.Failed")); + System.err.println(); + if (DetectionUtils.isJunit()) { + return; + } System.exit(1); } System.out.format(Messages.getString( "ServerInitDatabase.LoadLimit.Done")); + System.out.println(); } if (sbusiness != null || salias != null || sroles != null) { if (sbusiness != null) { @@ -222,10 +259,18 @@ public static void main(String[] args) { } System.out.println(Messages.getString( "ServerInitDatabase.LoadDone")); + System.out.println(); + if (DetectionUtils.isJunit()) { + return; + } System.exit(0); } catch (WaarpDatabaseException e) { System.err.println(Messages.getString( "ServerInitDatabase.ErrDatabase")); + System.err.println(); + if (DetectionUtils.isJunit()) { + return; + } System.exit(3); } finally { if (DbConstant.admin != null) { diff --git a/src/main/java/messages.properties b/src/main/resources/messages.properties similarity index 100% rename from src/main/java/messages.properties rename to src/main/resources/messages.properties diff --git a/src/main/java/messages_en.properties b/src/main/resources/messages_en.properties similarity index 100% rename from src/main/java/messages_en.properties rename to src/main/resources/messages_en.properties diff --git a/src/main/java/messages_fr.properties b/src/main/resources/messages_fr.properties similarity index 100% rename from src/main/java/messages_fr.properties rename to src/main/resources/messages_fr.properties diff --git a/src/main/java/restmessages.properties b/src/main/resources/restmessages.properties similarity index 100% rename from src/main/java/restmessages.properties rename to src/main/resources/restmessages.properties diff --git a/src/main/java/restmessages_en.properties b/src/main/resources/restmessages_en.properties similarity index 100% rename from src/main/java/restmessages_en.properties rename to src/main/resources/restmessages_en.properties diff --git a/src/main/java/restmessages_fr.properties b/src/main/resources/restmessages_fr.properties similarity index 100% rename from src/main/java/restmessages_fr.properties rename to src/main/resources/restmessages_fr.properties diff --git a/src/test/java/.gitkeep b/src/test/java/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/src/test/java/org/waarp/openr66/dao/database/DBAllDAOTest.java b/src/test/java/org/waarp/openr66/dao/database/DBAllDAOTest.java new file mode 100644 index 000000000..9e1ae1fab --- /dev/null +++ b/src/test/java/org/waarp/openr66/dao/database/DBAllDAOTest.java @@ -0,0 +1,972 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +package org.waarp.openr66.dao.database; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.dao.BusinessDAO; +import org.waarp.openr66.dao.Filter; +import org.waarp.openr66.dao.HostDAO; +import org.waarp.openr66.dao.LimitDAO; +import org.waarp.openr66.dao.MultipleMonitorDAO; +import org.waarp.openr66.dao.RuleDAO; +import org.waarp.openr66.dao.TransferDAO; +import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.pojo.Business; +import org.waarp.openr66.pojo.Host; +import org.waarp.openr66.pojo.Limit; +import org.waarp.openr66.pojo.MultipleMonitor; +import org.waarp.openr66.pojo.Rule; +import org.waarp.openr66.pojo.Transfer; +import org.waarp.openr66.pojo.UpdatedInfo; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.net.URL; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Timestamp; +import java.util.ArrayList; + +import static org.junit.Assert.*; + +public abstract class DBAllDAOTest { + + private Connection con; + + public void runScript(String script) { + try { + ScriptRunner runner = new ScriptRunner(con, false, true); + URL url = + Thread.currentThread().getContextClassLoader().getResource(script); + runner.runScript(new BufferedReader(new FileReader(url.getPath()))); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Before + public void setUp() { + try { + con = getConnection(); + initDB(); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + public abstract Connection getConnection() throws SQLException; + + public abstract void initDB() throws SQLException; + + @After + public void wrapUp() { + try { + cleanDB(); + con.close(); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + public abstract void cleanDB() throws SQLException; + + /******************* + * BUSINESS + *******************/ + @Test + public void testDeleteAllBusiness() { + try { + BusinessDAO dao = new DBBusinessDAO(getConnection()); + dao.deleteAll(); + + ResultSet res = con.createStatement() + .executeQuery("SELECT * FROM hostconfig"); + assertEquals(false, res.next()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testDeleteBusiness() { + try { + BusinessDAO dao = new DBBusinessDAO(getConnection()); + dao.delete(new Business("server1", "", "", "", "")); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM hostconfig where hostid = 'server1'"); + assertEquals(false, res.next()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testGetAllBusiness() { + try { + BusinessDAO dao = new DBBusinessDAO(getConnection()); + assertEquals(5, dao.getAll().size()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testSelectBusiness() { + try { + BusinessDAO dao = new DBBusinessDAO(getConnection()); + Business business = dao.select("server1"); + Business business2 = dao.select("ghost"); + + assertEquals("joyaux", business.getBusiness()); + assertEquals("marchand", business.getRoles()); + assertEquals("le borgne", business.getAliases()); + assertEquals("misc", business.getOthers()); + assertEquals(UpdatedInfo.NOTUPDATED, business.getUpdatedInfo()); + assertEquals(null, business2); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testExistBusiness() { + try { + BusinessDAO dao = new DBBusinessDAO(getConnection()); + assertEquals(true, dao.exist("server1")); + assertEquals(false, dao.exist("ghost")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + @Test + public void testInsertBusiness() { + try { + BusinessDAO dao = new DBBusinessDAO(getConnection()); + dao.insert(new Business("chacha", + "lolo", "lala", "minou", "ect", + UpdatedInfo.TOSUBMIT)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT COUNT(1) as count FROM hostconfig"); + res.next(); + assertEquals(6, res.getInt("count")); + + ResultSet res2 = con.createStatement() + .executeQuery( + "SELECT * FROM hostconfig WHERE hostid = 'chacha'"); + res2.next(); + assertEquals("chacha", res2.getString("hostid")); + assertEquals("lolo", res2.getString("business")); + assertEquals("lala", res2.getString("roles")); + assertEquals("minou", res2.getString("aliases")); + assertEquals("ect", res2.getString("others")); + assertEquals(UpdatedInfo.TOSUBMIT.ordinal(), res2.getInt("updatedInfo")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testUpdateBusiness() { + try { + BusinessDAO dao = new DBBusinessDAO(getConnection()); + dao.update(new Business("server2", + "lolo", "lala", "minou", "ect", + UpdatedInfo.RUNNING)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM hostconfig WHERE hostid = 'server2'"); + res.next(); + assertEquals("server2", res.getString("hostid")); + assertEquals("lolo", res.getString("business")); + assertEquals("lala", res.getString("roles")); + assertEquals("minou", res.getString("aliases")); + assertEquals("ect", res.getString("others")); + assertEquals(UpdatedInfo.RUNNING.ordinal(), res.getInt("updatedInfo")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + @Test + public void testFindBusiness() { + ArrayList map = new ArrayList(); + map.add(new Filter(DBBusinessDAO.BUSINESS_FIELD, "=", "ba")); + try { + BusinessDAO dao = new DBBusinessDAO(getConnection()); + assertEquals(2, dao.find(map).size()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + /********************* + * HOST + *********************/ + + @Test + public void testDeleteAllHost() { + try { + HostDAO dao = new DBHostDAO(getConnection()); + dao.deleteAll(); + + ResultSet res = con.createStatement() + .executeQuery("SELECT * FROM hosts"); + assertEquals(false, res.next()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testDeleteHost() { + try { + HostDAO dao = new DBHostDAO(getConnection()); + dao.delete(new Host("server1", "", 666, null, false, false)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM hosts where hostid = 'server1'"); + assertEquals(false, res.next()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testGetAllHost() { + try { + HostDAO dao = new DBHostDAO(getConnection()); + assertEquals(3, dao.getAll().size()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testSelectHost() { + try { + HostDAO dao = new DBHostDAO(getConnection()); + Host host = dao.select("server1"); + Host host2 = dao.select("ghost"); + + assertEquals("server1", host.getHostid()); + assertEquals("127.0.0.1", host.getAddress()); + assertEquals(6666, host.getPort()); + //HostKey is tested in Insert and Update + assertEquals(true, host.isSSL()); + assertEquals(true, host.isClient()); + assertEquals(true, host.isProxified()); + assertEquals(false, host.isAdmin()); + assertEquals(false, host.isActive()); + assertEquals(UpdatedInfo.TOSUBMIT, host.getUpdatedInfo()); + + assertEquals(null, host2); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testExistHost() { + try { + HostDAO dao = new DBHostDAO(getConnection()); + assertEquals(true, dao.exist("server1")); + assertEquals(false, dao.exist("ghost")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + @Test + public void testInsertHost() { + try { + HostDAO dao = new DBHostDAO(getConnection()); + dao.insert( + new Host("chacha", "address", 666, "aaa".getBytes("utf-8"), false, + false)); + + ResultSet res = con.createStatement() + .executeQuery("SELECT COUNT(1) as count FROM hosts"); + res.next(); + assertEquals(4, res.getInt("count")); + + ResultSet res2 = con.createStatement() + .executeQuery( + "SELECT * FROM hosts WHERE hostid = 'chacha'"); + res2.next(); + assertEquals("chacha", res2.getString("hostid")); + assertEquals("address", res2.getString("address")); + assertEquals(666, res2.getInt("port")); + assertArrayEquals("aaa".getBytes("utf-8"), res2.getBytes("hostkey")); + assertEquals(false, res2.getBoolean("isssl")); + assertEquals(false, res2.getBoolean("isclient")); + assertEquals(false, res2.getBoolean("isproxified")); + assertEquals(true, res2.getBoolean("adminrole")); + assertEquals(true, res2.getBoolean("isactive")); + assertEquals(0, res2.getInt("updatedinfo")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testUpdateHost() { + try { + HostDAO dao = new DBHostDAO(getConnection()); + dao.update( + new Host("server2", "address", 666, "password".getBytes("utf-8"), + false, false)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM hosts WHERE hostid = 'server2'"); + res.next(); + assertEquals("server2", res.getString("hostid")); + assertEquals("address", res.getString("address")); + assertEquals(666, res.getInt("port")); + assertArrayEquals("password".getBytes("utf-8"), res.getBytes("hostkey")); + assertEquals(false, res.getBoolean("isssl")); + assertEquals(false, res.getBoolean("isclient")); + assertEquals(false, res.getBoolean("isproxified")); + assertEquals(true, res.getBoolean("adminrole")); + assertEquals(true, res.getBoolean("isactive")); + assertEquals(0, res.getInt("updatedinfo")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + @Test + public void testFindHost() { + ArrayList map = new ArrayList(); + map.add(new Filter(DBHostDAO.ADDRESS_FIELD, "=", "127.0.0.1")); + try { + HostDAO dao = new DBHostDAO(getConnection()); + assertEquals(2, dao.find(map).size()); + } catch (Exception e) { + e.printStackTrace(); + fail(e.getMessage()); + } + } + + + /********************* + * LIMIT + *********************/ + + @Test + public void testDeleteAllLimit() { + try { + LimitDAO dao = new DBLimitDAO(getConnection()); + dao.deleteAll(); + + ResultSet res = con.createStatement() + .executeQuery("SELECT * FROM configuration"); + assertEquals(false, res.next()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testDeleteLimit() { + try { + LimitDAO dao = new DBLimitDAO(getConnection()); + dao.delete(new Limit("server1", 0l)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM configuration where hostid = 'server1'"); + assertEquals(false, res.next()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testGetAllLimit() { + try { + LimitDAO dao = new DBLimitDAO(getConnection()); + assertEquals(3, dao.getAll().size()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testSelectLimit() { + try { + LimitDAO dao = new DBLimitDAO(getConnection()); + Limit limit = dao.select("server1"); + Limit limit2 = dao.select("ghost"); + + assertEquals("server1", limit.getHostid()); + assertEquals(1, limit.getReadGlobalLimit()); + assertEquals(2, limit.getWriteGlobalLimit()); + assertEquals(3, limit.getReadSessionLimit()); + assertEquals(4, limit.getWriteSessionLimit()); + assertEquals(5, limit.getDelayLimit()); + assertEquals(UpdatedInfo.NOTUPDATED, limit.getUpdatedInfo()); + assertEquals(null, limit2); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testExistLimit() { + try { + LimitDAO dao = new DBLimitDAO(getConnection()); + assertEquals(true, dao.exist("server1")); + assertEquals(false, dao.exist("ghost")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + @Test + public void testInsertLimit() { + try { + LimitDAO dao = new DBLimitDAO(getConnection()); + dao.insert(new Limit("chacha", 4l, + 1l, 5l, 13l, 12, + UpdatedInfo.TOSUBMIT)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT COUNT(1) as count FROM configuration"); + res.next(); + assertEquals(4, res.getInt("count")); + + ResultSet res2 = con.createStatement() + .executeQuery( + "SELECT * FROM configuration WHERE hostid = 'chacha'"); + res2.next(); + assertEquals("chacha", res2.getString("hostid")); + assertEquals(4, res2.getLong("delaylimit")); + assertEquals(1, res2.getLong("readGlobalLimit")); + assertEquals(5, res2.getLong("writeGlobalLimit")); + assertEquals(13, res2.getLong("readSessionLimit")); + assertEquals(12, res2.getLong("writeSessionLimit")); + assertEquals(UpdatedInfo.TOSUBMIT.ordinal(), res2.getInt("updatedInfo")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testUpdateLimit() { + try { + LimitDAO dao = new DBLimitDAO(getConnection()); + dao.update(new Limit("server2", 4l, + 1l, 5l, 13l, 12l, + UpdatedInfo.RUNNING)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM configuration WHERE hostid = 'server2'"); + res.next(); + assertEquals("server2", res.getString("hostid")); + assertEquals(4, res.getLong("delaylimit")); + assertEquals(1, res.getLong("readGlobalLimit")); + assertEquals(5, res.getLong("writeGlobalLimit")); + assertEquals(13, res.getLong("readSessionLimit")); + assertEquals(12, res.getLong("writeSessionLimit")); + assertEquals(UpdatedInfo.RUNNING.ordinal(), res.getInt("updatedInfo")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + @Test + public void testFindLimit() { + ArrayList map = new ArrayList(); + map.add(new Filter(DBLimitDAO.READ_SESSION_LIMIT_FIELD, ">", 2)); + try { + LimitDAO dao = new DBLimitDAO(getConnection()); + assertEquals(2, dao.find(map).size()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + /********************* + * MULTIPLE MONITOR + *********************/ + + + @Test + public void testDeleteAllMultipleMonitor() { + try { + MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + dao.deleteAll(); + + ResultSet res = con.createStatement() + .executeQuery("SELECT * FROM multiplemonitor"); + assertEquals(false, res.next()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testDeleteMultipleMonitor() { + try { + MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + dao.delete(new MultipleMonitor("server1", 0, 0, 0)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM multiplemonitor where hostid = 'server1'"); + assertEquals(false, res.next()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testGetAllMultipleMonitor() { + try { + MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + assertEquals(4, dao.getAll().size()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testSelectMultipleMonitor() { + try { + MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + MultipleMonitor multiple = dao.select("server1"); + MultipleMonitor multiple2 = dao.select("ghost"); + + assertEquals("server1", multiple.getHostid()); + assertEquals(11, multiple.getCountConfig()); + assertEquals(29, multiple.getCountRule()); + assertEquals(18, multiple.getCountHost()); + assertEquals(null, multiple2); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testExistMultipleMonitor() { + try { + MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + assertEquals(true, dao.exist("server1")); + assertEquals(false, dao.exist("ghost")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + @Test + public void testInsertMultipleMonitor() { + try { + MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + dao.insert(new MultipleMonitor("chacha", 31, 19, 98)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT COUNT(1) as count FROM multiplemonitor"); + res.next(); + assertEquals(5, res.getInt("count")); + + ResultSet res2 = con.createStatement() + .executeQuery( + "SELECT * FROM multiplemonitor WHERE hostid = 'chacha'"); + res2.next(); + assertEquals("chacha", res2.getString("hostid")); + assertEquals(98, res2.getInt("countRule")); + assertEquals(19, res2.getInt("countHost")); + assertEquals(31, res2.getInt("countConfig")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testUpdateMultipleMonitor() { + try { + MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + dao.update(new MultipleMonitor("server2", 31, 19, 98)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM multiplemonitor WHERE hostid = 'server2'"); + res.next(); + assertEquals("server2", res.getString("hostid")); + assertEquals(98, res.getInt("countRule")); + assertEquals(19, res.getInt("countHost")); + assertEquals(31, res.getInt("countConfig")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + @Test + public void testFindMultipleMonitor() { + ArrayList map = new ArrayList(); + map.add(new Filter(DBMultipleMonitorDAO.COUNT_CONFIG_FIELD, "=", 0)); + try { + MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + assertEquals(2, dao.find(map).size()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + /********************* + * RULE + *********************/ + + + @Test + public void testDeleteAllRule() { + try { + RuleDAO dao = new DBRuleDAO(getConnection()); + dao.deleteAll(); + + ResultSet res = con.createStatement() + .executeQuery("SELECT * FROM rules"); + assertEquals(false, res.next()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testDeleteRule() { + try { + RuleDAO dao = new DBRuleDAO(getConnection()); + dao.delete(new Rule("default", 1)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM rules where idrule = 'default'"); + assertEquals(false, res.next()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testGetAllRule() { + try { + RuleDAO dao = new DBRuleDAO(getConnection()); + assertEquals(3, dao.getAll().size()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testSelectRule() { + try { + RuleDAO dao = new DBRuleDAO(getConnection()); + Rule rule = dao.select("dummy"); + Rule rule2 = dao.select("ghost"); + + assertEquals("dummy", rule.getName()); + assertEquals(1, rule.getMode()); + assertEquals(3, rule.getHostids().size()); + assertEquals("/in", rule.getRecvPath()); + assertEquals("/out", rule.getSendPath()); + assertEquals("/arch", rule.getArchivePath()); + assertEquals("/work", rule.getWorkPath()); + assertEquals(0, rule.getRPreTasks().size()); + assertEquals(1, rule.getRPostTasks().size()); + assertEquals(2, rule.getRErrorTasks().size()); + assertEquals(3, rule.getSPreTasks().size()); + assertEquals(0, rule.getSPostTasks().size()); + assertEquals(0, rule.getSErrorTasks().size()); + assertEquals(UpdatedInfo.UNKNOWN, rule.getUpdatedInfo()); + assertEquals(null, rule2); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testExistRule() { + try { + RuleDAO dao = new DBRuleDAO(getConnection()); + assertEquals(true, dao.exist("dummy")); + assertEquals(false, dao.exist("ghost")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + @Test + public void testInsertRule() { + try { + RuleDAO dao = new DBRuleDAO(getConnection()); + dao.insert(new Rule("chacha", 2)); + + ResultSet res = con.createStatement() + .executeQuery("SELECT COUNT(1) as count FROM rules"); + res.next(); + assertEquals(4, res.getInt("count")); + + ResultSet res2 = con.createStatement() + .executeQuery( + "SELECT * FROM rules WHERE idrule = 'chacha'"); + res2.next(); + assertEquals("chacha", res2.getString("idrule")); + assertEquals(2, res2.getInt("modetrans")); + assertEquals("", res2.getString("hostids")); + assertEquals("", res2.getString("recvpath") == null? "" : + res2.getString("recvpath")); + assertEquals("", res2.getString("sendpath") == null? "" : + res2.getString("sendpath")); + assertEquals("", res2.getString("archivepath") == null? "" : + res2.getString("archivepath")); + assertEquals("", res2.getString("workpath") == null? "" : + res2.getString("workpath")); + assertEquals("", res2.getString("rpretasks")); + assertEquals("", res2.getString("rposttasks")); + assertEquals("", res2.getString("rerrortasks")); + assertEquals("", res2.getString("spretasks")); + assertEquals("", res2.getString("sposttasks")); + assertEquals("", res2.getString("serrortasks")); + assertEquals(0, res2.getInt("updatedInfo")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + @Test + public void testUpdateRule() { + try { + RuleDAO dao = new DBRuleDAO(getConnection()); + dao.update(new Rule("dummy", 2)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM rules WHERE idrule = 'dummy'"); + res.next(); + assertEquals("dummy", res.getString("idrule")); + assertEquals(2, res.getInt("modetrans")); + assertEquals("", res.getString("hostids")); + assertEquals("", res.getString("recvpath") == null? "" : + res.getString("recvpath")); + assertEquals("", res.getString("sendpath") == null? "" : + res.getString("sendpath")); + assertEquals("", res.getString("archivepath") == null? "" : + res.getString("archivepath")); + assertEquals("", res.getString("workpath") == null? "" : + res.getString("workpath")); + assertEquals("", res.getString("rpretasks")); + assertEquals("", res.getString("rposttasks")); + assertEquals("", res.getString("rerrortasks")); + assertEquals("", res.getString("spretasks")); + assertEquals("", res.getString("sposttasks")); + assertEquals("", res.getString("serrortasks")); + assertEquals(0, res.getInt("updatedInfo")); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + @Test + public void testFindRule() { + ArrayList map = new ArrayList(); + map.add(new Filter(DBRuleDAO.MODE_TRANS_FIELD, "=", 1)); + try { + RuleDAO dao = new DBRuleDAO(getConnection()); + assertEquals(2, dao.find(map).size()); + } catch (Exception e) { + fail(e.getMessage()); + } + } + + + /********************* + * TRANSFER + *********************/ + + @Test + public void testDeleteAllTransfer() throws Exception { + TransferDAO dao = getDAO(getConnection()); + dao.deleteAll(); + + ResultSet res = con.createStatement() + .executeQuery("SELECT * FROM runner"); + assertEquals(false, res.next()); + } + + public abstract TransferDAO getDAO(Connection con) throws DAOException; + + @Test + public void testDeleteTransfer() throws Exception { + TransferDAO dao = getDAO(getConnection()); + dao.delete(new Transfer(0l, "", 1, "", "", "", false, 0, false, + "server1", "server1", "server2", "", + Transfer.TASKSTEP.NOTASK, Transfer.TASKSTEP.NOTASK, + 0, + ErrorCode.Unknown, ErrorCode.Unknown, 0, null, + null)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM runner where specialid = 0"); + assertEquals(false, res.next()); + } + + @Test + public void testGetAllTransfer() throws Exception { + TransferDAO dao = getDAO(getConnection()); + assertEquals(4, dao.getAll().size()); + } + + @Test + public void testSelectTransfer() throws Exception { + TransferDAO dao = getDAO(getConnection()); + Transfer transfer = dao.select(0l, "server1", "server2", "server1"); + Transfer transfer2 = dao.select(1l, "server1", "server2", "server1"); + + assertEquals(0, transfer.getId()); + assertEquals(null, transfer2); + } + + @Test + public void testExistTransfer() throws Exception { + TransferDAO dao = getDAO(getConnection()); + assertEquals(true, dao.exist(0l, "server1", "server2", "server1")); + assertEquals(false, dao.exist(1l, "server1", "server2", "server1")); + } + + @Test + public void testInsertTransfer() throws Exception { + TransferDAO dao = getDAO(getConnection()); + Transfer transfer = new Transfer("server2", "rule", 1, false, + "file", "info", 3); + // Requester and requested are setup manualy + transfer.setRequester("dummy"); + transfer.setOwnerRequest("dummy"); + transfer.setStart(new Timestamp(1112242l)); + transfer.setStop(new Timestamp(122l)); + transfer.setTransferInfo("transfer info"); + dao.insert(transfer); + + ResultSet res = con.createStatement() + .executeQuery("SELECT COUNT(1) as count FROM runner"); + res.next(); + assertEquals(5, res.getInt("count")); + + ResultSet res2 = con.createStatement() + .executeQuery( + "SELECT * FROM runner WHERE idrule = 'rule'"); + res2.next(); + assertEquals("rule", res2.getString("idrule")); + assertEquals(1, res2.getInt("modetrans")); + assertEquals("file", res2.getString("filename")); + assertEquals("file", res2.getString("originalname")); + assertEquals("info", res2.getString("fileinfo")); + assertEquals(false, res2.getBoolean("ismoved")); + assertEquals(3, res2.getInt("blocksz")); + } + + @Test + public void testUpdateTransfer() throws Exception { + TransferDAO dao = getDAO(getConnection()); + + dao.update(new Transfer(0l, "rule", 13, "test", "testOrig", + "testInfo", true, 42, true, "server1", "server1", + "server2", "transferInfo", + Transfer.TASKSTEP.ERRORTASK, + Transfer.TASKSTEP.TRANSFERTASK, 27, + ErrorCode.CompleteOk, + ErrorCode.Unknown, 64, new Timestamp(192l), + new Timestamp(1511l), UpdatedInfo.TOSUBMIT)); + + ResultSet res = con.createStatement() + .executeQuery( + "SELECT * FROM runner WHERE specialid=0 and " + + "ownerreq='server1' and requester='server1' and " + + "requested='server2'"); + if (!res.next()) { + fail("Result not found"); + } + assertEquals(0, res.getLong("specialid")); + assertEquals("rule", res.getString("idrule")); + assertEquals(13, res.getInt("modetrans")); + assertEquals("test", res.getString("filename")); + assertEquals("testOrig", res.getString("originalname")); + assertEquals("testInfo", res.getString("fileinfo")); + assertEquals(true, res.getBoolean("ismoved")); + assertEquals(42, res.getInt("blocksz")); + assertEquals(true, res.getBoolean("retrievemode")); + assertEquals("server1", res.getString("ownerreq")); + assertEquals("server1", res.getString("requester")); + assertEquals("server2", res.getString("requested")); + assertEquals(Transfer.TASKSTEP.ERRORTASK.ordinal(), + res.getInt("globalstep")); + assertEquals(Transfer.TASKSTEP.TRANSFERTASK.ordinal(), + res.getInt("globallaststep")); + assertEquals(27, res.getInt("step")); + assertEquals(ErrorCode.CompleteOk.code, + res.getString("stepstatus").charAt(0)); + assertEquals(ErrorCode.Unknown.code, res.getString("infostatus").charAt(0)); + assertEquals(64, res.getInt("rank")); + assertEquals(new Timestamp(192l), res.getTimestamp("starttrans")); + assertEquals(new Timestamp(1511l), res.getTimestamp("stoptrans")); + assertEquals(UpdatedInfo.TOSUBMIT.ordinal(), res.getInt("updatedInfo")); + } + + + @Test + public void testFindTransfer() throws Exception { + ArrayList map = new ArrayList(); + map.add(new Filter(DBTransferDAO.ID_RULE_FIELD, "=", "default")); + map.add(new Filter(DBTransferDAO.OWNER_REQUEST_FIELD, "=", "server1")); + + TransferDAO dao = getDAO(getConnection()); + assertEquals(3, dao.find(map).size()); + } + +} + diff --git a/src/test/java/org/waarp/openr66/dao/database/DBBusinessDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/DBBusinessDAOIT.java deleted file mode 100644 index 7bffb9765..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/DBBusinessDAOIT.java +++ /dev/null @@ -1,189 +0,0 @@ -package org.waarp.openr66.dao.database; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.net.URL; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; - -import org.waarp.openr66.dao.BusinessDAO; -import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.pojo.Business; -import org.waarp.openr66.pojo.UpdatedInfo; - -public abstract class DBBusinessDAOIT { - - private Connection con; - - public abstract Connection getConnection() throws SQLException; - public abstract void initDB() throws SQLException; - public abstract void cleanDB() throws SQLException; - - public void runScript(String script) { - try { - ScriptRunner runner = new ScriptRunner(con, false, true); - URL url = Thread.currentThread().getContextClassLoader().getResource(script); - runner.runScript(new BufferedReader(new FileReader(url.getPath()))); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Before - public void setUp() { - try { - con = getConnection(); - initDB(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @After - public void wrapUp() { - try { - cleanDB(); - con.close(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testDeleteAll() { - try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); - dao.deleteAll(); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM hostconfig"); - assertEquals(false, res.next()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testDelete() { - try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); - dao.delete(new Business("server1", "", "", "", "")); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM hostconfig where hostid = 'server1'"); - assertEquals(false, res.next()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testGetAll() { - try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); - assertEquals(5, dao.getAll().size()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testSelect() { - try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); - Business business = dao.select("server1"); - Business business2 = dao.select("ghost"); - - assertEquals("joyaux", business.getBusiness()); - assertEquals("marchand", business.getRoles()); - assertEquals("le borgne", business.getAliases()); - assertEquals("misc", business.getOthers()); - assertEquals(UpdatedInfo.NOTUPDATED, business.getUpdatedInfo()); - assertEquals(null, business2); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testExist() { - try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); - assertEquals(true, dao.exist("server1")); - assertEquals(false, dao.exist("ghost")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - - @Test - public void testInsert() { - try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); - dao.insert(new Business("chacha", - "lolo", "lala", "minou", "ect", - UpdatedInfo.TOSUBMIT)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT COUNT(1) as count FROM hostconfig"); - res.next(); - assertEquals(6, res.getInt("count")); - - ResultSet res2 = con.createStatement() - .executeQuery("SELECT * FROM hostconfig WHERE hostid = 'chacha'"); - res2.next(); - assertEquals("chacha", res2.getString("hostid")); - assertEquals("lolo", res2.getString("business")); - assertEquals("lala", res2.getString("roles")); - assertEquals("minou", res2.getString("aliases")); - assertEquals("ect", res2.getString("others")); - assertEquals(UpdatedInfo.TOSUBMIT.ordinal(), res2.getInt("updatedInfo")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testUpdate() { - try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); - dao.update(new Business("server2", - "lolo", "lala", "minou", "ect", - UpdatedInfo.RUNNING)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM hostconfig WHERE hostid = 'server2'"); - res.next(); - assertEquals("server2", res.getString("hostid")); - assertEquals("lolo", res.getString("business")); - assertEquals("lala", res.getString("roles")); - assertEquals("minou", res.getString("aliases")); - assertEquals("ect", res.getString("others")); - assertEquals(UpdatedInfo.RUNNING.ordinal(), res.getInt("updatedInfo")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - - @Test - public void testFind() { - ArrayList map = new ArrayList(); - map.add(new Filter(DBBusinessDAO.BUSINESS_FIELD, "=", "ba")); - try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); - assertEquals(2, dao.find(map).size()); - } catch (Exception e) { - fail(e.getMessage()); - } - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/DBHostDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/DBHostDAOIT.java deleted file mode 100644 index 6f2b5a55e..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/DBHostDAOIT.java +++ /dev/null @@ -1,199 +0,0 @@ -package org.waarp.openr66.dao.database; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.net.URL; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; - -import org.waarp.openr66.dao.HostDAO; -import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.pojo.Host; -import org.waarp.openr66.pojo.UpdatedInfo; - -public abstract class DBHostDAOIT { - - private Connection con; - - public abstract Connection getConnection() throws SQLException; - public abstract void initDB() throws SQLException; - public abstract void cleanDB() throws SQLException; - - public void runScript(String script) { - try { - ScriptRunner runner = new ScriptRunner(con, false, true); - URL url = Thread.currentThread().getContextClassLoader().getResource(script); - runner.runScript(new BufferedReader(new FileReader(url.getPath()))); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Before - public void setUp() { - try { - con = getConnection(); - initDB(); - } catch (Exception e) { - fail(e.toString()); - } - } - - @After - public void wrapUp() { - try { - cleanDB(); - con.close(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testDeleteAll() { - try { - HostDAO dao = new DBHostDAO(getConnection()); - dao.deleteAll(); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM hosts"); - assertEquals(false, res.next()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testDelete() { - try { - HostDAO dao = new DBHostDAO(getConnection()); - dao.delete(new Host("server1", "", 666, null, false, false)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM hosts where hostid = 'server1'"); - assertEquals(false, res.next()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testGetAll() { - try { - HostDAO dao = new DBHostDAO(getConnection()); - assertEquals(3, dao.getAll().size()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testSelect() { - try { - HostDAO dao = new DBHostDAO(getConnection()); - Host host = dao.select("server1"); - Host host2 = dao.select("ghost"); - - assertEquals("server1", host.getHostid()); - assertEquals("127.0.0.1", host.getAddress()); - assertEquals(6666, host.getPort()); - //HostKey is tested in Insert and Update - assertEquals(true, host.isSSL()); - assertEquals(true, host.isClient()); - assertEquals(true, host.isProxified()); - assertEquals(false, host.isAdmin()); - assertEquals(false, host.isActive()); - assertEquals(UpdatedInfo.TOSUBMIT, host.getUpdatedInfo()); - - assertEquals(null, host2); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testExist() { - try { - HostDAO dao = new DBHostDAO(getConnection()); - assertEquals(true, dao.exist("server1")); - assertEquals(false, dao.exist("ghost")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - - @Test - public void testInsert() { - try { - HostDAO dao = new DBHostDAO(getConnection()); - dao.insert(new Host("chacha", "address", 666, "aaa".getBytes("utf-8"), false, false)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT COUNT(1) as count FROM hosts"); - res.next(); - assertEquals(4, res.getInt("count")); - - ResultSet res2 = con.createStatement() - .executeQuery("SELECT * FROM hosts WHERE hostid = 'chacha'"); - res2.next(); - assertEquals("chacha", res2.getString("hostid")); - assertEquals("address", res2.getString("address")); - assertEquals(666, res2.getInt("port")); - assertArrayEquals("aaa".getBytes("utf-8"), res2.getBytes("hostkey")); - assertEquals(false, res2.getBoolean("isssl")); - assertEquals(false, res2.getBoolean("isclient")); - assertEquals(false, res2.getBoolean("isproxified")); - assertEquals(true, res2.getBoolean("adminrole")); - assertEquals(true, res2.getBoolean("isactive")); - assertEquals(0, res2.getInt("updatedinfo")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testUpdate() { - try { - HostDAO dao = new DBHostDAO(getConnection()); - dao.update(new Host("server2", "address", 666, "password".getBytes("utf-8"), false, false)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM hosts WHERE hostid = 'server2'"); - res.next(); - assertEquals("server2", res.getString("hostid")); - assertEquals("address", res.getString("address")); - assertEquals(666, res.getInt("port")); - assertArrayEquals("password".getBytes("utf-8"), res.getBytes("hostkey")); - assertEquals(false, res.getBoolean("isssl")); - assertEquals(false, res.getBoolean("isclient")); - assertEquals(false, res.getBoolean("isproxified")); - assertEquals(true, res.getBoolean("adminrole")); - assertEquals(true, res.getBoolean("isactive")); - assertEquals(0, res.getInt("updatedinfo")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - - @Test - public void testFind() { - ArrayList map = new ArrayList(); - map.add(new Filter(DBHostDAO.ADDRESS_FIELD, "=", "127.0.0.1")); - try { - HostDAO dao = new DBHostDAO(getConnection()); - assertEquals(2, dao.find(map).size()); - } catch (Exception e) { - fail(e.getMessage()); - } - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/DBLimitDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/DBLimitDAOIT.java deleted file mode 100644 index f0f86a244..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/DBLimitDAOIT.java +++ /dev/null @@ -1,193 +0,0 @@ -package org.waarp.openr66.dao.database; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.net.URL; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; - -import org.waarp.openr66.dao.LimitDAO; -import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.pojo.Limit; -import org.waarp.openr66.pojo.UpdatedInfo; - -public abstract class DBLimitDAOIT { - - private Connection con; - - public abstract Connection getConnection() throws SQLException; - public abstract void initDB() throws SQLException; - public abstract void cleanDB() throws SQLException; - - public void runScript(String script) { - try { - ScriptRunner runner = new ScriptRunner(con, false, true); - URL url = Thread.currentThread().getContextClassLoader().getResource(script); - runner.runScript(new BufferedReader(new FileReader(url.getPath()))); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Before - public void setUp() { - try { - con = getConnection(); - initDB(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @After - public void wrapUp() { - try { - cleanDB(); - con.close(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testDeleteAll() { - try { - LimitDAO dao = new DBLimitDAO(getConnection()); - dao.deleteAll(); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM configuration"); - assertEquals(false, res.next()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testDelete() { - try { - LimitDAO dao = new DBLimitDAO(getConnection()); - dao.delete(new Limit("server1", 0l)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM configuration where hostid = 'server1'"); - assertEquals(false, res.next()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testGetAll() { - try { - LimitDAO dao = new DBLimitDAO(getConnection()); - assertEquals(3, dao.getAll().size()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testSelect() { - try { - LimitDAO dao = new DBLimitDAO(getConnection()); - Limit limit = dao.select("server1"); - Limit limit2 = dao.select("ghost"); - - assertEquals("server1", limit.getHostid()); - assertEquals(1, limit.getReadGlobalLimit()); - assertEquals(2, limit.getWriteGlobalLimit()); - assertEquals(3, limit.getReadSessionLimit()); - assertEquals(4, limit.getWriteSessionLimit()); - assertEquals(5, limit.getDelayLimit()); - assertEquals(UpdatedInfo.NOTUPDATED, limit.getUpdatedInfo()); - assertEquals(null, limit2); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testExist() { - try { - LimitDAO dao = new DBLimitDAO(getConnection()); - assertEquals(true, dao.exist("server1")); - assertEquals(false, dao.exist("ghost")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - - @Test - public void testInsert() { - try { - LimitDAO dao = new DBLimitDAO(getConnection()); - dao.insert(new Limit("chacha", 4l, - 1l, 5l, 13l, 12, - UpdatedInfo.TOSUBMIT)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT COUNT(1) as count FROM configuration"); - res.next(); - assertEquals(4, res.getInt("count")); - - ResultSet res2 = con.createStatement() - .executeQuery("SELECT * FROM configuration WHERE hostid = 'chacha'"); - res2.next(); - assertEquals("chacha", res2.getString("hostid")); - assertEquals(4, res2.getLong("delaylimit")); - assertEquals(1, res2.getLong("readGlobalLimit")); - assertEquals(5, res2.getLong("writeGlobalLimit")); - assertEquals(13, res2.getLong("readSessionLimit")); - assertEquals(12, res2.getLong("writeSessionLimit")); - assertEquals(UpdatedInfo.TOSUBMIT.ordinal(), res2.getInt("updatedInfo")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testUpdate() { - try { - LimitDAO dao = new DBLimitDAO(getConnection()); - dao.update(new Limit("server2", 4l, - 1l, 5l, 13l, 12l, - UpdatedInfo.RUNNING)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM configuration WHERE hostid = 'server2'"); - res.next(); - assertEquals("server2", res.getString("hostid")); - assertEquals(4, res.getLong("delaylimit")); - assertEquals(1, res.getLong("readGlobalLimit")); - assertEquals(5, res.getLong("writeGlobalLimit")); - assertEquals(13, res.getLong("readSessionLimit")); - assertEquals(12, res.getLong("writeSessionLimit")); - assertEquals(UpdatedInfo.RUNNING.ordinal(), res.getInt("updatedInfo")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - - @Test - public void testFind() { - ArrayList map = new ArrayList(); - map.add(new Filter(DBLimitDAO.READ_SESSION_LIMIT_FIELD, ">", 2)); - try { - LimitDAO dao = new DBLimitDAO(getConnection()); - assertEquals(2, dao.find(map).size()); - } catch (Exception e) { - fail(e.getMessage()); - } - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/DBMultipleMonitorDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/DBMultipleMonitorDAOIT.java deleted file mode 100644 index 78dd12096..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/DBMultipleMonitorDAOIT.java +++ /dev/null @@ -1,179 +0,0 @@ -package org.waarp.openr66.dao.database; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.net.URL; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; - -import org.waarp.openr66.dao.MultipleMonitorDAO; -import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.pojo.MultipleMonitor; - -public abstract class DBMultipleMonitorDAOIT { - - private Connection con; - - public abstract Connection getConnection() throws SQLException; - public abstract void initDB() throws SQLException; - public abstract void cleanDB() throws SQLException; - - public void runScript(String script) { - try { - ScriptRunner runner = new ScriptRunner(con, false, true); - URL url = Thread.currentThread().getContextClassLoader().getResource(script); - runner.runScript(new BufferedReader(new FileReader(url.getPath()))); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Before - public void setUp() { - try { - con = getConnection(); - initDB(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @After - public void wrapUp() { - try { - cleanDB(); - con.close(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testDeleteAll() { - try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); - dao.deleteAll(); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM multiplemonitor"); - assertEquals(false, res.next()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testDelete() { - try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); - dao.delete(new MultipleMonitor("server1", 0, 0, 0)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM multiplemonitor where hostid = 'server1'"); - assertEquals(false, res.next()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testGetAll() { - try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); - assertEquals(4, dao.getAll().size()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testSelect() { - try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); - MultipleMonitor multiple = dao.select("server1"); - MultipleMonitor multiple2 = dao.select("ghost"); - - assertEquals("server1", multiple.getHostid()); - assertEquals(11, multiple.getCountConfig()); - assertEquals(29, multiple.getCountRule()); - assertEquals(18, multiple.getCountHost()); - assertEquals(null, multiple2); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testExist() { - try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); - assertEquals(true, dao.exist("server1")); - assertEquals(false, dao.exist("ghost")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - - @Test - public void testInsert() { - try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); - dao.insert(new MultipleMonitor("chacha", 31, 19, 98)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT COUNT(1) as count FROM multiplemonitor"); - res.next(); - assertEquals(5, res.getInt("count")); - - ResultSet res2 = con.createStatement() - .executeQuery("SELECT * FROM multiplemonitor WHERE hostid = 'chacha'"); - res2.next(); - assertEquals("chacha", res2.getString("hostid")); - assertEquals(98, res2.getInt("countRule")); - assertEquals(19, res2.getInt("countHost")); - assertEquals(31, res2.getInt("countConfig")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testUpdate() { - try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); - dao.update(new MultipleMonitor("server2", 31, 19, 98)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM multiplemonitor WHERE hostid = 'server2'"); - res.next(); - assertEquals("server2", res.getString("hostid")); - assertEquals(98, res.getInt("countRule")); - assertEquals(19, res.getInt("countHost")); - assertEquals(31, res.getInt("countConfig")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - - @Test - public void testFind() { - ArrayList map = new ArrayList(); - map.add(new Filter(DBMultipleMonitorDAO.COUNT_CONFIG_FIELD, "=" , 0)); - try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); - assertEquals(2, dao.find(map).size()); - } catch (Exception e) { - fail(e.getMessage()); - } - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/DBRuleDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/DBRuleDAOIT.java deleted file mode 100644 index 2b26d4528..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/DBRuleDAOIT.java +++ /dev/null @@ -1,210 +0,0 @@ -package org.waarp.openr66.dao.database; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.net.URL; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.ArrayList; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import static org.junit.Assert.*; - -import org.waarp.openr66.dao.RuleDAO; -import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.pojo.Rule; -import org.waarp.openr66.pojo.UpdatedInfo; - -public abstract class DBRuleDAOIT { - - private Connection con; - - public abstract Connection getConnection() throws SQLException; - public abstract void initDB() throws SQLException; - public abstract void cleanDB() throws SQLException; - - public void runScript(String script) { - try { - ScriptRunner runner = new ScriptRunner(con, false, true); - URL url = Thread.currentThread().getContextClassLoader().getResource(script); - runner.runScript(new BufferedReader(new FileReader(url.getPath()))); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Before - public void setUp() { - try { - con = getConnection(); - initDB(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @After - public void wrapUp() { - try { - cleanDB(); - con.close(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testDeleteAll() { - try { - RuleDAO dao = new DBRuleDAO(getConnection()); - dao.deleteAll(); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM rules"); - assertEquals(false, res.next()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testDelete() { - try { - RuleDAO dao = new DBRuleDAO(getConnection()); - dao.delete(new Rule("default", 1)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM rules where idrule = 'default'"); - assertEquals(false, res.next()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testGetAll() { - try { - RuleDAO dao = new DBRuleDAO(getConnection()); - assertEquals(3, dao.getAll().size()); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testSelect() { - try { - RuleDAO dao = new DBRuleDAO(getConnection()); - Rule rule = dao.select("dummy"); - Rule rule2 = dao.select("ghost"); - - assertEquals("dummy", rule.getName()); - assertEquals(1, rule.getMode()); - assertEquals(3, rule.getHostids().size()); - assertEquals("/in", rule.getRecvPath()); - assertEquals("/out", rule.getSendPath()); - assertEquals("/arch", rule.getArchivePath()); - assertEquals("/work", rule.getWorkPath()); - assertEquals(0, rule.getRPreTasks().size()); - assertEquals(1, rule.getRPostTasks().size()); - assertEquals(2, rule.getRErrorTasks().size()); - assertEquals(3, rule.getSPreTasks().size()); - assertEquals(0, rule.getSPostTasks().size()); - assertEquals(0, rule.getSErrorTasks().size()); - assertEquals(UpdatedInfo.UNKNOWN, rule.getUpdatedInfo()); - assertEquals(null, rule2); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testExist() { - try { - RuleDAO dao = new DBRuleDAO(getConnection()); - assertEquals(true, dao.exist("dummy")); - assertEquals(false, dao.exist("ghost")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - - @Test - public void testInsert() { - try { - RuleDAO dao = new DBRuleDAO(getConnection()); - dao.insert(new Rule("chacha", 2)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT COUNT(1) as count FROM rules"); - res.next(); - assertEquals(4, res.getInt("count")); - - ResultSet res2 = con.createStatement() - .executeQuery("SELECT * FROM rules WHERE idrule = 'chacha'"); - res2.next(); - assertEquals("chacha", res2.getString("idrule")); - assertEquals(2, res2.getInt("modetrans")); - assertEquals("", res2.getString("hostids")); - assertEquals("", res2.getString("recvpath")); - assertEquals("", res2.getString("sendpath")); - assertEquals("", res2.getString("archivepath")); - assertEquals("", res2.getString("workpath")); - assertEquals("", res2.getString("rpretasks")); - assertEquals("", res2.getString("rposttasks")); - assertEquals("", res2.getString("rerrortasks")); - assertEquals("", res2.getString("spretasks")); - assertEquals("", res2.getString("sposttasks")); - assertEquals("", res2.getString("serrortasks")); - assertEquals(0, res2.getInt("updatedInfo")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testUpdate() { - try { - RuleDAO dao = new DBRuleDAO(getConnection()); - dao.update(new Rule("dummy", 2)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM rules WHERE idrule = 'dummy'"); - res.next(); - assertEquals("dummy", res.getString("idrule")); - assertEquals(2, res.getInt("modetrans")); - assertEquals("", res.getString("hostids")); - assertEquals("", res.getString("recvpath")); - assertEquals("", res.getString("sendpath")); - assertEquals("", res.getString("archivepath")); - assertEquals("", res.getString("workpath")); - assertEquals("", res.getString("rpretasks")); - assertEquals("", res.getString("rposttasks")); - assertEquals("", res.getString("rerrortasks")); - assertEquals("", res.getString("spretasks")); - assertEquals("", res.getString("sposttasks")); - assertEquals("", res.getString("serrortasks")); - assertEquals(0, res.getInt("updatedInfo")); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - - @Test - public void testFind() { - ArrayList map = new ArrayList(); - map.add(new Filter(DBRuleDAO.MODE_TRANS_FIELD, "=", 1)); - try { - RuleDAO dao = new DBRuleDAO(getConnection()); - assertEquals(2, dao.find(map).size()); - } catch (Exception e) { - fail(e.getMessage()); - } - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/DBTransferDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/DBTransferDAOIT.java deleted file mode 100644 index 31b9b3dac..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/DBTransferDAOIT.java +++ /dev/null @@ -1,192 +0,0 @@ -package org.waarp.openr66.dao.database; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.waarp.openr66.context.ErrorCode; -import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.dao.TransferDAO; -import org.waarp.openr66.dao.exception.DAOException; -import org.waarp.openr66.pojo.Transfer; -import org.waarp.openr66.pojo.UpdatedInfo; -import org.waarp.openr66.protocol.configuration.Configuration; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.net.URL; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Timestamp; -import java.util.ArrayList; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -public abstract class DBTransferDAOIT { - - private Connection con; - - public abstract TransferDAO getDAO(Connection con) throws DAOException; - public abstract Connection getConnection() throws SQLException; - public abstract void initDB() throws SQLException; - public abstract void cleanDB() throws SQLException; - - public void runScript(String script) { - try { - ScriptRunner runner = new ScriptRunner(con, false, true); - URL url = Thread.currentThread().getContextClassLoader().getResource(script); - runner.runScript(new BufferedReader(new FileReader(url.getPath()))); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Before - public void setUp() { - try { - con = getConnection(); - initDB(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @After - public void wrapUp() { - try { - cleanDB(); - con.close(); - } catch (Exception e) { - fail(e.getMessage()); - } - } - - @Test - public void testDeleteAll() throws Exception { - TransferDAO dao = getDAO(getConnection()); - dao.deleteAll(); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM runner"); - assertEquals(false, res.next()); - } - - @Test - public void testDelete() throws Exception { - TransferDAO dao = getDAO(getConnection()); - dao.delete(new Transfer(0l, "", 1, "", "", "", false, 0, false, - "server1", "server1", "server2", "", - Transfer.TASKSTEP.NOTASK, Transfer.TASKSTEP.NOTASK, 0, - ErrorCode.Unknown, ErrorCode.Unknown, 0, null, null)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM runner where specialid = 0"); - assertEquals(false, res.next()); - } - - @Test - public void testGetAll() throws Exception { - TransferDAO dao = getDAO(getConnection()); - assertEquals(4, dao.getAll().size()); - } - - @Test - public void testSelect() throws Exception { - TransferDAO dao = getDAO(getConnection()); - Transfer transfer = dao.select(0l, "server1", "server2", "server1"); - Transfer transfer2 = dao.select(1l, "server1", "server2", "server1"); - - assertEquals(0, transfer.getId()); - assertEquals(null, transfer2); - } - - @Test - public void testExist() throws Exception { - TransferDAO dao = getDAO(getConnection()); - assertEquals(true, dao.exist(0l, "server1", "server2", "server1")); - assertEquals(false, dao.exist(1l, "server1", "server2", "server1")); - } - - @Test - public void testInsert() throws Exception { - TransferDAO dao = getDAO(getConnection()); - Transfer transfer = new Transfer("server2", "rule", 1, false, - "file", "info", 3); - // Requester and requested are setup manualy - transfer.setRequester("dummy"); - transfer.setOwnerRequest("dummy"); - transfer.setStart(new Timestamp(1112242l)); - transfer.setStop(new Timestamp(122l)); - dao.insert(transfer); - - ResultSet res = con.createStatement() - .executeQuery("SELECT COUNT(1) as count FROM runner"); - res.next(); - assertEquals(5, res.getInt("count")); - - ResultSet res2 = con.createStatement() - .executeQuery("SELECT * FROM runner WHERE idrule = 'rule'"); - res2.next(); - assertEquals("rule", res2.getString("idrule")); - assertEquals(1, res2.getInt("modetrans")); - assertEquals("file", res2.getString("filename")); - assertEquals("file", res2.getString("originalname")); - assertEquals("info", res2.getString("fileinfo")); - assertEquals(false, res2.getBoolean("ismoved")); - assertEquals(3, res2.getInt("blocksz")); - } - - @Test - public void testUpdate() throws Exception { - TransferDAO dao = getDAO(getConnection()); - - dao.update(new Transfer(0l, "rule", 13, "test", "testOrig", - "testInfo", true, 42, true, "server1", "server1", - "server2", "transferInfo", Transfer.TASKSTEP.ERRORTASK, - Transfer.TASKSTEP.TRANSFERTASK, 27, ErrorCode.CompleteOk, - ErrorCode.Unknown, 64, new Timestamp(192l), - new Timestamp(1511l), UpdatedInfo.TOSUBMIT)); - - ResultSet res = con.createStatement() - .executeQuery("SELECT * FROM runner WHERE specialid=0 and " + - "ownerreq='server1' and requester='server1' and " + - "requested='server2'"); - if (!res.next()) { - fail("Result not found"); - } - assertEquals(0, res.getLong("specialid")); - assertEquals("rule", res.getString("idrule")); - assertEquals(13, res.getInt("modetrans")); - assertEquals("test", res.getString("filename")); - assertEquals("testOrig", res.getString("originalname")); - assertEquals("testInfo", res.getString("fileinfo")); - assertEquals(true, res.getBoolean("ismoved")); - assertEquals(42, res.getInt("blocksz")); - assertEquals(true, res.getBoolean("retrievemode")); - assertEquals("server1", res.getString("ownerreq")); - assertEquals("server1", res.getString("requester")); - assertEquals("server2", res.getString("requested")); - assertEquals(Transfer.TASKSTEP.ERRORTASK.ordinal(), res.getInt("globalstep")); - assertEquals(Transfer.TASKSTEP.TRANSFERTASK.ordinal(), res.getInt("globallaststep")); - assertEquals(27, res.getInt("step")); - assertEquals(ErrorCode.CompleteOk.code, res.getString("stepstatus").charAt(0)); - assertEquals(ErrorCode.Unknown.code, res.getString("infostatus").charAt(0)); - assertEquals(64, res.getInt("rank")); - assertEquals(new Timestamp(192l), res.getTimestamp("starttrans")); - assertEquals(new Timestamp(1511l), res.getTimestamp("stoptrans")); - assertEquals(UpdatedInfo.TOSUBMIT.ordinal(), res.getInt("updatedInfo")); - } - - - @Test - public void testFind() throws Exception { - ArrayList map = new ArrayList(); - map.add(new Filter(DBTransferDAO.ID_RULE_FIELD, "=", "default")); - map.add(new Filter(DBTransferDAO.OWNER_REQUEST_FIELD,"=", "server1")); - - TransferDAO dao = getDAO(getConnection()); - assertEquals(3, dao.find(map).size()); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/ScriptRunner.java b/src/test/java/org/waarp/openr66/dao/database/ScriptRunner.java index a83157410..4e894d315 100644 --- a/src/test/java/org/waarp/openr66/dao/database/ScriptRunner.java +++ b/src/test/java/org/waarp/openr66/dao/database/ScriptRunner.java @@ -1,3 +1,23 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + package org.waarp.openr66.dao.database; /* * Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class @@ -22,8 +42,17 @@ * limitations under the License. */ -import java.io.*; -import java.sql.*; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.LineNumberReader; +import java.io.PrintWriter; +import java.io.Reader; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -33,245 +62,250 @@ */ public class ScriptRunner { - private static final String DEFAULT_DELIMITER = ";"; - /** - * regex to detect delimiter. - * ignores spaces, allows delimiter in comment, allows an equals-sign - */ - public static final Pattern delimP = Pattern.compile("^\\s*(--)?\\s*delimiter\\s*=?\\s*([^\\s]+)+\\s*.*$", Pattern.CASE_INSENSITIVE); - - private final Connection connection; + /** + * regex to detect delimiter. ignores spaces, allows delimiter in comment, + * allows an equals-sign + */ + public static final Pattern delimP = + Pattern.compile("^\\s*(--)?\\s*delimiter\\s*=?\\s*([^\\s]+)+\\s*.*$", + Pattern.CASE_INSENSITIVE); + private static final String DEFAULT_DELIMITER = ";"; + private final Connection connection; - private final boolean stopOnError; - private final boolean autoCommit; + private final boolean stopOnError; + private final boolean autoCommit; - @SuppressWarnings("UseOfSystemOutOrSystemErr") - private PrintWriter logWriter = null; - @SuppressWarnings("UseOfSystemOutOrSystemErr") - private PrintWriter errorLogWriter = null; + @SuppressWarnings("UseOfSystemOutOrSystemErr") + private PrintWriter logWriter = null; + @SuppressWarnings("UseOfSystemOutOrSystemErr") + private PrintWriter errorLogWriter = null; - private String delimiter = DEFAULT_DELIMITER; - private boolean fullLineDelimiter = false; + private String delimiter = DEFAULT_DELIMITER; + private boolean fullLineDelimiter = false; - /** - * Default constructor - */ - public ScriptRunner(Connection connection, boolean autoCommit, - boolean stopOnError) { - this.connection = connection; - this.autoCommit = autoCommit; - this.stopOnError = stopOnError; - File logFile = new File("create_db.log"); - File errorLogFile = new File("create_db_error.log"); - try { - if (logFile.exists()) { - logWriter = new PrintWriter(new FileWriter(logFile, true)); - } else { - logWriter = new PrintWriter(new FileWriter(logFile, false)); - } - } catch(IOException e){ - System.err.println("Unable to access or create the db_create log"); - } - try { - if (errorLogFile.exists()) { - errorLogWriter = new PrintWriter(new FileWriter(errorLogFile, true)); - } else { - errorLogWriter = new PrintWriter(new FileWriter(errorLogFile, false)); - } - } catch(IOException e){ - System.err.println("Unable to access or create the db_create error log"); - } - String timeStamp = new SimpleDateFormat("dd/mm/yyyy HH:mm:ss").format(new java.util.Date()); - println("\n-------\n" + timeStamp + "\n-------\n"); - printlnError("\n-------\n" + timeStamp + "\n-------\n"); + /** + * Default constructor + */ + public ScriptRunner(Connection connection, boolean autoCommit, + boolean stopOnError) { + this.connection = connection; + this.autoCommit = autoCommit; + this.stopOnError = stopOnError; + File logFile = new File("create_db.log"); + File errorLogFile = new File("create_db_error.log"); + try { + if (logFile.exists()) { + logWriter = new PrintWriter(new FileWriter(logFile, true)); + } else { + logWriter = new PrintWriter(new FileWriter(logFile, false)); + } + } catch (IOException e) { + System.err.println("Unable to access or create the db_create log"); } - - public void setDelimiter(String delimiter, boolean fullLineDelimiter) { - this.delimiter = delimiter; - this.fullLineDelimiter = fullLineDelimiter; + try { + if (errorLogFile.exists()) { + errorLogWriter = new PrintWriter(new FileWriter(errorLogFile, true)); + } else { + errorLogWriter = new PrintWriter(new FileWriter(errorLogFile, false)); + } + } catch (IOException e) { + System.err.println("Unable to access or create the db_create error log"); } + String timeStamp = new SimpleDateFormat("dd/mm/yyyy HH:mm:ss") + .format(new java.util.Date()); + println("\n-------\n" + timeStamp + "\n-------\n"); + printlnError("\n-------\n" + timeStamp + "\n-------\n"); + } - /** - * Setter for logWriter property - * - * @param logWriter - the new value of the logWriter property - */ - public void setLogWriter(PrintWriter logWriter) { - this.logWriter = logWriter; + private void println(Object o) { + if (logWriter != null) { + logWriter.println(o); } + } - /** - * Setter for errorLogWriter property - * - * @param errorLogWriter - the new value of the errorLogWriter property - */ - public void setErrorLogWriter(PrintWriter errorLogWriter) { - this.errorLogWriter = errorLogWriter; + private void printlnError(Object o) { + if (errorLogWriter != null) { + errorLogWriter.println(o); } + } + + /** + * Setter for logWriter property + * + * @param logWriter - the new value of the logWriter property + */ + public void setLogWriter(PrintWriter logWriter) { + this.logWriter = logWriter; + } - /** - * Runs an SQL script (read in using the Reader parameter) - * - * @param reader - the source of the script - */ - public void runScript(Reader reader) throws IOException, SQLException { - try { - boolean originalAutoCommit = connection.getAutoCommit(); - try { - if (originalAutoCommit != this.autoCommit) { - connection.setAutoCommit(this.autoCommit); - } - runScript(connection, reader); - } finally { - connection.setAutoCommit(originalAutoCommit); - } - } catch (IOException e) { - throw e; - } catch (SQLException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException("Error running script. Cause: " + e, e); + /** + * Setter for errorLogWriter property + * + * @param errorLogWriter - the new value of the errorLogWriter property + */ + public void setErrorLogWriter(PrintWriter errorLogWriter) { + this.errorLogWriter = errorLogWriter; + } + + /** + * Runs an SQL script (read in using the Reader parameter) + * + * @param reader - the source of the script + */ + public void runScript(Reader reader) throws IOException, SQLException { + try { + boolean originalAutoCommit = connection.getAutoCommit(); + try { + if (originalAutoCommit != this.autoCommit) { + connection.setAutoCommit(this.autoCommit); } + runScript(connection, reader); + } finally { + connection.setAutoCommit(originalAutoCommit); + } + } catch (IOException e) { + throw e; + } catch (SQLException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException("Error running script. Cause: " + e, e); } + } - /** - * Runs an SQL script (read in using the Reader parameter) using the - * connection passed in - * - * @param conn - the connection to use for the script - * @param reader - the source of the script - * @throws SQLException if any SQL errors occur - * @throws IOException if there is an error reading from the Reader - */ - private void runScript(Connection conn, Reader reader) throws IOException, - SQLException { - StringBuffer command = null; - try { - LineNumberReader lineReader = new LineNumberReader(reader); - String line; - while ((line = lineReader.readLine()) != null) { - if (command == null) { - command = new StringBuffer(); - } - String trimmedLine = line.trim(); - final Matcher delimMatch = delimP.matcher(trimmedLine); - if (trimmedLine.length() < 1 - || trimmedLine.startsWith("//")) { - // Do nothing - } else if (delimMatch.matches()) { - setDelimiter(delimMatch.group(2), false); - } else if (trimmedLine.startsWith("--")) { - println(trimmedLine); - } else if (trimmedLine.length() < 1 - || trimmedLine.startsWith("--")) { - // Do nothing - } else if (!fullLineDelimiter - && trimmedLine.endsWith(getDelimiter()) - || fullLineDelimiter - && trimmedLine.equals(getDelimiter())) { - command.append(line.substring(0, line - .lastIndexOf(getDelimiter()))); - command.append(" "); - this.execCommand(conn, command, lineReader); - command = null; - } else { - command.append(line); - command.append("\n"); - } - } - if (command != null) { - this.execCommand(conn, command, lineReader); - } - if (!autoCommit) { - conn.commit(); - } - } - catch (IOException e) { - throw new IOException(String.format("Error executing '%s': %s", command, e.getMessage()), e); - } finally { - conn.rollback(); - flush(); - } + /** + * Runs an SQL script (read in using the Reader parameter) using the + * connection passed in + * + * @param conn - the connection to use for the script + * @param reader - the source of the script + * + * @throws SQLException if any SQL errors occur + * @throws IOException if there is an error reading from the Reader + */ + private void runScript(Connection conn, Reader reader) throws IOException, + SQLException { + StringBuffer command = null; + try { + LineNumberReader lineReader = new LineNumberReader(reader); + String line; + while ((line = lineReader.readLine()) != null) { + if (command == null) { + command = new StringBuffer(); + } + String trimmedLine = line.trim(); + final Matcher delimMatch = delimP.matcher(trimmedLine); + if (trimmedLine.length() < 1 + || trimmedLine.startsWith("//")) { + // Do nothing + } else if (delimMatch.matches()) { + setDelimiter(delimMatch.group(2), false); + } else if (trimmedLine.startsWith("--")) { + println(trimmedLine); + } else if (trimmedLine.length() < 1 + || trimmedLine.startsWith("--")) { + // Do nothing + } else if (!fullLineDelimiter + && trimmedLine.endsWith(getDelimiter()) + || fullLineDelimiter + && trimmedLine.equals(getDelimiter())) { + command.append(line.substring(0, line + .lastIndexOf(getDelimiter()))); + command.append(" "); + this.execCommand(conn, command, lineReader); + command = null; + } else { + command.append(line); + command.append("\n"); + } + } + if (command != null) { + this.execCommand(conn, command, lineReader); + } + if (!autoCommit) { + conn.commit(); + } + } catch (IOException e) { + throw new IOException( + String.format("Error executing '%s': %s", command, e.getMessage()), + e); + } finally { + conn.rollback(); + flush(); } + } - private void execCommand(Connection conn, StringBuffer command, - LineNumberReader lineReader) throws SQLException { - Statement statement = conn.createStatement(); + public void setDelimiter(String delimiter, boolean fullLineDelimiter) { + this.delimiter = delimiter; + this.fullLineDelimiter = fullLineDelimiter; + } - println(command); + private String getDelimiter() { + return delimiter; + } - boolean hasResults = false; - try { - hasResults = statement.execute(command.toString()); - } catch (SQLException e) { - final String errText = String.format("Error executing '%s' (line %d): %s", - command, lineReader.getLineNumber(), e.getMessage()); - printlnError(errText); - System.err.println(errText); - if (stopOnError) { - throw new SQLException(errText, e); - } - } - - if (autoCommit && !conn.getAutoCommit()) { - conn.commit(); - } + private void execCommand(Connection conn, StringBuffer command, + LineNumberReader lineReader) throws SQLException { + Statement statement = conn.createStatement(); - ResultSet rs = statement.getResultSet(); - if (hasResults && rs != null) { - ResultSetMetaData md = rs.getMetaData(); - int cols = md.getColumnCount(); - for (int i = 1; i <= cols; i++) { - String name = md.getColumnLabel(i); - print(name + "\t"); - } - println(""); - while (rs.next()) { - for (int i = 1; i <= cols; i++) { - String value = rs.getString(i); - print(value + "\t"); - } - println(""); - } - } + println(command); - try { - statement.close(); - } catch (Exception e) { - // Ignore to workaround a bug in Jakarta DBCP - } + boolean hasResults = false; + try { + hasResults = statement.execute(command.toString()); + } catch (SQLException e) { + final String errText = String.format("Error executing '%s' (line %d): %s", + command, lineReader.getLineNumber(), + e.getMessage()); + printlnError(errText); + System.err.println(errText); + if (stopOnError) { + throw new SQLException(errText, e); + } } - private String getDelimiter() { - return delimiter; + if (autoCommit && !conn.getAutoCommit()) { + conn.commit(); } - @SuppressWarnings("UseOfSystemOutOrSystemErr") - - private void print(Object o) { - if (logWriter != null) { - logWriter.print(o); + ResultSet rs = statement.getResultSet(); + if (hasResults && rs != null) { + ResultSetMetaData md = rs.getMetaData(); + int cols = md.getColumnCount(); + for (int i = 1; i <= cols; i++) { + String name = md.getColumnLabel(i); + print(name + "\t"); + } + println(""); + while (rs.next()) { + for (int i = 1; i <= cols; i++) { + String value = rs.getString(i); + print(value + "\t"); } + println(""); + } } - private void println(Object o) { - if (logWriter != null) { - logWriter.println(o); - } + try { + statement.close(); + } catch (Exception e) { + // Ignore to workaround a bug in Jakarta DBCP } + } - private void printlnError(Object o) { - if (errorLogWriter != null) { - errorLogWriter.println(o); - } + private void flush() { + if (logWriter != null) { + logWriter.flush(); + } + if (errorLogWriter != null) { + errorLogWriter.flush(); } + } - private void flush() { - if (logWriter != null) { - logWriter.flush(); - } - if (errorLogWriter != null) { - errorLogWriter.flush(); - } + @SuppressWarnings("UseOfSystemOutOrSystemErr") + + private void print(Object o) { + if (logWriter != null) { + logWriter.print(o); } + } } diff --git a/src/test/java/org/waarp/openr66/dao/database/h2/DbH2DAOTest.java b/src/test/java/org/waarp/openr66/dao/database/h2/DbH2DAOTest.java new file mode 100644 index 000000000..fd302e063 --- /dev/null +++ b/src/test/java/org/waarp/openr66/dao/database/h2/DbH2DAOTest.java @@ -0,0 +1,61 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +package org.waarp.openr66.dao.database.h2; + +import org.waarp.openr66.dao.database.DBAllDAOTest; +import org.waarp.openr66.dao.database.DBTransferDAO; +import org.waarp.openr66.dao.exception.DAOException; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class DbH2DAOTest extends DBAllDAOTest { + + private String createScript = "h2/create.sql"; + private String populateScript = "h2/populate.sql"; + private String cleanScript = "h2/clean.sql"; + + @Override + public Connection getConnection() throws SQLException { + return DriverManager.getConnection( + "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", + "openr66", + "openr66"); + } + + @Override + public void initDB() { + runScript(createScript); + runScript(populateScript); + } + + @Override + public void cleanDB() { + runScript(cleanScript); + } + + @Override + public DBTransferDAO getDAO(Connection con) throws DAOException { + return new H2TransferDAO(con); + } + +} diff --git a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBBusinessMariaDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mariadb/DBBusinessMariaDBDAOIT.java deleted file mode 100644 index 58a72ec27..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBBusinessMariaDBDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.mariadb; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MariaDBContainer; -import org.waarp.openr66.dao.database.DBBusinessDAOIT; - -public class DBBusinessMariaDBDAOIT extends DBBusinessDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MariaDBContainer db = new MariaDBContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBHostMariaDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mariadb/DBHostMariaDBDAOIT.java deleted file mode 100644 index 1d953707d..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBHostMariaDBDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.mariadb; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MariaDBContainer; -import org.waarp.openr66.dao.database.DBHostDAOIT; - -public class DBHostMariaDBDAOIT extends DBHostDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MariaDBContainer db = new MariaDBContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBLimitMariaDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mariadb/DBLimitMariaDBDAOIT.java deleted file mode 100644 index 34205d057..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBLimitMariaDBDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.mariadb; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MariaDBContainer; -import org.waarp.openr66.dao.database.DBLimitDAOIT; - -public class DBLimitMariaDBDAOIT extends DBLimitDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MariaDBContainer db = new MariaDBContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBMultipleMonitorMariaDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mariadb/DBMultipleMonitorMariaDBDAOIT.java deleted file mode 100644 index a4a1d79f7..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBMultipleMonitorMariaDBDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.mariadb; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MariaDBContainer; -import org.waarp.openr66.dao.database.DBMultipleMonitorDAOIT; - -public class DBMultipleMonitorMariaDBDAOIT extends DBMultipleMonitorDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MariaDBContainer db = new MariaDBContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBRuleMariaDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mariadb/DBRuleMariaDBDAOIT.java deleted file mode 100644 index 997fed651..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBRuleMariaDBDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.mariadb; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MariaDBContainer; -import org.waarp.openr66.dao.database.DBRuleDAOIT; - -public class DBRuleMariaDBDAOIT extends DBRuleDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MariaDBContainer db = new MariaDBContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBTransferMariaDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mariadb/DBTransferMariaDBDAOIT.java deleted file mode 100644 index ef0f5b8e6..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mariadb/DBTransferMariaDBDAOIT.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.waarp.openr66.dao.database.mariadb; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MariaDBContainer; -import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.database.DBTransferDAOIT; -import org.waarp.openr66.dao.database.MariaDBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; - -public class DBTransferMariaDBDAOIT extends DBTransferDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MariaDBContainer db = new MariaDBContainer(); - - @Override - public DBTransferDAO getDAO(Connection con) throws DAOException { - return new MariaDBTransferDAO(con); - } - - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/mariadb/DbMariadbDAOTest.java b/src/test/java/org/waarp/openr66/dao/database/mariadb/DbMariadbDAOTest.java new file mode 100644 index 000000000..d28cddd55 --- /dev/null +++ b/src/test/java/org/waarp/openr66/dao/database/mariadb/DbMariadbDAOTest.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +package org.waarp.openr66.dao.database.mariadb; + +import org.junit.ClassRule; +import org.testcontainers.containers.MariaDBContainer; +import org.waarp.openr66.dao.database.DBAllDAOTest; +import org.waarp.openr66.dao.database.DBTransferDAO; +import org.waarp.openr66.dao.database.h2.H2TransferDAO; +import org.waarp.openr66.dao.exception.DAOException; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class DbMariadbDAOTest extends DBAllDAOTest { + + @ClassRule + public static MariaDBContainer db = new MariaDBContainer(); + private String createScript = "mariadb/create.sql"; + private String populateScript = "mariadb/populate.sql"; + private String cleanScript = "mariadb/clean.sql"; + + @Override + public DBTransferDAO getDAO(Connection con) throws DAOException { + return new MariaDBTransferDAO(con); + } + + + @Override + public Connection getConnection() throws SQLException { + return DriverManager.getConnection( + db.getJdbcUrl(), + db.getUsername(), + db.getPassword()); + } + + @Override + public void initDB() { + runScript(createScript); + runScript(populateScript); + } + + @Override + public void cleanDB() { + runScript(cleanScript); + } +} diff --git a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBBusinessMySQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mySQL/DBBusinessMySQLDAOIT.java deleted file mode 100644 index b8b370c72..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBBusinessMySQLDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.mySQL; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MySQLContainer; -import org.waarp.openr66.dao.database.DBBusinessDAOIT; - -public class DBBusinessMySQLDAOIT extends DBBusinessDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MySQLContainer db = new MySQLContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBHostMySQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mySQL/DBHostMySQLDAOIT.java deleted file mode 100644 index e299444b2..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBHostMySQLDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.mySQL; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MySQLContainer; -import org.waarp.openr66.dao.database.DBHostDAOIT; - -public class DBHostMySQLDAOIT extends DBHostDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MySQLContainer db = new MySQLContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBLimitMySQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mySQL/DBLimitMySQLDAOIT.java deleted file mode 100644 index 86d913271..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBLimitMySQLDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.mySQL; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MySQLContainer; -import org.waarp.openr66.dao.database.DBLimitDAOIT; - -public class DBLimitMySQLDAOIT extends DBLimitDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MySQLContainer db = new MySQLContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBMultipleMonitorMySQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mySQL/DBMultipleMonitorMySQLDAOIT.java deleted file mode 100644 index 25985bd81..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBMultipleMonitorMySQLDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.mySQL; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MySQLContainer; -import org.waarp.openr66.dao.database.DBMultipleMonitorDAOIT; - -public class DBMultipleMonitorMySQLDAOIT extends DBMultipleMonitorDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MySQLContainer db = new MySQLContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBMySQLDAOTransfer.java b/src/test/java/org/waarp/openr66/dao/database/mySQL/DBMySQLDAOTransfer.java new file mode 100644 index 000000000..075a5c07a --- /dev/null +++ b/src/test/java/org/waarp/openr66/dao/database/mySQL/DBMySQLDAOTransfer.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +package org.waarp.openr66.dao.database.mySQL; + +import org.junit.ClassRule; +import org.testcontainers.containers.MySQLContainer; +import org.waarp.openr66.dao.database.DBAllDAOTest; +import org.waarp.openr66.dao.database.DBTransferDAO; +import org.waarp.openr66.dao.database.mariadb.MariaDBTransferDAO; +import org.waarp.openr66.dao.exception.DAOException; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class DBMySQLDAOTransfer extends DBAllDAOTest { + + @ClassRule + public static MySQLContainer db = new MySQLContainer(); + private String createScript = "mysql/create.sql"; + private String populateScript = "mysql/populate.sql"; + private String cleanScript = "mysql/clean.sql"; + + @Override + public DBTransferDAO getDAO(Connection con) throws DAOException { + return new MariaDBTransferDAO(con); + } + + @Override + public Connection getConnection() throws SQLException { + return DriverManager.getConnection( + db.getJdbcUrl(), + db.getUsername(), + db.getPassword()); + } + + @Override + public void initDB() { + runScript(createScript); + runScript(populateScript); + } + + @Override + public void cleanDB() { + runScript(cleanScript); + } +} + diff --git a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBRuleMySQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mySQL/DBRuleMySQLDAOIT.java deleted file mode 100644 index 036da04ae..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBRuleMySQLDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.mySQL; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MySQLContainer; -import org.waarp.openr66.dao.database.DBRuleDAOIT; - -public class DBRuleMySQLDAOIT extends DBRuleDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MySQLContainer db = new MySQLContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBTransferMySQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/mySQL/DBTransferMySQLDAOIT.java deleted file mode 100644 index cdbd4ddd3..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBTransferMySQLDAOIT.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.waarp.openr66.dao.database.mySQL; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.MySQLContainer; -import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.database.DBTransferDAOIT; -import org.waarp.openr66.dao.database.MariaDBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; - -public class DBTransferMySQLDAOIT extends DBTransferDAOIT { - - private String createScript = "mysql/create.sql"; - private String populateScript = "mysql/populate.sql"; - private String cleanScript = "mysql/clean.sql"; - - @ClassRule - public static MySQLContainer db = new MySQLContainer(); - - @Override - public DBTransferDAO getDAO(Connection con) throws DAOException { - return new MariaDBTransferDAO(con); - } - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/oracle/DBBusinessOracleDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/oracle/DBBusinessOracleDBDAOIT.java deleted file mode 100644 index 9765761a9..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/oracle/DBBusinessOracleDBDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.oracle; - -import org.junit.ClassRule; -import org.testcontainers.containers.OracleContainer; -import org.waarp.openr66.dao.database.DBBusinessDAOIT; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -public class DBBusinessOracleDBDAOIT extends DBBusinessDAOIT { - - private String createScript = "oracle/create.sql"; - private String populateScript = "oracle/populate.sql"; - private String cleanScript = "oracle/clean.sql"; - - @ClassRule - public static OracleContainer db = new OracleContainer("epiclabs/docker-oracle-xe-11g"); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/oracle/DBHostOracleDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/oracle/DBHostOracleDBDAOIT.java deleted file mode 100644 index b979d6bc3..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/oracle/DBHostOracleDBDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.oracle; - -import org.junit.ClassRule; -import org.testcontainers.containers.OracleContainer; -import org.waarp.openr66.dao.database.DBHostDAOIT; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -public class DBHostOracleDBDAOIT extends DBHostDAOIT { - - private String createScript = "oracle/create.sql"; - private String populateScript = "oracle/populate.sql"; - private String cleanScript = "oracles/clean.sql"; - - @ClassRule - public static OracleContainer db = new OracleContainer("epiclabs/docker-oracle-xe-11g"); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/oracle/DBLimitOracleDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/oracle/DBLimitOracleDBDAOIT.java deleted file mode 100644 index faaabe960..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/oracle/DBLimitOracleDBDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.oracle; - -import org.junit.ClassRule; -import org.testcontainers.containers.OracleContainer; -import org.waarp.openr66.dao.database.DBLimitDAOIT; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -public class DBLimitOracleDBDAOIT extends DBLimitDAOIT { - - private String createScript = "oracle/create.sql"; - private String populateScript = "oracle/populate.sql"; - private String cleanScript = "oracle/clean.sql"; - - @ClassRule - public static OracleContainer db = new OracleContainer("epiclabs/docker-oracle-xe-11g"); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/oracle/DBMultipleMonitorOracleDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/oracle/DBMultipleMonitorOracleDBDAOIT.java deleted file mode 100644 index 7475a29ce..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/oracle/DBMultipleMonitorOracleDBDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.oracle; - -import org.junit.ClassRule; -import org.testcontainers.containers.OracleContainer; -import org.waarp.openr66.dao.database.DBMultipleMonitorDAOIT; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -public class DBMultipleMonitorOracleDBDAOIT extends DBMultipleMonitorDAOIT { - - private String createScript = "oracle/create.sql"; - private String populateScript = "oracle/populate.sql"; - private String cleanScript = "oracle/clean.sql"; - - @ClassRule - public static OracleContainer db = new OracleContainer("epiclabs/docker-oracle-xe-11g"); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/oracle/DBOracleDBDAOTest.java b/src/test/java/org/waarp/openr66/dao/database/oracle/DBOracleDBDAOTest.java new file mode 100644 index 000000000..1fe786fdb --- /dev/null +++ b/src/test/java/org/waarp/openr66/dao/database/oracle/DBOracleDBDAOTest.java @@ -0,0 +1,66 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +package org.waarp.openr66.dao.database.oracle; + +import org.junit.ClassRule; +import org.testcontainers.containers.OracleContainer; +import org.waarp.openr66.dao.database.DBAllDAOTest; +import org.waarp.openr66.dao.database.DBTransferDAO; +import org.waarp.openr66.dao.exception.DAOException; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class DBOracleDBDAOTest extends DBAllDAOTest { + + @ClassRule + public static OracleContainer db = + new OracleContainer("epiclabs/docker-oracle-xe-11g"); + private String createScript = "oracle/create.sql"; + private String populateScript = "oracle/populate.sql"; + private String cleanScript = "oracle/clean.sql"; + + @Override + public DBTransferDAO getDAO(Connection con) throws DAOException { + return new OracleTransferDAO(con); + } + + @Override + public Connection getConnection() throws SQLException { + return DriverManager.getConnection( + db.getJdbcUrl(), + db.getUsername(), + db.getPassword()); + } + + @Override + public void initDB() { + runScript(createScript); + runScript(populateScript); + } + + @Override + public void cleanDB() { + runScript(cleanScript); + } +} + diff --git a/src/test/java/org/waarp/openr66/dao/database/oracle/DBRuleOracleDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/oracle/DBRuleOracleDBDAOIT.java deleted file mode 100644 index 284935720..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/oracle/DBRuleOracleDBDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.oracle; - -import org.junit.ClassRule; -import org.testcontainers.containers.OracleContainer; -import org.waarp.openr66.dao.database.DBRuleDAOIT; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -public class DBRuleOracleDBDAOIT extends DBRuleDAOIT { - - private String createScript = "oracle/create.sql"; - private String populateScript = "oracle/populate.sql"; - private String cleanScript = "oracle/clean.sql"; - - @ClassRule - public static OracleContainer db = new OracleContainer("epiclabs/docker-oracle-xe-11g"); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/oracle/DBTransferOracleDBDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/oracle/DBTransferOracleDBDAOIT.java deleted file mode 100644 index 91fa95ec2..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/oracle/DBTransferOracleDBDAOIT.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.waarp.openr66.dao.database.oracle; - -import org.junit.ClassRule; -import org.testcontainers.containers.OracleContainer; -import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.database.DBTransferDAOIT; -import org.waarp.openr66.dao.database.OracleTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -public class DBTransferOracleDBDAOIT extends DBTransferDAOIT { - - private String createScript = "oracle/create.sql"; - private String populateScript = "oracle/populate.sql"; - private String cleanScript = "oracle/clean.sql"; - - @ClassRule - public static OracleContainer db = new OracleContainer("epiclabs/docker-oracle-xe-11g"); - - @Override - public DBTransferDAO getDAO(Connection con) throws DAOException { - return new OracleTransferDAO(con); - } - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/postgres/DBBusinessPostgreSQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/postgres/DBBusinessPostgreSQLDAOIT.java deleted file mode 100644 index 098230473..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/postgres/DBBusinessPostgreSQLDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.postgres; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.PostgreSQLContainer; -import org.waarp.openr66.dao.database.DBBusinessDAOIT; - -public class DBBusinessPostgreSQLDAOIT extends DBBusinessDAOIT { - - private String createScript = "postgresql/create.sql"; - private String populateScript = "postgresql/populate.sql"; - private String cleanScript = "postgresql/clean.sql"; - - @ClassRule - public static PostgreSQLContainer db = new PostgreSQLContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/postgres/DBHostPostgreSQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/postgres/DBHostPostgreSQLDAOIT.java deleted file mode 100644 index 07cbae142..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/postgres/DBHostPostgreSQLDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.postgres; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.PostgreSQLContainer; -import org.waarp.openr66.dao.database.DBHostDAOIT; - -public class DBHostPostgreSQLDAOIT extends DBHostDAOIT { - - private String createScript = "postgresql/create.sql"; - private String populateScript = "postgresql/populate.sql"; - private String cleanScript = "postgresql/clean.sql"; - - @ClassRule - public static PostgreSQLContainer db = new PostgreSQLContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/postgres/DBLimitPostgreSQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/postgres/DBLimitPostgreSQLDAOIT.java deleted file mode 100644 index 5a2eda65e..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/postgres/DBLimitPostgreSQLDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.postgres; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.PostgreSQLContainer; -import org.waarp.openr66.dao.database.DBLimitDAOIT; - -public class DBLimitPostgreSQLDAOIT extends DBLimitDAOIT { - - private String createScript = "postgresql/create.sql"; - private String populateScript = "postgresql/populate.sql"; - private String cleanScript = "postgresql/clean.sql"; - - @ClassRule - public static PostgreSQLContainer db = new PostgreSQLContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/postgres/DBMultipleMonitorPostgreSQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/postgres/DBMultipleMonitorPostgreSQLDAOIT.java deleted file mode 100644 index 6a2cd9a61..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/postgres/DBMultipleMonitorPostgreSQLDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.postgres; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.PostgreSQLContainer; -import org.waarp.openr66.dao.database.DBMultipleMonitorDAOIT; - -public class DBMultipleMonitorPostgreSQLDAOIT extends DBMultipleMonitorDAOIT { - - private String createScript = "postgresql/create.sql"; - private String populateScript = "postgresql/populate.sql"; - private String cleanScript = "postgresql/clean.sql"; - - @ClassRule - public static PostgreSQLContainer db = new PostgreSQLContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/postgres/DBPostgreSQLDAOTest.java b/src/test/java/org/waarp/openr66/dao/database/postgres/DBPostgreSQLDAOTest.java new file mode 100644 index 000000000..30471c6dc --- /dev/null +++ b/src/test/java/org/waarp/openr66/dao/database/postgres/DBPostgreSQLDAOTest.java @@ -0,0 +1,65 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +package org.waarp.openr66.dao.database.postgres; + +import org.junit.ClassRule; +import org.testcontainers.containers.PostgreSQLContainer; +import org.waarp.openr66.dao.database.DBAllDAOTest; +import org.waarp.openr66.dao.database.DBTransferDAO; +import org.waarp.openr66.dao.exception.DAOException; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class DBPostgreSQLDAOTest extends DBAllDAOTest { + + @ClassRule + public static PostgreSQLContainer db = new PostgreSQLContainer(); + private String createScript = "postgresql/create.sql"; + private String populateScript = "postgresql/populate.sql"; + private String cleanScript = "postgresql/clean.sql"; + + @Override + public DBTransferDAO getDAO(Connection con) throws DAOException { + return new PostgreSQLTransferDAO(con); + } + + @Override + public Connection getConnection() throws SQLException { + return DriverManager.getConnection( + db.getJdbcUrl(), + db.getUsername(), + db.getPassword()); + } + + @Override + public void initDB() { + runScript(createScript); + runScript(populateScript); + } + + @Override + public void cleanDB() { + runScript(cleanScript); + } +} + diff --git a/src/test/java/org/waarp/openr66/dao/database/postgres/DBRulePostgreSQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/postgres/DBRulePostgreSQLDAOIT.java deleted file mode 100644 index 9d7b576e8..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/postgres/DBRulePostgreSQLDAOIT.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.waarp.openr66.dao.database.postgres; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.PostgreSQLContainer; -import org.waarp.openr66.dao.database.DBRuleDAOIT; - -public class DBRulePostgreSQLDAOIT extends DBRuleDAOIT { - - private String createScript = "postgresql/create.sql"; - private String populateScript = "postgresql/populate.sql"; - private String cleanScript = "postgresql/clean.sql"; - - @ClassRule - public static PostgreSQLContainer db = new PostgreSQLContainer(); - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/dao/database/postgres/DBTransferPostgreSQLDAOIT.java b/src/test/java/org/waarp/openr66/dao/database/postgres/DBTransferPostgreSQLDAOIT.java deleted file mode 100644 index d0fc78d68..000000000 --- a/src/test/java/org/waarp/openr66/dao/database/postgres/DBTransferPostgreSQLDAOIT.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.waarp.openr66.dao.database.postgres; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -import org.junit.ClassRule; -import org.testcontainers.containers.PostgreSQLContainer; -import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.database.DBTransferDAOIT; -import org.waarp.openr66.dao.database.PostgreSQLTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; - -public class DBTransferPostgreSQLDAOIT extends DBTransferDAOIT { - - private String createScript = "postgresql/create.sql"; - private String populateScript = "postgresql/populate.sql"; - private String cleanScript = "postgresql/clean.sql"; - - @ClassRule - public static PostgreSQLContainer db = new PostgreSQLContainer(); - - @Override - public DBTransferDAO getDAO(Connection con) throws DAOException { - return new PostgreSQLTransferDAO(con); - } - - @Override - public Connection getConnection() throws SQLException { - return DriverManager.getConnection( - db.getJdbcUrl(), - db.getUsername(), - db.getPassword()); - } - - @Override - public void initDB() { - runScript(createScript); - runScript(populateScript); - } - - @Override - public void cleanDB() { - runScript(cleanScript); - } -} - diff --git a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestR66PseudoMain.java b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestR66PseudoMain.java index c53b9cbe5..fb6c8cd48 100644 --- a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestR66PseudoMain.java +++ b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestR66PseudoMain.java @@ -1,99 +1,102 @@ -/** - This file is part of Waarp Project. - - Copyright 2009, Frederic Bregier, and individual contributors by the @author - tags. See the COPYRIGHT.txt in the distribution for a full listing of - individual contributors. - - All Waarp Project is free software: you can redistribute it and/or - modify it under the terms of the GNU General Public License as published - by the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Waarp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with Waarp . If not, see . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.http.rest.test; -import java.io.File; -import java.io.IOException; - import org.waarp.common.exception.CryptoException; import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; import org.waarp.gateway.kernel.rest.RestConfiguration; import org.waarp.openr66.protocol.http.rest.HttpRestR66Handler; import org.waarp.openr66.protocol.http.rest.HttpRestR66Handler.RESTHANDLERS; import org.waarp.openr66.server.R66Server; +import java.io.File; +import java.io.IOException; + /** * @author "Frederic Bregier" - * */ public class HttpTestR66PseudoMain { - public static RestConfiguration config; + public static RestConfiguration config; - public static RestConfiguration getTestConfiguration() throws CryptoException, IOException { - RestConfiguration configuration = new RestConfiguration(); - configuration.REST_PORT = 8088; - configuration.REST_SSL = false; - configuration.RESTHANDLERS_CRUD = new byte[RESTHANDLERS.values().length]; - for (int i = 0; i < configuration.RESTHANDLERS_CRUD.length; i++) { - configuration.RESTHANDLERS_CRUD[i] = RestConfiguration.CRUD.ALL.mask; - } - configuration.REST_AUTHENTICATED = true; - configuration.initializeKey(new File("/opt/R66/certs/key.sha256")); - configuration.REST_TIME_LIMIT = 10000; - configuration.REST_SIGNATURE = true; - configuration.REST_ADDRESS = "127.0.0.1"; - return configuration; + public static RestConfiguration getTestConfiguration2() + throws CryptoException, IOException { + RestConfiguration configuration = new RestConfiguration(); + configuration.REST_PORT = 8089; + configuration.REST_SSL = false; + configuration.RESTHANDLERS_CRUD = new byte[RESTHANDLERS.values().length]; + for (int i = 0; i < configuration.RESTHANDLERS_CRUD.length; i++) { + configuration.RESTHANDLERS_CRUD[i] = RestConfiguration.CRUD.READ.mask; } + configuration.REST_AUTHENTICATED = false; + configuration.REST_TIME_LIMIT = 100000; + configuration.REST_SIGNATURE = false; + configuration.REST_ADDRESS = "127.0.0.1"; + return configuration; + } - public static RestConfiguration getTestConfiguration2() throws CryptoException, IOException { - RestConfiguration configuration = new RestConfiguration(); - configuration.REST_PORT = 8089; - configuration.REST_SSL = false; - configuration.RESTHANDLERS_CRUD = new byte[RESTHANDLERS.values().length]; - for (int i = 0; i < configuration.RESTHANDLERS_CRUD.length; i++) { - configuration.RESTHANDLERS_CRUD[i] = RestConfiguration.CRUD.READ.mask; - } - configuration.REST_AUTHENTICATED = false; - configuration.REST_TIME_LIMIT = 100000; - configuration.REST_SIGNATURE = false; - configuration.REST_ADDRESS = "127.0.0.1"; - return configuration; + /** + * @param args + * + * @throws Exception + */ + public static void main(String[] args) throws Exception { + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + final WaarpLogger logger = WaarpLoggerFactory + .getLogger(HttpTestR66PseudoMain.class); + String pathTemp = "/tmp"; + if (!R66Server.initialize(args[0])) { + System.err.println("Error during startup"); + DetectionUtils.SystemExit(1); + return; } - /** - * @param args - * @throws Exception - */ - public static void main(String[] args) throws Exception { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - final WaarpLogger logger = WaarpLoggerFactory - .getLogger(HttpTestR66PseudoMain.class); - String pathTemp = "/tmp"; - if (!R66Server.initialize(args[0])) { - System.err.println("Error during startup"); - System.exit(1); - } + config = getTestConfiguration(); + HttpRestR66Handler.initialize(pathTemp); + HttpRestR66Handler.initializeService(config); - config = getTestConfiguration(); - HttpRestR66Handler.initialize(pathTemp); - HttpRestR66Handler.initializeService(config); - - logger.warn("Server RestOpenR66 starts"); + logger.warn("Server RestOpenR66 starts"); /* HmacSha256 sha = new HmacSha256(); sha.generateKey(); sha.saveSecretKey(new File("J:/Temp/temp/key.sha256")); */ + } + + public static RestConfiguration getTestConfiguration() + throws CryptoException, IOException { + RestConfiguration configuration = new RestConfiguration(); + configuration.REST_PORT = 8088; + configuration.REST_SSL = false; + configuration.RESTHANDLERS_CRUD = new byte[RESTHANDLERS.values().length]; + for (int i = 0; i < configuration.RESTHANDLERS_CRUD.length; i++) { + configuration.RESTHANDLERS_CRUD[i] = RestConfiguration.CRUD.ALL.mask; } + configuration.REST_AUTHENTICATED = true; + configuration.initializeKey(new File("/opt/R66/certs/key.sha256")); + configuration.REST_TIME_LIMIT = 10000; + configuration.REST_SIGNATURE = true; + configuration.REST_ADDRESS = "127.0.0.1"; + return configuration; + } } diff --git a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestResponseHandler.java b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestResponseHandler.java index 4bc03f158..3c4b131f4 100644 --- a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestResponseHandler.java +++ b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestResponseHandler.java @@ -1,12 +1,32 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + /* * Copyright 2009 Red Hat, Inc. - * + * * Red Hat licenses this file to you under the Apache License, version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at: - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the @@ -15,12 +35,10 @@ */ package org.waarp.openr66.protocol.http.rest.test; -import java.util.Iterator; -import java.util.concurrent.atomic.AtomicInteger; - +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; import io.netty.channel.Channel; import io.netty.handler.codec.http.HttpMethod; - import org.waarp.common.crypto.ssl.WaarpSslUtility; import org.waarp.common.json.JsonHandler; import org.waarp.gateway.kernel.exception.HttpInvalidAuthenticationException; @@ -41,242 +59,269 @@ import org.waarp.openr66.protocol.localhandler.packet.json.StopOrCancelJsonPacket; import org.waarp.openr66.protocol.localhandler.packet.json.TransferRequestJsonPacket; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.Iterator; +import java.util.concurrent.atomic.AtomicInteger; /** * Test Rest client response handler - * - * Note that for testing, result is only the last "json" command, and therefore future is only - * validated once all items are passed in a chain. - * In normal condition, each step should produce: setting the RestArgument to the RestFuture and + *

+ * Note that for testing, result is only the last "json" command, and therefore + * future is only validated once all items + * are passed in a chain. In normal condition, each step should produce: setting + * the RestArgument to the RestFuture and * validating (error or ok) to RestFuture. - * + * * @author Frederic Bregier */ public class HttpTestResponseHandler extends HttpRestR66ClientResponseHandler { - /** - * @param channel - * @throws HttpInvalidAuthenticationException - */ + /** + * @param channel + * + * @throws HttpInvalidAuthenticationException + */ - @Override - protected boolean afterError(Channel channel, RestArgument ra) { - HttpTestRestR66Client.count.incrementAndGet(); - WaarpSslUtility.closingSslChannel(channel); - return false; - } + @Override + protected boolean afterError(Channel channel, RestArgument ra) { + HttpTestRestR66Client.count.incrementAndGet(); + WaarpSslUtility.closingSslChannel(channel); + return false; + } - @Override - protected boolean afterDbGet(Channel channel, RestArgument ra) throws HttpInvalidAuthenticationException { - HttpTestRestR66Client.count.incrementAndGet(); - // Update - HttpTestRestR66Client.updateData(channel, ra); - return true; - } + @Override + protected boolean afterDbGet(Channel channel, RestArgument ra) + throws HttpInvalidAuthenticationException { + HttpTestRestR66Client.count.incrementAndGet(); + // Update + HttpTestRestR66Client.updateData(channel, ra); + return true; + } - @Override - protected boolean afterDbPost(Channel channel, RestArgument ra) throws HttpInvalidAuthenticationException { - HttpTestRestR66Client.count.incrementAndGet(); - if (ra.getAnswer().path(DbHostAuth.Columns.ADMINROLE.name()).asBoolean()) { - WaarpSslUtility.closingSslChannel(channel); - return false; - } - // Select 1 - HttpTestRestR66Client.readData(channel, ra); - return true; + @Override + protected boolean afterDbPost(Channel channel, RestArgument ra) + throws HttpInvalidAuthenticationException { + HttpTestRestR66Client.count.incrementAndGet(); + if (ra.getAnswer().path(DbHostAuth.Columns.ADMINROLE.name()).asBoolean()) { + WaarpSslUtility.closingSslChannel(channel); + return false; } + // Select 1 + HttpTestRestR66Client.readData(channel, ra); + return true; + } - @Override - protected boolean afterDbPut(Channel channel, RestArgument ra) throws HttpInvalidAuthenticationException { - HttpTestRestR66Client.count.incrementAndGet(); - if (ra.getAnswer().path(DbHostConfiguration.Columns.HOSTID.name()).asText().equals("hosta")) { - WaarpSslUtility.closingSslChannel(channel); - return false; - } - // Delete 1 - HttpTestRestR66Client.deleteData(channel, ra); - return true; + @Override + protected boolean afterDbPut(Channel channel, RestArgument ra) + throws HttpInvalidAuthenticationException { + HttpTestRestR66Client.count.incrementAndGet(); + if (ra.getAnswer().path(DbHostConfiguration.Columns.HOSTID.name()).asText() + .equals("hosta")) { + WaarpSslUtility.closingSslChannel(channel); + return false; } + // Delete 1 + HttpTestRestR66Client.deleteData(channel, ra); + return true; + } - @Override - protected boolean afterDbDelete(Channel channel, RestArgument ra) { - HttpTestRestR66Client.count.incrementAndGet(); - WaarpSslUtility.closingSslChannel(channel); - return false; - } + @Override + protected boolean afterDbDelete(Channel channel, RestArgument ra) { + HttpTestRestR66Client.count.incrementAndGet(); + WaarpSslUtility.closingSslChannel(channel); + return false; + } - @Override - protected boolean afterDbGetMultiple(Channel channel, RestArgument ra) { - HttpTestRestR66Client.count.incrementAndGet(); - WaarpSslUtility.closingSslChannel(channel); - return false; - } + @Override + protected boolean afterDbGetMultiple(Channel channel, RestArgument ra) { + HttpTestRestR66Client.count.incrementAndGet(); + WaarpSslUtility.closingSslChannel(channel); + return false; + } - @Override - protected boolean afterDbOptions(Channel channel, RestArgument ra) throws HttpInvalidAuthenticationException { - HttpTestRestR66Client.count.incrementAndGet(); - boolean newMessage = false; - AtomicInteger counter = null; - RestFuture future = channel.attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); - if (future.getOtherObject() == null) { - counter = new AtomicInteger(); - future.setOtherObject(counter); - JsonNode node = ra.getDetailedAllowOption(); - if (!node.isMissingNode()) { - for (JsonNode jsonNode : node) { - Iterator iterator = jsonNode.fieldNames(); - while (iterator.hasNext()) { - String name = iterator.next(); - if (!jsonNode.path(name).path(RestArgument.REST_FIELD.JSON_PATH.field).isMissingNode()) { - break; - } - if (name.equals(RootOptionsRestMethodHandler.ROOT)) { - continue; - } - counter.incrementAndGet(); - HttpTestRestR66Client.options(channel, name); - newMessage = true; - } - } + @Override + protected boolean afterDbOptions(Channel channel, RestArgument ra) + throws HttpInvalidAuthenticationException { + HttpTestRestR66Client.count.incrementAndGet(); + boolean newMessage = false; + AtomicInteger counter = null; + RestFuture future = + channel.attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); + if (future.getOtherObject() == null) { + counter = new AtomicInteger(); + future.setOtherObject(counter); + JsonNode node = ra.getDetailedAllowOption(); + if (!node.isMissingNode()) { + for (JsonNode jsonNode : node) { + Iterator iterator = jsonNode.fieldNames(); + while (iterator.hasNext()) { + String name = iterator.next(); + if (!jsonNode.path(name) + .path(RestArgument.REST_FIELD.JSON_PATH.field) + .isMissingNode()) { + break; } - } - if (!newMessage) { - counter = (AtomicInteger) future.getOtherObject(); - newMessage = counter.decrementAndGet() > 0; - if (!newMessage) { - future.setOtherObject(null); + if (name.equals(RootOptionsRestMethodHandler.ROOT)) { + continue; } + counter.incrementAndGet(); + HttpTestRestR66Client.options(channel, name); + newMessage = true; + } } - if (!newMessage) { - WaarpSslUtility.closingSslChannel(channel); - } - return newMessage; + } } + if (!newMessage) { + counter = (AtomicInteger) future.getOtherObject(); + newMessage = counter.decrementAndGet() > 0; + if (!newMessage) { + future.setOtherObject(null); + } + } + if (!newMessage) { + WaarpSslUtility.closingSslChannel(channel); + } + return newMessage; + } - @Override - protected boolean action(Channel channel, RestArgument ra, ACTIONS_TYPE act) { - HttpTestRestR66Client.count.incrementAndGet(); - boolean newMessage = false; - switch (act) { - case CreateTransfer: { - // Continue with GetTransferInformation - TransferRequestJsonPacket recv; - try { - recv = (TransferRequestJsonPacket) JsonPacket.createFromBuffer(JsonHandler.writeAsString(ra - .getResults().get(0))); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return newMessage; - } - InformationJsonPacket node = new InformationJsonPacket(recv.getSpecialId(), false, recv.getRequested()); - HttpTestRestR66Client.action(channel, HttpMethod.GET, RESTHANDLERS.Control.uri, node); - newMessage = true; - break; - } - case ExecuteBusiness: - // End - break; - case ExportConfig: - // no Import in automatic test - break; - case GetBandwidth: - // End - break; - case GetInformation: - // End - break; - case GetLog: - // End - break; - case GetTransferInformation: { - // Continue with Stop in StopOrCancelTransfer - ObjectNode answer = (ObjectNode) ra.getResults().get(0); - StopOrCancelJsonPacket node = new StopOrCancelJsonPacket(); - node.setRequestUserPacket(); - node.setStop(); - node.setRequested(answer.path(DbTaskRunner.Columns.REQUESTED.name()).asText()); - node.setRequester(answer.path(DbTaskRunner.Columns.REQUESTER.name()).asText()); - node.setSpecialid(answer.path(DbTaskRunner.Columns.SPECIALID.name()).asLong()); - HttpTestRestR66Client.action(channel, HttpMethod.PUT, RESTHANDLERS.Control.uri, node); - newMessage = true; - break; - } - case ImportConfig: - // End - break; - case OPTIONS: - break; - case RestartTransfer: { - // Continue with delete transfer - RestartTransferJsonPacket recv; - try { - recv = (RestartTransferJsonPacket) JsonPacket.createFromBuffer(JsonHandler.writeAsString(ra - .getResults().get(0))); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return newMessage; - } - try { - HttpTestRestR66Client.deleteData(channel, recv.getRequested(), recv.getRequester(), - recv.getSpecialid()); - } catch (HttpInvalidAuthenticationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - newMessage = true; - break; - } - case SetBandwidth: { - // Continue with GetBandwidth - BandwidthJsonPacket recv; - try { - recv = (BandwidthJsonPacket) JsonPacket.createFromBuffer(JsonHandler.writeAsString(ra.getResults() - .get(0))); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return newMessage; - } - recv.setSetter(false); - HttpTestRestR66Client.action(channel, HttpMethod.GET, RESTHANDLERS.Bandwidth.uri, recv); - newMessage = true; - break; - } - case ShutdownOrBlock: - // End - break; - case StopOrCancelTransfer: { - // Continue with RestartTransfer - StopOrCancelJsonPacket recv; - try { - recv = (StopOrCancelJsonPacket) JsonPacket.createFromBuffer(JsonHandler.writeAsString(ra - .getResults().get(0))); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return newMessage; - } - RestartTransferJsonPacket node = new RestartTransferJsonPacket(); - node.setRequestUserPacket(); - node.setRequested(recv.getRequested()); - node.setRequester(recv.getRequester()); - node.setSpecialid(recv.getSpecialid()); - HttpTestRestR66Client.action(channel, HttpMethod.PUT, RESTHANDLERS.Control.uri, node); - newMessage = true; - break; - } - case GetStatus: - break; - default: - break; - - } - if (!newMessage) { - WaarpSslUtility.closingSslChannel(channel); - } + @Override + protected boolean action(Channel channel, RestArgument ra, ACTIONS_TYPE act) { + HttpTestRestR66Client.count.incrementAndGet(); + boolean newMessage = false; + switch (act) { + case CreateTransfer: { + // Continue with GetTransferInformation + TransferRequestJsonPacket recv; + try { + recv = (TransferRequestJsonPacket) JsonPacket + .createFromBuffer(JsonHandler.writeAsString(ra + .getResults() + .get(0))); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); return newMessage; + } + InformationJsonPacket node = + new InformationJsonPacket(recv.getSpecialId(), false, + recv.getRequested()); + HttpTestRestR66Client + .action(channel, HttpMethod.GET, RESTHANDLERS.Control.uri, node); + newMessage = true; + break; + } + case ExecuteBusiness: + // End + break; + case ExportConfig: + // no Import in automatic test + break; + case GetBandwidth: + // End + break; + case GetInformation: + // End + break; + case GetLog: + // End + break; + case GetTransferInformation: { + // Continue with Stop in StopOrCancelTransfer + ObjectNode answer = (ObjectNode) ra.getResults().get(0); + StopOrCancelJsonPacket node = new StopOrCancelJsonPacket(); + node.setRequestUserPacket(); + node.setStop(); + node.setRequested( + answer.path(DbTaskRunner.Columns.REQUESTED.name()).asText()); + node.setRequester( + answer.path(DbTaskRunner.Columns.REQUESTER.name()).asText()); + node.setSpecialid( + answer.path(DbTaskRunner.Columns.SPECIALID.name()).asLong()); + HttpTestRestR66Client + .action(channel, HttpMethod.PUT, RESTHANDLERS.Control.uri, node); + newMessage = true; + break; + } + case ImportConfig: + // End + break; + case OPTIONS: + break; + case RestartTransfer: { + // Continue with delete transfer + RestartTransferJsonPacket recv; + try { + recv = (RestartTransferJsonPacket) JsonPacket + .createFromBuffer(JsonHandler.writeAsString(ra + .getResults() + .get(0))); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return newMessage; + } + try { + HttpTestRestR66Client + .deleteData(channel, recv.getRequested(), recv.getRequester(), + recv.getSpecialid()); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + newMessage = true; + break; + } + case SetBandwidth: { + // Continue with GetBandwidth + BandwidthJsonPacket recv; + try { + recv = (BandwidthJsonPacket) JsonPacket + .createFromBuffer(JsonHandler.writeAsString(ra.getResults() + .get(0))); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return newMessage; + } + recv.setSetter(false); + HttpTestRestR66Client + .action(channel, HttpMethod.GET, RESTHANDLERS.Bandwidth.uri, recv); + newMessage = true; + break; + } + case ShutdownOrBlock: + // End + break; + case StopOrCancelTransfer: { + // Continue with RestartTransfer + StopOrCancelJsonPacket recv; + try { + recv = (StopOrCancelJsonPacket) JsonPacket + .createFromBuffer(JsonHandler.writeAsString(ra + .getResults() + .get(0))); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return newMessage; + } + RestartTransferJsonPacket node = new RestartTransferJsonPacket(); + node.setRequestUserPacket(); + node.setRequested(recv.getRequested()); + node.setRequester(recv.getRequester()); + node.setSpecialid(recv.getSpecialid()); + HttpTestRestR66Client + .action(channel, HttpMethod.PUT, RESTHANDLERS.Control.uri, node); + newMessage = true; + break; + } + case GetStatus: + break; + default: + break; + + } + if (!newMessage) { + WaarpSslUtility.closingSslChannel(channel); } + return newMessage; + } } diff --git a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestClientInitializer.java b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestClientInitializer.java index b990bf5d9..da310aa77 100644 --- a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestClientInitializer.java +++ b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestClientInitializer.java @@ -1,12 +1,32 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + /* * Copyright 2009 Red Hat, Inc. - * + * * Red Hat licenses this file to you under the Apache License, version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at: - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the @@ -15,44 +35,45 @@ */ package org.waarp.openr66.protocol.http.rest.test; -import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelInitializer; +import io.netty.channel.ChannelPipeline; import io.netty.channel.socket.SocketChannel; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpContentDecompressor; import io.netty.handler.ssl.SslHandler; import io.netty.handler.stream.ChunkedWriteHandler; - import org.waarp.common.crypto.ssl.WaarpSslContextFactory; /** * Test Rest client pipeline factory */ -public class HttpTestRestClientInitializer extends ChannelInitializer { - private final WaarpSslContextFactory waarpSslContextFactory; +public class HttpTestRestClientInitializer + extends ChannelInitializer { + private final WaarpSslContextFactory waarpSslContextFactory; - public HttpTestRestClientInitializer(WaarpSslContextFactory waarpSslContextFactory) { - this.waarpSslContextFactory = waarpSslContextFactory; - } + public HttpTestRestClientInitializer( + WaarpSslContextFactory waarpSslContextFactory) { + this.waarpSslContextFactory = waarpSslContextFactory; + } - protected void initChannel(SocketChannel ch) throws Exception { - // Create a default pipeline implementation. - ChannelPipeline pipeline = ch.pipeline(); + protected void initChannel(SocketChannel ch) throws Exception { + // Create a default pipeline implementation. + ChannelPipeline pipeline = ch.pipeline(); - // Enable HTTPS if necessary. - if (waarpSslContextFactory != null) { - SslHandler handler = waarpSslContextFactory.initInitializer(false, false); - pipeline.addLast("ssl", handler); - } + // Enable HTTPS if necessary. + if (waarpSslContextFactory != null) { + SslHandler handler = waarpSslContextFactory.initInitializer(false, false); + pipeline.addLast("ssl", handler); + } - pipeline.addLast("codec", new HttpClientCodec()); - // Remove the following line if you don't want automatic content - // decompression. - pipeline.addLast("inflater", new HttpContentDecompressor()); + pipeline.addLast("codec", new HttpClientCodec()); + // Remove the following line if you don't want automatic content + // decompression. + pipeline.addLast("inflater", new HttpContentDecompressor()); - // to be used since huge file transfer - pipeline.addLast("streamer", new ChunkedWriteHandler()); + // to be used since huge file transfer + pipeline.addLast("streamer", new ChunkedWriteHandler()); - pipeline.addLast("handler", new HttpTestResponseHandler()); - } + pipeline.addLast("handler", new HttpTestResponseHandler()); + } } diff --git a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestR66Client.java b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestR66Client.java index 6f4a0363a..eacce413d 100644 --- a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestR66Client.java +++ b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestR66Client.java @@ -1,38 +1,27 @@ -/** - This file is part of Waarp Project. - - Copyright 2009, Frederic Bregier, and individual contributors by the @author - tags. See the COPYRIGHT.txt in the distribution for a full listing of - individual contributors. - - All Waarp Project is free software: you can redistribute it and/or - modify it under the terms of the GNU General Public License as published - by the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Waarp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with Waarp . If not, see . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.http.rest.test; -import java.io.File; -import java.io.IOException; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - +import com.fasterxml.jackson.databind.node.ObjectNode; import io.netty.channel.Channel; import io.netty.handler.codec.http.HttpMethod; - import org.joda.time.DateTime; import org.waarp.common.crypto.Des; import org.waarp.common.crypto.ssl.WaarpSslUtility; @@ -83,883 +72,1090 @@ import org.waarp.openr66.protocol.localhandler.packet.json.ShutdownOrBlockJsonPacket; import org.waarp.openr66.protocol.localhandler.packet.json.TransferRequestJsonPacket; -import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.File; +import java.io.IOException; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; + +import static org.junit.Assert.*; /** * @author "Frederic Bregier" - * */ public class HttpTestRestR66Client implements Runnable { - private static WaarpLogger logger; - public static int NB = 2; - - public static int NBPERTHREAD = 100; - - private static HttpRestR66Client clientHelper; - private static final String keydesfilename = "/opt/R66/certs/test-key.des"; - private static final String baseURI = "/"; - private static String host = "127.0.0.1"; - - private static final String userAuthent = "admin2"; - private static final String keyAuthent = "test"; - - private static final long limit = 10000000; - private static final long delaylimit = 5000; - private static final String hostid = "hostZZ"; - private static final String address = "10.10.10.10"; - private static final String hostkey = "ABCDEFGH"; - private static final String business = "hostas"; - private static final String roles = "hostasFULLADMIN"; - private static final String aliases = "hostZZhostZZ2"; - private static final String others = "2.4.25"; - private static final String idRule = "ruleZZ"; - private static final String ids = "hostahostZZ"; - private static final String tasks = "LOGlog0"; - - public static boolean DEBUG = false; - private static boolean isStatus = false; - public static AtomicLong count = new AtomicLong(); - - /** - * @param args - */ - @SuppressWarnings("unused") - public static void main(String[] args) { - if (args.length > 2) { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(WaarpLogLevel.DEBUG)); - } else { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - } - logger = WaarpLoggerFactory.getLogger(HttpTestRestR66Client.class); - Configuration.configuration.setHOST_ID(hostid); - if (args.length > 0) { - NB = Integer.parseInt(args[0]); - if (Configuration.configuration.getCLIENT_THREAD() < NB) { - Configuration.configuration.setCLIENT_THREAD(NB + 1); - } - if (args.length > 1) { - NBPERTHREAD = Integer.parseInt(args[1]); - } + public static String keydesfilename = "/opt/R66/certs/test-key.des"; + private static final String baseURI = "/"; + private static final String userAuthent = "admin2"; + private static final String keyAuthent = "test"; + private static final long limit = 10000000; + private static final long delaylimit = 5000; + private static final String hostid = "hostZZ"; + private static final String address = "10.10.10.10"; + private static final String hostkey = "ABCDEFGH"; + private static final String business = + "hostas"; + private static final String roles = + "hostasFULLADMIN"; + private static final String aliases = + "hostZZhostZZ2"; + private static final String others = "2.4.25"; + private static final String idRule = "ruleZZ"; + private static final String ids = + "hostahostZZ"; + private static final String tasks = + "LOGlog0"; + public static int NB = 2; + public static int NBPERTHREAD = 10; + public static boolean DEBUG = false; + public static AtomicLong count = new AtomicLong(); + public static int rank = 1; + private static WaarpLogger logger; + private static HttpRestR66Client clientHelper; + private static String host = "127.0.0.1"; + private static boolean isStatus = false; + + /** + * @param args + */ + @SuppressWarnings("unused") + public static void main(String[] args) { + if (args.length > 2) { + WaarpLoggerFactory + .setDefaultFactory(new WaarpSlf4JLoggerFactory(WaarpLogLevel.DEBUG)); + } else { + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + } + logger = WaarpLoggerFactory.getLogger(HttpTestRestR66Client.class); + Configuration.configuration.setHOST_ID(hostid); + if (args.length > 0) { + NB = Integer.parseInt(args[0]); + if (Configuration.configuration.getCLIENT_THREAD() < NB) { + Configuration.configuration.setCLIENT_THREAD(NB + 1); + } + if (args.length > 1) { + NBPERTHREAD = Integer.parseInt(args[1]); + } + } + if (NB == 1 && NBPERTHREAD == 1) { + DEBUG = true; + } + + try { + HttpTestR66PseudoMain.config = + HttpTestR66PseudoMain.getTestConfiguration2(); + } catch (CryptoException e2) { + // TODO Auto-generated catch block + e2.printStackTrace(); + assertFalse("Cant connect", true); + return; + } catch (IOException e2) { + // TODO Auto-generated catch block + e2.printStackTrace(); + assertFalse("Cant connect", true); + return; + } + if (HttpTestR66PseudoMain.config.REST_ADDRESS != null) { + host = HttpTestR66PseudoMain.config.REST_ADDRESS; + } + String filename = keydesfilename; + Configuration.configuration.setCryptoFile(filename); + File keyfile = new File(filename); + Des des = new Des(); + try { + des.setSecretKey(keyfile); + } catch (CryptoException e) { + logger.error("Unable to load CryptoKey from Config file"); + assertFalse("Cant Load", true); + return; + } catch (IOException e) { + logger.error("Unable to load CryptoKey from Config file"); + assertFalse("Cant Load", true); + return; + } + Configuration.configuration.setCryptoKey(des); + Configuration.configuration + .startJunitRestSupport(HttpTestR66PseudoMain.config); + // Configure the client. + clientHelper = new HttpRestR66Client(baseURI, + new HttpTestRestClientInitializer( + null), + Configuration.configuration + .getCLIENT_THREAD(), + Configuration.configuration + .getTIMEOUTCON()); + logger.warn("ClientHelper created"); + try { + try { + long start = System.currentTimeMillis(); + for (int i = 0; i < NBPERTHREAD; i++) { + options(null); } - if (NB == 1 && NBPERTHREAD == 1) { - DEBUG = true; + long stop = System.currentTimeMillis(); + long diff = stop - start == 0? 1 : stop - start; + logger.warn("Options: " + count.get() * 1000 / diff + + " req/s NbPerThread: " + NBPERTHREAD + "=" + + count.get()); + assertTrue("Options", count.get() > 0); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertFalse("Cant connect", true); + } + count.set(0); + long start = System.currentTimeMillis(); + rank = 1; + RESTHANDLERS handler1 = RESTHANDLERS.DbConfiguration; + try { + multiDataRequests(handler1); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertFalse("Cant connect", true); + } + handler1 = RESTHANDLERS.DbHostAuth; + try { + multiDataRequests(handler1); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertFalse("Cant connect", true); + } + handler1 = RESTHANDLERS.DbHostConfiguration; + try { + multiDataRequests(handler1); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertFalse("Cant connect", true); + } + handler1 = RESTHANDLERS.DbRule; + try { + multiDataRequests(handler1); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertFalse("Cant connect", true); + } + handler1 = RESTHANDLERS.DbTaskRunner; + try { + multiDataRequests(handler1); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertFalse("Cant connect", true); + } + long stop = System.currentTimeMillis(); + long diff = stop - start == 0? 1 : stop - start; + logger.warn("Create: " + count.get() * 1000 / diff + " req/s " + + NBPERTHREAD + "=?" + count.get()); + assertTrue("Create", count.get() > 0); + count.set(0); + start = System.currentTimeMillis(); + for (RestMethodHandler methodHandler : HttpTestR66PseudoMain.config.restHashMap + .values()) { + if (methodHandler instanceof DataModelRestMethodHandler) { + RESTHANDLERS handler = RESTHANDLERS + .getRESTHANDLER(methodHandler.getPath()); + try { + realAllData(handler); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertFalse("Cant connect", true); + } } + } + stop = System.currentTimeMillis(); + diff = stop - start == 0? 1 : stop - start; + logger.warn("ReadAll: " + count.get() * 1000 / diff + " req/s " + + NBPERTHREAD + "=?" + count.get()); + assertTrue("ReadAll", count.get() > 0); + count.set(0); + start = System.currentTimeMillis(); + for (int i = 0; i < NBPERTHREAD; i++) { try { - HttpTestR66PseudoMain.config = HttpTestR66PseudoMain.getTestConfiguration(); - } catch (CryptoException e2) { - // TODO Auto-generated catch block - e2.printStackTrace(); - return; - } catch (IOException e2) { - // TODO Auto-generated catch block - e2.printStackTrace(); - return; + multiDataRequests(RESTHANDLERS.DbTaskRunner); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertFalse("Cant connect", true); } - if (HttpTestR66PseudoMain.config.REST_ADDRESS != null) { - host = HttpTestR66PseudoMain.config.REST_ADDRESS; + } + stop = System.currentTimeMillis(); + diff = stop - start == 0? 1 : stop - start; + logger.warn( + "CreateMultiple: " + count.get() * 1000 / diff + " req/s " + + NBPERTHREAD + "=?" + count.get()); + assertTrue("CreateMultiple", count.get() > 0); + + count.set(0); + start = System.currentTimeMillis(); + launchThreads(); + stop = System.currentTimeMillis(); + diff = stop - start == 0? 1 : stop - start; + logger.warn("CreateMultipleThread: " + count.get() * 1000 / diff + + " req/s " + NBPERTHREAD * NB + "=?" + + count.get()); + assertTrue("CreateMultipleThread", count.get() > 0); + + // Set usefull item first + if (RestConfiguration.CRUD.UPDATE.isValid( + HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[RESTHANDLERS.DbHostConfiguration + .ordinal()])) { + rank = 2; + + String key = null, value = null; + Channel channel = clientHelper.getChannel(host, + HttpTestR66PseudoMain.config.REST_PORT); + if (channel != null) { + String buz = null; + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; + // Need business + buz = + "hostashosta2hostas2" + + + "hostatesttests" + + "" + userAuthent + + ""; + } else { + // Need business + buz = + "hostashosta2hostas2" + + + "hostatesttests" + + + "monadmin"; + } + ObjectNode node = JsonHandler.createObjectNode(); + node.put(DbHostConfiguration.Columns.BUSINESS.name(), buz); + logger.warn("Send query: " + + RESTHANDLERS.DbHostConfiguration.uri); + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, + HttpMethod.PUT, + host, + RESTHANDLERS.DbHostConfiguration.uri + + "/hosta", key, value, null, + JsonHandler.writeAsString(node)); + try { + future.await(); + } catch (InterruptedException e) { + } + WaarpSslUtility.closingSslChannel(channel); + // assertTrue("Action should be ok", future.isSuccess()); } - String filename = keydesfilename; - Configuration.configuration.setCryptoFile(filename); - File keyfile = new File(filename); - Des des = new Des(); - try { - des.setSecretKey(keyfile); - } catch (CryptoException e) { - logger.error("Unable to load CryptoKey from Config file"); - return; - } catch (IOException e) { - logger.error("Unable to load CryptoKey from Config file"); - return; + // Need Hostzz + channel = clientHelper.getChannel(host, + HttpTestR66PseudoMain.config.REST_PORT); + if (channel != null) { + AbstractDbData dbData; + dbData = new DbHostAuth(hostid + rank, address, + HttpTestR66PseudoMain.config.REST_PORT, + false, + hostkey.getBytes(), true, false); + logger.warn("Send query: " + RESTHANDLERS.DbHostAuth.uri); + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, + HttpMethod.POST, + host, RESTHANDLERS.DbHostAuth.uri, key, + value, null, dbData.asJson()); + try { + future.await(); + } catch (InterruptedException e) { + } + WaarpSslUtility.closingSslChannel(channel); + logger.warn("Sent query: " + RESTHANDLERS.DbHostAuth.uri); + assertTrue("Action should be ok", future.isSuccess()); } - Configuration.configuration.setCryptoKey(des); - HttpRestR66Handler.instantiateHandlers(HttpTestR66PseudoMain.config); - // Configure the client. - clientHelper = new HttpRestR66Client(baseURI, new HttpTestRestClientInitializer(null), - Configuration.configuration.getCLIENT_THREAD(), Configuration.configuration.getTIMEOUTCON()); - logger.warn("ClientHelper created"); - try { - try { - long start = System.currentTimeMillis(); - for (int i = 0; i < NBPERTHREAD; i++) { - options(null); - } - long stop = System.currentTimeMillis(); - long diff = stop - start == 0 ? 1 : stop - start; - logger.warn("Options: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?" + count.get()); - } catch (HttpInvalidAuthenticationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - count.set(0); - long start = System.currentTimeMillis(); - if (false) { - for (RESTHANDLERS handler : HttpRestR66Handler.RESTHANDLERS.values()) { - try { - deleteData(handler); - } catch (HttpInvalidAuthenticationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - long stop = System.currentTimeMillis(); - long diff = stop - start == 0 ? 1 : stop - start; - if (false) { - logger.warn("Delete: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?" + count.get()); - } - count.set(0); - start = System.currentTimeMillis(); - for (RestMethodHandler methodHandler : HttpTestR66PseudoMain.config.restHashMap.values()) { - if (methodHandler instanceof DataModelRestMethodHandler) { - RESTHANDLERS handler = RESTHANDLERS.getRESTHANDLER(methodHandler.getPath()); - try { - multiDataRequests(handler); - } catch (HttpInvalidAuthenticationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - stop = System.currentTimeMillis(); - diff = stop - start == 0 ? 1 : stop - start; - logger.warn("Create: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?" + count.get()); - count.set(0); - start = System.currentTimeMillis(); - for (RestMethodHandler methodHandler : HttpTestR66PseudoMain.config.restHashMap.values()) { - if (methodHandler instanceof DataModelRestMethodHandler) { - RESTHANDLERS handler = RESTHANDLERS.getRESTHANDLER(methodHandler.getPath()); - try { - realAllData(handler); - } catch (HttpInvalidAuthenticationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - stop = System.currentTimeMillis(); - diff = stop - start == 0 ? 1 : stop - start; - logger.warn("ReadAll: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?" + count.get()); - - count.set(0); - start = System.currentTimeMillis(); - for (int i = 0; i < NBPERTHREAD; i++) { - try { - multiDataRequests(RESTHANDLERS.DbTaskRunner); - } catch (HttpInvalidAuthenticationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - stop = System.currentTimeMillis(); - diff = stop - start == 0 ? 1 : stop - start; - logger.warn("CreateMultiple: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?" + count.get()); - - count.set(0); - start = System.currentTimeMillis(); - launchThreads(); - stop = System.currentTimeMillis(); - diff = stop - start == 0 ? 1 : stop - start; - logger.warn("CreateMultipleThread: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD * NB + "=?" - + count.get()); + } - // Set usefull item first - if (RestConfiguration.CRUD.UPDATE - .isValid(HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[RESTHANDLERS.DbHostConfiguration.ordinal()])) { - String key = null, value = null; - Channel channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); - if (channel != null) { - String buz = null; - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - // Need business - buz = "hostashosta2hostas2" - + - "hostatesttests" - + - "" + userAuthent + ""; - } else { - // Need business - buz = "hostashosta2hostas2" - + - "hostatesttests" - + - "monadmin"; - } - ObjectNode node = JsonHandler.createObjectNode(); - node.put(DbHostConfiguration.Columns.BUSINESS.name(), buz); - logger.warn("Send query: " + RESTHANDLERS.DbHostConfiguration.uri); - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.PUT, - host, RESTHANDLERS.DbHostConfiguration.uri + "/hosta", key, value, - null, - JsonHandler.writeAsString(node)); - try { - future.await(); - } catch (InterruptedException e) { - } - WaarpSslUtility.closingSslChannel(channel); - } - // Need Hostzz - channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); - if (channel != null) { - AbstractDbData dbData; - dbData = new DbHostAuth(hostid, address, HttpTestR66PseudoMain.config.REST_PORT, false, - hostkey.getBytes(), true, false); - logger.warn("Send query: " + RESTHANDLERS.DbHostAuth.uri); - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.POST, - host, RESTHANDLERS.DbHostAuth.uri, key, value, - null, - dbData.asJson()); - try { - future.await(); - } catch (InterruptedException e) { - } - WaarpSslUtility.closingSslChannel(channel); - } - } + // Other Command as actions + count.set(0); + start = System.currentTimeMillis(); + for (RestMethodHandler methodHandler : HttpTestR66PseudoMain.config.restHashMap + .values()) { + if (methodHandler instanceof DataModelRestMethodHandler) { + RESTHANDLERS handler = RESTHANDLERS + .getRESTHANDLER(methodHandler.getPath()); + logger.warn("Send query: " + handler); + try { + action(handler); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertFalse("Cant connect", true); + } + } + } + getStatus(); + stop = System.currentTimeMillis(); + diff = stop - start == 0? 1 : stop - start; + logger.warn("Commands: " + count.get() * 1000 / diff + " req/s " + + NBPERTHREAD * NB + "=?" + count.get()); + assertTrue("Commands", count.get() > 0); - // Other Command as actions - count.set(0); - start = System.currentTimeMillis(); - for (RestMethodHandler methodHandler : HttpTestR66PseudoMain.config.restHashMap.values()) { - if (methodHandler instanceof DataModelRestMethodHandler) { - RESTHANDLERS handler = RESTHANDLERS.getRESTHANDLER(methodHandler.getPath()); - try { - action(handler); - } catch (HttpInvalidAuthenticationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - getStatus(); - stop = System.currentTimeMillis(); - diff = stop - start == 0 ? 1 : stop - start; - logger.warn("Commands: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD * NB + "=?" + count.get()); - - count.set(0); - start = System.currentTimeMillis(); - for (int i = 0; i < NBPERTHREAD; i++) { - getStatus(); - } - stop = System.currentTimeMillis(); - diff = stop - start == 0 ? 1 : stop - start; - logger.warn("GetStatusMultiple: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD + "=?" - + count.get()); + count.set(0); + start = System.currentTimeMillis(); + logger.warn("Request status"); + for (int i = 0; i < NBPERTHREAD; i++) { + getStatus(); + } + stop = System.currentTimeMillis(); + diff = stop - start == 0? 1 : stop - start; + logger.warn( + "GetStatusMultiple: " + count.get() * 1000 / diff + + " req/s " + NBPERTHREAD + "=?" + count.get()); + assertTrue("GetStatusMultiple", count.get() > 0); - count.set(0); - isStatus = true; - start = System.currentTimeMillis(); - launchThreads(); - stop = System.currentTimeMillis(); - diff = stop - start == 0 ? 1 : stop - start; - logger.warn("GetStatusMultipleThread: " + count.get() * 1000 / diff + " req/s " + NBPERTHREAD * NB + "=?" - + count.get()); + count.set(0); + isStatus = true; + start = System.currentTimeMillis(); + launchThreads(); + stop = System.currentTimeMillis(); + diff = stop - start == 0? 1 : stop - start; + logger.warn( + "GetStatusMultipleThread: " + count.get() * 1000 / diff + + " req/s " + NBPERTHREAD * NB + "=?" + + count.get()); + assertTrue("GetStatusMultipleThread", count.get() > 0); - // Clean - if (RestConfiguration.CRUD.UPDATE - .isValid(HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[RESTHANDLERS.DbHostConfiguration.ordinal()])) { - String key = null, value = null; - Channel channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); - if (channel != null) { - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - } - // Reset business - String buz = "hostashosta2hostas2" - + - "hostatesttests"; - ObjectNode node = JsonHandler.createObjectNode(); - node.put(DbHostConfiguration.Columns.BUSINESS.name(), buz); - logger.warn("Send query: " + RESTHANDLERS.DbHostConfiguration.uri); - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.PUT, - host, RESTHANDLERS.DbHostConfiguration.uri + "/hosta", key, value, - null, - JsonHandler.writeAsString(node)); - try { - future.await(); - } catch (InterruptedException e) { - } - WaarpSslUtility.closingSslChannel(channel); - } - // Remove Hostzz - channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); - if (channel != null) { - try { - RestFuture future = deleteData(channel, RESTHANDLERS.DbHostAuth); - try { - future.await(); - } catch (InterruptedException e) { - } - } catch (HttpInvalidAuthenticationException e1) { - } - WaarpSslUtility.closingSslChannel(channel); - } - // Shutdown - channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); - if (channel != null) { - ShutdownOrBlockJsonPacket shutd = new ShutdownOrBlockJsonPacket(); - shutd.setRestartOrBlock(false); - shutd.setShutdownOrBlock(true); - shutd.setRequestUserPacket(LocalPacketFactory.SHUTDOWNPACKET); - String pwd = "pwdhttp"; - byte[] bpwd = FilesystemBasedDigest.passwdCrypt(pwd.getBytes(WaarpStringUtils.UTF8)); - shutd.setKey(bpwd); - logger.warn("Send query: " + RESTHANDLERS.Server.uri); - RestFuture future = action(channel, HttpMethod.PUT, RESTHANDLERS.Server.uri, shutd); - try { - future.await(); - } catch (InterruptedException e) { - } - WaarpSslUtility.closingSslChannel(channel); - } - } - try { - Thread.sleep(100); - } catch (InterruptedException e1) { - } - } finally { - logger.debug("ClientHelper closing"); - clientHelper.closeAll(); - logger.warn("ClientHelper closed"); + count.set(0); + start = System.currentTimeMillis(); + if (true) { + for (RESTHANDLERS handler : HttpRestR66Handler.RESTHANDLERS + .values()) { + try { + deleteData(handler); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + assertFalse("Cant connect", true); + } } - } + } + stop = System.currentTimeMillis(); + diff = stop - start == 0? 1 : stop - start; + if (true) { + logger.warn("Delete: " + count.get() * 1000 / diff + " req/s " + + NBPERTHREAD + "=?" + count.get()); + assertTrue("Delete", count.get() > 0); + } - public static void launchThreads() { - // init thread model - ExecutorService pool = Executors.newFixedThreadPool(NB); - HttpTestRestR66Client[] clients = new HttpTestRestR66Client[NB]; - for (int i = 0; i < NB; i++) { - clients[i] = new HttpTestRestR66Client(); + // Clean + if (RestConfiguration.CRUD.UPDATE.isValid( + HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[RESTHANDLERS.DbHostConfiguration + .ordinal()])) { + String key = null, value = null; + Channel channel = clientHelper.getChannel(host, + HttpTestR66PseudoMain.config.REST_PORT); + if (channel != null) { + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; + } + // Reset business + String buz = + "hostashosta2hostas2" + + + "hostatesttests"; + ObjectNode node = JsonHandler.createObjectNode(); + node.put(DbHostConfiguration.Columns.BUSINESS.name(), buz); + logger.warn("Send query: " + + RESTHANDLERS.DbHostConfiguration.uri); + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, + HttpMethod.PUT, + host, + RESTHANDLERS.DbHostConfiguration.uri + + "/hosta", key, value, null, + JsonHandler.writeAsString(node)); + try { + future.await(); + } catch (InterruptedException e) { + } + WaarpSslUtility.closingSslChannel(channel); + // assertTrue("Action should be ok", future.isSuccess()); } - for (int i = 0; i < NB; i++) { - pool.execute(clients[i]); + // Remove Hostzz + channel = clientHelper.getChannel(host, + HttpTestR66PseudoMain.config.REST_PORT); + if (channel != null) { + RestFuture future = null; + try { + future = deleteData(channel, RESTHANDLERS.DbHostAuth); + try { + future.await(); + } catch (InterruptedException e) { + } + } catch (HttpInvalidAuthenticationException e1) { + } + WaarpSslUtility.closingSslChannel(channel); + // assertTrue("Action should be ok", future.isSuccess()); } - pool.shutdown(); - try { - while (!pool.awaitTermination(100000, TimeUnit.SECONDS)) - ; - } catch (InterruptedException e) { + // Shutdown + channel = clientHelper.getChannel(host, + HttpTestR66PseudoMain.config.REST_PORT); + if (channel != null) { + ShutdownOrBlockJsonPacket shutd = + new ShutdownOrBlockJsonPacket(); + shutd.setRestartOrBlock(false); + shutd.setShutdownOrBlock(true); + shutd.setRequestUserPacket( + LocalPacketFactory.SHUTDOWNPACKET); + String pwd = "pwdhttp"; + byte[] bpwd = FilesystemBasedDigest + .passwdCrypt(pwd.getBytes(WaarpStringUtils.UTF8)); + shutd.setKey(bpwd); + logger.warn("Send query: " + RESTHANDLERS.Server.uri); + RestFuture future = action(channel, HttpMethod.PUT, + RESTHANDLERS.Server.uri, shutd); + try { + future.await(); + } catch (InterruptedException e) { + } + WaarpSslUtility.closingSslChannel(channel); + assertTrue("Action should be ok", future.isSuccess()); } + } + try { + Thread.sleep(100); + } catch (InterruptedException e1) { + } + } finally { + logger.debug("ClientHelper closing"); + // clientHelper.closeAll(); + logger.warn("ClientHelper closed"); } + } - public static void options(String uri) throws HttpInvalidAuthenticationException { - Channel channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); - if (channel == null) { - logger.warn("Cannot connect to: " + host + ":" + HttpTestR66PseudoMain.config.REST_PORT); - return; - } - RestFuture future = options(channel, uri); - try { - future.await(); - } catch (InterruptedException e) { - } - logger.debug("Closing Channel"); - WaarpSslUtility.closingSslChannel(channel); - logger.debug("Channel closed"); + public static void launchThreads() { + // init thread model + ExecutorService pool = Executors.newFixedThreadPool(NB); + HttpTestRestR66Client[] clients = new HttpTestRestR66Client[NB]; + for (int i = 0; i < NB; i++) { + clients[i] = new HttpTestRestR66Client(); + } + for (int i = 0; i < NB; i++) { + pool.execute(clients[i]); + } + pool.shutdown(); + try { + while (!pool.awaitTermination(100000, TimeUnit.SECONDS)) { + ; + } + } catch (InterruptedException e) { } + } - protected static RestFuture options(Channel channel, String uri) throws HttpInvalidAuthenticationException { - logger.debug("Send query"); - String key = null, value = null; - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - } - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.OPTIONS, host, - uri, key, value, null, null); - logger.debug("Query sent"); - return future; - } - - protected static AbstractDbData getItem(RESTHANDLERS data) throws HttpInvalidAuthenticationException { - switch (data) { - case DbConfiguration: - return new DbConfiguration(hostid, limit, limit, limit, limit, delaylimit); - case DbHostAuth: - return new DbHostAuth(hostid, address, HttpTestR66PseudoMain.config.REST_PORT, false, - hostkey.getBytes(), false, false); - case DbHostConfiguration: - return new DbHostConfiguration(hostid, business, roles, aliases, others); - case DbRule: - return new DbRule(idRule, ids, 2, "/recv", "/send", "/arch", "/work", tasks, tasks, tasks, tasks, - tasks, tasks); - case DbTaskRunner: - ObjectNode source = JsonHandler.createObjectNode(); - source.put(Columns.IDRULE.name(), idRule); - source.put(Columns.RANK.name(), 0); - source.put(Columns.BLOCKSZ.name(), 65536); - source.put(Columns.FILEINFO.name(), "file info"); - source.put(Columns.FILENAME.name(), "filename"); - source.put(Columns.GLOBALLASTSTEP.name(), TASKSTEP.NOTASK.ordinal()); - source.put(Columns.GLOBALSTEP.name(), TASKSTEP.NOTASK.ordinal()); - source.put(Columns.INFOSTATUS.name(), ErrorCode.Unknown.ordinal()); - source.put(Columns.ISMOVED.name(), false); - source.put(Columns.MODETRANS.name(), 2); - source.put(Columns.ORIGINALNAME.name(), "original filename"); - source.put(Columns.OWNERREQ.name(), Configuration.configuration.getHOST_ID()); - source.put(Columns.SPECIALID.name(), DbConstant.ILLEGALVALUE); - source.put(Columns.REQUESTED.name(), hostid); - source.put(Columns.REQUESTER.name(), hostid); - source.put(Columns.RETRIEVEMODE.name(), true); - source.put(Columns.STARTTRANS.name(), System.currentTimeMillis()); - source.put(Columns.STOPTRANS.name(), System.currentTimeMillis()); - source.put(Columns.STEP.name(), -1); - source.put(Columns.STEPSTATUS.name(), ErrorCode.Unknown.ordinal()); - source.put(Columns.TRANSFERINFO.name(), "transfer info"); - source.put(DbTaskRunner.JSON_RESCHEDULE, false); - source.put(DbTaskRunner.JSON_THROUGHMODE, false); - source.put(DbTaskRunner.JSON_ORIGINALSIZE, 123L); - try { - return new DbTaskRunner(source); - } catch (WaarpDatabaseException e) { - throw new HttpInvalidAuthenticationException(e); - } - default: - break; - } - return null; + public static void options(String uri) + throws HttpInvalidAuthenticationException { + Channel channel = clientHelper + .getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); + if (channel == null) { + logger.warn("Cannot connect to: " + host + ":" + + HttpTestR66PseudoMain.config.REST_PORT); + assertFalse("Cant connect", true); + return; + } + RestFuture future = options(channel, uri); + try { + future.await(); + } catch (InterruptedException e) { } + logger.debug("Closing Channel"); + WaarpSslUtility.closingSslChannel(channel); + assertTrue("Action should be ok", future.isSuccess()); + logger.debug("Channel closed"); + } - protected static void realAllData(RESTHANDLERS data) throws HttpInvalidAuthenticationException { - if (!RestConfiguration.CRUD.READ.isValid(HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[data.ordinal()])) { - return; - } - Channel channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); - if (channel == null) { - logger.warn("Cannot connect to: " + host + ":" + HttpTestR66PseudoMain.config.REST_PORT); - return; - } - RestFuture future = realAllData(channel, data); - try { - future.await(); - } catch (InterruptedException e) { - } - WaarpSslUtility.closingSslChannel(channel); - logger.debug("Channel closed"); + protected static RestFuture options(Channel channel, String uri) + throws HttpInvalidAuthenticationException { + logger.debug("Send query"); + String key = null, value = null; + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; } + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.OPTIONS, + host, + uri, key, value, null, null); + logger.debug("Query sent"); + return future; + } - protected static RestFuture realAllData(Channel channel, RESTHANDLERS data) - throws HttpInvalidAuthenticationException { - logger.debug("Send query"); - String key = null, value = null; - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - } - ObjectNode answer = JsonHandler.createObjectNode(); - switch (data) { - case DbConfiguration: - answer.put(DbConfigurationR66RestMethodHandler.FILTER_ARGS.BANDWIDTH.name(), -1); - break; - case DbHostAuth: - answer.put(DbHostAuthR66RestMethodHandler.FILTER_ARGS.ISSSL.name(), true); - answer.put(DbHostAuthR66RestMethodHandler.FILTER_ARGS.ISACTIVE.name(), true); - break; - case DbHostConfiguration: - answer.put(DbHostConfigurationR66RestMethodHandler.FILTER_ARGS.BUSINESS.name(), "hosta"); - break; - case DbRule: - answer.put(DbRuleR66RestMethodHandler.FILTER_ARGS.MODETRANS.name(), 2); - break; - case DbTaskRunner: - answer.put(DbTaskRunnerR66RestMethodHandler.FILTER_ARGS.STOPTRANS.name(), new DateTime().toString()); - answer.put(Columns.OWNERREQ.name(), Configuration.configuration.getHOST_ID()); - break; - default: - RestFuture restFuture = channel.attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); - restFuture.cancel(); - WaarpSslUtility.closingSslChannel(channel); - return restFuture; - } - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.GET, host, - data.uri, key, value, null, - JsonHandler.writeAsString(answer)); - logger.debug("Query sent"); - return future; + protected static void realAllData(RESTHANDLERS data) + throws HttpInvalidAuthenticationException { + if (!RestConfiguration.CRUD.READ.isValid( + HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[data + .ordinal()])) { + logger.warn("Not allow to READ"); + return; + } + Channel channel = clientHelper + .getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); + if (channel == null) { + logger.warn("Cannot connect to: " + host + ":" + + HttpTestR66PseudoMain.config.REST_PORT); + assertFalse("Cant connect", true); + return; } + RestFuture future = realAllData(channel, data); + try { + future.await(); + } catch (InterruptedException e) { + } + WaarpSslUtility.closingSslChannel(channel); + assertTrue("Action should be ok", future.isSuccess()); + logger.debug("Channel closed"); + } - protected static void deleteData(RESTHANDLERS data) throws HttpInvalidAuthenticationException { - if (!RestConfiguration.CRUD.DELETE.isValid(HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[data.ordinal()])) { - return; - } - Channel channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); - if (channel == null) { - logger.warn("Cannot connect to: " + host + ":" + HttpTestR66PseudoMain.config.REST_PORT); - return; - } - RestFuture future = deleteData(channel, data); - try { - future.await(); - } catch (InterruptedException e) { - } - WaarpSslUtility.closingSslChannel(channel); - logger.debug("Channel closed"); - } - - protected static RestFuture deleteData(Channel channel, RESTHANDLERS data) - throws HttpInvalidAuthenticationException { - logger.debug("Send query"); - AbstractDbData dbData = getItem(data); - if (dbData == null) { - RestFuture future = channel.attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); - future.cancel(); - WaarpSslUtility.closingSslChannel(channel); - return future; - } - String item = dbData.getJson().path(clientHelper.getPrimaryPropertyName(dbData.getClass().getSimpleName())) - .asText(); - String key = null, value = null; - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - } - Map args = null; - if (dbData instanceof DbTaskRunner) { - args = new HashMap(); - args.put(DbTaskRunner.Columns.REQUESTER.name(), hostid); - args.put(DbTaskRunner.Columns.REQUESTED.name(), hostid); - args.put(Columns.OWNERREQ.name(), Configuration.configuration.getHOST_ID()); - } - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.DELETE, host, - data.uri + "/" + item, key, value, - args, - null); - logger.debug("Query sent"); - return future; + protected static RestFuture realAllData(Channel channel, RESTHANDLERS data) + throws HttpInvalidAuthenticationException { + logger.debug("Send query"); + String key = null, value = null; + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; + } + ObjectNode answer = JsonHandler.createObjectNode(); + switch (data) { + case DbConfiguration: + answer + .put(DbConfigurationR66RestMethodHandler.FILTER_ARGS.BANDWIDTH.name(), + -1); + break; + case DbHostAuth: + answer.put(DbHostAuthR66RestMethodHandler.FILTER_ARGS.ISSSL.name(), true); + answer.put(DbHostAuthR66RestMethodHandler.FILTER_ARGS.ISACTIVE.name(), + true); + break; + case DbHostConfiguration: + answer.put( + DbHostConfigurationR66RestMethodHandler.FILTER_ARGS.BUSINESS.name(), + "hosta"); + break; + case DbRule: + answer.put(DbRuleR66RestMethodHandler.FILTER_ARGS.MODETRANS.name(), 2); + break; + case DbTaskRunner: + answer.put(DbTaskRunnerR66RestMethodHandler.FILTER_ARGS.STOPTRANS.name(), + new DateTime().toString()); + answer.put(Columns.OWNERREQ.name(), + Configuration.configuration.getHOST_ID()); + break; + default: + RestFuture restFuture = + channel.attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); + restFuture.cancel(); + WaarpSslUtility.closingSslChannel(channel); + return restFuture; } + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.GET, host, + data.uri, key, value, null, + JsonHandler.writeAsString(answer)); + logger.debug("Query sent"); + return future; + } - protected static void multiDataRequests(RESTHANDLERS data) throws HttpInvalidAuthenticationException { - if (!RestConfiguration.CRUD.CREATE.isValid(HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[data.ordinal()])) { - return; - } - Channel channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); - if (channel == null) { - logger.warn("Cannot connect to: " + host + ":" + HttpTestR66PseudoMain.config.REST_PORT); - return; - } - RestFuture future = createData(channel, data); + protected static void deleteData(RESTHANDLERS data) + throws HttpInvalidAuthenticationException { + if (!RestConfiguration.CRUD.DELETE.isValid( + HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[data + .ordinal()])) { + logger.warn("Not allow to DELETE"); + return; + } + Channel channel = clientHelper + .getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); + if (channel == null) { + logger.warn("Cannot connect to: " + host + ":" + + HttpTestR66PseudoMain.config.REST_PORT); + assertFalse("Cant connect", true); + return; + } + RestFuture future = deleteData(channel, data); + future.awaitForDoneOrInterruptible(); + WaarpSslUtility.closingSslChannel(channel); + if (!future.isSuccess()) { + logger.warn("Can't DELETE {}", data); + } + // assertTrue("Action should be ok", future.isSuccess()); + logger.debug("Channel closed"); + } + + protected static RestFuture deleteData(Channel channel, RESTHANDLERS data) + throws HttpInvalidAuthenticationException { + logger.debug("Send query"); + AbstractDbData dbData = getItem(data); + if (dbData == null) { + RestFuture future = channel.attr( + HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); + future.cancel(); + WaarpSslUtility.closingSslChannel(channel); + return future; + } + String item = dbData.getJson().path(clientHelper.getPrimaryPropertyName( + dbData.getClass().getSimpleName())) + .asText(); + String key = null, value = null; + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; + } + Map args = null; + if (dbData instanceof DbTaskRunner) { + args = new HashMap(); + args.put(DbTaskRunner.Columns.REQUESTER.name(), hostid + rank); + args.put(DbTaskRunner.Columns.REQUESTED.name(), hostid + rank); + args.put(Columns.OWNERREQ.name(), + Configuration.configuration.getHOST_ID()); + } + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, + HttpMethod.DELETE, host, + data.uri + "/" + item, key, value, args, null); + logger.debug("Query sent"); + return future; + } + + protected static RestFuture readData(Channel channel, RestArgument arg) + throws HttpInvalidAuthenticationException { + logger.debug("Send query"); + String base = arg.getBaseUri(); + String item = clientHelper.getPrimaryProperty(arg); + String key = null, value = null; + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; + } + Map args = null; + if (base.equals(HttpRestR66Handler.RESTHANDLERS.DbTaskRunner.uri)) { + args = new HashMap(); + args.put(DbTaskRunner.Columns.REQUESTER.name(), hostid + rank); + args.put(DbTaskRunner.Columns.REQUESTED.name(), hostid + rank); + args.put(Columns.OWNERREQ.name(), + Configuration.configuration.getHOST_ID()); + } + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, + HttpMethod.GET, host, + base + "/" + item, key, value, args, null); + logger.debug("Query sent"); + return future; + } + + protected static RestFuture updateData(Channel channel, RestArgument arg) + throws HttpInvalidAuthenticationException { + logger.debug("Send query"); + ObjectNode answer = arg.getAnswer(); + String base = arg.getBaseUri(); + String item = clientHelper.getPrimaryProperty(arg); + RESTHANDLERS dbdata = clientHelper.getRestHandler(arg); + String key = null, value = null; + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; + } + Map args = null; + if (base.equals(HttpRestR66Handler.RESTHANDLERS.DbTaskRunner.uri)) { + args = new HashMap(); + args.put(DbTaskRunner.Columns.REQUESTER.name(), hostid + rank); + args.put(DbTaskRunner.Columns.REQUESTED.name(), hostid + rank); + args.put(Columns.OWNERREQ.name(), + Configuration.configuration.getHOST_ID()); + } + // update + answer.removeAll(); + switch (dbdata) { + case DbConfiguration: + answer.put(DbConfiguration.Columns.READGLOBALLIMIT.name(), 0); + break; + case DbHostAuth: + answer.put(DbHostAuth.Columns.PORT.name(), 100); + break; + case DbHostConfiguration: + answer.put(DbHostConfiguration.Columns.OTHERS.name(), ""); + break; + case DbRule: + answer.put(DbRule.Columns.MODETRANS.name(), 4); + break; + case DbTaskRunner: + answer.put(DbTaskRunner.Columns.FILEINFO.name(), "New Fileinfo"); + break; + default: + RestFuture future = channel.attr( + HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); + future.cancel(); + WaarpSslUtility.closingSslChannel(channel); + return future; + } + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, + HttpMethod.PUT, host, + base + "/" + item, key, value, args, + JsonHandler.writeAsString(answer)); + logger.debug("Query sent"); + return future; + } + + protected static RestFuture deleteData(Channel channel, RestArgument arg) + throws HttpInvalidAuthenticationException { + logger.debug("Send query"); + String base = arg.getBaseUri(); + String item = clientHelper.getPrimaryProperty(arg); + String key = null, value = null; + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; + } + Map args = null; + if (base.equals(HttpRestR66Handler.RESTHANDLERS.DbTaskRunner.uri)) { + args = new HashMap(); + args.put(DbTaskRunner.Columns.REQUESTER.name(), hostid + rank); + args.put(DbTaskRunner.Columns.REQUESTED.name(), hostid + rank); + args.put(Columns.OWNERREQ.name(), + Configuration.configuration.getHOST_ID()); + } + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, + HttpMethod.DELETE, host, + base + "/" + item, key, value, args, null); + logger.debug("Query sent"); + return future; + } + + protected static RestFuture deleteData(Channel channel, String reqd, + String reqr, long specid) + throws HttpInvalidAuthenticationException { + logger.debug("Send query"); + String key = null, value = null; + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; + } + Map args = new HashMap(); + args.put(DbTaskRunner.Columns.REQUESTER.name(), reqr); + args.put(DbTaskRunner.Columns.REQUESTED.name(), reqd); + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.DELETE, + host, + RESTHANDLERS.DbTaskRunner.uri + "/" + specid, key, value, + args, + null); + logger.debug("Query sent"); + return future; + } + + protected static void action(RESTHANDLERS data) + throws HttpInvalidAuthenticationException { + if (!RestConfiguration.CRUD.READ.isValid( + HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[data + .ordinal()])) { + logger.warn("Not allow to READ"); + return; + } + Channel channel = clientHelper + .getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); + if (channel == null) { + logger.warn("Cannot connect to: " + host + ":" + + HttpTestR66PseudoMain.config.REST_PORT); + assertFalse("Cant connect", true); + return; + } + RestFuture future = action(channel, data); + try { + future.await(); + } catch (InterruptedException e) { + } + WaarpSslUtility.closingSslChannel(channel); + // assertTrue("Action should be ok", future.isSuccess()); + logger.debug("Channel closed"); + } + + protected static RestFuture action(Channel channel, RESTHANDLERS data) + throws HttpInvalidAuthenticationException { + logger.warn("Send query: " + data); + JsonPacket packet = null; + HttpMethod method = null; + switch (data) { + case Bandwidth: { + BandwidthJsonPacket node = new BandwidthJsonPacket(); + node.setReadglobal(0); + node.setReadsession(0); + node.setSetter(true); + node.setRequestUserPacket(); + packet = node; + method = HttpMethod.PUT; + break; + } + case Business: { + BusinessRequestJsonPacket node = new BusinessRequestJsonPacket(); + node.setClassName(TestExecJavaTask.class.getName()); + node.setArguments("business 100 other arguments 0"); + node.setRequestUserPacket(); + node.setToApplied(true); + packet = node; + method = HttpMethod.GET; + break; + } + case Config: { + ConfigExportJsonPacket node = new ConfigExportJsonPacket(); + node.setHost(true); + node.setRule(true); + node.setBusiness(true); + node.setAlias(true); + node.setRoles(true); + node.setRequestUserPacket(); + packet = node; + method = HttpMethod.GET; + break; + } + case Information: { + InformationJsonPacket node = new InformationJsonPacket( + (byte) InformationPacket.ASKENUM.ASKLIST.ordinal(), + "rule4", "test*"); + packet = node; + method = HttpMethod.GET; + break; + } + case Log: { + LogJsonPacket node = new LogJsonPacket(); + node.setStop(new Date()); + node.setRequestUserPacket(); + packet = node; + method = HttpMethod.GET; + break; + } + case Server: { + ShutdownOrBlockJsonPacket node = new ShutdownOrBlockJsonPacket(); + node.setRestartOrBlock(true); + node.setShutdownOrBlock(false); + String pwd = "pwdhttp"; + byte[] bpwd = FilesystemBasedDigest + .passwdCrypt(pwd.getBytes(WaarpStringUtils.UTF8)); + node.setKey(bpwd); + node.setRequestUserPacket(LocalPacketFactory.BLOCKREQUESTPACKET); + packet = node; + method = HttpMethod.PUT; + break; + } + case Control: { + TransferRequestJsonPacket node = new TransferRequestJsonPacket(); + node.setRequestUserPacket(); + node.setRulename("rule4"); + node.setRank(0); + node.setBlocksize(65536); + node.setFileInformation("file info"); + node.setFilename("filename"); + node.setMode(2); + node.setSpecialId(DbConstant.ILLEGALVALUE); + node.setRequested(hostid); + node.setStart(new Date()); + node.setOriginalSize(123L); + node.setRequestUserPacket(); + packet = node; + method = HttpMethod.POST; + break; + } + default: + break; + } + return action(channel, method, data.uri, packet); + } + + protected static RestFuture action(Channel channel, HttpMethod method, + String uri, JsonPacket packet) { + if (packet == null) { + RestFuture future = + channel.attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); + future.cancel(); + WaarpSslUtility.closingSslChannel(channel); + return future; + } + String key = null, value = null; + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; + } + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, method, host, uri, + key, + value, + null, + packet.toString()); + logger.debug("Query sent"); + return future; + } + + @Override + public void run() { + if (isStatus) { + for (int i = 0; i < NBPERTHREAD; i++) { + getStatus(); + } + } else { + for (int i = 0; i < NBPERTHREAD; i++) { try { - future.await(); - } catch (InterruptedException e) { - } - WaarpSslUtility.closingSslChannel(channel); - logger.debug("Channel closed"); - } - - protected static RestFuture createData(Channel channel, RESTHANDLERS data) - throws HttpInvalidAuthenticationException { - logger.debug("Send query"); - AbstractDbData dbData = getItem(data); - if (dbData == null) { - RestFuture future = channel.attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); - future.cancel(); - WaarpSslUtility.closingSslChannel(channel); - return future; + multiDataRequests(RESTHANDLERS.DbTaskRunner); + } catch (HttpInvalidAuthenticationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); } - String key = null, value = null; - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - } - Map args = null; - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.POST, host, - data.uri, key, value, - args, - dbData.asJson()); - logger.debug("Query sent"); - return future; - } - - protected static RestFuture readData(Channel channel, RestArgument arg) throws HttpInvalidAuthenticationException { - logger.debug("Send query"); - String base = arg.getBaseUri(); - String item = clientHelper.getPrimaryProperty(arg); - String key = null, value = null; - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - } - Map args = null; - if (base.equals(HttpRestR66Handler.RESTHANDLERS.DbTaskRunner.uri)) { - args = new HashMap(); - args.put(DbTaskRunner.Columns.REQUESTER.name(), hostid); - args.put(DbTaskRunner.Columns.REQUESTED.name(), hostid); - args.put(Columns.OWNERREQ.name(), Configuration.configuration.getHOST_ID()); - } - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.GET, host, base - + "/" + item, key, value, - args, - null); - logger.debug("Query sent"); - return future; - } - - protected static RestFuture updateData(Channel channel, RestArgument arg) throws HttpInvalidAuthenticationException { - logger.debug("Send query"); - ObjectNode answer = arg.getAnswer(); - String base = arg.getBaseUri(); - String item = clientHelper.getPrimaryProperty(arg); - RESTHANDLERS dbdata = clientHelper.getRestHandler(arg); - String key = null, value = null; - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - } - Map args = null; - if (base.equals(HttpRestR66Handler.RESTHANDLERS.DbTaskRunner.uri)) { - args = new HashMap(); - args.put(DbTaskRunner.Columns.REQUESTER.name(), hostid); - args.put(DbTaskRunner.Columns.REQUESTED.name(), hostid); - args.put(Columns.OWNERREQ.name(), Configuration.configuration.getHOST_ID()); - } - // update - answer.removeAll(); - switch (dbdata) { - case DbConfiguration: - answer.put(DbConfiguration.Columns.READGLOBALLIMIT.name(), 0); - break; - case DbHostAuth: - answer.put(DbHostAuth.Columns.PORT.name(), 100); - break; - case DbHostConfiguration: - answer.put(DbHostConfiguration.Columns.OTHERS.name(), ""); - break; - case DbRule: - answer.put(DbRule.Columns.MODETRANS.name(), 4); - break; - case DbTaskRunner: - answer.put(DbTaskRunner.Columns.FILEINFO.name(), "New Fileinfo"); - break; - default: - RestFuture future = channel.attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); - future.cancel(); - WaarpSslUtility.closingSslChannel(channel); - return future; - } - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.PUT, host, base - + "/" + item, key, value, - args, - JsonHandler.writeAsString(answer)); - logger.debug("Query sent"); - return future; - } - - protected static RestFuture deleteData(Channel channel, RestArgument arg) throws HttpInvalidAuthenticationException { - logger.debug("Send query"); - String base = arg.getBaseUri(); - String item = clientHelper.getPrimaryProperty(arg); - String key = null, value = null; - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - } - Map args = null; - if (base.equals(HttpRestR66Handler.RESTHANDLERS.DbTaskRunner.uri)) { - args = new HashMap(); - args.put(DbTaskRunner.Columns.REQUESTER.name(), hostid); - args.put(DbTaskRunner.Columns.REQUESTED.name(), hostid); - args.put(Columns.OWNERREQ.name(), Configuration.configuration.getHOST_ID()); - } - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.DELETE, host, base - + "/" + item, key, value, - args, - null); - logger.debug("Query sent"); - return future; + } } + } - protected static RestFuture deleteData(Channel channel, String reqd, String reqr, long specid) - throws HttpInvalidAuthenticationException { - logger.debug("Send query"); - String key = null, value = null; - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - } - Map args = new HashMap(); - args.put(DbTaskRunner.Columns.REQUESTER.name(), reqr); - args.put(DbTaskRunner.Columns.REQUESTED.name(), reqd); - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.DELETE, host, - RESTHANDLERS.DbTaskRunner.uri + "/" + specid, key, value, - args, - null); - logger.debug("Query sent"); - return future; - } - - protected static void getStatus() { - if (!RestConfiguration.CRUD.READ.isValid(HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[RESTHANDLERS.Server + protected static void getStatus() { + if (!RestConfiguration.CRUD.READ + .isValid( + HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[RESTHANDLERS.Server .ordinal()])) { - return; - } - Channel channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); - if (channel == null) { - logger.warn("Cannot connect to: " + host + ":" + HttpTestR66PseudoMain.config.REST_PORT); - return; - } - String key = null, value = null; - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - } - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.GET, host, - RESTHANDLERS.Server.uri, key, value, - null, null); - logger.debug("Query sent"); - try { - future.await(); - } catch (InterruptedException e) { - } - WaarpSslUtility.closingSslChannel(channel); - logger.debug("Channel closed"); + logger.warn("Not allow to READ"); + return; + } + Channel channel = clientHelper + .getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); + if (channel == null) { + logger.warn("Cannot connect to: " + host + ":" + + HttpTestR66PseudoMain.config.REST_PORT); + assertFalse("Cant connect", true); + return; + } + String key = null, value = null; + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; } + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, + HttpMethod.GET, host, + RESTHANDLERS.Server.uri, key, value, null, null); + logger.debug("Query sent"); + try { + future.await(); + } catch (InterruptedException e) { + } + WaarpSslUtility.closingSslChannel(channel); + assertTrue("Action should be ok", future.isSuccess()); + logger.debug("Channel closed"); + } - protected static void action(RESTHANDLERS data) throws HttpInvalidAuthenticationException { - if (!RestConfiguration.CRUD.READ.isValid(HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[data.ordinal()])) { - return; - } - Channel channel = clientHelper.getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); - if (channel == null) { - logger.warn("Cannot connect to: " + host + ":" + HttpTestR66PseudoMain.config.REST_PORT); - return; - } - RestFuture future = action(channel, data); - try { - future.await(); - } catch (InterruptedException e) { - } - WaarpSslUtility.closingSslChannel(channel); - logger.debug("Channel closed"); - } - - protected static RestFuture action(Channel channel, RESTHANDLERS data) throws HttpInvalidAuthenticationException { - logger.warn("Send query: " + data); - JsonPacket packet = null; - HttpMethod method = null; - switch (data) { - case Bandwidth: { - BandwidthJsonPacket node = new BandwidthJsonPacket(); - node.setReadglobal(0); - node.setReadsession(0); - node.setSetter(true); - node.setRequestUserPacket(); - packet = node; - method = HttpMethod.PUT; - break; - } - case Business: { - BusinessRequestJsonPacket node = new BusinessRequestJsonPacket(); - node.setClassName(TestExecJavaTask.class.getName()); - node.setArguments("business 100 other arguments 0"); - node.setRequestUserPacket(); - node.setToApplied(true); - packet = node; - method = HttpMethod.GET; - break; - } - case Config: { - ConfigExportJsonPacket node = new ConfigExportJsonPacket(); - node.setHost(true); - node.setRule(true); - node.setBusiness(true); - node.setAlias(true); - node.setRoles(true); - node.setRequestUserPacket(); - packet = node; - method = HttpMethod.GET; - break; - } - case Information: { - InformationJsonPacket node = new InformationJsonPacket( - (byte) InformationPacket.ASKENUM.ASKLIST.ordinal(), - "rule4", "test*"); - packet = node; - method = HttpMethod.GET; - break; - } - case Log: { - LogJsonPacket node = new LogJsonPacket(); - node.setStop(new Date()); - node.setRequestUserPacket(); - packet = node; - method = HttpMethod.GET; - break; - } - case Server: { - ShutdownOrBlockJsonPacket node = new ShutdownOrBlockJsonPacket(); - node.setRestartOrBlock(true); - node.setShutdownOrBlock(false); - String pwd = "pwdhttp"; - byte[] bpwd = FilesystemBasedDigest.passwdCrypt(pwd.getBytes(WaarpStringUtils.UTF8)); - node.setKey(bpwd); - node.setRequestUserPacket(LocalPacketFactory.BLOCKREQUESTPACKET); - packet = node; - method = HttpMethod.PUT; - break; - } - case Control: { - TransferRequestJsonPacket node = new TransferRequestJsonPacket(); - node.setRequestUserPacket(); - node.setRulename("rule4"); - node.setRank(0); - node.setBlocksize(65536); - node.setFileInformation("file info"); - node.setFilename("filename"); - node.setMode(2); - node.setSpecialId(DbConstant.ILLEGALVALUE); - node.setRequested(hostid); - node.setStart(new Date()); - node.setOriginalSize(123L); - node.setRequestUserPacket(); - packet = node; - method = HttpMethod.POST; - break; - } - default: - break; - } - return action(channel, method, data.uri, packet); + protected static void multiDataRequests(RESTHANDLERS data) + throws HttpInvalidAuthenticationException { + if (!RestConfiguration.CRUD.CREATE.isValid( + HttpTestR66PseudoMain.config.RESTHANDLERS_CRUD[data + .ordinal()])) { + logger.warn("Not allow to CREATE"); + return; } + Channel channel = clientHelper + .getChannel(host, HttpTestR66PseudoMain.config.REST_PORT); + if (channel == null) { + logger.warn("Cannot connect to: " + host + ":" + + HttpTestR66PseudoMain.config.REST_PORT); + assertFalse("Cant connect", true); + return; + } + RestFuture future = createData(channel, data); + try { + future.await(); + } catch (InterruptedException e) { + } + WaarpSslUtility.closingSslChannel(channel); + assertTrue("Action should be ok", future.isSuccess()); + logger.debug("Channel closed"); + } - protected static RestFuture action(Channel channel, HttpMethod method, String uri, JsonPacket packet) { - if (packet == null) { - RestFuture future = channel.attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); - future.cancel(); - WaarpSslUtility.closingSslChannel(channel); - return future; - } - String key = null, value = null; - if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { - key = userAuthent; - value = keyAuthent; - } - RestFuture future = clientHelper.sendQuery(HttpTestR66PseudoMain.config, channel, method, host, uri, key, - value, - null, - packet.toString()); - logger.debug("Query sent"); - return future; - } - - @Override - public void run() { - if (isStatus) { - for (int i = 0; i < NBPERTHREAD; i++) { - getStatus(); - } - } else { - for (int i = 0; i < NBPERTHREAD; i++) { - try { - multiDataRequests(RESTHANDLERS.DbTaskRunner); - } catch (HttpInvalidAuthenticationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } + protected static RestFuture createData(Channel channel, RESTHANDLERS data) + throws HttpInvalidAuthenticationException { + logger.debug("Send query"); + AbstractDbData dbData = getItem(data); + if (dbData == null) { + RestFuture future = + channel.attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT).get(); + future.cancel(); + WaarpSslUtility.closingSslChannel(channel); + return future; + } + String key = null, value = null; + if (HttpTestR66PseudoMain.config.REST_AUTHENTICATED) { + key = userAuthent; + value = keyAuthent; + } + Map args = null; + RestFuture future = clientHelper + .sendQuery(HttpTestR66PseudoMain.config, channel, HttpMethod.POST, host, + data.uri, key, value, + args, + dbData.asJson()); + logger.debug("Query sent"); + return future; + } + + protected static AbstractDbData getItem(RESTHANDLERS data) + throws HttpInvalidAuthenticationException { + switch (data) { + case DbConfiguration: + return new DbConfiguration(hostid + rank, limit, limit, limit, + limit, delaylimit); + case DbHostAuth: + return new DbHostAuth(hostid + rank, address, + HttpTestR66PseudoMain.config.REST_PORT, false, + hostkey.getBytes(), false, false); + case DbHostConfiguration: + return new DbHostConfiguration(hostid + rank, business, roles, + aliases, others); + case DbRule: + return new DbRule(idRule, ids, 2, "/recv", "/send", "/arch", + "/work", tasks, tasks, tasks, tasks, + tasks, tasks); + case DbTaskRunner: + ObjectNode source = JsonHandler.createObjectNode(); + source.put(Columns.IDRULE.name(), idRule); + source.put(Columns.RANK.name(), 0); + source.put(Columns.BLOCKSZ.name(), 65536); + source.put(Columns.FILEINFO.name(), "file info"); + source.put(Columns.FILENAME.name(), "filename"); + source.put(Columns.GLOBALLASTSTEP.name(), + TASKSTEP.NOTASK.ordinal()); + source.put(Columns.GLOBALSTEP.name(), TASKSTEP.NOTASK.ordinal()); + source.put(Columns.INFOSTATUS.name(), ErrorCode.Unknown.ordinal()); + source.put(Columns.ISMOVED.name(), false); + source.put(Columns.MODETRANS.name(), 2); + source.put(Columns.ORIGINALNAME.name(), "original filename"); + source.put(Columns.OWNERREQ.name(), + Configuration.configuration.getHOST_ID()); + source.put(Columns.SPECIALID.name(), DbConstant.ILLEGALVALUE); + source.put(Columns.REQUESTED.name(), hostid + rank); + source.put(Columns.REQUESTER.name(), hostid + rank); + source.put(Columns.RETRIEVEMODE.name(), true); + source.put(Columns.STARTTRANS.name(), System.currentTimeMillis()); + source.put(Columns.STOPTRANS.name(), System.currentTimeMillis()); + source.put(Columns.STEP.name(), -1); + source.put(Columns.STEPSTATUS.name(), ErrorCode.Unknown.ordinal()); + source.put(Columns.TRANSFERINFO.name(), "transfer info"); + source.put(DbTaskRunner.JSON_RESCHEDULE, false); + source.put(DbTaskRunner.JSON_THROUGHMODE, false); + source.put(DbTaskRunner.JSON_ORIGINALSIZE, 123L); + try { + return new DbTaskRunner(source); + } catch (WaarpDatabaseException e) { + throw new HttpInvalidAuthenticationException(e); + } + default: + break; } + return null; + } } diff --git a/src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java b/src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java new file mode 100644 index 000000000..70348e0f4 --- /dev/null +++ b/src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java @@ -0,0 +1,68 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +/** + * + */ +package org.waarp.openr66.protocol.junit; + +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.waarp.common.command.exception.CommandAbstractException; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; +import org.waarp.openr66.protocol.test.TestTasks; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +/** + * @author frederic + * + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class AllTasksTest extends TestAbstract { + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + setUpBeforeClassMinimal("Linux/config/config-serverInitB.xml"); + setUpDbBeforeClass(); + } + + @Test + public void test2_Tasks() throws IOException, OpenR66RunnerErrorException, + CommandAbstractException { + System.err.println("Start Tasks"); + File totest = new File("/tmp/R66/in/testTask.txt"); + FileWriter fileWriter = new FileWriter(totest); + fileWriter.write("Test content"); + fileWriter.flush(); + fileWriter.close(); + TestTasks.main(new String[] { + new File(dir, "config-serverA-minimal.xml").getAbsolutePath(), + "/tmp/R66/in", + "/tmp/R66/out", totest.getName() + }); + System.err.println("End Tasks"); + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java b/src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java new file mode 100644 index 000000000..09c735337 --- /dev/null +++ b/src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java @@ -0,0 +1,1238 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +/** + * + */ +package org.waarp.openr66.protocol.junit; + +import org.apache.thrift.TException; +import org.apache.thrift.protocol.TBinaryProtocol; +import org.apache.thrift.protocol.TProtocol; +import org.apache.thrift.transport.TSocket; +import org.apache.thrift.transport.TTransport; +import org.apache.thrift.transport.TTransportException; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runners.MethodSorters; +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseSqlException; +import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.openr66.client.Message; +import org.waarp.openr66.client.MultipleDirectTransfer; +import org.waarp.openr66.client.MultipleSubmitTransfer; +import org.waarp.openr66.client.RequestInformation; +import org.waarp.openr66.client.RequestTransfer; +import org.waarp.openr66.client.SubmitTransfer; +import org.waarp.openr66.client.utils.OutputFormat.FIELDS; +import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.context.R66FiniteDualStates; +import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.task.test.TestExecJavaTask; +import org.waarp.openr66.database.DbConstant; +import org.waarp.openr66.database.data.DbHostAuth; +import org.waarp.openr66.database.data.DbRule; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.configuration.Messages; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; +import org.waarp.openr66.protocol.exception.OpenR66ProtocolPacketException; +import org.waarp.openr66.protocol.http.rest.test.HttpTestRestR66Client; +import org.waarp.openr66.protocol.localhandler.LocalChannelReference; +import org.waarp.openr66.protocol.localhandler.packet.AbstractLocalPacket; +import org.waarp.openr66.protocol.localhandler.packet.InformationPacket; +import org.waarp.openr66.protocol.localhandler.packet.JsonCommandPacket; +import org.waarp.openr66.protocol.localhandler.packet.KeepAlivePacket; +import org.waarp.openr66.protocol.localhandler.packet.LocalPacketFactory; +import org.waarp.openr66.protocol.localhandler.packet.NoOpPacket; +import org.waarp.openr66.protocol.localhandler.packet.TestPacket; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.localhandler.packet.json.BandwidthJsonPacket; +import org.waarp.openr66.protocol.localhandler.packet.json.BusinessRequestJsonPacket; +import org.waarp.openr66.protocol.localhandler.packet.json.ConfigExportJsonPacket; +import org.waarp.openr66.protocol.localhandler.packet.json.ConfigImportJsonPacket; +import org.waarp.openr66.protocol.localhandler.packet.json.InformationJsonPacket; +import org.waarp.openr66.protocol.localhandler.packet.json.JsonPacket; +import org.waarp.openr66.protocol.localhandler.packet.json.LogJsonPacket; +import org.waarp.openr66.protocol.localhandler.packet.json.ShutdownOrBlockJsonPacket; +import org.waarp.openr66.protocol.localhandler.packet.json.StopOrCancelJsonPacket; +import org.waarp.openr66.protocol.test.TestBusinessRequest; +import org.waarp.openr66.protocol.test.TestProgressBarTransfer; +import org.waarp.openr66.protocol.test.TestRecvThroughClient; +import org.waarp.openr66.protocol.test.TestRecvThroughClient.TestRecvThroughHandler; +import org.waarp.openr66.protocol.test.TestSendThroughClient; +import org.waarp.openr66.protocol.test.TestTransaction; +import org.waarp.openr66.protocol.test.TestTransferNoDb; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.protocol.utils.R66Future; +import org.waarp.thrift.r66.Action; +import org.waarp.thrift.r66.R66Request; +import org.waarp.thrift.r66.R66Service; +import org.waarp.thrift.r66.RequestMode; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.net.SocketAddress; +import java.sql.Timestamp; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static org.junit.Assert.*; + +/** + * @author frederic + * + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +public class NetworkClientTest extends TestAbstract { + + private static final int nbThread = 10; + private static final ArrayList dbTaskRunners = + new ArrayList(); + + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + setUpBeforeClassMinimal("Linux/config/config-serverInitB.xml"); + setUpDbBeforeClass(); + // setUpBeforeClassServer("Linux/config/config-serverInitB.xml", "config-serverB.xml", false); + setUpBeforeClassServer("Linux/config/config-serverInitA.xml", + "config-serverA-minimal.xml", true); + setUpBeforeClassClient("config-clientB.xml"); + } + + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + Thread.sleep(1000); + for (DbTaskRunner dbTaskRunner : dbTaskRunners) { + try { + dbTaskRunner.delete(); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot apply nolog to " + dbTaskRunner.toString(), + e); + } + } + DbHostAuth host = + new DbHostAuth("hostas"); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + byte scode = -1; + + // Shutdown server + logger.warn("Shutdown Server"); + Configuration.configuration.setTIMEOUTCON(100); + R66Future future = new R66Future(true); + ShutdownOrBlockJsonPacket node8 = new ShutdownOrBlockJsonPacket(); + node8.setRestartOrBlock(false); + node8.setShutdownOrBlock(true); + node8.setKey(FilesystemBasedDigest.passwdCrypt( + Configuration.configuration.getSERVERADMINKEY())); + AbstractLocalPacket valid = new JsonCommandPacket(node8, + LocalPacketFactory.BLOCKREQUESTPACKET); + sendInformation(valid, socketServerAddress, future, scode, false, + R66FiniteDualStates.SHUTDOWN, true); + Thread.sleep(1000); + + tearDownAfterClassClient(); + tearDownAfterClassMinimal(); + tearDownAfterClassServer(); + } + + private static void sendInformation(AbstractLocalPacket informationPacket, + final SocketAddress socketServerAddress, + R66Future future, byte scode, + boolean check, + R66FiniteDualStates state, + boolean isSsl) + throws OpenR66ProtocolPacketException { + logger.warn("Start connection for Extra commands {}", + informationPacket.getClass().getSimpleName()); + LocalChannelReference localChannelReference = networkTransaction + .createConnectionWithRetry(socketServerAddress, + isSsl, future); + if (localChannelReference == null) { + if (state != R66FiniteDualStates.SHUTDOWN) { + assertTrue("Connection not OK", false); + } else { + return; + } + } + localChannelReference.sessionNewState(state); + logger.warn("Send {}", informationPacket); + ChannelUtils.writeAbstractLocalPacket(localChannelReference, + informationPacket, false); + if (informationPacket instanceof KeepAlivePacket || + informationPacket instanceof NoOpPacket) { + // do no await + localChannelReference.close(); + return; + } else { + localChannelReference.getFutureRequest() + .awaitForDoneOrInterruptible(); + future.awaitForDoneOrInterruptible(); + + } + R66Result r66result = future.getResult(); + if (state == R66FiniteDualStates.VALIDOTHER) { + logger.warn("feedback: {}", r66result); + } else { + ValidPacket info = (ValidPacket) r66result.getOther(); + if (info != null && scode != -1) { + logger.warn("nb: {}", Integer.parseInt(info.getSmiddle())); + String[] files = info.getSheader().split("\n"); + int i = 0; + for (String file : files) { + i++; + logger.warn("file: {} {}", i, file); + } + } else { + if (info != null && info.getSheader() != null) { + try { + DbTaskRunner runner = DbTaskRunner + .fromStringXml(info.getSheader(), false); + logger.warn("{}", runner.getJson()); + } catch (OpenR66ProtocolBusinessException e) { + logger.warn("{}: {}", FIELDS.transfer.name(), + info.getSheader()); + } + } + } + } + localChannelReference.close(); + if (check) { + assertTrue("Information not OK", future.isSuccess()); + } else { + logger.warn("Get {} {}", future.isSuccess(), + future.isSuccess()? "OK" + : future.getCause() != null? + future.getCause().getMessage() : "No Cause"); + } + } + + @Test + public void test1_PingPongPacket() throws WaarpDatabaseException { + DbHostAuth host = + new DbHostAuth("hosta"); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + ExecutorService executorService = Executors.newCachedThreadPool(); + int nb = nbThread; + R66Future[] arrayFuture = new R66Future[nb]; + logger.warn("Start Test of Transaction"); + long time1 = System.currentTimeMillis(); + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + TestPacket packet = new TestPacket("Test", "" + i, 0); + TestTransaction transaction = + new TestTransaction(networkTransaction, arrayFuture[i], + socketServerAddress, + packet); + executorService.execute(transaction); + } + int success = 0; + int error = 0; + for (int i = 0; i < nb; i++) { + arrayFuture[i].awaitForDoneOrInterruptible(); + if (arrayFuture[i].isSuccess()) { + success++; + } else { + error++; + } + } + long time2 = System.currentTimeMillis(); + logger.warn("Success: " + success + " Error: " + error + " NB/s: " + + success * TestPacket.pingpong * 1000 / (time2 - time1)); + executorService.shutdown(); + assertEquals("Success should be total", nb, success); + assertEquals("Errors should be 0", 0, error); + } + + @Test + public void test8_BusinessRequest() throws WaarpDatabaseException { + logger.warn("Start Test of BusinessRequest"); + DbHostAuth host = + new DbHostAuth("hostas"); + assertEquals("Error should be at 0", 0, + TestBusinessRequest.runTest(networkTransaction, host, 5)); + } + + @Test + public void test4_RecvThroughClient() throws IOException { + logger.warn("Start Test of Recv Through Transfer"); + File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); + TestRecvThroughHandler handler = new TestRecvThroughHandler(); + R66Future future = new R66Future(true); + TestRecvThroughClient transaction = + new TestRecvThroughClient(future, handler, "hostas", + "testTask.txt", + "rule6", "Test RecvThrough Small", + true, 8192, networkTransaction); + long time1 = System.currentTimeMillis(); + transaction.run(); + future.awaitForDoneOrInterruptible(); + + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + checkFinalResult(future, result, delay, 10); + totest.delete(); + + int size = 100000000; + File totestBig = generateOutFile("/tmp/R66/out/testTaskBig.txt", size); + future = new R66Future(true); + transaction = new TestRecvThroughClient(future, handler, "hostas", + "testTaskBig.txt", "rule6", + "Test RecvThrough Big", true, + 65536, networkTransaction); + time1 = System.currentTimeMillis(); + transaction.run(); + future.awaitForDoneOrInterruptible(); + + time2 = System.currentTimeMillis(); + delay = time2 - time1; + result = future.getResult(); + checkFinalResult(future, result, delay, size); + totestBig.delete(); + } + + private File generateOutFile(String name, int size) throws IOException { + File file = new File(name); + FileWriter fileWriterBig = new FileWriter(file); + for (int i = 0; i < size / 10; i++) { + fileWriterBig.write("0123456789"); + } + fileWriterBig.flush(); + fileWriterBig.close(); + return file; + } + + private void checkFinalResult(R66Future future, R66Result result, + long delay, long size) { + if (future.isSuccess()) { + if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { + logger.warn("Warning with Id: " + + result.getRunner().getSpecialId() + " on file: " + + (result.getFile() != null? + result.getFile().toString() : "no file") + " delay: " + + delay + + " kbps: " + (size * 8 / delay)); + } else { + logger.warn("Success with Id: " + + result.getRunner().getSpecialId() + + " on Final file: " + + (result.getFile() != null? + result.getFile().toString() : "no file") + " delay: " + + delay + + " kbps: " + (size * 8 / delay)); + } + if (result.getRunner().shallIgnoreSave()) { + // In case of success, delete the runner + dbTaskRunners.add(result.getRunner()); + } + } else { + if (result == null || result.getRunner() == null) { + logger.warn("Transfer in Error with no Id", future.getCause()); + assertEquals("Result should not be null, neither runner", true, + false); + } + if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { + logger.warn("Transfer in Warning with Id: " + + result.getRunner().getSpecialId(), + future.getCause()); + assertEquals("Transfer in Warning", true, false); + } else { + logger.error("Transfer in Error with Id: " + + result.getRunner().getSpecialId(), + future.getCause()); + assertEquals("Transfer in Error", true, false); + } + } + } + + @Test + public void test4_SendThroughClient() throws IOException { + logger.warn("Start Test of Send Through Transfer"); + File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); + R66Future future = new R66Future(true); + TestSendThroughClient transaction = + new TestSendThroughClient(future, "hostas", "testTask.txt", + "rule5", + "Test SendThrough Small", true, 8192, + networkTransaction); + long time1 = System.currentTimeMillis(); + if (!transaction.initiateRequest()) { + logger.error("Transfer in Error", future.getCause()); + return; + } + if (transaction.sendFile()) { + transaction.finalizeRequest(); + } else { + transaction.transferInError(null); + } + future.awaitForDoneOrInterruptible(); + + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + checkFinalResult(future, result, delay, 10); + totest.delete(); + + int size = 100000000; + File totestBig = generateOutFile("/tmp/R66/out/testTaskBig.txt", size); + future = new R66Future(true); + transaction = + new TestSendThroughClient(future, "hostas", "testTaskBig.txt", + "rule5", "Test SendThrough Big", + true, 65536, networkTransaction); + time1 = System.currentTimeMillis(); + if (!transaction.initiateRequest()) { + logger.error("Transfer in Error", future.getCause()); + return; + } + if (transaction.sendFile()) { + transaction.finalizeRequest(); + } else { + transaction.transferInError(null); + } + future.awaitForDoneOrInterruptible(); + + time2 = System.currentTimeMillis(); + delay = time2 - time1; + result = future.getResult(); + checkFinalResult(future, result, delay, size); + totestBig.delete(); + } + + @Test + public void test3_ProgressBarTransfer() throws IOException { + logger.warn("Start Test of ProgressBar Transfer"); + int size = 10000000; + File totestBig = generateOutFile("/tmp/R66/out/testTaskBig.txt", size); + R66Future future = new R66Future(true); + long time1 = System.currentTimeMillis(); + TestProgressBarTransfer transaction = + new TestProgressBarTransfer(future, "hostas", "testTaskBig.txt", + "rule3", + "Test Send Small ProgressBar", true, + 65536, DbConstant.ILLEGALVALUE, + networkTransaction, 100); + transaction.run(); + future.awaitForDoneOrInterruptible(); + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + checkFinalResult(future, result, delay, size); + totestBig.delete(); + } + + @Test + public void test6_SendUsingTrafficShaping() throws IOException { + logger.warn("Start Test of Send TrafficShaping Transfer"); + int size = 20000; + long bandwidth = 5000; + File totestBig = generateOutFile("/tmp/R66/out/testTaskBig.txt", size); + + Configuration.configuration + .changeNetworkLimit(bandwidth, bandwidth, bandwidth, bandwidth, + 1000); + + R66Future future = new R66Future(true); + long time1 = System.currentTimeMillis(); + TestTransferNoDb transaction = + new TestTransferNoDb(future, "hostas", "testTaskBig.txt", + "rule3", + "Test SendDirect Big With Traffic Shaping", + true, 8192, DbConstant.ILLEGALVALUE, + networkTransaction); + transaction.run(); + future.awaitForDoneOrInterruptible(); + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + Configuration.configuration.changeNetworkLimit(0, 0, 0, 0, 1000); + R66Result result = future.getResult(); + checkFinalResult(future, result, delay, size); + totestBig.delete(); + } + + @Test + public void test6_RecvUsingTrafficShaping() throws IOException { + logger.warn("Start Test of Recv TrafficShaping Transfer"); + int size = 20000; + long bandwidth = 5000; + File totestBig = generateOutFile("/tmp/R66/out/testTaskBig.txt", size); + + Configuration.configuration + .changeNetworkLimit(bandwidth, bandwidth, bandwidth, bandwidth, + 1000); + + R66Future future = new R66Future(true); + long time1 = System.currentTimeMillis(); + TestTransferNoDb transaction = + new TestTransferNoDb(future, "hostas", "testTaskBig.txt", + "rule4", + "Test RecvDirect Big With Traffic Shaping", + true, 8192, DbConstant.ILLEGALVALUE, + networkTransaction); + transaction.run(); + future.awaitForDoneOrInterruptible(); + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + Configuration.configuration.changeNetworkLimit(0, 0, 0, 0, 1000); + R66Result result = future.getResult(); + checkFinalResult(future, result, delay, size); + totestBig.delete(); + } + + @Test + public void test5_DirectTransfer() + throws WaarpDatabaseException, IOException { + File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); + ExecutorService executorService = Executors.newCachedThreadPool(); + int nb = nbThread; + R66Future[] arrayFuture = new R66Future[nb]; + logger.warn("Start Test of DirectTransfer"); + long time1 = System.currentTimeMillis(); + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + TestTransferNoDb transaction = + new TestTransferNoDb(arrayFuture[i], "hostas", + "testTask.txt", "rule3", + "Test SendDirect Small", true, 8192, + DbConstant.ILLEGALVALUE, + networkTransaction); + executorService.execute(transaction); + } + int success = 0; + int error = 0; + for (int i = 0; i < nb; i++) { + arrayFuture[i].awaitForDoneOrInterruptible(); + if (arrayFuture[i].getRunner() != null) { + dbTaskRunners.add(arrayFuture[i].getRunner()); + } + if (arrayFuture[i].isSuccess()) { + success++; + } else { + error++; + } + } + long time2 = System.currentTimeMillis(); + logger.warn("Success: " + success + " Error: " + error + " NB/s: " + + success * 1000 / (time2 - time1)); + executorService.shutdown(); + totest.delete(); + assertEquals("Success should be total", nb, success); + assertEquals("Errors should be 0", 0, error); + } + + @Test + public void test5_SubmitTransfer() + throws IOException, InterruptedException { + File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); + int nb = nbThread; + R66Future[] arrayFuture = new R66Future[nb]; + logger.warn("Start Test of SubmitTransfer"); + + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + Timestamp newstart = + new Timestamp(System.currentTimeMillis() + i * 10); + SubmitTransfer transaction = + new SubmitTransfer(arrayFuture[i], "hostas", "testTask.txt", + "rule3", + "Test Send Submit Small", true, 8192, + DbConstant.ILLEGALVALUE, newstart); + transaction.run(); + } + int success = 0; + int error = 0; + for (int i = 0; i < nb; i++) { + arrayFuture[i].awaitForDoneOrInterruptible(); + if (arrayFuture[i].isSuccess()) { + success++; + } else { + error++; + } + } + logger.warn( + "Prepare transfer Success: " + success + " Error: " + error); + assertEquals("Success should be total", nb, success); + assertEquals("Errors should be 0", 0, error); + // Now wait for all transfers done + for (int i = 0; i < nb; i++) { + if (arrayFuture[i].isSuccess()) { + DbTaskRunner runner = arrayFuture[i].getRunner(); + if (runner != null) { + waitForAllDone(runner); + dbTaskRunners.add(runner); + } + } + } + Thread.sleep(100); + totest.delete(); + } + + private void waitForAllDone(DbTaskRunner runner) { + while (true) { + R66Future futureInfo = new R66Future(true); + RequestInformation requestInformation = + new RequestInformation(futureInfo, "hostas", null, null, + (byte) -1, + runner.getSpecialId(), true, + networkTransaction); + requestInformation.run(); + futureInfo.awaitForDoneOrInterruptible(); + if (futureInfo.isSuccess()) { + R66Result r66result = futureInfo.getResult(); + ValidPacket info = (ValidPacket) r66result.getOther(); + String xml = info.getSheader(); + try { + runner = DbTaskRunner.fromStringXml(xml, true); + logger.info("Get Runner from remote: {}", runner); + if (runner.getSpecialId() == DbConstant.ILLEGALVALUE || + !runner.isSender()) { + logger.error(Messages.getString( + "RequestTransfer.18")); //$NON-NLS-1$ + break; + } + if (runner.isAllDone()) { + break; + } + } catch (OpenR66ProtocolBusinessException e1) { + logger.error(Messages.getString( + "RequestTransfer.18")); //$NON-NLS-1$ + break; + } + } else { + logger.error( + Messages.getString("RequestTransfer.18")); //$NON-NLS-1$ + break; + } + } + } + + @Test + public void test1_JsonGenerator() { + int nb = 11; + logger.warn("Start Test Json"); + DbPreparedStatement preparedStatement; + try { + preparedStatement = DbTaskRunner + .getFilterPrepareStatement(DbConstant.admin.getSession(), + nb, false, null, + null, null, null, null, null, + false, false, false, false, true, + null); + preparedStatement.executeQuery(); + String tasks = DbTaskRunner.getJson(preparedStatement, nb); + preparedStatement.realClose(); + assertFalse("Json should not be empty", tasks.isEmpty()); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + assertEquals("Json in Error", true, false); + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + assertEquals("Json in Error", true, false); + } catch (OpenR66ProtocolBusinessException e) { + e.printStackTrace(); + assertEquals("Json in Error", true, false); + } + } + + @Test + public void test1_JsonGeneratorDbHostAuth() { + // FIXME SHOULD BE POSSIBLE !! + int nb = 11; + logger.warn("Start Test Json"); + DbPreparedStatement preparedStatement; + try { + preparedStatement = DbHostAuth + .getFilterPrepareStament(DbConstant.admin.getSession(), + null, null); + preparedStatement.executeQuery(); + String hosts = DbHostAuth.getJson(preparedStatement, nb); + preparedStatement.realClose(); + assertFalse("Json should not be empty", hosts.isEmpty()); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + assertEquals("Json in Error", true, false); + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + assertEquals("Json in Error", true, false); + } catch (OpenR66ProtocolBusinessException e) { + e.printStackTrace(); + assertEquals("Json in Error", true, false); + } + } + + @Test + public void test1_JsonGeneratorDbRule() { + // FIXME SHOULD BE POSSIBLE !! + int nb = 11; + logger.warn("Start Test Json"); + DbPreparedStatement preparedStatement; + try { + preparedStatement = DbRule.getFilterPrepareStament( + DbConstant.admin.getSession(), null, -1); + preparedStatement.executeQuery(); + String rules = DbRule.getJson(preparedStatement, nb); + preparedStatement.realClose(); + assertFalse("Json should not be empty", rules.isEmpty()); + } catch (WaarpDatabaseNoConnectionException e) { + e.printStackTrace(); + assertEquals("Json in Error", true, false); + } catch (WaarpDatabaseSqlException e) { + e.printStackTrace(); + assertEquals("Json in Error", true, false); + } catch (OpenR66ProtocolBusinessException e) { + e.printStackTrace(); + assertEquals("Json in Error", true, false); + } + logger.warn("End Test Json"); + } + + @Test + public void test9_ExtraCommands() + throws WaarpDatabaseException, IOException, InterruptedException, + OpenR66ProtocolPacketException { + File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); + DbHostAuth host = + new DbHostAuth("hostas"); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + R66Future futureTransfer = new R66Future(true); + TestTransferNoDb transaction = + new TestTransferNoDb(futureTransfer, "hostas", "testTask.txt", + "rule3", + "Test SendDirect Small", true, 8192, + DbConstant.ILLEGALVALUE, + networkTransaction); + transaction.run(); + futureTransfer.await(); + assertTrue("File transfer not ok", futureTransfer.isSuccess()); + long id = futureTransfer.getRunner().getSpecialId(); + logger.warn("Remote Task: {}", id); + + // InformationPacket + logger.warn("Start Extra commands: InformationPacket"); + byte scode = -1; + InformationPacket informationPacket = + new InformationPacket("" + id, scode, "0"); + R66Future future = new R66Future(true); + sendInformation(informationPacket, socketServerAddress, future, scode, + false, R66FiniteDualStates.INFORMATION, + true); + + future = new R66Future(true); + scode = (byte) InformationPacket.ASKENUM.ASKEXIST.ordinal(); + informationPacket = + new InformationPacket("rule3", scode, "testTask.txt"); + sendInformation(informationPacket, socketServerAddress, future, scode, + true, R66FiniteDualStates.INFORMATION, + true); + + future = new R66Future(true); + scode = (byte) InformationPacket.ASKENUM.ASKLIST.ordinal(); + informationPacket = + new InformationPacket("rule3", scode, "testTask.txt"); + sendInformation(informationPacket, socketServerAddress, future, scode, + true, R66FiniteDualStates.INFORMATION, + true); + + future = new R66Future(true); + scode = (byte) InformationPacket.ASKENUM.ASKMLSDETAIL.ordinal(); + informationPacket = + new InformationPacket("rule3", scode, "testTask.txt"); + sendInformation(informationPacket, socketServerAddress, future, scode, + true, R66FiniteDualStates.INFORMATION, + true); + + future = new R66Future(true); + scode = (byte) InformationPacket.ASKENUM.ASKMLSLIST.ordinal(); + informationPacket = + new InformationPacket("rule3", scode, "testTask.txt"); + sendInformation(informationPacket, socketServerAddress, future, scode, + true, R66FiniteDualStates.INFORMATION, + true); + + // ValidPacket BANDWIDTH + future = new R66Future(true); + ValidPacket valid = + new ValidPacket("-1", "-1", LocalPacketFactory.BANDWIDTHPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + + // MultipleDirectTransfer + logger.warn("Start MultipleDirectTransfer"); + future = new R66Future(true); + MultipleDirectTransfer multipleDirectTransfer = + new MultipleDirectTransfer(future, "hostas,hostas", + "testTask.txt,testTask.txt", "rule3", + "MultipleDirectTransfer", true, 1024, + DbConstant.ILLEGALVALUE, + networkTransaction); + multipleDirectTransfer.run(); + future.awaitForDoneOrInterruptible(); + assertTrue("All sends should be OK", future.isSuccess()); + + // RequestTransfer + logger.warn("Start RequestTransfer check"); + future = new R66Future(true); + RequestTransfer requestTransfer = + new RequestTransfer(future, id, "hostas", "hostas", false, + false, false, + networkTransaction); + requestTransfer.run(); + future.awaitForDoneOrInterruptible(); + assertFalse("Request of Transfer should be OK", future.isSuccess()); + + // RequestTransfer + logger.warn("Start RequestTransfer stop"); + future = new R66Future(true); + requestTransfer = + new RequestTransfer(future, id, "hostas", "hostas", false, true, + false, networkTransaction); + requestTransfer.run(); + future.awaitForDoneOrInterruptible(); + assertFalse("Request of Transfer should be OK", future.isSuccess()); + + // RequestTransfer + logger.warn("Start RequestTransfer cancel"); + future = new R66Future(true); + requestTransfer = + new RequestTransfer(future, id, "hostas", "hostas", true, false, + false, networkTransaction); + requestTransfer.run(); + future.awaitForDoneOrInterruptible(); + assertFalse("Request of Transfer should be OK", future.isSuccess()); + + // RequestInformation + logger.warn("Start RequestInformation"); + future = new R66Future(true); + RequestInformation requestInformation = + new RequestInformation(future, "hostas", "rule3", + "testTask.txt", scode, + id, false, networkTransaction); + requestInformation.run(); + future.awaitForDoneOrInterruptible(); + assertTrue("Request of information should be OK", future.isSuccess()); + + // Message + logger.warn("Start Message"); + future = new R66Future(true); + TestPacket packet = new TestPacket("MSG", "Message", 2); + Message message = + new Message(networkTransaction, future, "hostas", packet); + message.run(); + future.awaitForDoneOrInterruptible(); + assertTrue("Message should be OK", future.isSuccess()); + + // MultipleSubmitTransfer + logger.warn("Start MultipleSubmitTransfer"); + future = new R66Future(true); + MultipleSubmitTransfer multipleSubmitTransfer = + new MultipleSubmitTransfer(future, "hostas", "testTask.txt", + "rule3", "Multiple Submit", true, + 1024, DbConstant.ILLEGALVALUE, null, + networkTransaction); + multipleSubmitTransfer.run(); + future.awaitForDoneOrInterruptible(); + assertTrue("All submits should be OK", future.isSuccess()); + + // ValidPacket CONFEXPORTPACKET + logger.warn("Start Valid CONFEXPORTPACKET"); + future = new R66Future(true); + valid = new ValidPacket(Boolean.TRUE.toString(), + Boolean.TRUE.toString(), + LocalPacketFactory.CONFEXPORTPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + + // ValidPacket CONFIMPORTPACKET + logger.warn("Start Valid CONFIMPORTPACKET"); + future = new R66Future(true); + valid = new ValidPacket("0 /tmp/R66/arch/hostb_Authentications.xml", + "0 /tmp/R66/arch/hostb.rules.xml", + LocalPacketFactory.CONFIMPORTPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + + // ValidPacket LOG + logger.warn("Start Valid LOG"); + future = new R66Future(true); + valid = new ValidPacket(null, null, LocalPacketFactory.LOGPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + + // ValidPacket LOGPURGE + logger.warn("Start Valid LOGPURGE"); + future = new R66Future(true); + valid = new ValidPacket(null, null, LocalPacketFactory.LOGPURGEPACKET); + sendInformation(valid, socketServerAddress, future, scode, false, + R66FiniteDualStates.VALIDOTHER, true); + + // ValidPacket VALID + logger.warn("Start Valid VALID"); + future = new R66Future(true); + valid = new ValidPacket(null, "hostas hostas " + id, + LocalPacketFactory.VALIDPACKET); + sendInformation(valid, socketServerAddress, future, scode, false, + R66FiniteDualStates.VALIDOTHER, true); + + // ValidPacket STOP + logger.warn("Start Valid STOP"); + future = new R66Future(true); + valid = new ValidPacket(null, "hostas hostas " + id, + LocalPacketFactory.STOPPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + + // ValidPacket CANCEL + logger.warn("Start Valid CANCEL"); + future = new R66Future(true); + valid = new ValidPacket(null, "hostas hostas " + id, + LocalPacketFactory.CANCELPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + + // NoOpPacket + logger.warn("Start NoOp"); + long timeout = Configuration.configuration.getTIMEOUTCON(); + Configuration.configuration.setTIMEOUTCON(100); + future = new R66Future(true); + NoOpPacket noOpPacket = new NoOpPacket(); + sendInformation(noOpPacket, socketServerAddress, future, scode, true, + R66FiniteDualStates.INFORMATION, true); + + // KeepAlivePacket + logger.warn("Start KeepAlive"); + future = new R66Future(true); + KeepAlivePacket keepAlivePacket = new KeepAlivePacket(); + sendInformation(keepAlivePacket, socketServerAddress, future, scode, + true, R66FiniteDualStates.INFORMATION, + true); + Configuration.configuration.setTIMEOUTCON(timeout); + + totest.delete(); + } + + @Test + public void test8_JsonCommands() + throws IOException, WaarpDatabaseException, InterruptedException, + OpenR66ProtocolPacketException { + File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); + DbHostAuth host = + new DbHostAuth("hostas"); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + R66Future futureTransfer = new R66Future(true); + TestTransferNoDb transaction = + new TestTransferNoDb(futureTransfer, "hostas", "testTask.txt", + "rule3", + "Test SendDirect Small", true, 8192, + DbConstant.ILLEGALVALUE, + networkTransaction); + transaction.run(); + futureTransfer.await(); + assertTrue("File transfer not ok", futureTransfer.isSuccess()); + long id = futureTransfer.getResult().getRunner().getSpecialId(); + logger.warn("Remote Task: {}", + futureTransfer.getResult().getRunner().getSpecialId()); + + byte scode = -1; + + logger.warn("BandwidthJsonPacket"); + R66Future future = new R66Future(true); + AbstractLocalPacket valid = null; + BandwidthJsonPacket node = new BandwidthJsonPacket(); + // will ask current values instead + node.setSetter(false); + valid = new JsonCommandPacket(node, LocalPacketFactory.BANDWIDTHPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("BandwidthUnlimit"); + future = new R66Future(true); + node = new BandwidthJsonPacket(); + // will ask current values instead + node.setSetter(true); + node.setWriteglobal(0); + node.setReadglobal(0); + node.setWritesession(0); + node.setReadsession(0); + valid = new JsonCommandPacket(node, LocalPacketFactory.BANDWIDTHPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("Information"); + future = new R66Future(true); + InformationJsonPacket node4 = + new InformationJsonPacket(id, true, "hostas"); + valid = new JsonCommandPacket(node4, + LocalPacketFactory.INFORMATIONPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("Information2"); + future = new R66Future(true); + node4 = new InformationJsonPacket( + (byte) InformationPacket.ASKENUM.ASKMLSDETAIL.ordinal(), + "rule3", + "testTask.txt"); + valid = new JsonCommandPacket(node4, + LocalPacketFactory.INFORMATIONPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("Stop"); + future = new R66Future(true); + StopOrCancelJsonPacket node5 = new StopOrCancelJsonPacket(); + node5.setRequested("hostas"); + node5.setRequester("hostas"); + node5.setSpecialid(id); + valid = new JsonCommandPacket(node5, LocalPacketFactory.STOPPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + logger.warn("Cancel"); + future = new R66Future(true); + valid = new JsonCommandPacket(node5, LocalPacketFactory.CANCELPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("Log"); + future = new R66Future(true); + LogJsonPacket node6 = new LogJsonPacket(); + node6.setClean(true); + node6.setPurge(false); + valid = new JsonCommandPacket(node6, LocalPacketFactory.LOGPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + logger.warn("Log2"); + future = new R66Future(true); + node6.setPurge(true); + valid = new JsonCommandPacket(node6, LocalPacketFactory.LOGPURGEPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("Config"); + future = new R66Future(true); + ConfigExportJsonPacket node7 = new ConfigExportJsonPacket(); + node7.setHost(true); + node7.setAlias(true); + node7.setBusiness(true); + node7.setRoles(true); + node7.setRule(true); + valid = new JsonCommandPacket(node7, + LocalPacketFactory.CONFEXPORTPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("Config Import"); + future = new R66Future(true); + ConfigImportJsonPacket node8 = new ConfigImportJsonPacket(); + node8.setHost("/tmp/R66/arch/hostb_Authentications.xml"); + node8.setRule("/tmp/R66/arch/hostb.rules.xml"); + valid = new JsonCommandPacket(node8, + LocalPacketFactory.CONFIMPORTPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("Test"); + future = new R66Future(true); + JsonPacket node9 = new JsonPacket(); + node9.setComment("Test Message"); + node9.setRequestUserPacket(LocalPacketFactory.TESTPACKET); + valid = new JsonCommandPacket(node9, LocalPacketFactory.TESTPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("Block only"); + future = new R66Future(true); + ShutdownOrBlockJsonPacket node2 = new ShutdownOrBlockJsonPacket(); + node2.setRestartOrBlock(false); + node2.setShutdownOrBlock(false); + node2.setKey(FilesystemBasedDigest.passwdCrypt( + Configuration.configuration.getSERVERADMINKEY())); + valid = new JsonCommandPacket(node2, + LocalPacketFactory.BLOCKREQUESTPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("Business"); + future = new R66Future(true); + BusinessRequestJsonPacket node3 = new BusinessRequestJsonPacket(); + node3.setClassName(TestExecJavaTask.class.getName()); + node3.setArguments(" business 0"); + node3.setExtraArguments(" simple business request"); + node3.setDelay(0); + valid = new JsonCommandPacket(node3, + LocalPacketFactory.BUSINESSREQUESTPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("End Json"); + totest.delete(); + } + + @Test + public void test1_ThriftClient() throws IOException { + logger.warn("Start Test Thrift Client"); + int PORT = 4266; + int tries = 10000; + TTransport transport = null; + try { + File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); + transport = new TSocket("localhost", PORT); + TProtocol protocol = new TBinaryProtocol(transport); + R66Service.Client client = new R66Service.Client(protocol); + transport.open(); + R66Request request = new R66Request(RequestMode.INFOFILE); + request.setDestuid("hostas"); + request.setFromuid("hostas"); + request.setRule("rule3"); + request.setAction(Action.List); + + System.out.println("REQUEST1: " + request.toString()); + List list = client.infoListQuery(request); + System.out.println("RESULT1: " + list.size()); + for (String slist : list) { + System.out.println(slist); + } + assertFalse("List should not be empty", list.isEmpty()); + long start = System.currentTimeMillis(); + for (int i = 0; i < tries; i++) { + list = client.infoListQuery(request); + } + long end = System.currentTimeMillis(); + System.out.println("Delay: " + (end - start) + " : " + + ((tries * 1000) / (end - start))); + + request.setMode(RequestMode.INFOFILE); + request.setAction(Action.Mlsx); + list = client.infoListQuery(request); + System.out.println("RESULT3: " + list.size()); + for (String slist : list) { + System.out.println(slist); + } + assertFalse("List should not be empty", list.isEmpty()); + + request = new R66Request(RequestMode.ASYNCTRANSFER); + request.setDestuid("hostas"); + request.setFromuid("hostas"); + request.setRule("rule3"); + request.setFile("testTask.txt"); + request.setInfo("Submitted from Thrift"); + System.out.println("REQUEST4: " + request.toString()); + org.waarp.thrift.r66.R66Result result = + client.transferRequestQuery(request); + System.out.println("RESULT4: " + result); + + long startEx = System.currentTimeMillis(); + boolean dontknow = false; + long tid = result.getTid(); + for (int i = 0; i < tries; i++) { + dontknow = client.isStillRunning("hostas", "hostas", tid); + } + long endEx = System.currentTimeMillis(); + System.out.println("StillRunning: " + dontknow); + System.out.println("Delay: " + (endEx - startEx) + " : " + + ((tries * 1000) / (endEx - startEx))); + + request.setMode(RequestMode.INFOREQUEST); + request.setTid(tid); + request.setAction(Action.Detail); + result = client.infoTransferQuery(request); + System.out.println("RESULT2: " + result.toString()); + long startQu = System.currentTimeMillis(); + for (int i = 0; i < tries; i++) { + result = client.infoTransferQuery(request); + } + long endQu = System.currentTimeMillis(); + System.out.println("Delay: " + (endQu - startQu) + " : " + + ((tries * 1000) / (endQu - startQu))); + + System.out.println( + "Exist: " + client.isStillRunning(request.getFromuid(), + request.getDestuid(), + request.getTid())); + + // Wrong request + request = new R66Request(RequestMode.INFOFILE); + + System.out.println("WRONG REQUEST: " + request.toString()); + list = client.infoListQuery(request); + System.out.println("RESULT of Wrong Request: " + list.size()); + for (String slist : list) { + System.out.println(slist); + } + totest.delete(); + } catch (TTransportException e) { + e.printStackTrace(); + assertEquals("Thrift in Error", true, false); + } catch (TException e) { + e.printStackTrace(); + assertEquals("Thrift in Error", true, false); + } + transport.close(); + } + + @Test + public void test9_RestR66() throws Exception { + HttpTestRestR66Client.keydesfilename = + new File(dir, "certs/test-key.des").getAbsolutePath(); + HttpTestRestR66Client.main(new String[] { "1" }); + } +} diff --git a/src/test/java/org/waarp/openr66/protocol/junit/NetworkTransactionTest.java b/src/test/java/org/waarp/openr66/protocol/junit/NetworkTransactionTest.java new file mode 100644 index 000000000..5cfd9f300 --- /dev/null +++ b/src/test/java/org/waarp/openr66/protocol/junit/NetworkTransactionTest.java @@ -0,0 +1,48 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +package org.waarp.openr66.protocol.junit; + +import io.netty.channel.Channel; +import org.junit.Test; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; + +import java.net.InetSocketAddress; + +import static org.junit.Assert.*; +import static org.mockito.Mockito.*; + +public class NetworkTransactionTest { + + @Test + public void testisBlacklistedPreventNPE() { + Channel chan = mock(Channel.class); + when(chan.remoteAddress()).thenReturn(null); + NetworkTransaction.isBlacklisted(chan); + + reset(chan); + + InetSocketAddress addr = + new InetSocketAddress("cannotberesolved", 6666); + assertNull(addr.getAddress()); + doReturn(addr).when(chan).remoteAddress(); + NetworkTransaction.isBlacklisted(chan); + } +} diff --git a/src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java b/src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java new file mode 100644 index 000000000..0880851ef --- /dev/null +++ b/src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java @@ -0,0 +1,260 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +/** + * + */ +package org.waarp.openr66.protocol.junit; + +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.taskdefs.Java; +import org.apache.tools.ant.types.Commandline.Argument; +import org.apache.tools.ant.types.Path; +import org.junit.After; +import org.junit.Before; +import org.waarp.common.utility.DetectionUtils; +import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.protocol.configuration.Configuration; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; +import org.waarp.openr66.protocol.utils.ChannelUtils; +import org.waarp.openr66.server.R66Server; +import org.waarp.openr66.server.ServerInitDatabase; + +import java.io.File; + +/** + * @author frederic + * + */ +public abstract class TestAbstract extends TestAbstractMinimal { + + protected static NetworkTransaction networkTransaction = null; + private static Project project; + private static File homeDir; + + public static void setUpDbBeforeClass() throws Exception { + String serverInit = "Linux/config/config-serverInitB.xml"; + setUpBeforeClassMinimal(serverInit); + + ClassLoader classLoader = TestAbstract.class.getClassLoader(); + DetectionUtils.setJunit(true); + File file = new File(classLoader.getResource(serverInit).getFile()); + String newfile = file.getAbsolutePath().replace("target/test-classes", + "src/test/resources"); + file = new File(newfile); + dir = file.getParentFile(); + logger.warn("File {} exists? {}", file, file.isFile()); + homeDir = dir.getParentFile().getParentFile().getParentFile() + .getParentFile().getParentFile(); + logger.warn("Dir {} exists? {}", homeDir, homeDir.isDirectory()); + + // global ant project settings + project = new Project(); + project.setBaseDir(homeDir); + project.init(); + WaarpLoggerListener listener = new WaarpLoggerListener(); + project.addBuildListener(listener); + listener.setMessageOutputLevel(Project.MSG_WARN); + project.fireBuildStarted(); + + initiateDbB(); + initiateDbA(); + + project.log("finished"); + project.fireBuildFinished(null); + } + + + public static void initiateDbB() { + DetectionUtils.setJunit(true); + String serverInit = "config-serverInitB.xml"; + File file = new File(dir, serverInit); + logger.warn("File {} exists? {}", file, file.isFile()); + File fileAuth = new File(dir, "OpenR66-authent-A.xml"); + File fileLimit = new File(dir, "limitConfiga.xml"); + logger.warn("File {} exists? {}", fileAuth, fileAuth.isFile()); + logger.warn("File {} exists? {}", fileLimit, fileLimit.isFile()); + + String[] args = { + file.getAbsolutePath(), "-initdb", "-dir", + dir.getAbsolutePath(), "-auth", + new File(dir, "OpenR66-authent-A.xml").getAbsolutePath(), + "-limit", + new File(dir, "limitConfiga.xml").getAbsolutePath() + }; + executeJvm(homeDir, ServerInitDatabase.class, args); + } + + public static void initiateDbA() { + DetectionUtils.setJunit(true); + String serverInit = "config-serverInitA.xml"; + + File file = new File(dir, serverInit); + logger.warn("File {} exists? {}", file, file.isFile()); + File fileAuth = new File(dir, "OpenR66-authent-A.xml"); + File fileLimit = new File(dir, "limitConfiga.xml"); + logger.warn("File {} exists? {}", fileAuth, fileAuth.isFile()); + logger.warn("File {} exists? {}", fileLimit, fileLimit.isFile()); + + String[] args = { + file.getAbsolutePath(), "-initdb", "-dir", + dir.getAbsolutePath(), "-auth", + new File(dir, "OpenR66-authent-A.xml").getAbsolutePath(), + "-limit", + new File(dir, "limitConfiga.xml").getAbsolutePath() + }; + executeJvm(homeDir, ServerInitDatabase.class, args); + } + + public static void executeJvm(File homeDir, Class zclass, + String[] args) { + try { + /** initialize an java task **/ + Java javaTask = new Java(); + javaTask.setNewenvironment(false); + javaTask.setTaskName(zclass.getSimpleName()); + javaTask.setProject(project); + javaTask.setFork(true); + javaTask.setFailonerror(true); + javaTask.setClassname(zclass.getName()); + + // add some vm args + Argument jvmArgs = javaTask.createJvmarg(); + jvmArgs.setLine("-Xms512m -Xmx1024m"); + + // added some args for to class to launch + Argument taskArgs = javaTask.createArg(); + StringBuilder builder = new StringBuilder(); + for (String string : args) { + builder.append(' ').append(string); + } + taskArgs.setLine(builder.toString()); + + /** set the class path */ + String classpath = System.getProperty("java.class.path"); + Path classPath = javaTask.createClasspath(); + classPath.setPath(classpath); + javaTask.setClasspath(classPath); + + javaTask.init(); + int ret = javaTask.executeJava(); + System.err + .println(zclass.getName() + " " + args[0] + " return code: " + ret); + } catch (BuildException e) { + e.printStackTrace(); + } + } + + /** + * @throws java.lang.Exception + */ + public static void setUpBeforeClassServer(String serverInit, + String serverConfig, + boolean start) throws Exception { + ClassLoader classLoader = TestAbstract.class.getClassLoader(); + File file = new File(classLoader.getResource(serverInit).getFile()); + if (file.exists()) { + dir = file.getParentFile(); + System.err + .println("Find serverInit file: " + file.getAbsolutePath()); + ServerInitDatabase.main(new String[] { + file.getAbsolutePath(), "-initdb", "-dir", + dir.getAbsolutePath(), "-auth", + new File(dir, "OpenR66-authent-A.xml").getAbsolutePath(), + "-limit", + new File(dir, "limitConfiga.xml").getAbsolutePath() + }); + logger.warn("Init Done"); + if (start) { + File file2 = new File(dir, serverConfig); + if (file2.exists()) { + System.err.println( + "Find server file: " + file2.getAbsolutePath()); + R66Server.main(new String[] { file2.getAbsolutePath() }); + logger.warn("Start Done"); + } else { + System.err.println("Cannot find server file: " + + file2.getAbsolutePath()); + } + } + } else { + System.err.println( + "Cannot find serverInit file: " + file.getAbsolutePath()); + } + } + + /** + * @throws java.lang.Exception + */ + public static void tearDownAfterClassServer() throws Exception { + ChannelUtils.exit(); + } + + /** + * @throws java.lang.Exception + */ + public static void setUpBeforeClassClient(String clientConfig) + throws Exception { + File clientConfigFile = new File(dir, clientConfig); + if (clientConfigFile.isFile()) { + System.err + .println( + "Find serverInit file: " + clientConfigFile.getAbsolutePath()); + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, + new File(dir, clientConfig) + .getAbsolutePath())) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + } else { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + Configuration.configuration.pipelineInit(); + networkTransaction = new NetworkTransaction(); + } + + /** + * @throws java.lang.Exception + */ + public static void tearDownAfterClassClient() throws Exception { + networkTransaction.closeAll(); + } + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + Configuration.configuration.setTIMEOUTCON(10000); + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + Configuration.configuration.setTIMEOUTCON(100); + } +} diff --git a/src/test/java/org/waarp/openr66/protocol/junit/TestAbstractMinimal.java b/src/test/java/org/waarp/openr66/protocol/junit/TestAbstractMinimal.java new file mode 100644 index 000000000..fa74b526b --- /dev/null +++ b/src/test/java/org/waarp/openr66/protocol/junit/TestAbstractMinimal.java @@ -0,0 +1,96 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +/** + * + */ +package org.waarp.openr66.protocol.junit; + +import org.waarp.common.file.FileUtils; +import org.waarp.common.logging.WaarpLogger; +import org.waarp.common.logging.WaarpLoggerFactory; +import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; +import org.waarp.openr66.protocol.configuration.Configuration; + +import java.io.File; +import java.io.FileFilter; + +/** + * @author frederic + * + */ +public abstract class TestAbstractMinimal { + /** + * Internal Logger + */ + protected static WaarpLogger logger; + protected static File dir; + + /** + * @throws java.lang.Exception + */ + public static void setUpBeforeClassMinimal(String serverInit) + throws Exception { + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(TestAbstractMinimal.class); + } + ClassLoader classLoader = TestAbstractMinimal.class.getClassLoader(); + DetectionUtils.setJunit(true); + File file = new File(classLoader.getResource(serverInit).getFile()); + if (file.exists()) { + dir = file.getParentFile(); + File tmp = new File("/tmp/R66"); + tmp.mkdirs(); + FileUtils.forceDeleteRecursiveDir(tmp); + new File(tmp, "in").mkdir(); + new File(tmp, "out").mkdir(); + new File(tmp, "arch").mkdir(); + new File(tmp, "work").mkdir(); + File conf = new File(tmp, "conf"); + conf.mkdir(); + File[] files = dir.listFiles(new FileFilter() { + @Override + public boolean accept(File file) { + return file.isFile(); + } + }); + File [] copied = FileUtils.copyRecursive(dir, conf, false); + for (File fileCopied : copied) { + System.out.print(fileCopied.getAbsolutePath() + " "); + } + System.out.println(" Done"); + } else { + System.err.println( + "Cannot find serverInit file: " + file.getAbsolutePath()); + } + } + + /** + * + */ + public static void tearDownAfterClassMinimal() { + File tmp = new File("/tmp/R66"); + tmp.mkdirs(); + FileUtils.forceDeleteRecursiveDir(tmp); + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/junit/WaarpLoggerListener.java b/src/test/java/org/waarp/openr66/protocol/junit/WaarpLoggerListener.java new file mode 100644 index 000000000..96ffb8470 --- /dev/null +++ b/src/test/java/org/waarp/openr66/protocol/junit/WaarpLoggerListener.java @@ -0,0 +1,258 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +/** + * + */ +package org.waarp.openr66.protocol.junit; + +import org.apache.tools.ant.BuildEvent; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.BuildListener; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.util.DateUtils; +import org.apache.tools.ant.util.StringUtils; +import org.waarp.common.logging.WaarpLogLevel; +import org.waarp.common.logging.WaarpLogger; +import org.waarp.common.logging.WaarpLoggerFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; +import java.util.EventListener; + +/** + * WaarpLoggerListerner for Ant in Junit + * + * @author frederic bregier + * + */ +public class WaarpLoggerListener implements BuildListener, EventListener { + /** + * Size of left-hand column for right-justified task name. + * + * @see #messageLogged(BuildEvent) + */ + public static final int LEFT_COLUMN_SIZE = 12; + /** Line separator */ + protected static final String lSep = StringUtils.LINE_SEP; + /** + * Internal Logger + */ + private static final WaarpLogger logger = + WaarpLoggerFactory.getLogger(WaarpLoggerListener.class); + /** Lowest level of message to write out */ + private int msgOutputLevel = Project.MSG_WARN; + // CheckStyle:ConstantNameCheck OFF - bc + private WaarpLogLevel wlevel = WaarpLogLevel.WARN; + // CheckStyle:ConstantNameCheck ON + /** Time of the start of the build */ + private long startTime = System.currentTimeMillis(); + + /** + * Sets the highest level of message this logger should respond to. + * + * Only messages with a message level lower than or equal to the given level should be written to the log. + *

+ * Constants for the message levels are in the {@link Project Project} class. The order of the levels, from + * least to most verbose, is MSG_ERR, MSG_WARN, MSG_INFO, + * MSG_VERBOSE, MSG_DEBUG. + *

+ * The default message level for DefaultLogger is Project.MSG_ERR. + * + * @param level the logging level for the logger. + */ + public void setMessageOutputLevel(int level) { + this.msgOutputLevel = level; + switch (msgOutputLevel) { + case Project.MSG_DEBUG: + wlevel = WaarpLogLevel.DEBUG; + break; + case Project.MSG_VERBOSE: + wlevel = WaarpLogLevel.TRACE; + break; + case Project.MSG_INFO: + wlevel = WaarpLogLevel.INFO; + break; + case Project.MSG_WARN: + wlevel = WaarpLogLevel.WARN; + break; + case Project.MSG_ERR: + wlevel = WaarpLogLevel.ERROR; + break; + } + } + + @Override + public void buildStarted(BuildEvent event) { + startTime = System.currentTimeMillis(); + } + + @Override + public void buildFinished(BuildEvent event) { + Throwable error = event.getException(); + StringBuffer message = new StringBuffer(); + if (error == null) { + message.append(StringUtils.LINE_SEP); + message.append(getBuildSuccessfulMessage()); + } else { + message.append(StringUtils.LINE_SEP); + message.append(getBuildFailedMessage()); + message.append(StringUtils.LINE_SEP); + + if (Project.MSG_VERBOSE <= msgOutputLevel || + !(error instanceof BuildException)) { + message.append(StringUtils.getStackTrace(error)); + } else { + message.append(error.toString()).append(lSep); + } + } + message.append(StringUtils.LINE_SEP); + message.append("Total time: "); + message.append(formatTime(System.currentTimeMillis() - startTime)); + + String msg = message.toString(); + if (error == null) { + printMessage(msg, Project.MSG_VERBOSE); + } else { + printMessage(msg, Project.MSG_ERR); + } + } + + /** + * This is an override point: the message that indicates that a build succeeded. Subclasses can change/enhance + * the message. + * + * @return The classic "BUILD SUCCESSFUL" + */ + protected String getBuildSuccessfulMessage() { + return "BUILD SUCCESSFUL"; + } + + /** + * This is an override point: the message that indicates whether a build failed. Subclasses can change/enhance + * the message. + * + * @return The classic "BUILD FAILED" + */ + protected String getBuildFailedMessage() { + return "BUILD FAILED"; + } + + /** + * Convenience method to format a specified length of time. + * + * @param millis Length of time to format, in milliseconds. + * + * @return the time as a formatted string. + * + * @see DateUtils#formatElapsedTime(long) + */ + protected static String formatTime(final long millis) { + return DateUtils.formatElapsedTime(millis); + } + + /** + * Prints a message to log. + * + * @param message The message to print. Should not be null. + * @param priority The priority of the message. (Ignored in this implementation.) + */ + protected void printMessage(final String message, final int priority) { + logger.log(wlevel, message); + } + + @Override + public void targetStarted(BuildEvent event) { + if (Project.MSG_INFO <= msgOutputLevel && + !event.getTarget().getName().equals("")) { + String msg = + StringUtils.LINE_SEP + event.getTarget().getName() + ":"; + + printMessage(msg, event.getPriority()); + } + } + + @Override + public void targetFinished(BuildEvent event) { + } + + @Override + public void taskStarted(BuildEvent event) { + } + + @Override + public void taskFinished(BuildEvent event) { + } + + @Override + public void messageLogged(BuildEvent event) { + int priority = event.getPriority(); + // Filter out messages based on priority + if (priority <= msgOutputLevel) { + + StringBuffer message = new StringBuffer(); + if (event.getTask() != null) { + // Print out the name of the task if we're in one + String name = event.getTask().getTaskName(); + String label = "[" + name + "] "; + int size = LEFT_COLUMN_SIZE - label.length(); + StringBuffer tmp = new StringBuffer(); + for (int i = 0; i < size; i++) { + tmp.append(" "); + } + tmp.append(label); + label = tmp.toString(); + + try { + BufferedReader r = new BufferedReader( + new StringReader(event.getMessage())); + String line = r.readLine(); + boolean first = true; + do { + if (first) { + if (line == null) { + message.append(label); + break; + } + } else { + message.append(StringUtils.LINE_SEP); + } + first = false; + message.append(label).append(line); + line = r.readLine(); + } while (line != null); + } catch (IOException e) { + // shouldn't be possible + message.append(label).append(event.getMessage()); + } + } else { + message.append(event.getMessage()); + } + Throwable ex = event.getException(); + if (Project.MSG_DEBUG <= msgOutputLevel && ex != null) { + message.append(StringUtils.getStackTrace(ex)); + } + + String msg = message.toString(); + printMessage(msg, priority); + } + } +} diff --git a/src/test/java/org/waarp/openr66/protocol/localhandler/packet/json/TransferRequestJsonPacketTest.java b/src/test/java/org/waarp/openr66/protocol/localhandler/packet/json/TransferRequestJsonPacketTest.java index e60937899..8cafa4da1 100644 --- a/src/test/java/org/waarp/openr66/protocol/localhandler/packet/json/TransferRequestJsonPacketTest.java +++ b/src/test/java/org/waarp/openr66/protocol/localhandler/packet/json/TransferRequestJsonPacketTest.java @@ -1,68 +1,97 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + package org.waarp.openr66.protocol.localhandler.packet.json; +import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; -import static org.junit.Assert.*; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.junit.Assert.*; public class TransferRequestJsonPacketTest extends JsonPacket { - - @Test - public void testItIsDeserialized() { - try { - String json = "{\"requested\": \"server1\", \"@class\": \"org.waarp.openr66.protocol.localhandler.packet.json.TransferRequestJsonPacket\", \"rulename\": \"send\", \"filename\": \"test.dat\"}"; - Object res = new ObjectMapper().readValue(json, TransferRequestJsonPacket.class); - assertEquals(TransferRequestJsonPacket.class, res.getClass()); - } catch(Exception e) { - fail("Got unexpected exception" + e); - } + + @Test + public void testItIsDeserialized() { + try { + String json = + "{\"requested\": \"server1\", \"@class\": \"org.waarp.openr66.protocol.localhandler.packet.json.TransferRequestJsonPacket\", \"rulename\": \"send\", \"filename\": \"test.dat\"}"; + Object res = + new ObjectMapper().readValue(json, TransferRequestJsonPacket.class); + assertEquals(TransferRequestJsonPacket.class, res.getClass()); + } catch (Exception e) { + fail("Got unexpected exception" + e); } - - @Test - public void testItIsDeserializedFromJsonPacket() { - try { - String json = "{\"requested\": \"server1\", \"@class\": \"org.waarp.openr66.protocol.localhandler.packet.json.TransferRequestJsonPacket\", \"rulename\": \"send\", \"filename\": \"test.dat\"}"; - Object res = new ObjectMapper().readValue(json, JsonPacket.class); - assertEquals(TransferRequestJsonPacket.class, res.getClass()); - } catch(Exception e) { - fail("Got unexpected exception" + e); - } + } + + @Test + public void testItIsDeserializedFromJsonPacket() { + try { + String json = + "{\"requested\": \"server1\", \"@class\": \"org.waarp.openr66.protocol.localhandler.packet.json.TransferRequestJsonPacket\", \"rulename\": \"send\", \"filename\": \"test.dat\"}"; + Object res = new ObjectMapper().readValue(json, JsonPacket.class); + assertEquals(TransferRequestJsonPacket.class, res.getClass()); + } catch (Exception e) { + fail("Got unexpected exception" + e); } + } - @Test - public void testSetFileInformation() { - TransferRequestJsonPacket packet = new TransferRequestJsonPacket(); + @Test + public void testSetFileInformation() { + TransferRequestJsonPacket packet = new TransferRequestJsonPacket(); - packet.setFileInformation("foo"); - assertEquals("The given value should have been set", "foo", packet.getFileInformation()); - - packet.setFileInformation((String)null); - assertEquals("null should be set as an empty string", "", packet.getFileInformation()); - } + packet.setFileInformation("foo"); + assertEquals("The given value should have been set", "foo", + packet.getFileInformation()); + + packet.setFileInformation((String) null); + assertEquals("null should be set as an empty string", "", + packet.getFileInformation()); + } - @Test - public void testFileInformationShouldBeDeserialized() { - System.out.println("in should be deserialized"); - try { - String json = "{\"fileInformation\": \"foo\", \"@class\": \"org.waarp.openr66.protocol.localhandler.packet.json.TransferRequestJsonPacket\"}"; - TransferRequestJsonPacket res = new ObjectMapper().readValue(json, TransferRequestJsonPacket.class); - assertEquals("fileInformation should be deserialized", - "foo", res.getFileInformation()); - } catch(Exception e) { - fail("Got unexpected exception" + e); - } + @Test + public void testFileInformationShouldBeDeserialized() { + System.out.println("in should be deserialized"); + try { + String json = + "{\"fileInformation\": \"foo\", \"@class\": \"org.waarp.openr66.protocol.localhandler.packet.json.TransferRequestJsonPacket\"}"; + TransferRequestJsonPacket res = + new ObjectMapper().readValue(json, TransferRequestJsonPacket.class); + assertEquals("fileInformation should be deserialized", + "foo", res.getFileInformation()); + } catch (Exception e) { + fail("Got unexpected exception" + e); } + } - @Test - public void testFileInformationShouldNotBeNullAfterDeserialization() { - System.out.println("in should not be null"); - try { - String json = "{\"@class\": \"org.waarp.openr66.protocol.localhandler.packet.json.TransferRequestJsonPacket\"}"; - TransferRequestJsonPacket res = new ObjectMapper().readValue(json, TransferRequestJsonPacket.class); - assertEquals("fileInformation should not be null", - "", res.getFileInformation()); - } catch(Exception e) { - fail("Got unexpected exception" + e); - } + @Test + public void testFileInformationShouldNotBeNullAfterDeserialization() { + System.out.println("in should not be null"); + try { + String json = + "{\"@class\": \"org.waarp.openr66.protocol.localhandler.packet.json.TransferRequestJsonPacket\"}"; + TransferRequestJsonPacket res = + new ObjectMapper().readValue(json, TransferRequestJsonPacket.class); + assertEquals("fileInformation should not be null", + "", res.getFileInformation()); + } catch (Exception e) { + fail("Got unexpected exception" + e); } + } } diff --git a/src/test/java/org/waarp/openr66/protocol/networkhandler/NetworkTransactionTest.java b/src/test/java/org/waarp/openr66/protocol/networkhandler/NetworkTransactionTest.java deleted file mode 100644 index 0e2cb67f0..000000000 --- a/src/test/java/org/waarp/openr66/protocol/networkhandler/NetworkTransactionTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.waarp.openr66.protocol.networkhandler; - -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; -import org.junit.Test; - -import io.netty.channel.Channel; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.SocketAddress; - -public class NetworkTransactionTest { - - @Test - public void testisBlacklistedPreventNPE() { - Channel chan = mock(Channel.class); - when(chan.remoteAddress()).thenReturn(null); - NetworkTransaction.isBlacklisted(chan); - - reset(chan); - - InetSocketAddress addr = new InetSocketAddress("cannotberesolved", 6666); - //assertNull(addr.getAddress()); - doReturn(addr).when(chan).remoteAddress(); - NetworkTransaction.isBlacklisted(chan); - } -} diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java b/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java index 008c68a21..0653d759c 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java @@ -1,25 +1,24 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Waarp . If not, see - * . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.test; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; @@ -33,120 +32,140 @@ import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; import org.waarp.openr66.protocol.utils.R66Future; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + /** * Test class for internal Business test - * + * * @author Frederic Bregier - * */ public class TestBusinessRequest extends AbstractBusinessRequest { - /** - * Internal Logger - */ - private static WaarpLogger logger; + /** + * Internal Logger + */ + private static WaarpLogger logger; + + public TestBusinessRequest(NetworkTransaction networkTransaction, + R66Future future, String remoteHost, + BusinessRequestPacket packet) { + super(TestBusinessRequest.class, future, remoteHost, networkTransaction, + packet); + } - public TestBusinessRequest(NetworkTransaction networkTransaction, - R66Future future, String remoteHost, BusinessRequestPacket packet) { - super(TestBusinessRequest.class, future, remoteHost, networkTransaction, packet); + public static void main(String[] args) { + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(TestBusinessRequest.class); } + if (args.length < 1) { + logger + .error("Needs at least the configuration file as first argument"); + return; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + return; + } + Configuration.configuration.pipelineInit(); - public static void main(String[] args) { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); + NetworkTransaction networkTransaction = new NetworkTransaction(); + DbHostAuth host = Configuration.configuration.getHOST_AUTH(); + runTest(networkTransaction, host, 1); + networkTransaction.closeAll(); + } + + public static int runTest(NetworkTransaction networkTransaction, + DbHostAuth host, int nbToDo) { if (logger == null) { logger = WaarpLoggerFactory.getLogger(TestBusinessRequest.class); } - if (args.length < 1) { - logger - .error("Needs at least the configuration file as first argument"); - return; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - return; - } - Configuration.configuration.pipelineInit(); - - final NetworkTransaction networkTransaction = new NetworkTransaction(); - DbHostAuth host = Configuration.configuration.getHOST_AUTH(); ExecutorService executorService = Executors.newCachedThreadPool(); - int nb = 100; - if (args.length > 1) { - nb = Integer.parseInt(args[1]); - } + int nb = nbToDo; - R66Future[] arrayFuture = new R66Future[nb]; - logger.info("Start Test of Transaction"); - long time1 = System.currentTimeMillis(); - for (int i = 0; i < nb; i++) { - arrayFuture[i] = new R66Future(true); - BusinessRequestPacket packet = new BusinessRequestPacket( - TestExecJavaTask.class.getName() + " business 0 simple business request", 0); - TestBusinessRequest transaction = new TestBusinessRequest( - networkTransaction, arrayFuture[i], host.getHostid(), - packet); - executorService.execute(transaction); - } - int success = 0; - int error = 0; - for (int i = 0; i < nb; i++) { - arrayFuture[i].awaitUninterruptibly(); - if (arrayFuture[i].isSuccess()) { - success++; - } else { - error++; - } - } - long time2 = System.currentTimeMillis(); - logger.warn("Simple TestExecJavaTask Success: " + success + " Error: " + error + " NB/s: " + - success * 100 * 1000 / (time2 - time1)); - R66Future future = new R66Future(true); - classname = BusinessRequest.DEFAULT_CLASS; - BusinessRequestPacket packet = - new BusinessRequestPacket(classname + " LOG warn some information 1", 0); - BusinessRequest transaction = new BusinessRequest( - networkTransaction, future, host.getHostid(), packet); - transaction.run(); - future.awaitUninterruptibly(); - if (future.isSuccess()) { - success++; - } else { - error++; - } - long time3 = System.currentTimeMillis(); - logger.warn("Simple DefaultClass LOG Success: " + success + " Error: " + error + " NB/s: " + - 1000 / (time3 - time2)); + R66Future[] arrayFuture = new R66Future[nb]; + logger.info("Start Test of Transaction"); + long time1 = System.currentTimeMillis(); + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + BusinessRequestPacket packet = new BusinessRequestPacket( + TestExecJavaTask.class.getName() + + " business 0 simple business request", 0); + TestBusinessRequest transaction = new TestBusinessRequest( + networkTransaction, arrayFuture[i], host.getHostid(), + packet); + executorService.execute(transaction); + } + int success = 0; + int error = 0; + for (int i = 0; i < nb; i++) { + arrayFuture[i].awaitUninterruptibly(); + if (arrayFuture[i].isSuccess()) { + success++; + } else { + error++; + } + } + long time2 = System.currentTimeMillis(); + logger.warn( + "Simple TestExecJavaTask Success: " + success + " Error: " + error + + " NB/s: " + + success * 100 * 1000 / (time2 - time1)); + R66Future future = new R66Future(true); + classname = BusinessRequest.DEFAULT_CLASS; + BusinessRequestPacket packet = + new BusinessRequestPacket(classname + " LOG warn some information 1", + 0); + BusinessRequest transaction = new BusinessRequest( + networkTransaction, future, host.getHostid(), packet); + transaction.run(); + future.awaitUninterruptibly(); + if (future.isSuccess()) { + success++; + } else { + error++; + } + long time3 = System.currentTimeMillis(); + logger.warn( + "Simple DefaultClass LOG Success: " + success + " Error: " + error + + " NB/s: " + + 1000 / (time3 - time2)); - future = new R66Future(true); - classname = BusinessRequest.DEFAULT_CLASS; - packet = - new BusinessRequestPacket(classname + " EXECJAVA " + TestExecJavaTask.class.getName() - + " business 0 execjava business request 0", 0); - transaction = new BusinessRequest( - networkTransaction, future, host.getHostid(), packet); - transaction.run(); - future.awaitUninterruptibly(); - if (future.isSuccess()) { - success++; - } else { - error++; - } - long time4 = System.currentTimeMillis(); - logger.warn("Simple ExecJava Success: " + success + " Error: " + error + " NB/s: " + - 1000 / (time4 - time3)); + future = new R66Future(true); + classname = BusinessRequest.DEFAULT_CLASS; + packet = + new BusinessRequestPacket( + classname + " EXECJAVA " + TestExecJavaTask.class.getName() + + " business 0 execjava business request 0", 0); + transaction = new BusinessRequest( + networkTransaction, future, host.getHostid(), packet); + transaction.run(); + future.awaitUninterruptibly(); + if (future.isSuccess()) { + success++; + } else { + error++; + } + long time4 = System.currentTimeMillis(); + logger.warn( + "Simple ExecJava Success: " + success + " Error: " + error + " NB/s: " + + 1000 / (time4 - time3)); logger.info("Start Test of Increasing Transaction"); time1 = System.currentTimeMillis(); - String argsAdd = "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; + String argsAdd = + "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; String value = " business 0 "; int lastnb = nb; for (int i = 0; i < nb; i++) { arrayFuture[i] = new R66Future(true); try { - value += argsAdd + argsAdd + argsAdd + argsAdd + argsAdd + argsAdd + argsAdd + argsAdd + argsAdd - + argsAdd; + value += argsAdd + argsAdd + argsAdd + argsAdd + argsAdd + + argsAdd + argsAdd + argsAdd + argsAdd + + argsAdd; } catch (OutOfMemoryError e) { logger.warn("Send size: " + value.length()); lastnb = i; @@ -154,28 +173,28 @@ public static void main(String[] args) { } packet = new BusinessRequestPacket( TestExecJavaTask.class.getName() + value, 0); - TestBusinessRequest transaction2 = new TestBusinessRequest( - networkTransaction, arrayFuture[i], host.getHostid(), - packet); + TestBusinessRequest transaction2 = + new TestBusinessRequest(networkTransaction, arrayFuture[i], + host.getHostid(), packet); executorService.execute(transaction2); } - success = 0; - error = 0; + int success2 = 0; + int error2 = 0; for (int i = 0; i < lastnb; i++) { - arrayFuture[i].awaitUninterruptibly(); + arrayFuture[i].awaitForDoneOrInterruptible(); if (arrayFuture[i].isSuccess()) { - success++; + success2++; } else { - error++; + error2++; } } time2 = System.currentTimeMillis(); - logger.warn("Simple TestExecJavaTask with increasing argument size Success: " + success + " Error: " + error - + " NB/s: " + - success * 100 * 1000 / (time2 - time1)); - + logger.warn( + "Simple TestExecJavaTask with increasing argument size Success: " + + success2 + " Error: " + error2 + + " NB/s: " + success2 * nb * 1000 / (time2 - time1)); executorService.shutdown(); - networkTransaction.closeAll(); + return error + error2; } } diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestJsonGenerator.java b/src/test/java/org/waarp/openr66/protocol/test/TestJsonGenerator.java deleted file mode 100644 index 42367ede3..000000000 --- a/src/test/java/org/waarp/openr66/protocol/test/TestJsonGenerator.java +++ /dev/null @@ -1,131 +0,0 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Waarp . If not, see - * . - */ -package org.waarp.openr66.protocol.test; - -import org.waarp.common.database.DbPreparedStatement; -import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; -import org.waarp.common.database.exception.WaarpDatabaseSqlException; -import org.waarp.common.logging.WaarpLogger; -import org.waarp.common.logging.WaarpLoggerFactory; -import org.waarp.common.logging.WaarpSlf4JLoggerFactory; -import org.waarp.openr66.configuration.FileBasedConfiguration; -import org.waarp.openr66.database.DbConstant; -import org.waarp.openr66.database.data.DbHostAuth; -import org.waarp.openr66.database.data.DbRule; -import org.waarp.openr66.database.data.DbTaskRunner; -import org.waarp.openr66.protocol.configuration.Configuration; -import org.waarp.openr66.protocol.configuration.Messages; -import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; - -/** - * Test class for JsonGenerator - * - * @author Frederic Bregier - * - */ -public class TestJsonGenerator { - /** - * Internal Logger - */ - static protected volatile WaarpLogger logger; - static int nb = 11; - - /** - * @param args - * @param rank - * @return True if OK - */ - protected static boolean getSpecialParams(String[] args, int rank) { - for (int i = rank; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-nb")) { - i++; - nb = Integer.parseInt(args[i]); - } - } - return true; - } - - public static void main(String[] args) { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpLoggerFactory.getLogger(TestJsonGenerator.class); - } - if (args.length == 0 || !FileBasedConfiguration - .setSubmitClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger.error(Messages.getString("Configuration.NeedCorrectConfig")); //$NON-NLS-1$ - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isActive()) { - DbConstant.admin.close(); - } - System.exit(1); - } - getSpecialParams(args, 1); - logger.warn("Start Test Json"); - DbPreparedStatement preparedStatement; - try { - preparedStatement = DbTaskRunner.getFilterPrepareStatement(DbConstant.admin.getSession(), nb, false, - null, null, null, null, null, null, - false, false, false, false, true, null); - preparedStatement.executeQuery(); - String tasks = DbTaskRunner.getJson(preparedStatement, nb); - System.out.println(tasks); - preparedStatement.realClose(); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - } catch (OpenR66ProtocolBusinessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - System.out.println(); - try { - preparedStatement = DbHostAuth.getFilterPrepareStament(DbConstant.admin.getSession(), - null, null); - preparedStatement.executeQuery(); - String hosts = DbHostAuth.getJson(preparedStatement, nb); - System.out.println(hosts); - preparedStatement.realClose(); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - } catch (OpenR66ProtocolBusinessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - System.out.println(); - try { - preparedStatement = DbRule.getFilterPrepareStament(DbConstant.admin.getSession(), - null, -1); - preparedStatement.executeQuery(); - String rules = DbRule.getJson(preparedStatement, nb); - System.out.println(rules); - preparedStatement.realClose(); - } catch (WaarpDatabaseNoConnectionException e) { - e.printStackTrace(); - } catch (WaarpDatabaseSqlException e) { - e.printStackTrace(); - } catch (OpenR66ProtocolBusinessException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - -} diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestProgressBarTransfer.java b/src/test/java/org/waarp/openr66/protocol/test/TestProgressBarTransfer.java index fb244fa9c..bf193d294 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestProgressBarTransfer.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestProgressBarTransfer.java @@ -1,25 +1,28 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Waarp . If not, see - * . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.test; import org.waarp.common.database.exception.WaarpDatabaseException; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; import org.waarp.openr66.client.ProgressBarTransfer; import org.waarp.openr66.context.ErrorCode; import org.waarp.openr66.context.R66Result; @@ -31,145 +34,164 @@ /** * @author Frederic Bregier - * */ public class TestProgressBarTransfer extends ProgressBarTransfer { - /** - * @param future - * @param remoteHost - * @param filename - * @param rulename - * @param fileinfo - * @param isMD5 - * @param blocksize - * @param id - * @param networkTransaction - * @param callbackdelay - */ - public TestProgressBarTransfer(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, - int blocksize, long id, NetworkTransaction networkTransaction, - long callbackdelay) { - super(future, remoteHost, filename, rulename, fileinfo, isMD5, - blocksize, id, networkTransaction, callbackdelay); + /** + * @param future + * @param remoteHost + * @param filename + * @param rulename + * @param fileinfo + * @param isMD5 + * @param blocksize + * @param id + * @param networkTransaction + * @param callbackdelay + */ + public TestProgressBarTransfer(R66Future future, String remoteHost, + String filename, String rulename, + String fileinfo, boolean isMD5, + int blocksize, long id, + NetworkTransaction networkTransaction, + long callbackdelay) { + super(future, remoteHost, filename, rulename, fileinfo, isMD5, + blocksize, id, networkTransaction, callbackdelay); + } + + public static void main(String[] args) { + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(ProgressBarTransfer.class); } + if (!getParams(args, false)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isActive()) { + DbConstant.admin.close(); + } + ChannelUtils.stopLogger(); + DetectionUtils.SystemExit(2); + return; + } + long time1 = System.currentTimeMillis(); + R66Future future = new R66Future(true); - @Override - public void callBack(int currentBlock, int blocksize) { - if (filesize == 0) { - System.err.println("Block: " + currentBlock + " BSize: " + blocksize); + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + TestProgressBarTransfer transaction = new TestProgressBarTransfer(future, + rhost, + localFilename, + rule, + fileInfo, + ismd5, + block, + idt, + networkTransaction, + 100); + transaction.normalInfoAsWarn = snormalInfoAsWarn; + transaction.run(); + future.awaitUninterruptibly(); + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + if (future.isSuccess()) { + if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { + logger.warn("Transfer in status: WARNED " + + result.getRunner().toShortString() + + + " " + + rhost + + "" + + + " " + + + (result.getFile() != null? + result.getFile().toString() + "" + : "no file") + + " delay: " + delay); } else { - System.err.println("Block: " + currentBlock + " BSize: " + blocksize + " on " + - (int) (Math.ceil(((double) filesize / (double) blocksize)))); + logger.info("Transfer in status: SUCCESS " + + result.getRunner().toShortString() + + + " " + + rhost + + "" + + + " " + + + (result.getFile() != null? + result.getFile().toString() + "" + : "no file") + + " delay: " + delay); } - } - - @Override - public void lastCallBack(boolean success, int currentBlock, int blocksize) { - if (filesize == 0) { - System.err.println("Status: " + success + " Block: " + currentBlock + " BSize: " - + blocksize); + if (nolog || result.getRunner().shallIgnoreSave()) { + // In case of success, delete the runner + try { + result.getRunner().delete(); + } catch (WaarpDatabaseException e) { + logger.warn("Cannot apply nolog to " + + result.getRunner().toShortString(), + e); + } + } + } else { + if (result == null || result.getRunner() == null) { + logger.error("Transfer in FAILURE with no Id", future.getCause()); + networkTransaction.closeAll(); + DetectionUtils.SystemExit(ErrorCode.Unknown.ordinal()); + return; + } + if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { + logger.warn("Transfer is WARNED " + + result.getRunner().toShortString() + + " " + rhost + "", future.getCause()); + networkTransaction.closeAll(); + DetectionUtils.SystemExit(result.getCode().ordinal()); } else { - System.err.println("Status: " + success + " Block: " + currentBlock + " BSize: " - + blocksize + - " Size=" + filesize); + logger.error("Transfer in FAILURE " + + result.getRunner().toShortString() + + " " + rhost + "", + future.getCause()); + networkTransaction.closeAll(); + DetectionUtils.SystemExit(result.getCode().ordinal()); } + } + } finally { + networkTransaction.closeAll(); + // In case something wrong append + if (future.isDone() && future.isSuccess()) { + DetectionUtils.SystemExit(0); + } else { + DetectionUtils.SystemExit(66); + } } + } - public static void main(String[] args) { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpLoggerFactory.getLogger(ProgressBarTransfer.class); - } - if (!getParams(args, false)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isActive()) { - DbConstant.admin.close(); - } - ChannelUtils.stopLogger(); - System.exit(2); - } - long time1 = System.currentTimeMillis(); - R66Future future = new R66Future(true); + @Override + public void callBack(int currentBlock, int blocksize) { + if (filesize == 0) { + System.err.println("Block: " + currentBlock + " BSize: " + blocksize); + } else { + System.err + .println("Block: " + currentBlock + " BSize: " + blocksize + " on " + + (int) (Math.ceil(((double) filesize / (double) blocksize)))); + } + } - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - TestProgressBarTransfer transaction = new TestProgressBarTransfer(future, - rhost, localFilename, rule, fileInfo, ismd5, block, idt, - networkTransaction, 100); - transaction.normalInfoAsWarn = snormalInfoAsWarn; - transaction.run(); - future.awaitUninterruptibly(); - long time2 = System.currentTimeMillis(); - long delay = time2 - time1; - R66Result result = future.getResult(); - if (future.isSuccess()) { - if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { - logger.warn("Transfer in status: WARNED " - + result.getRunner().toShortString() - + - " " - + rhost - + "" - + - " " - + - (result.getFile() != null ? result.getFile().toString() + "" - : "no file") - + " delay: " + delay); - } else { - logger.info("Transfer in status: SUCCESS " - + result.getRunner().toShortString() - + - " " - + rhost - + "" - + - " " - + - (result.getFile() != null ? result.getFile().toString() + "" - : "no file") - + " delay: " + delay); - } - if (nolog || result.getRunner().shallIgnoreSave()) { - // In case of success, delete the runner - try { - result.getRunner().delete(); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot apply nolog to " + result.getRunner().toShortString(), - e); - } - } - } else { - if (result == null || result.getRunner() == null) { - logger.error("Transfer in FAILURE with no Id", future.getCause()); - networkTransaction.closeAll(); - System.exit(ErrorCode.Unknown.ordinal()); - } - if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { - logger.warn("Transfer is WARNED " + result.getRunner().toShortString() + - " " + rhost + "", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.getCode().ordinal()); - } else { - logger.error("Transfer in FAILURE " + result.getRunner().toShortString() + - " " + rhost + "", future.getCause()); - networkTransaction.closeAll(); - System.exit(result.getCode().ordinal()); - } - } - } finally { - networkTransaction.closeAll(); - // In case something wrong append - if (future.isDone() && future.isSuccess()) { - System.exit(0); - } else { - System.exit(66); - } - } + @Override + public void lastCallBack(boolean success, int currentBlock, int blocksize) { + if (filesize == 0) { + System.err + .println("Status: " + success + " Block: " + currentBlock + " BSize: " + + blocksize); + } else { + System.err + .println("Status: " + success + " Block: " + currentBlock + " BSize: " + + blocksize + + " Size=" + filesize); } + } } diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestRecvThroughClient.java b/src/test/java/org/waarp/openr66/protocol/test/TestRecvThroughClient.java index f3650f16e..86d4d87f5 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestRecvThroughClient.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestRecvThroughClient.java @@ -1,25 +1,28 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Waarp . If not, see - * . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.test; import io.netty.buffer.ByteBuf; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; import org.waarp.openr66.client.RecvThroughClient; import org.waarp.openr66.client.RecvThroughHandler; import org.waarp.openr66.context.ErrorCode; @@ -32,107 +35,120 @@ /** * Test class for Recv Through client - * + * * @author Frederic Bregier - * */ public class TestRecvThroughClient extends RecvThroughClient { - public static class TestRecvThroughHandler extends RecvThroughHandler { - @Override - public void writeByteBuf(ByteBuf buffer) - throws OpenR66ProtocolBusinessException { - buffer.skipBytes(buffer.readableBytes()); - // byte [] array = this.getByte(buffer); - // FIXME one should use the array for its own goal - // logger.debug("Write {}", array.length); - } + /** + * @param future + * @param remoteHost + * @param filename + * @param rulename + * @param fileinfo + * @param isMD5 + * @param blocksize + * @param networkTransaction + */ + public TestRecvThroughClient(R66Future future, TestRecvThroughHandler handler, + String remoteHost, + String filename, String rulename, + String fileinfo, boolean isMD5, + int blocksize, + NetworkTransaction networkTransaction) { + super(future, handler, remoteHost, filename, rulename, fileinfo, isMD5, + blocksize, + DbConstant.ILLEGALVALUE, networkTransaction); + } + /** + * @param args + */ + public static void main(String[] args) { + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(TestRecvThroughHandler.class); } - - /** - * @param future - * @param remoteHost - * @param filename - * @param rulename - * @param fileinfo - * @param isMD5 - * @param blocksize - * @param networkTransaction - */ - public TestRecvThroughClient(R66Future future, TestRecvThroughHandler handler, - String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, - int blocksize, NetworkTransaction networkTransaction) { - super(future, handler, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, - DbConstant.ILLEGALVALUE, networkTransaction); + if (!getParams(args, false)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isActive()) { + DbConstant.admin.close(); + } + DetectionUtils.SystemExit(1); + return; } + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + R66Future future = new R66Future(true); + TestRecvThroughHandler handler = new TestRecvThroughHandler(); + TestRecvThroughClient transaction = new TestRecvThroughClient(future, + handler, + rhost, + localFilename, + rule, + fileInfo, + ismd5, + block, + networkTransaction); + transaction.normalInfoAsWarn = snormalInfoAsWarn; + long time1 = System.currentTimeMillis(); + transaction.run(); + future.awaitUninterruptibly(); - /** - * @param args - */ - public static void main(String[] args) { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); - if (logger == null) { - logger = WaarpLoggerFactory.getLogger(TestRecvThroughHandler.class); + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + if (future.isSuccess()) { + if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { + logger.warn("Warning with Id: " + + result.getRunner().getSpecialId() + " on file: " + + (result.getFile() != null? result.getFile().toString() : + "no file") + + " delay: " + delay); + } else { + logger.warn("Success with Id: " + + result.getRunner().getSpecialId() + " on Final file: " + + (result.getFile() != null? result.getFile().toString() : + "no file") + + " delay: " + delay); } - if (!getParams(args, false)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isActive()) { - DbConstant.admin.close(); - } - System.exit(1); + } else { + if (result == null || result.getRunner() == null) { + logger.warn("Transfer in Error with no Id", future.getCause()); + networkTransaction.closeAll(); + DetectionUtils.SystemExit(1); + return; } - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - R66Future future = new R66Future(true); - TestRecvThroughHandler handler = new TestRecvThroughHandler(); - TestRecvThroughClient transaction = new TestRecvThroughClient(future, - handler, - rhost, localFilename, rule, fileInfo, ismd5, block, - networkTransaction); - transaction.normalInfoAsWarn = snormalInfoAsWarn; - long time1 = System.currentTimeMillis(); - transaction.run(); - future.awaitUninterruptibly(); - - long time2 = System.currentTimeMillis(); - long delay = time2 - time1; - R66Result result = future.getResult(); - if (future.isSuccess()) { - if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { - logger.warn("Warning with Id: " + - result.getRunner().getSpecialId() + " on file: " + - (result.getFile() != null ? result.getFile().toString() : "no file") - + " delay: " + delay); - } else { - logger.warn("Success with Id: " + - result.getRunner().getSpecialId() + " on Final file: " + - (result.getFile() != null ? result.getFile().toString() : "no file") - + " delay: " + delay); - } - } else { - if (result == null || result.getRunner() == null) { - logger.warn("Transfer in Error with no Id", future.getCause()); - networkTransaction.closeAll(); - System.exit(1); - } - if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { - logger.warn("Transfer in Warning with Id: " + - result.getRunner().getSpecialId(), future.getCause()); - networkTransaction.closeAll(); - System.exit(result.getCode().ordinal()); - } else { - logger.error("Transfer in Error with Id: " + - result.getRunner().getSpecialId(), future.getCause()); - networkTransaction.closeAll(); - System.exit(result.getCode().ordinal()); - } - } - } finally { - networkTransaction.closeAll(); + if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { + logger.warn("Transfer in Warning with Id: " + + result.getRunner().getSpecialId(), future.getCause()); + networkTransaction.closeAll(); + DetectionUtils.SystemExit(result.getCode().ordinal()); + return; + } else { + logger.error("Transfer in Error with Id: " + + result.getRunner().getSpecialId(), future.getCause()); + networkTransaction.closeAll(); + DetectionUtils.SystemExit(result.getCode().ordinal()); + return; } + } + } finally { + networkTransaction.closeAll(); + } + } + + public static class TestRecvThroughHandler extends RecvThroughHandler { + @Override + public void writeByteBuf(ByteBuf buffer) + throws OpenR66ProtocolBusinessException { + buffer.skipBytes(buffer.readableBytes()); + // byte [] array = this.getByte(buffer); + // FIXME one should use the array for its own goal + // logger.debug("Write {}", array.length); } + } + } diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughClient.java b/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughClient.java index 801b89cfb..dfe105b05 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughClient.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughClient.java @@ -1,20 +1,22 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Waarp . If not, see - * . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.test; import io.netty.channel.ChannelFuture; @@ -24,6 +26,8 @@ import org.waarp.common.file.DataBlock; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; +import org.waarp.common.utility.WaarpNettyUtil; import org.waarp.openr66.client.SendThroughClient; import org.waarp.openr66.context.ErrorCode; import org.waarp.openr66.context.R66Result; @@ -38,185 +42,188 @@ /** * Test class for Send Through client - * + * * @author Frederic Bregier - * */ public class TestSendThroughClient extends SendThroughClient { - /** - * @param future - * @param remoteHost - * @param filename - * @param rulename - * @param fileinfo - * @param isMD5 - * @param blocksize - * @param networkTransaction - */ - public TestSendThroughClient(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, - int blocksize, NetworkTransaction networkTransaction) { - super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, - DbConstant.ILLEGALVALUE, networkTransaction); + /** + * @param future + * @param remoteHost + * @param filename + * @param rulename + * @param fileinfo + * @param isMD5 + * @param blocksize + * @param networkTransaction + */ + public TestSendThroughClient(R66Future future, String remoteHost, + String filename, String rulename, + String fileinfo, boolean isMD5, + int blocksize, + NetworkTransaction networkTransaction) { + super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, + DbConstant.ILLEGALVALUE, networkTransaction); + } + + /** + * @param args + */ + public static void main(String[] args) { + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(TestSendThroughClient.class); } + if (!getParams(args, false)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isActive()) { + DbConstant.admin.close(); + } + DetectionUtils.SystemExit(1); + return; + } + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + R66Future future = new R66Future(true); + TestSendThroughClient transaction = new TestSendThroughClient(future, + rhost, + localFilename, + rule, + fileInfo, + ismd5, + block, + networkTransaction); + transaction.normalInfoAsWarn = snormalInfoAsWarn; + long time1 = System.currentTimeMillis(); + if (!transaction.initiateRequest()) { + logger.error("Transfer in Error", future.getCause()); + return; + } + if (transaction.sendFile()) { + transaction.finalizeRequest(); + } else { + transaction.transferInError(null); + } + future.awaitForDoneOrInterruptible(); - public boolean sendFile() { - R66File r66file = localChannelReference.getSession().getFile(); - boolean retrieveDone = false; - try { - DataBlock block = null; - try { - block = r66file.readDataBlock(); - } catch (FileEndOfTransferException e) { - // Last block (in fact, no data to read) - retrieveDone = true; - return retrieveDone; - } - if (block == null) { - // Last block (in fact, no data to read) - retrieveDone = true; - return retrieveDone; - } - ChannelFuture future1 = null, future2 = null; - if (block != null) { - block.getBlock().retain(); - future1 = this.writeWhenPossible(block); - } - // While not last block - while (block != null && !block.isEOF()) { - try { - future1.await(); - } catch (InterruptedException e) { - } - if (!future1.isSuccess()) { - return false; - } - try { - block = r66file.readDataBlock(); - } catch (FileEndOfTransferException e) { - // Wait for last write - retrieveDone = true; - try { - future1.await(); - } catch (InterruptedException e1) { - } - return future1.isSuccess(); - } - block.getBlock().retain(); - future2 = this.writeWhenPossible(block); - future1 = future2; - } - // Wait for last write - if (future1 != null) { - try { - future1.await(); - } catch (InterruptedException e) { - } - return future1.isSuccess(); - } - retrieveDone = true; - return retrieveDone; - } catch (FileTransferException e) { - // An error occurs! - this.transferInError(new OpenR66ProtocolSystemException(e)); - return false; - } catch (OpenR66ProtocolPacketException e) { - // An error occurs! - this.transferInError(e); - return false; - } catch (OpenR66RunnerErrorException e) { - // An error occurs! - this.transferInError(e); - return false; - } catch (OpenR66ProtocolSystemException e) { - // An error occurs! - this.transferInError(e); - return false; + long time2 = System.currentTimeMillis(); + long delay = time2 - time1; + R66Result result = future.getResult(); + if (future.isSuccess()) { + if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { + logger.warn("Warning with Id: " + + result.getRunner().getSpecialId() + " on file: " + + (result.getFile() != null? result.getFile().toString() : + "no file") + + " delay: " + delay); + } else { + logger.warn("Success with Id: " + + result.getRunner().getSpecialId() + " on Final file: " + + (result.getFile() != null? result.getFile().toString() : + "no file") + + " delay: " + delay); + } + if (nolog || result.getRunner().shallIgnoreSave()) { + // In case of success, delete the runner + try { + result.getRunner().delete(); + } catch (WaarpDatabaseException e) { + logger + .warn("Cannot apply nolog to " + result.getRunner().toString(), + e); + } } + } else { + if (result == null || result.getRunner() == null) { + logger.warn("Transfer in Error with no Id", future.getCause()); + networkTransaction.closeAll(); + DetectionUtils.SystemExit(1); + return; + } + if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { + logger.warn("Transfer in Warning with Id: " + + result.getRunner().getSpecialId(), future.getCause()); + networkTransaction.closeAll(); + DetectionUtils.SystemExit(result.getCode().ordinal()); + } else { + logger.error("Transfer in Error with Id: " + + result.getRunner().getSpecialId(), future.getCause()); + networkTransaction.closeAll(); + DetectionUtils.SystemExit(result.getCode().ordinal()); + } + } + } finally { + networkTransaction.closeAll(); } - /** - * @param args - */ - public static void main(String[] args) { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpLoggerFactory.getLogger(TestSendThroughClient.class); - } - if (!getParams(args, false)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isActive()) { - DbConstant.admin.close(); - } - System.exit(1); + } + + public boolean sendFile() { + R66File r66file = localChannelReference.getSession().getFile(); + boolean retrieveDone = false; + try { + DataBlock block = null; + try { + block = r66file.readDataBlock(); + } catch (FileEndOfTransferException e) { + // Last block (in fact, no data to read) + retrieveDone = true; + return retrieveDone; + } + if (block == null) { + // Last block (in fact, no data to read) + retrieveDone = true; + return retrieveDone; + } + ChannelFuture future1 = null, future2 = null; + if (block != null) { + block.getBlock().retain(); + future1 = this.writeWhenPossible(block); + } + // While not last block + while (block != null && !block.isEOF()) { + WaarpNettyUtil.awaitDoneOrInterrupted(future1); + if (!future1.isSuccess()) { + return false; } - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); try { - R66Future future = new R66Future(true); - TestSendThroughClient transaction = new TestSendThroughClient(future, - rhost, localFilename, rule, fileInfo, ismd5, block, - networkTransaction); - transaction.normalInfoAsWarn = snormalInfoAsWarn; - long time1 = System.currentTimeMillis(); - if (!transaction.initiateRequest()) { - logger.error("Transfer in Error", future.getCause()); - return; - } - if (transaction.sendFile()) { - transaction.finalizeRequest(); - } else { - transaction.transferInError(null); - } - future.awaitUninterruptibly(); - - long time2 = System.currentTimeMillis(); - long delay = time2 - time1; - R66Result result = future.getResult(); - if (future.isSuccess()) { - if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { - logger.warn("Warning with Id: " + - result.getRunner().getSpecialId() + " on file: " + - (result.getFile() != null ? result.getFile().toString() : "no file") - + " delay: " + delay); - } else { - logger.warn("Success with Id: " + - result.getRunner().getSpecialId() + " on Final file: " + - (result.getFile() != null ? result.getFile().toString() : "no file") - + " delay: " + delay); - } - if (nolog || result.getRunner().shallIgnoreSave()) { - // In case of success, delete the runner - try { - result.getRunner().delete(); - } catch (WaarpDatabaseException e) { - logger.warn("Cannot apply nolog to " + result.getRunner().toString(), e); - } - } - } else { - if (result == null || result.getRunner() == null) { - logger.warn("Transfer in Error with no Id", future.getCause()); - networkTransaction.closeAll(); - System.exit(1); - } - if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { - logger.warn("Transfer in Warning with Id: " + - result.getRunner().getSpecialId(), future.getCause()); - networkTransaction.closeAll(); - System.exit(result.getCode().ordinal()); - } else { - logger.error("Transfer in Error with Id: " + - result.getRunner().getSpecialId(), future.getCause()); - networkTransaction.closeAll(); - System.exit(result.getCode().ordinal()); - } - } - } finally { - networkTransaction.closeAll(); + block = r66file.readDataBlock(); + } catch (FileEndOfTransferException e) { + // Wait for last write + retrieveDone = true; + WaarpNettyUtil.awaitDoneOrInterrupted(future1); + return future1.isSuccess(); } - + block.getBlock().retain(); + future2 = this.writeWhenPossible(block); + future1 = future2; + } + // Wait for last write + if (future1 != null) { + WaarpNettyUtil.awaitDoneOrInterrupted(future1); + return future1.isSuccess(); + } + retrieveDone = true; + return retrieveDone; + } catch (FileTransferException e) { + // An error occurs! + this.transferInError(new OpenR66ProtocolSystemException(e)); + return false; + } catch (OpenR66ProtocolPacketException e) { + // An error occurs! + this.transferInError(e); + return false; + } catch (OpenR66RunnerErrorException e) { + // An error occurs! + this.transferInError(e); + return false; + } catch (OpenR66ProtocolSystemException e) { + // An error occurs! + this.transferInError(e); + return false; } + } } diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughForward.java b/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughForward.java index 4d8ee71bb..f7f3c4f37 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughForward.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestSendThroughForward.java @@ -1,20 +1,22 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Waarp . If not, see - * . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.test; import io.netty.buffer.ByteBuf; @@ -29,7 +31,6 @@ import org.waarp.openr66.context.ErrorCode; import org.waarp.openr66.context.R66Result; import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.database.DbConstant; import org.waarp.openr66.database.data.DbRule; import org.waarp.openr66.database.data.DbTaskRunner; import org.waarp.openr66.protocol.configuration.Configuration; @@ -48,27 +49,30 @@ /** * WARNING: This class is not functional neither integrated
- * - * Test class for Send Through to another R66 Server as forward
- * Only a subpart of SenThroughClient is to be made since steps 1-2 and steps 7-8 are only for - * client, not for server. - * + *

+ * Test class for Send Through to another R66 Server as forward
Only a + * subpart of SenThroughClient is to be made + * since steps 1-2 and steps 7-8 are only for client, not for server. + *

* 3) Prepare the request of transfer:
* R66Future futureReq = new R66Future(true);
* TestSendThroughForward transaction = new TestSendThroughForward(futureReq,...);
* if (! transaction.initiateRequest()) { error }
*
- * 4) Once initiateRequest() gives true, you are ready to send the data in through mode using the + * 4) Once initiateRequest() gives true, you are ready to send the data in + * through mode using the * TestRecvThroughForwardHandler:
*
- * 5) Once you have finished, so this is the last block, you have to do the following:
- * If the last block is not empty:
+ * 5) Once you have finished, so this is the last block, you have to do the + * following:
If the last block is not + * empty:
* DataBlock block = transaction.transformToDataBlock(data);
* block.setEOF(true);
* futureWrite = transaction.writeWhenPossible(block);
* futureWrite.awaitUninterruptibly();
*
- * If the last block is empty, it is already handled by TestRecvThroughForwardHandler
+ * If the last block is empty, it is already handled by + * TestRecvThroughForwardHandler
*
* 6) If everything is in success:
* transaction.finalizeRequest();
@@ -77,192 +81,200 @@ * futureReq.awaitUninterruptibly();
* R66Result result = futureReq.getResult();
*
- * + * * @author Frederic Bregier - * */ public class TestSendThroughForward extends SendThroughClient { - public TestRecvThroughForwardHandler handler; - public DbSession dbSession; - public volatile boolean foundEOF = false; - protected DbTaskRunner sourceRunner; + public TestRecvThroughForwardHandler handler; + public DbSession dbSession; + public volatile boolean foundEOF = false; + protected DbTaskRunner sourceRunner; - public static class TestRecvThroughForwardHandler extends RecvThroughHandler { - - protected TestSendThroughForward client; - @Override - public void writeByteBuf(ByteBuf buffer) - throws OpenR66ProtocolBusinessException { - DataBlock block = new DataBlock(); - if (buffer.readableBytes() <= 0) { - // last block - block.setEOF(true); - } else { - block.setBlock(buffer); - } - try { - client.writeWhenPossible(block).await(Configuration.configuration.getTIMEOUTCON()); - } catch (OpenR66RunnerErrorException e) { - client.transferInError(e); - } catch (OpenR66ProtocolPacketException e) { - client.transferInError(e); - } catch (OpenR66ProtocolSystemException e) { - client.transferInError(e); - } catch (InterruptedException e) { - client.transferInError(new OpenR66ProtocolSystemException(e)); - } - if (block.isEOF()) { - client.finalizeRequest(); - client.foundEOF = true; - } - } + /** + * @param future + * @param remoteHost + * @param filename + * @param rulename + * @param fileinfo + * @param isMD5 + * @param blocksize + * @param networkTransaction + * @param idt Id Transfer if any temptative already exists + * @param dbSession + * @param runner (recv runner) + */ + public TestSendThroughForward(R66Future future, String remoteHost, + String filename, String rulename, + String fileinfo, boolean isMD5, + int blocksize, + NetworkTransaction networkTransaction, long idt, + DbSession dbSession, DbTaskRunner runner) { + super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, + idt, networkTransaction); + handler = new TestRecvThroughForwardHandler(); + handler.client = this; + this.dbSession = dbSession; + this.sourceRunner = runner; + } + @Override + public boolean initiateRequest() { + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(TestSendThroughForward.class); } - - /** - * @param future - * @param remoteHost - * @param filename - * @param rulename - * @param fileinfo - * @param isMD5 - * @param blocksize - * @param networkTransaction - * @param idt - * Id Transfer if any temptative already exists - * @param dbSession - * @param runner - * (recv runner) - */ - public TestSendThroughForward(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, - int blocksize, NetworkTransaction networkTransaction, long idt, - DbSession dbSession, DbTaskRunner runner) { - super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, - idt, networkTransaction); - handler = new TestRecvThroughForwardHandler(); - handler.client = this; - this.dbSession = dbSession; - this.sourceRunner = runner; + DbRule rule; + try { + rule = new DbRule(rulename); + } catch (WaarpDatabaseException e) { + logger.error("Cannot get Rule: " + rulename, e); + future.setResult( + new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + ErrorCode.Internal, null)); + future.setFailure(e); + return false; } - - @Override - public boolean initiateRequest() { - if (logger == null) { - logger = WaarpLoggerFactory.getLogger(TestSendThroughForward.class); - } - DbRule rule; + int mode = rule.getMode(); + if (isMD5) { + mode = RequestPacket.getModeMD5(mode); + } + String sep = PartnerConfiguration.getSeparator(remoteHost); + RequestPacket request = new RequestPacket(rulename, + mode, filename, blocksize, + sourceRunner.getRank(), + id, fileinfo, -1, sep); + // Not isRecv since it is the requester, so send => isSender is true + boolean isSender = true; + try { + try { + // no delay + taskRunner = + new DbTaskRunner(rule, isSender, request, + remoteHost, null); + } catch (WaarpDatabaseException e) { + logger.error("Cannot get task", e); + future.setResult( + new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + ErrorCode.Internal, null)); + future.setFailure(e); + return false; + } + ClientRunner runner = + new ClientRunner(networkTransaction, taskRunner, future); + runner.setRecvThroughHandler(handler); + runner.setSendThroughMode(); + OpenR66ProtocolNotYetConnectionException exc = null; + for (int i = 0; i < Configuration.RETRYNB; i++) { try { - rule = new DbRule(rulename); - } catch (WaarpDatabaseException e) { - logger.error("Cannot get Rule: " + rulename, e); - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, - ErrorCode.Internal, null)); - future.setFailure(e); - return false; + localChannelReference = runner.initRequest(); + exc = null; + break; + } catch (OpenR66RunnerErrorException e) { + logger.error("Cannot Transfer", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.Internal, taskRunner)); + future.setFailure(e); + return false; + } catch (OpenR66ProtocolNoConnectionException e) { + logger.error("Cannot Connect", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.ConnectionImpossible, + taskRunner)); + finalizeInErrorTransferRequest(runner, taskRunner, + ErrorCode.ConnectionImpossible); + future.setFailure(e); + return false; + } catch (OpenR66ProtocolPacketException e) { + logger.error("Bad Protocol", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.TransferError, taskRunner)); + future.setFailure(e); + return false; + } catch (OpenR66ProtocolNotYetConnectionException e) { + logger.debug("Not Yet Connected", e); + exc = e; + continue; } - int mode = rule.getMode(); - if (isMD5) { - mode = RequestPacket.getModeMD5(mode); - } - String sep = PartnerConfiguration.getSeparator(remoteHost); - RequestPacket request = new RequestPacket(rulename, - mode, filename, blocksize, sourceRunner.getRank(), - id, fileinfo, -1, sep); - // Not isRecv since it is the requester, so send => isSender is true - boolean isSender = true; - try { - try { - // no delay - taskRunner = - new DbTaskRunner(rule, isSender, request, - remoteHost, null); - } catch (WaarpDatabaseException e) { - logger.error("Cannot get task", e); - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, - ErrorCode.Internal, null)); - future.setFailure(e); - return false; - } - ClientRunner runner = new ClientRunner(networkTransaction, taskRunner, future); - runner.setRecvThroughHandler(handler); - runner.setSendThroughMode(); - OpenR66ProtocolNotYetConnectionException exc = null; - for (int i = 0; i < Configuration.RETRYNB; i++) { - try { - localChannelReference = runner.initRequest(); - exc = null; - break; - } catch (OpenR66RunnerErrorException e) { - logger.error("Cannot Transfer", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.Internal, taskRunner)); - future.setFailure(e); - return false; - } catch (OpenR66ProtocolNoConnectionException e) { - logger.error("Cannot Connect", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - finalizeInErrorTransferRequest(runner, taskRunner, ErrorCode.ConnectionImpossible); - future.setFailure(e); - return false; - } catch (OpenR66ProtocolPacketException e) { - logger.error("Bad Protocol", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.TransferError, taskRunner)); - future.setFailure(e); - return false; - } catch (OpenR66ProtocolNotYetConnectionException e) { - logger.debug("Not Yet Connected", e); - exc = e; - continue; - } - } - if (exc != null) { - taskRunner.setLocalChannelReference(new LocalChannelReference()); - logger.error("Cannot Connect", exc); - future.setResult(new R66Result(exc, null, true, - ErrorCode.ConnectionImpossible, taskRunner)); - future.setFailure(exc); - return false; - } - try { - localChannelReference.waitReadyForSendThrough(); - } catch (OpenR66Exception e) { - logger.error("Cannot Transfer", e); - future.setResult(new R66Result(e, null, true, - ErrorCode.Internal, taskRunner)); - future.setFailure(e); - return false; - } - if (taskRunner.getRank() < sourceRunner.getRank()) { - sourceRunner.setRankAtStartup(taskRunner.getRank()); - } - // now start the send from external data - return true; - } finally { - if (taskRunner != null) { - // not delete but sourceRunner and taskRunner should be stopped - // and taskRunner not allowed to be restarted alone - if (future.isFailed()) { - taskRunner.changeUpdatedInfo(UpdatedInfo.INERROR); - taskRunner.forceSaveStatus(); - } - } + } + if (exc != null) { + taskRunner.setLocalChannelReference(new LocalChannelReference()); + logger.error("Cannot Connect", exc); + future.setResult(new R66Result(exc, null, true, + ErrorCode.ConnectionImpossible, + taskRunner)); + future.setFailure(exc); + return false; + } + try { + localChannelReference.waitReadyForSendThrough(); + } catch (OpenR66Exception e) { + logger.error("Cannot Transfer", e); + future.setResult(new R66Result(e, null, true, + ErrorCode.Internal, taskRunner)); + future.setFailure(e); + return false; + } + if (taskRunner.getRank() < sourceRunner.getRank()) { + sourceRunner.setRankAtStartup(taskRunner.getRank()); + } + // now start the send from external data + return true; + } finally { + if (taskRunner != null) { + // not delete but sourceRunner and taskRunner should be stopped + // and taskRunner not allowed to be restarted alone + if (future.isFailed()) { + taskRunner.changeUpdatedInfo(UpdatedInfo.INERROR); + taskRunner.forceSaveStatus(); } + } } + } - @Override - public void finalizeRequest() { - if (foundEOF) { - return; - } - super.finalizeRequest(); + @Override + public void finalizeRequest() { + if (foundEOF) { + return; } + super.finalizeRequest(); + } + + @Override + public void transferInError(OpenR66Exception e) { + super.transferInError(e); + } + + public static class TestRecvThroughForwardHandler extends RecvThroughHandler { + + protected TestSendThroughForward client; @Override - public void transferInError(OpenR66Exception e) { - super.transferInError(e); + public void writeByteBuf(ByteBuf buffer) + throws OpenR66ProtocolBusinessException { + DataBlock block = new DataBlock(); + if (buffer.readableBytes() <= 0) { + // last block + block.setEOF(true); + } else { + block.setBlock(buffer); + } + try { + client.writeWhenPossible(block) + .await(Configuration.configuration.getTIMEOUTCON()); + } catch (OpenR66RunnerErrorException e) { + client.transferInError(e); + } catch (OpenR66ProtocolPacketException e) { + client.transferInError(e); + } catch (OpenR66ProtocolSystemException e) { + client.transferInError(e); + } catch (InterruptedException e) { + client.transferInError(new OpenR66ProtocolSystemException(e)); + } + if (block.isEOF()) { + client.finalizeRequest(); + client.foundEOF = true; + } } + } + } diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestSubmitTransfer.java b/src/test/java/org/waarp/openr66/protocol/test/TestSubmitTransfer.java index 5c01ad105..bbccf584f 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestSubmitTransfer.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestSubmitTransfer.java @@ -1,110 +1,119 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Waarp . If not, see - * . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.test; -import java.sql.Timestamp; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; import org.waarp.openr66.client.SubmitTransfer; import org.waarp.openr66.database.DbConstant; import org.waarp.openr66.protocol.utils.R66Future; +import java.sql.Timestamp; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + /** * Test class for multiple SubmitTransfer - * + * * @author Frederic Bregier - * */ public class TestSubmitTransfer extends SubmitTransfer { - static int nb = 100; + static int nb = 100; - /** - * @param args - * @param rank - * @return True if OK - */ - protected static boolean getSpecialParams(String[] args, int rank) { - for (int i = rank; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-nb")) { - i++; - nb = Integer.parseInt(args[i]); - } else if (args[i].equalsIgnoreCase("-md5")) { - } else if (args[i].charAt(0) == '-') { - i++;// jump one - } - } - return true; - } + public TestSubmitTransfer(R66Future future, String remoteHost, + String filename, String rulename, String fileinfo, + boolean isMD5, int blocksize, + Timestamp starttime) { + super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, + DbConstant.ILLEGALVALUE, starttime); + } - public TestSubmitTransfer(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, - Timestamp starttime) { - super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, - DbConstant.ILLEGALVALUE, starttime); + public static void main(String[] args) { + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(SubmitTransfer.class); } + if (!getParams(args, true)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isActive()) { + DbConstant.admin.close(); + } + DetectionUtils.SystemExit(1); + return; + } + getSpecialParams(args, 1); - public static void main(String[] args) { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpLoggerFactory.getLogger(SubmitTransfer.class); - } - if (!getParams(args, true)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isActive()) { - DbConstant.admin.close(); - } - System.exit(1); - } - getSpecialParams(args, 1); + ExecutorService executorService = Executors.newCachedThreadPool(); + R66Future[] arrayFuture = new R66Future[nb]; - ExecutorService executorService = Executors.newCachedThreadPool(); - R66Future[] arrayFuture = new R66Future[nb]; + logger.warn("Start Test Submit"); + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + Timestamp newstart = ttimestart; + if (newstart != null) { + // delay of 10 ms between each + newstart = new Timestamp(newstart.getTime() + i * 10); + } + TestSubmitTransfer transaction = new TestSubmitTransfer(arrayFuture[i], + rhost, + localFilename, + rule, fileInfo, + ismd5, block, + newstart); + transaction.normalInfoAsWarn = snormalInfoAsWarn; + // executorService.execute(transaction); + transaction.run(); + } + int success = 0; + int error = 0; + for (int i = 0; i < nb; i++) { + arrayFuture[i].awaitUninterruptibly(); + if (arrayFuture[i].isSuccess()) { + success++; + } else { + error++; + } + } + executorService.shutdown(); + logger.warn("Prepare transfer Success: " + success + " Error: " + error); + } - logger.warn("Start Test Submit"); - for (int i = 0; i < nb; i++) { - arrayFuture[i] = new R66Future(true); - Timestamp newstart = ttimestart; - if (newstart != null) { - // delay of 10 ms between each - newstart = new Timestamp(newstart.getTime() + i * 10); - } - TestSubmitTransfer transaction = new TestSubmitTransfer(arrayFuture[i], - rhost, localFilename, rule, fileInfo, ismd5, block, newstart); - transaction.normalInfoAsWarn = snormalInfoAsWarn; - // executorService.execute(transaction); - transaction.run(); - } - int success = 0; - int error = 0; - for (int i = 0; i < nb; i++) { - arrayFuture[i].awaitUninterruptibly(); - if (arrayFuture[i].isSuccess()) { - success++; - } else { - error++; - } - } - executorService.shutdown(); - logger.warn("Prepare transfer Success: " + success + " Error: " + error); + /** + * @param args + * @param rank + * + * @return True if OK + */ + protected static boolean getSpecialParams(String[] args, int rank) { + for (int i = rank; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-nb")) { + i++; + nb = Integer.parseInt(args[i]); + } else if (args[i].equalsIgnoreCase("-md5")) { + } else if (args[i].charAt(0) == '-') { + i++;// jump one + } } + return true; + } } diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestTasks.java b/src/test/java/org/waarp/openr66/protocol/test/TestTasks.java index e75685941..03efe8843 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestTasks.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestTasks.java @@ -1,27 +1,25 @@ -/** - This file is part of Waarp Project. - - Copyright 2009, Frederic Bregier, and individual contributors by the @author - tags. See the COPYRIGHT.txt in the distribution for a full listing of - individual contributors. - - All Waarp Project is free software: you can redistribute it and/or - modify it under the terms of the GNU General Public License as published - by the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - Waarp is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with Waarp . If not, see . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.test; -import java.io.File; - +import org.waarp.common.command.exception.CommandAbstractException; import org.waarp.common.database.DbAdmin; import org.waarp.common.database.exception.WaarpDatabaseException; import org.waarp.common.logging.WaarpLoggerFactory; @@ -29,17 +27,24 @@ import org.waarp.openr66.configuration.FileBasedConfiguration; import org.waarp.openr66.context.ErrorCode; import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.task.ChModTask; import org.waarp.openr66.context.task.CopyRenameTask; import org.waarp.openr66.context.task.CopyTask; import org.waarp.openr66.context.task.DeleteTask; +import org.waarp.openr66.context.task.ExecOutputTask; import org.waarp.openr66.context.task.ExecTask; +import org.waarp.openr66.context.task.FileCheckTask; import org.waarp.openr66.context.task.LogTask; import org.waarp.openr66.context.task.MoveRenameTask; import org.waarp.openr66.context.task.MoveTask; +import org.waarp.openr66.context.task.RenameTask; +import org.waarp.openr66.context.task.SnmpTask; import org.waarp.openr66.context.task.TarTask; import org.waarp.openr66.context.task.TranscodeTask; +import org.waarp.openr66.context.task.UnzeroedFileTask; import org.waarp.openr66.context.task.ValidFilePathTask; import org.waarp.openr66.context.task.ZipTask; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; import org.waarp.openr66.database.DbConstant; import org.waarp.openr66.database.data.DbRule; import org.waarp.openr66.database.data.DbTaskRunner; @@ -48,53 +53,114 @@ import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; import org.waarp.openr66.protocol.localhandler.packet.RequestPacket.TRANSFERMODE; +import java.io.File; + +import static org.junit.Assert.*; + /** * The object of this class is to test various tasks. - * - * @author "Frederic Bregier" * + * @author "Frederic Bregier" */ public class TestTasks { - /** - * @param args - */ - public static void main(String[] args) { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (args.length < 4) { - System.err.println("Need config inDirectory outDirectory filename (in inDirectory)"); - return; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - System.err.println("Needs a correct configuration file as first argument"); - return; - } - String in = args[1]; - String out = args[2]; - String filename = args[3]; - File file = new File(in + "/" + filename); - File out2 = new File(out + "/move"); - out2.mkdirs(); - long size = file.length(); - String argRule = out + "/#DATE#_%s_%s_" + filename; - String argTransfer = "basic information"; - R66Session session = new R66Session(); - DbRule rule = new DbRule("idRule", (String) null, TRANSFERMODE.SENDMODE.ordinal(), out, null, null, in, - null, null, null, null, null, null); - RequestPacket requestPacket = new RequestPacket(rule.getIdRule(), rule.getMode(), filename, - Configuration.BUFFERSIZEDEFAULT, (int) size / Configuration.BUFFERSIZEDEFAULT + 1, - 1, argTransfer, size, PartnerConfiguration.BAR_SEPARATOR_FIELD); - DbTaskRunner runner = null; - DbConstant.admin = new DbAdmin(); - session.getAuth().specialNoSessionAuth(false, "false"); - try { - runner = new DbTaskRunner(session, rule, false, requestPacket); - } catch (WaarpDatabaseException e) { - } - runner.setPostTask(); - session.setBadRunner(runner, ErrorCode.QueryAlreadyFinished); + /** + * @param args + */ + public static void main(String[] args) { + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (args.length < 4) { + System.err.println( + "Need config inDirectory outDirectory filename (in inDirectory)"); + return; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + System.err + .println("Needs a correct configuration file as first argument"); + return; + } + String in = args[1]; + String out = args[2]; + String filename = args[3]; + File file = new File(in + "/" + filename); + File out2 = new File(out + "/move"); + out2.mkdirs(); + long size = file.length(); + String argRule = out + "/#DATE#_%s_%s_" + filename; + String argTransfer = "basic information"; + R66Session session = new R66Session(); + DbRule rule = + new DbRule("idRule", (String) null, TRANSFERMODE.SENDMODE.ordinal(), + out, null, null, in, + null, null, null, null, null, null); + RequestPacket requestPacket = + new RequestPacket(rule.getIdRule(), rule.getMode(), filename, + Configuration.BUFFERSIZEDEFAULT, + (int) size / Configuration.BUFFERSIZEDEFAULT + 1, + 1, argTransfer, size, + PartnerConfiguration.BAR_SEPARATOR_FIELD); + DbTaskRunner runner = null; + DbConstant.admin = new DbAdmin(); + session.getAuth().specialNoSessionAuth(false, "false"); + try { + runner = new DbTaskRunner(session, rule, false, requestPacket); + } catch (WaarpDatabaseException e) { + } + runner.setPostTask(); + session.setBadRunner(runner, ErrorCode.QueryAlreadyFinished); + + // FILECHECK + FileCheckTask fileCheckTask = + new FileCheckTask("SIZE LT 10000 SIZE GT 5 DFCHECK", 1, + argTransfer, session); + fileCheckTask.run(); + try { + fileCheckTask.getFutureCompletion().await(); + } catch (InterruptedException e) { + } + System.out.println("FileCheckTask: " + + fileCheckTask.getFutureCompletion().isSuccess()); + assertEquals("FileCheckTask should be OK", true, + fileCheckTask.getFutureCompletion().isSuccess()); + + // UnzeroedFileTask + UnzeroedFileTask unzeroedFileTask = + new UnzeroedFileTask("", 0, argTransfer, session); + unzeroedFileTask.run(); + try { + unzeroedFileTask.getFutureCompletion().await(); + } catch (InterruptedException e) { + } + System.out.println("UnzeroedFileTask: " + + unzeroedFileTask.getFutureCompletion().isSuccess()); + assertEquals("UnzeroedFileTask should be OK", true, + unzeroedFileTask.getFutureCompletion().isSuccess()); + + // CHMOD + ChModTask chModTask = new ChModTask("u=rw", 1, argTransfer, session); + chModTask.run(); + try { + chModTask.getFutureCompletion().await(); + } catch (InterruptedException e) { + } + System.out.println( + "ChModTask: " + chModTask.getFutureCompletion().isSuccess()); + assertEquals("ChModTask should be OK", true, + chModTask.getFutureCompletion().isSuccess()); + + // SNMP + SnmpTask snmpTask = new SnmpTask(argRule, 0, argTransfer, session); + snmpTask.run(); + try { + snmpTask.getFutureCompletion().await(); + } catch (InterruptedException e) { + } + System.out.println( + "SnmpTask: " + snmpTask.getFutureCompletion().isSuccess()); + assertEquals("SnmpTask should be OK", true, + snmpTask.getFutureCompletion().isSuccess()); // LOG LogTask logTask = new LogTask(argRule, 1, argTransfer, session); @@ -104,22 +170,34 @@ public static void main(String[] args) { } catch (InterruptedException e) { } System.out.println("LOG: " + logTask.getFutureCompletion().isSuccess()); - logTask = new LogTask(argRule + " " + out + "/log.txt", 3, argTransfer, session); + assertEquals("LOG should be OK", true, + logTask.getFutureCompletion().isSuccess()); + // LOG + logTask = new LogTask(argRule + " " + out + "/log.txt", 3, argTransfer, + session); logTask.run(); try { logTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("LOG2: " + logTask.getFutureCompletion().isSuccess()); + System.out + .println("LOG2: " + logTask.getFutureCompletion().isSuccess()); + assertEquals("LOG2 should be OK", true, + logTask.getFutureCompletion().isSuccess()); // COPYRENAME - CopyRenameTask copyRenameTask = new CopyRenameTask(argRule + "_copyrename", 0, argTransfer, session); + CopyRenameTask copyRenameTask = + new CopyRenameTask(argRule + "_copyrename", 0, argTransfer, + session); copyRenameTask.run(); try { copyRenameTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("COPYRENAME: " + copyRenameTask.getFutureCompletion().isSuccess()); + System.out.println("COPYRENAME: " + + copyRenameTask.getFutureCompletion().isSuccess()); + assertEquals("COPYRENAME should be OK", true, + copyRenameTask.getFutureCompletion().isSuccess()); // COPY CopyTask copyTask = new CopyTask(out, 0, argTransfer, session); @@ -128,116 +206,213 @@ public static void main(String[] args) { copyTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("COPY: " + copyTask.getFutureCompletion().isSuccess()); + System.out + .println("COPY: " + copyTask.getFutureCompletion().isSuccess()); + assertEquals("COPY should be OK", true, + copyTask.getFutureCompletion().isSuccess()); // EXEC - ExecTask execTask = new ExecTask("ping 127.0.0.1", 10000, argTransfer, session); + ExecTask execTask = + new ExecTask("ping -c 1 127.0.0.1", 10000, argTransfer, + session); execTask.run(); try { execTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("EXEC: " + execTask.getFutureCompletion().isSuccess()); + System.out + .println("EXEC: " + execTask.getFutureCompletion().isSuccess()); + assertEquals("EXEC should be OK", true, + execTask.getFutureCompletion().isSuccess()); + + // EXECOUTPUT + ExecOutputTask execOutputTask = + new ExecOutputTask("ping -c 1 127.0.0.1", 10000, argTransfer, + session); + execOutputTask.run(); + try { + execOutputTask.getFutureCompletion().await(); + } catch (InterruptedException e) { + } + System.out.println("EXECOUTPUT: " + + execOutputTask.getFutureCompletion().isSuccess()); + assertEquals("EXECOUTPUT should be OK", true, + execOutputTask.getFutureCompletion().isSuccess()); // VALIDFILEPATH - ValidFilePathTask validFilePathTask = new ValidFilePathTask(in, 1, argTransfer, session); + ValidFilePathTask validFilePathTask = + new ValidFilePathTask(in, 1, argTransfer, session); validFilePathTask.run(); try { validFilePathTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("VALIDFILEPATH: " + validFilePathTask.getFutureCompletion().isSuccess()); + System.out.println("VALIDFILEPATH: " + + validFilePathTask.getFutureCompletion().isSuccess()); + assertEquals("VALIDFILEPATH should be OK", true, + validFilePathTask.getFutureCompletion().isSuccess()); // TAR - TarTask tarTask = new TarTask(out + "/test.tar " + out, 2, argTransfer, session); + TarTask tarTask = + new TarTask(out + "/test.tar " + out, 2, argTransfer, session); tarTask.run(); try { tarTask.getFutureCompletion().await(); } catch (InterruptedException e) { } System.out.println("TAR: " + tarTask.getFutureCompletion().isSuccess()); - tarTask = new TarTask(out + "/test.tar " + out + "/move", 1, argTransfer, session); + assertEquals("TAR should be OK", true, + tarTask.getFutureCompletion().isSuccess()); + + tarTask = + new TarTask(out + "/test.tar " + out + "/move", 1, argTransfer, + session); tarTask.run(); try { tarTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("UNTAR: " + tarTask.getFutureCompletion().isSuccess()); + System.out + .println("UNTAR: " + tarTask.getFutureCompletion().isSuccess()); + assertEquals("UNTAR should be OK", true, + tarTask.getFutureCompletion().isSuccess()); // ZIP - ZipTask zipTask = new ZipTask(out + "/test.zip " + out, 2, argTransfer, session); + ZipTask zipTask = + new ZipTask(out + "/test.zip " + out, 2, argTransfer, session); zipTask.run(); try { zipTask.getFutureCompletion().await(); } catch (InterruptedException e) { } System.out.println("ZIP: " + zipTask.getFutureCompletion().isSuccess()); - zipTask = new ZipTask(out + "/test.zip " + out + "/move", 1, argTransfer, session); + assertEquals("ZIP should be OK", true, + zipTask.getFutureCompletion().isSuccess()); + + zipTask = + new ZipTask(out + "/test.zip " + out + "/move", 1, argTransfer, + session); zipTask.run(); try { zipTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("UNZIP: " + zipTask.getFutureCompletion().isSuccess()); + System.out + .println("UNZIP: " + zipTask.getFutureCompletion().isSuccess()); + assertEquals("UNZIP should be OK", true, + zipTask.getFutureCompletion().isSuccess()); // TRANSCODE - TranscodeTask transcodeTask = new TranscodeTask("-from UTF8 -to ISO-8859-15", 0, argTransfer, session); + TranscodeTask transcodeTask = + new TranscodeTask("-from UTF8 -to ISO-8859-15", 0, argTransfer, + session); transcodeTask.run(); try { transcodeTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("TRANSCODE: " + transcodeTask.getFutureCompletion().isSuccess()); + System.out.println("TRANSCODE: " + + transcodeTask.getFutureCompletion().isSuccess()); + assertEquals("TRANSCODE should be OK", true, + transcodeTask.getFutureCompletion().isSuccess()); // MOVERENAME - MoveRenameTask moveReameTask = new MoveRenameTask(argRule + "_moverename", 0, argTransfer, session); + MoveRenameTask moveReameTask = + new MoveRenameTask(argRule + "_moverename", 0, argTransfer, + session); moveReameTask.run(); try { moveReameTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("MOVERENAME: " + moveReameTask.getFutureCompletion().isSuccess()); + System.out.println("MOVERENAME: " + + moveReameTask.getFutureCompletion().isSuccess()); + assertEquals("MOVERENAME should be OK", true, + moveReameTask.getFutureCompletion().isSuccess()); - copyRenameTask = new CopyRenameTask(in + "/" + filename, 0, argTransfer, session); + try { + session.setFileAfterPreRunner(false); + } catch (OpenR66RunnerErrorException e) { + e.printStackTrace(); + fail(e.getMessage()); + } catch (CommandAbstractException e) { + e.printStackTrace(); + fail(e.getMessage()); + } + copyRenameTask = new CopyRenameTask(in + "/" + filename, 0, argTransfer, + session); copyRenameTask.run(); try { copyRenameTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("COPYRENAME: " + copyRenameTask.getFutureCompletion().isSuccess()); + System.out.println("COPYRENAME: " + + copyRenameTask.getFutureCompletion().isSuccess()); + assertEquals("COPYRENAME should be OK", true, + copyRenameTask.getFutureCompletion().isSuccess()); // MOVE - MoveTask moveTask = new MoveTask(out + "/move", 0, argTransfer, session); + MoveTask moveTask = + new MoveTask(out + "/move", 0, argTransfer, session); moveTask.run(); try { moveTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("MOVE: " + moveTask.getFutureCompletion().isSuccess()); + System.out + .println("MOVE: " + moveTask.getFutureCompletion().isSuccess()); + assertEquals("MOVE should be OK", true, + moveTask.getFutureCompletion().isSuccess()); - zipTask = new ZipTask(out + "/testx.zip " + out, 2, argTransfer, session); + zipTask = + new ZipTask(out + "/testx.zip " + out, 2, argTransfer, session); zipTask.run(); try { zipTask.getFutureCompletion().await(); } catch (InterruptedException e) { } System.out.println("ZIP: " + zipTask.getFutureCompletion().isSuccess()); - zipTask = new ZipTask(out + "/testx.zip " + out + "/move", 1, argTransfer, session); + assertEquals("ZIP should be OK", true, + zipTask.getFutureCompletion().isSuccess()); + + zipTask = + new ZipTask(out + "/testx.zip " + out + "/move", 1, argTransfer, + session); zipTask.run(); try { zipTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("UNZIP: " + zipTask.getFutureCompletion().isSuccess()); + System.out + .println("UNZIP: " + zipTask.getFutureCompletion().isSuccess()); + assertEquals("UNZIP should be OK", true, + zipTask.getFutureCompletion().isSuccess()); + + // RENAME + RenameTask renameTask = + new RenameTask(out + "_rename2", 0, argTransfer, session); + renameTask.run(); + try { + renameTask.getFutureCompletion().await(); + } catch (InterruptedException e) { + } + System.out.println( + "RenameTask: " + renameTask.getFutureCompletion().isSuccess()); + assertEquals("RenameTask should be OK", true, + renameTask.getFutureCompletion().isSuccess()); // DELETE - DeleteTask deleteTask = new DeleteTask(out + "/move", 0, argTransfer, session); + DeleteTask deleteTask = + new DeleteTask(out + "/move", 0, argTransfer, session); deleteTask.run(); try { deleteTask.getFutureCompletion().await(); } catch (InterruptedException e) { } - System.out.println("DELETE: " + deleteTask.getFutureCompletion().isSuccess()); + System.out.println( + "DELETE: " + deleteTask.getFutureCompletion().isSuccess()); + assertEquals("DELETE should be OK", true, + deleteTask.getFutureCompletion().isSuccess()); } } diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestThriftClientExample.java b/src/test/java/org/waarp/openr66/protocol/test/TestThriftClientExample.java index d38012041..5a3a99e7c 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestThriftClientExample.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestThriftClientExample.java @@ -1,24 +1,24 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Waarp . If not, see - * . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.test; -import java.util.List; - import org.apache.thrift.TException; import org.apache.thrift.protocol.TBinaryProtocol; import org.apache.thrift.protocol.TProtocol; @@ -31,112 +31,117 @@ import org.waarp.thrift.r66.R66Service; import org.waarp.thrift.r66.RequestMode; +import java.util.List; + /** * Example of Java class to interact with the Thrift R66 service - * + * * @author "Frederic Bregier" - * */ public class TestThriftClientExample { - private static final int PORT = 4266; - private static final int tries = 10000; - - public static void main(String[] args) { - TTransport transport = null; - try { - transport = new TSocket("localhost", PORT); - TProtocol protocol = new TBinaryProtocol(transport); - R66Service.Client client = new R66Service.Client(protocol); - transport.open(); - R66Request request = new R66Request(RequestMode.INFOFILE); - request.setDestuid("hostas"); - request.setFromuid("tests"); - request.setRule("rule3"); - request.setAction(Action.List); - - System.out.println("REQUEST1: " + request.toString()); - List list = client.infoListQuery(request); - System.out.println("RESULT1: " + list.size()); - for (String slist : list) { - System.out.println(slist); - } - - long start = System.currentTimeMillis(); - for (int i = 0; i < tries; i++) { - list = client.infoListQuery(request); - } - long end = System.currentTimeMillis(); - System.out - .println("Delay: " + (end - start) + " : " + ((tries * 1000) / (end - start))); - - long startEx = System.currentTimeMillis(); - boolean dontknow = false; - for (int i = 0; i < tries; i++) { - dontknow = client.isStillRunning("tests", "hostas", 1346080633424L); - } - long endEx = System.currentTimeMillis(); - System.out.println("StillRunning: " + dontknow); - System.out - .println("Delay: " + (endEx - startEx) + " : " + ((tries * 1000) / (endEx - startEx))); - - request.setMode(RequestMode.INFOREQUEST); - request.setTid(1346080633424L); - request.setAction(Action.Detail); - R66Result result = client.infoTransferQuery(request); - System.out.println("RESULT2: " + result.toString()); - long startQu = System.currentTimeMillis(); - for (int i = 0; i < tries; i++) { - result = client.infoTransferQuery(request); - } - long endQu = System.currentTimeMillis(); - System.out - .println("Delay: " + (endQu - startQu) + " : " + ((tries * 1000) / (endQu - startQu))); - - System.out.println("Exist: " - + - client.isStillRunning(request.getFromuid(), request.getDestuid(), - request.getTid())); - - request.setMode(RequestMode.INFOFILE); - request.setAction(Action.Mlsx); - list = client.infoListQuery(request); - System.out.println("RESULT3: " + list.size()); - for (String slist : list) { - System.out.println(slist); - } - - request = new R66Request(RequestMode.ASYNCTRANSFER); - request.setDestuid("hostbs"); - request.setRule("rule3"); - request.setFile("Documents2.rar"); - request.setInfo("Submitted from Thrift"); - result = client.transferRequestQuery(request); - System.out.println("RESULT4: " + result); - - request = new R66Request(RequestMode.SYNCTRANSFER); - request.setDestuid("hostbs"); - request.setRule("rule3"); - request.setFile("Documents2.rar"); - request.setInfo("Submitted from Thrift"); - result = client.transferRequestQuery(request); - System.out.println("RESULT5: " + result); - - // Wrong request - request = new R66Request(RequestMode.INFOFILE); - - System.out.println("WRONG REQUEST: " + request.toString()); - list = client.infoListQuery(request); - System.out.println("RESULT of Wrong Request: " + list.size()); - for (String slist : list) { - System.out.println(slist); - } - - } catch (TTransportException e) { - e.printStackTrace(); - } catch (TException e) { - e.printStackTrace(); - } - transport.close(); + private static final int PORT = 4266; + private static final int tries = 10000; + + public static void main(String[] args) { + TTransport transport = null; + try { + transport = new TSocket("localhost", PORT); + TProtocol protocol = new TBinaryProtocol(transport); + R66Service.Client client = new R66Service.Client(protocol); + transport.open(); + R66Request request = new R66Request(RequestMode.INFOFILE); + request.setDestuid("hostas"); + request.setFromuid("tests"); + request.setRule("rule3"); + request.setAction(Action.List); + + System.out.println("REQUEST1: " + request.toString()); + List list = client.infoListQuery(request); + System.out.println("RESULT1: " + list.size()); + for (String slist : list) { + System.out.println(slist); + } + + long start = System.currentTimeMillis(); + for (int i = 0; i < tries; i++) { + list = client.infoListQuery(request); + } + long end = System.currentTimeMillis(); + System.out + .println("Delay: " + (end - start) + " : " + + ((tries * 1000) / (end - start))); + + long startEx = System.currentTimeMillis(); + boolean dontknow = false; + for (int i = 0; i < tries; i++) { + dontknow = client.isStillRunning("tests", "hostas", 1346080633424L); + } + long endEx = System.currentTimeMillis(); + System.out.println("StillRunning: " + dontknow); + System.out + .println("Delay: " + (endEx - startEx) + " : " + + ((tries * 1000) / (endEx - startEx))); + + request.setMode(RequestMode.INFOREQUEST); + request.setTid(1346080633424L); + request.setAction(Action.Detail); + R66Result result = client.infoTransferQuery(request); + System.out.println("RESULT2: " + result.toString()); + long startQu = System.currentTimeMillis(); + for (int i = 0; i < tries; i++) { + result = client.infoTransferQuery(request); + } + long endQu = System.currentTimeMillis(); + System.out + .println("Delay: " + (endQu - startQu) + " : " + + ((tries * 1000) / (endQu - startQu))); + + System.out.println("Exist: " + + + client.isStillRunning(request.getFromuid(), + request.getDestuid(), + request.getTid())); + + request.setMode(RequestMode.INFOFILE); + request.setAction(Action.Mlsx); + list = client.infoListQuery(request); + System.out.println("RESULT3: " + list.size()); + for (String slist : list) { + System.out.println(slist); + } + + request = new R66Request(RequestMode.ASYNCTRANSFER); + request.setDestuid("hostbs"); + request.setRule("rule3"); + request.setFile("Documents2.rar"); + request.setInfo("Submitted from Thrift"); + result = client.transferRequestQuery(request); + System.out.println("RESULT4: " + result); + + request = new R66Request(RequestMode.SYNCTRANSFER); + request.setDestuid("hostbs"); + request.setRule("rule3"); + request.setFile("Documents2.rar"); + request.setInfo("Submitted from Thrift"); + result = client.transferRequestQuery(request); + System.out.println("RESULT5: " + result); + + // Wrong request + request = new R66Request(RequestMode.INFOFILE); + + System.out.println("WRONG REQUEST: " + request.toString()); + list = client.infoListQuery(request); + System.out.println("RESULT of Wrong Request: " + list.size()); + for (String slist : list) { + System.out.println(slist); + } + + } catch (TTransportException e) { + e.printStackTrace(); + } catch (TException e) { + e.printStackTrace(); } + transport.close(); + } } diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java b/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java index 8452a96c5..4dde925c0 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java @@ -1,26 +1,24 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Waarp . If not, see - * . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.test; -import java.net.SocketAddress; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; @@ -35,117 +33,122 @@ import org.waarp.openr66.protocol.utils.ChannelUtils; import org.waarp.openr66.protocol.utils.R66Future; +import java.net.SocketAddress; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + /** * Test class for internal ping pong test - * + * * @author Frederic Bregier - * */ public class TestTransaction implements Runnable { - /** - * Internal Logger - */ - private static WaarpLogger logger; + /** + * Internal Logger + */ + private static WaarpLogger logger; - final private NetworkTransaction networkTransaction; + final private NetworkTransaction networkTransaction; - final private R66Future future; + final private R66Future future; - private final SocketAddress socketAddress; + private final SocketAddress socketAddress; - final private TestPacket testPacket; + final private TestPacket testPacket; - public TestTransaction(NetworkTransaction networkTransaction, - R66Future future, SocketAddress socketAddress, TestPacket packet) { - if (logger == null) { - logger = WaarpLoggerFactory.getLogger(TestTransaction.class); - } - this.networkTransaction = networkTransaction; - this.future = future; - this.socketAddress = socketAddress; - testPacket = packet; + public TestTransaction(NetworkTransaction networkTransaction, + R66Future future, SocketAddress socketAddress, + TestPacket packet) { + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(TestTransaction.class); } + this.networkTransaction = networkTransaction; + this.future = future; + this.socketAddress = socketAddress; + testPacket = packet; + } - public void run() { - LocalChannelReference localChannelReference = networkTransaction - .createConnectionWithRetry(socketAddress, false, future); - if (localChannelReference == null) { - logger.error("Cannot connect: ", future.getCause()); - future.setResult(null); - future.setFailure(future.getCause()); - return; - } - localChannelReference.sessionNewState(R66FiniteDualStates.TEST); - try { - ChannelUtils.writeAbstractLocalPacket(localChannelReference, testPacket, false); - } catch (OpenR66ProtocolPacketException e) { - future.setResult(null); - future.setFailure(e); - localChannelReference.getLocalChannel().close(); - return; - } + public static void main(String[] args) { + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(TestTransaction.class); } + if (args.length < 1) { + logger + .error("Needs at least the configuration file as first argument"); + return; + } + if (!FileBasedConfiguration + .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + logger + .error("Needs a correct configuration file as first argument"); + return; + } + DbHostAuth host = Configuration.configuration.getHOST_AUTH(); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger + .error("Needs a correct configuration file as first argument"); + return; + } + Configuration.configuration.pipelineInit(); - public static void main(String[] args) { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpLoggerFactory.getLogger(TestTransaction.class); - } - if (args.length < 1) { - logger - .error("Needs at least the configuration file as first argument"); - return; - } - if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { - logger - .error("Needs a correct configuration file as first argument"); - return; - } - DbHostAuth host = Configuration.configuration.getHOST_AUTH(); - final SocketAddress socketServerAddress; - try { - socketServerAddress = host.getSocketAddress(); - } catch (IllegalArgumentException e) { - logger - .error("Needs a correct configuration file as first argument"); - return; - } - Configuration.configuration.pipelineInit(); - - final NetworkTransaction networkTransaction = new NetworkTransaction(); - ExecutorService executorService = Executors.newCachedThreadPool(); - int nb = 100; - if (args.length > 1) { - nb = Integer.parseInt(args[1]); - } - R66Future[] arrayFuture = new R66Future[nb]; - logger.info("Start Test of Transaction"); - long time1 = System.currentTimeMillis(); - for (int i = 0; i < nb; i++) { - arrayFuture[i] = new R66Future(true); - TestPacket packet = new TestPacket("Test", "" + i, 0); - TestTransaction transaction = new TestTransaction( - networkTransaction, arrayFuture[i], socketServerAddress, - packet); - executorService.execute(transaction); - } - int success = 0; - int error = 0; - for (int i = 0; i < nb; i++) { - arrayFuture[i].awaitUninterruptibly(); - if (arrayFuture[i].isSuccess()) { - success++; - } else { - error++; - } - } - long time2 = System.currentTimeMillis(); - logger.warn("Success: " + success + " Error: " + error + " NB/s: " + + final NetworkTransaction networkTransaction = new NetworkTransaction(); + ExecutorService executorService = Executors.newCachedThreadPool(); + int nb = 100; + if (args.length > 1) { + nb = Integer.parseInt(args[1]); + } + R66Future[] arrayFuture = new R66Future[nb]; + logger.info("Start Test of Transaction"); + long time1 = System.currentTimeMillis(); + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + TestPacket packet = new TestPacket("Test", "" + i, 0); + TestTransaction transaction = new TestTransaction( + networkTransaction, arrayFuture[i], socketServerAddress, + packet); + executorService.execute(transaction); + } + int success = 0; + int error = 0; + for (int i = 0; i < nb; i++) { + arrayFuture[i].awaitForDoneOrInterruptible(); + if (arrayFuture[i].isSuccess()) { + success++; + } else { + error++; + } + } + long time2 = System.currentTimeMillis(); + logger.warn("Success: " + success + " Error: " + error + " NB/s: " + success * TestPacket.pingpong * 1000 / (time2 - time1)); - executorService.shutdown(); - networkTransaction.closeAll(); + executorService.shutdown(); + networkTransaction.closeAll(); + } + + public void run() { + LocalChannelReference localChannelReference = networkTransaction + .createConnectionWithRetry(socketAddress, false, future); + if (localChannelReference == null) { + logger.error("Cannot connect: ", future.getCause()); + future.setResult(null); + future.setFailure(future.getCause()); + return; + } + localChannelReference.sessionNewState(R66FiniteDualStates.TEST); + try { + ChannelUtils + .writeAbstractLocalPacket(localChannelReference, testPacket, false); + } catch (OpenR66ProtocolPacketException e) { + future.setResult(null); + future.setFailure(e); + localChannelReference.getLocalChannel().close(); + return; } + } } diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestTransferNoDb.java b/src/test/java/org/waarp/openr66/protocol/test/TestTransferNoDb.java index 736e6137a..9569a33a6 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestTransferNoDb.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestTransferNoDb.java @@ -1,28 +1,29 @@ -/** - * This file is part of Waarp Project. - * - * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the - * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of - * the GNU General Public License as published by the Free Software Foundation, either version 3 of - * the License, or (at your option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even - * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General - * Public License for more details. - * - * You should have received a copy of the GNU General Public License along with Waarp . If not, see - * . - */ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ package org.waarp.openr66.protocol.test; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - import org.waarp.common.command.exception.CommandAbstractException; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; +import org.waarp.common.utility.DetectionUtils; +import org.waarp.common.utility.UUID; import org.waarp.openr66.client.DirectTransfer; import org.waarp.openr66.context.ErrorCode; import org.waarp.openr66.context.R66Result; @@ -31,118 +32,168 @@ import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; import org.waarp.openr66.protocol.utils.R66Future; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + /** * Test class for multiple DirectTransfer - * + * * @author Frederic Bregier - * */ public class TestTransferNoDb extends DirectTransfer { static int nb = 100; + static int size = 1000; + static long bandwidth = 0; - /** - * @param args - * @param rank - * @return True if OK - */ - protected static boolean getSpecialParams(String[] args, int rank) { - for (int i = rank; i < args.length; i++) { - if (args[i].equalsIgnoreCase("-nb")) { - i++; - nb = Integer.parseInt(args[i]); - } else if (args[i].equalsIgnoreCase("-md5")) { - } else if (args[i].charAt(0) == '-') { - i++;// jump one - } + public TestTransferNoDb(R66Future future, String remoteHost, + String filename, String rulename, String fileinfo, + boolean isMD5, int blocksize, + long id, + NetworkTransaction networkTransaction) { + super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, + id, + networkTransaction); + } + + public static void main(String[] args) { + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + null)); + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(DirectTransfer.class); + } + if (!getParams(args, false)) { + logger.error("Wrong initialization"); + if (DbConstant.admin != null && DbConstant.admin.isActive()) { + DbConstant.admin.close(); + } + DetectionUtils.SystemExit(1); + return; + } + getSpecialParams(args, 1); + File file = new File(localFilename); + boolean exists = file.exists(); + if (!exists) { + localFilename = + file.getAbsolutePath() + UUID.jvmProcessId() + ".txt"; + file = new File(localFilename); + FileWriter fileWriterBig; + try { + fileWriterBig = new FileWriter(file); + for (int i = 0; i < size / 10; i++) { + fileWriterBig.write("0123456789"); } - return true; + fileWriterBig.flush(); + fileWriterBig.close(); + } catch (IOException e) { + logger.error(e); + return; + } } - - public TestTransferNoDb(R66Future future, String remoteHost, - String filename, String rulename, String fileinfo, boolean isMD5, int blocksize, - long id, - NetworkTransaction networkTransaction) { - super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, id, - networkTransaction); + if (bandwidth > 0) { + Configuration.configuration.setServerChannelReadLimit(bandwidth); + Configuration.configuration.setServerChannelWriteLimit(bandwidth); + Configuration.configuration.setServerGlobalReadLimit(bandwidth); + Configuration.configuration.setServerGlobalWriteLimit(bandwidth); } + Configuration.configuration.setCLIENT_THREAD(nb); + Configuration.configuration.pipelineInit(); + NetworkTransaction networkTransaction = new NetworkTransaction(); + try { + ExecutorService executorService = Executors.newCachedThreadPool(); - public static void main(String[] args) { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); - if (logger == null) { - logger = WaarpLoggerFactory.getLogger(DirectTransfer.class); + R66Future[] arrayFuture = new R66Future[nb]; + logger.info("Start of Test Transfer"); + long time1 = System.currentTimeMillis(); + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + TestTransferNoDb transaction = new TestTransferNoDb(arrayFuture[i], + rhost, + localFilename, rule, + fileInfo, ismd5, + block, + DbConstant.ILLEGALVALUE, + networkTransaction); + transaction.normalInfoAsWarn = snormalInfoAsWarn; + executorService.execute(transaction); + try { + Thread.sleep(10); + } catch (InterruptedException e) { } - if (!getParams(args, false)) { - logger.error("Wrong initialization"); - if (DbConstant.admin != null && DbConstant.admin.isActive()) { - DbConstant.admin.close(); - } - System.exit(1); + } + int success = 0; + int error = 0; + int warn = 0; + for (int i = 0; i < nb; i++) { + arrayFuture[i].awaitForDoneOrInterruptible(); + R66Result result = arrayFuture[i].getResult(); + if (arrayFuture[i].isSuccess()) { + if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { + warn++; + } else { + success++; + } + } else { + if (result.getRunner() != null && + result.getRunner().getErrorInfo() == ErrorCode.Warning) { + warn++; + } else { + error++; + } } - getSpecialParams(args, 1); - Configuration.configuration.setCLIENT_THREAD(nb); - Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - try { - ExecutorService executorService = Executors.newCachedThreadPool(); + } + long time2 = System.currentTimeMillis(); + long length = 0; + // Get the first result as testing only + R66Result result = arrayFuture[0].getResult(); + logger.warn("Final file: " + + (result.getFile() != null? result.getFile().toString() : + "no file")); + try { + length = result.getFile() != null? result.getFile().length() : 0L; + } catch (CommandAbstractException e) { + } + long delay = time2 - time1; + float nbs = success * 1000; + nbs /= delay; + float mbs = nbs * length / 1024; + logger.warn("Success: " + success + " Warning: " + warn + " Error: " + + error + " delay: " + delay + " NB/s: " + nbs + " KB/s: " + + mbs); + executorService.shutdown(); + if (!exists) { + file.delete(); + } + } finally { + networkTransaction.closeAll(); + } + } - R66Future[] arrayFuture = new R66Future[nb]; - logger.info("Start of Test Transfer"); - long time1 = System.currentTimeMillis(); - for (int i = 0; i < nb; i++) { - arrayFuture[i] = new R66Future(true); - TestTransferNoDb transaction = new TestTransferNoDb(arrayFuture[i], - rhost, localFilename, rule, fileInfo, ismd5, block, - DbConstant.ILLEGALVALUE, - networkTransaction); - transaction.normalInfoAsWarn = snormalInfoAsWarn; - executorService.execute(transaction); - try { - Thread.sleep(10); - } catch (InterruptedException e) { - } - } - int success = 0; - int error = 0; - int warn = 0; - for (int i = 0; i < nb; i++) { - arrayFuture[i].awaitUninterruptibly(); - R66Result result = arrayFuture[i].getResult(); - if (arrayFuture[i].isSuccess()) { - if (result.getRunner().getErrorInfo() == ErrorCode.Warning) { - warn++; - } else { - success++; - } - } else { - if (result.getRunner() != null && - result.getRunner().getErrorInfo() == ErrorCode.Warning) { - warn++; - } else { - error++; - } - } - } - long time2 = System.currentTimeMillis(); - long length = 0; - // Get the first result as testing only - R66Result result = arrayFuture[0].getResult(); - logger.warn("Final file: " + - (result.getFile() != null ? result.getFile().toString() : "no file")); - try { - length = result.getFile() != null ? result.getFile().length() : 0L; - } catch (CommandAbstractException e) { - } - long delay = time2 - time1; - float nbs = success * 1000; - nbs /= delay; - float mbs = nbs * length / 1024; - logger.warn("Success: " + success + " Warning: " + warn + " Error: " + - error + " delay: " + delay + " NB/s: " + nbs + " KB/s: " + mbs); - executorService.shutdown(); - } finally { - networkTransaction.closeAll(); - } + /** + * @param args + * @param rank + * + * @return True if OK + */ + protected static boolean getSpecialParams(String[] args, int rank) { + for (int i = rank; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-nb")) { + i++; + nb = Integer.parseInt(args[i]); + } else if (args[i].equalsIgnoreCase("-size")) { + i++; + size = Integer.parseInt(args[i]); + } else if (args[i].equalsIgnoreCase("-bandwidth")) { + i++; + bandwidth = Long.parseLong(args[i]); + } else if (args[i].equalsIgnoreCase("-md5")) { + } else if (args[i].charAt(0) == '-') { + i++;// jump one + } } + return true; + } } diff --git a/src/test/java/org/waarp/openr66/protocol/test/package-info.java b/src/test/java/org/waarp/openr66/protocol/test/package-info.java index 1f4b756a0..b0fe8510c 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/package-info.java +++ b/src/test/java/org/waarp/openr66/protocol/test/package-info.java @@ -1,6 +1,26 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + /** * Classes implementing Test only - * + * * @apiviz.exclude */ package org.waarp.openr66.protocol.test; diff --git a/src/test/resources/Linux/config/OPENR66-MIB b/src/test/resources/Linux/config/OPENR66-MIB new file mode 100755 index 000000000..77aac4082 --- /dev/null +++ b/src/test/resources/Linux/config/OPENR66-MIB @@ -0,0 +1,867 @@ +OPENR66-MIB DEFINITIONS ::= BEGIN + +IMPORTS + NOTIFICATION-GROUP, NOTIFICATION-TYPE, enterprises, OBJECT-TYPE, Counter32, Gauge32, Counter64, MODULE-IDENTITY, mib-2 + FROM SNMPv2-SMI + TimeStamp, TEXTUAL-CONVENTION + FROM SNMPv2-TC + SnmpAdminString + FROM SNMP-FRAMEWORK-MIB + system + FROM SNMPv2-MIB; + +openr66 MODULE-IDENTITY + LAST-UPDATED "201103050000Z" + ORGANIZATION "Waarp OpenR66" + CONTACT-INFO + " Frederic Bregier + + E-Mail: openr66@free.fr" + DESCRIPTION + "The MIB module describing OpenR66 Mib" + REVISION "201103050000Z" + DESCRIPTION + "This revision is the first setup of the OpenR66 MIB." +-- 1.3.6.1.4.1.66666.66.1.1 -- +::= { enterprises 66666 66 1 1 } + +-- root +waarp OBJECT IDENTIFIER ::= { enterprises 66666 } +r66 OBJECT IDENTIFIER ::= { waarp 66 } + +-- Textual conventions + +-- DistinguishedName is used to refer to objects in the +-- directory. + +DistinguishedName ::= TEXTUAL-CONVENTION + DISPLAY-HINT "255a" + STATUS current + DESCRIPTION + "A Distinguished Name represented in accordance with + RFC 2253, presented in the UTF-8 charset defined in + RFC 2279." + SYNTAX OCTET STRING (SIZE (0..255)) + +-- Uniform Resource Locators are stored in URLStrings. + +URLString ::= TEXTUAL-CONVENTION + DISPLAY-HINT "255a" + STATUS current + DESCRIPTION + "A Uniform Resource Locator represented in accordance + with RFCs 1738 and 2368, presented in the NVT ASCII + charset defined in RFC 854." + SYNTAX OCTET STRING (SIZE (0..255)) + + +-- The basic applEntry contains the different elements. + +applDefinitions OBJECT IDENTIFIER ::= { r66 1 } +applGlobalValues OBJECT IDENTIFIER ::= { r66 2 } +applDetailedValues OBJECT IDENTIFIER ::= { r66 3 } +applErrorValues OBJECT IDENTIFIER ::= { r66 4 } +waarptraps OBJECT IDENTIFIER ::= { r66 5 } + + +applName OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The name the network service application chooses to be + known by." + ::= {applDefinitions 1} + +applServerName OBJECT-TYPE + SYNTAX DistinguishedName + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The Server Name of this particular instance." + ::= {applDefinitions 2} + +applVersion OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The version of network service application software. + This field is usually defined by the vendor of the + network service application software." + ::= {applDefinitions 3} + +applDescription OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "A text description of the application. This information + is intended to identify and briefly describe the + application in a status display." + ::= {applDefinitions 4} + +applURL OBJECT-TYPE + SYNTAX URLString + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "A URL pointing to a description of the application. + This information is intended to identify and describe + the application in a status display." + ::= {applDefinitions 5} + +assocApplicationProtocol OBJECT-TYPE + SYNTAX OBJECT IDENTIFIER + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "An identification of the protocol being used for the + application. For an OSI Application, this will be the + Application Context. For Internet applications, OID + values of the form {applTCPProtoID port} or {applUDPProtoID + port} are used for TCP-based and UDP-based protocols, + respectively. In either case 'port' corresponds to the + primary port number being used by the protocol. The + usual IANA procedures may be used to register ports for + new protocols." + ::= {applDefinitions 6} + + +applUptime OBJECT-TYPE + SYNTAX TimeStamp + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The value of sysUpTime at the time the network service + application was last initialized. If the application was + last initialized prior to the last initialization of the + network management subsystem, then this object contains + a zero value." + ::= {applGlobalValues 1} + +applOperStatus OBJECT-TYPE + SYNTAX INTEGER { + up(1), + down(2), + halted(3), + congested(4), + restarting(5), + quiescing(6) + } + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Indicates the operational status of the network service + application. 'down' indicates that the network service is + not available. 'up' indicates that the network service + is operational and available. 'halted' indicates that the + service is operational but not available. 'congested' + indicates that the service is operational but no additional + inbound associations can be accommodated. 'restarting' + indicates that the service is currently unavailable but is + in the process of restarting and will be available soon. + 'quiescing' indicates that service is currently operational + but is in the process of shutting down. Additional inbound + associations may be rejected by applications in the + 'quiescing' state." + ::= {applGlobalValues 2} + +applLastChange OBJECT-TYPE + SYNTAX TimeStamp + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The value of sysUpTime at the time the network service + application entered its current operational state. If + the current state was entered prior to the last + initialization of the local network management subsystem, + then this object contains a zero value." + ::= {applGlobalValues 3} + +applInboundAssociations OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The number of current associations to the network service + application, where it is the responder. An inbound + association occurs when another application successfully + connects to this one." + ::= {applGlobalValues 4} + +applOutboundAssociations OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The number of current associations to the network service + application, where it is the initiator. An outbound + association occurs when this application successfully + connects to another one." + ::= {applGlobalValues 5} + +applAccumInboundAssociations OBJECT-TYPE + SYNTAX Counter32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The total number of associations to the application entity + since application initialization, where it was the responder." + ::= {applGlobalValues 6} + +applAccumOutboundAssociations OBJECT-TYPE + SYNTAX Counter32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The total number of associations to the application entity + since application initialization, where it was the initiator." + ::= {applGlobalValues 7} + +applLastInboundActivity OBJECT-TYPE + SYNTAX TimeStamp + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The value of sysUpTime at the time this application last + had an inbound association. If the last association + occurred prior to the last initialization of the network + subsystem, then this object contains a zero value." + ::= {applGlobalValues 8} + +applLastOutboundActivity OBJECT-TYPE + SYNTAX TimeStamp + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The value of sysUpTime at the time this application last + had an outbound association. If the last association + occurred prior to the last initialization of the network + subsystem, then this object contains a zero value." + ::= {applGlobalValues 9} + +applRejectedInboundAssociations OBJECT-TYPE + SYNTAX Counter32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The total number of inbound associations the application + entity has rejected, since application initialization. + Rejected associations are not counted in the accumulated + association totals. Note that this only counts + associations the application entity has rejected itself; + it does not count rejections that occur at lower layers + of the network. Thus, this counter may not reflect the + true number of failed inbound associations." + ::= {applGlobalValues 10} + +applFailedOutboundAssociations OBJECT-TYPE + SYNTAX Counter32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The total number associations where the application entity + is initiator and association establishment has failed, + since application initialization. Failed associations are + not counted in the accumulated association totals." + ::= {applGlobalValues 11} + + -- Bandwidth +applInboundBandwidthKBS OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The Inbound bandwidth usage in KB/s." + ::= {applGlobalValues 12} + +applOutboundBandwidthKBS OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "The Outbound bandwidth usage in KB/s." + ::= {applGlobalValues 13} + + -- Overall status including past, future and current transfers +nbInfoUnknown OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as Unknown." + ::= {applGlobalValues 14} + +nbInfoNotUpdated OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as NotUpdated." + ::= {applGlobalValues 15} + +nbInfoInterrupted OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as Interrupted." + ::= {applGlobalValues 16} + +nbInfoToSubmit OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as ToSubmit." + ::= {applGlobalValues 17} + +nbInfoError OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as Error." + ::= {applGlobalValues 18} + +nbInfoRunning OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as Running." + ::= {applGlobalValues 19} + +nbInfoDone OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count with Info as Done." + ::= {applGlobalValues 20} + + + -- Current situation of all transfers, running or not +nbStepAllTransfer OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in total, running or not." + ::= {applGlobalValues 21} + +memoryTotal OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Total Allocated Memory in KiloBytes." + ::= {applGlobalValues 22} + +memoryFree OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Total Free Memory in KiloBytes." + ::= {applGlobalValues 23} + +memoryUsed OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Total Used Memory in KiloBytes." + ::= {applGlobalValues 24} + +nbThreads OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Total number of active threads." + ::= {applGlobalValues 25} + +nbNetworkConnection OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Total number of active network connections." + ::= {applGlobalValues 26} + +-- detailed part + +nbStepNotask OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as NoTask." + ::= {applDetailedValues 1} + +nbStepPretask OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as PreTask." + ::= {applDetailedValues 2} + +nbStepTransfer OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as Transfer." + ::= {applDetailedValues 3} + +nbStepPosttask OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as PostTask." + ::= {applDetailedValues 4} + +nbStepAllDone OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as AllDone." + ::= {applDetailedValues 5} + +nbStepError OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Step is as Error." + ::= {applDetailedValues 6} + + + -- First on Running Transfers only +nbAllRunningStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count of all transfers currently in running." + ::= {applDetailedValues 7} + +nbRunningStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step Running." + ::= {applDetailedValues 8} + +nbInitOkStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step InitOk." + ::= {applDetailedValues 9} + +nbPreProcessingOkStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step PreProcessingOk." + ::= {applDetailedValues 10} + +nbTransferOkStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step TransferOk." + ::= {applDetailedValues 11} + +nbPostProcessingOkStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step PostProcessingOk." + ::= {applDetailedValues 12} + +nbCompleteOkStep OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count in Step CompleteOk." + ::= {applDetailedValues 13} + + + -- Error Status on all transfers +nbStatusConnectionImpossible OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is ConnectionImpossible." + ::= {applErrorValues 1} + +nbStatusServerOverloaded OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is ServerOverloaded." + ::= {applErrorValues 2} + +nbStatusBadAuthent OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is BadAuthent." + ::= {applErrorValues 3} + +nbStatusExternalOp OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is ExternalOp." + ::= {applErrorValues 4} + +nbStatusTransferError OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is TransferError." + ::= {applErrorValues 5} + +nbStatusMD5Error OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is MD5Error." + ::= {applErrorValues 6} + +nbStatusDisconnection OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Disconnection." + ::= {applErrorValues 7} + +nbStatusFinalOp OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is FinalOp." + ::= {applErrorValues 8} + +nbStatusUnimplemented OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Unimplemented." + ::= {applErrorValues 9} + +nbStatusInternal OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Internal." + ::= {applErrorValues 10} + +nbStatusWarning OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Warning." + ::= {applErrorValues 11} + +nbStatusQueryAlreadyFinished OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is QueryAlreadyFinished." + ::= {applErrorValues 12} + +nbStatusQueryStillRunning OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is QueryStillRunning." + ::= {applErrorValues 13} + +nbStatusNotKnownHost OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is NotKnownHost." + ::= {applErrorValues 14} + +nbStatusQueryRemotelyUnknown OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is QueryRemotelyUnknown." + ::= {applErrorValues 15} + +nbStatusCommandNotFound OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is CommandNotFound." + ::= {applErrorValues 16} + +nbStatusPassThroughMode OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is PassThroughMode." + ::= {applErrorValues 17} + +nbStatusRemoteShutdown OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is RemoteShutdown." + ::= {applErrorValues 18} + +nbStatusShutdown OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Shutdown." + ::= {applErrorValues 19} + +nbStatusRemoteError OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is RemoteError." + ::= {applErrorValues 20} + +nbStatusStopped OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Stopped." + ::= {applErrorValues 21} + +nbStatusCanceled OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Canceled." + ::= {applErrorValues 22} + +nbStatusFileNotFound OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is FileNotFound." + ::= {applErrorValues 23} + +nbStatusUnknown OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS read-only + STATUS current + DESCRIPTION + "Transfers count where Status is Unknown." + ::= {applErrorValues 24} + +-- test notification + +startOrShutdownObject OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Start Or Shutdown Extra Information." +::= { startOrShutdownWaarp 1 } + +startOrShutdownWaarp NOTIFICATION-TYPE + OBJECTS { startOrShutdownObject } + STATUS current + DESCRIPTION "Start or Shutdown SMIv2 notification" + ::= { waarpgroup 1 } + +errorObject OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Nature of Error." +::= { errorWaarp 1 } + +errorWaarp NOTIFICATION-TYPE + OBJECTS { errorObject } + STATUS current + DESCRIPTION "Error SMIv2 notification" + ::= { waarpgroup 2 } + +warningObject OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Nature of Warning." +::= { warningWaarp 1 } + +warningWaarp NOTIFICATION-TYPE + OBJECTS { warningObject } + STATUS current + DESCRIPTION "Warning SMIv2 notification" + ::= { waarpgroup 3 } + +overloadedObject OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Overloaded Server extra information." +::= { overloadedWaarp 1 } + +overloadedWaarp NOTIFICATION-TYPE + OBJECTS { overloadedObject } + STATUS current + DESCRIPTION "Overloaded SMIv2 notification" + ::= { waarpgroup 4 } + +globalStepInfo OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "GlobalStep rank." +::= { infoWaarp 1 } +stepInfo OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Step in GlobalStep." +::= { infoWaarp 2 } +rankFileInfo OBJECT-TYPE + SYNTAX Gauge32 + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "File Rank." +::= { infoWaarp 3 } +stepStatusInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Status of Step." +::= { infoWaarp 4 } +filenameInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Current Filename." +::= { infoWaarp 5 } +originalNameInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Original Filename." +::= { infoWaarp 6 } +idRuleInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "ID of Rule." +::= { infoWaarp 7 } +modeTransInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Mode of Transfer." +::= { infoWaarp 8 } +retrieveModeInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Retrieve Mode." +::= { infoWaarp 9 } +startTransInfo OBJECT-TYPE + SYNTAX TimeStamp + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Start Time of this transfer." +::= { infoWaarp 10 } +infoStatusInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Current Status." +::= { infoWaarp 11 } +requesterInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Requester Id for this transfer." +::= { infoWaarp 12 } +requestedInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Requested Id for this transfer." +::= { infoWaarp 13 } +specialIdInfo OBJECT-TYPE + SYNTAX SnmpAdminString + MAX-ACCESS accessible-for-notify + STATUS current + DESCRIPTION + "Unique Id for this Transfer." +::= { infoWaarp 14 } + +infoWaarp NOTIFICATION-TYPE + OBJECTS { globalStepInfo, stepInfo, rankFileInfo, stepStatusInfo, filenameInfo, + originalNameInfo, idRuleInfo, modeTransInfo, retrieveModeInfo, startTransInfo, + infoStatusInfo, requesterInfo, requestedInfo, specialIdInfo } + STATUS current + DESCRIPTION "Info SMIv2 notification" + ::= { waarpgroup 5 } + +waarpgroup NOTIFICATION-GROUP + NOTIFICATIONS { startOrShutdownWaarp,errorWaarp,warningWaarp,overloadedWaarp,infoWaarp } + STATUS current + DESCRIPTION "Group of Notification in Waarp" + ::= { waarptraps 1 } + +END diff --git a/src/test/resources/Linux/config/OpenR66-authent-A.xml b/src/test/resources/Linux/config/OpenR66-authent-A.xml new file mode 100755 index 000000000..a72facb0e --- /dev/null +++ b/src/test/resources/Linux/config/OpenR66-authent-A.xml @@ -0,0 +1,52 @@ + + + example for ServerA + + hosta +

127.0.0.1
+ 6666 + False + src/test/resources/Linux/config/certs/test-passwd.ggp + + + hostas +
127.0.0.1
+ 6667 + True + True + src/test/resources/Linux/config/certs/test-passwd.ggp +
+ + hostb +
127.0.0.1
+ 6676 + False + False + src/test/resources/Linux/config/certs/test-passwd2.ggp +
+ + hostbs +
127.0.0.1
+ 6677 + True + True + a5847a6ebb2eb5230554eb160326e7b1f53a193d9c6ee1b0 +
+ + test +
127.0.0.1
+ 6670 + False + True + src/test/resources/Linux/config/certs/test-passwd3.ggp +
+ + tests +
127.0.0.1
+ 6670 + True + True + True + src/test/resources/Linux/config/certs/test-passwd3.ggp +
+ diff --git a/src/test/resources/Linux/config/certs/client1.cer b/src/test/resources/Linux/config/certs/client1.cer new file mode 100755 index 0000000000000000000000000000000000000000..e9bafaf8fe3f435e83f69ae32d639c6227eab8bd GIT binary patch literal 937 zcmXqLVqR*{#MHZhnTe5!iN$Arw1NRI8>d#AN85K^Mn+av27??!ZUas>=1>+kVJ5dA zLp}o@5Ql?@HNY{*GZ@Bahw+6C1VQp#JY4SiIVq`m?ujL-hEPFnY=X?lf(CNpyoLq_ zmPTfVCdQUV7E$87M&Z9knwnm zCC>%(@LgV6M^?R(aBI?h=a{Ul6Y=bN8(Y^Lmq?=nUjI%wTraLa!jSlVDRZ!4miYER zayRe!Io{{ct?RA3wy@aJ!%^H>H}h+>cBK2?uMb&5h2B15VxRNRMCz%HtxKh0#*Wp; zMf`==>^mN9bV+qXtz=Zo+`yc|BLXK+=jJhf&E#BQrc>yDa%1@H$k|Hk*>1 dre@Prr#ov_ezK}ud-3YDQxc1p_^iKh1ptu7MwS2o literal 0 HcmV?d00001 diff --git a/src/test/resources/Linux/config/certs/client1.der b/src/test/resources/Linux/config/certs/client1.der new file mode 100755 index 0000000000000000000000000000000000000000..7229fd0bcbb6f753775599ee43df216edd91ceba GIT binary patch literal 1218 zcmV;z1U>sOf&{(-0RS)!1_>&LNQUrs4#*Aqyhl|0)hbn0N25j*P4Tl z7ZFZH+@<&aK3As#&jI_Za>STnRnc<+ixqE2aZ{5a!7xG9byD&;wT62--zRY7!2?)= z@W2vIEx~IUO-<+ub17NT@B^1{;$d0A*NHO7f48S;#D<#BqxTt@Gk&0GKI0XDeggIBP>|v*MsJ%K^H?UY4uwxSx5c#;RIC@?cxFloc=T#IV z2vn30;W@7p4hx@~7cS;qGh?;XayNEb(jT?0_#!qJvc?oNO)iA&-Al%RjufhR2tiT% zPO(1!Wt(ErqFPmon*1?5(c8O<~lf>dvEoF@&9y ze~v3iS2=GpU>9hd6IlOZrN3~y?Yr0v;WQia??=fXWyD)Ls%;M{lBte*a$9gl99x-) zXe>LTrbA#nipsWnR62Z263wAx#diXMfdJ`BUik_cAH>n3{fizg-r=x(QhAX2p)+)Z zo&iqwW0+}&F0ZRad#D+*O}UynN<8)#{=F!ewT(U+JDfMiE9&xIS}{5-X8Oo z3VHzKtV2S76o1FN;@y)2*WDs@w^9SHG3sAWq^g^t<%%~i3__T!JhsT!KB)y0mIQB9K?3vygClOBYkmZkQU`5`MTPVvW z+#hB;P?Ep(%?tirC-|Tag)uuyd3{PXGywvEfdHe?;?Y#&0jUpRI#egrBv38GkCNzE z=R6uRZ1R^cXIE6_g(xHTdxN;MNUiWK=D83~01!nOpK znR58BV;K8snF0Pk2;mkR{ThWcOtEj0WHJVQn{}>=S>*z*iO*ei!t;Oo%PCksy)QyY zBUu80fO_6IL;+TWj~!iF-pS|l{K6C&gpN_ak!sF?c4dO&fQCoNJBhz>2AA~CDjQYZ z7R=K1_~;C2fF`344h&%UVblrCui(Xm-EXabXu)jmnE0W|dxo0kHxW4qN!FIAt;sZ2 g8AT|IPj)gDuBAD*B9U-7{PmNvKV6REVn(6d#AN85K^Mn+av27??!ZUas>=1>+kVJ5dA zLp}o@5Ql?@HNY{*GZ@Bahw+6C1VQp#JY4SiIVq`m?ujL-hEPFnY=X?lf(CNpyoLq_ zmPTfVCME_3W>Mn2M&Z9--b1B zu(5ggf-~WnkK2C7X$$j}Bp>C>QW0I+SUT0=?9`Cm-D@|#k?Zvda18(OHEx#P6P{xA zhUuqV>-WC>lfqu{`UlVi=Ncd=1Qe3v$! z$lQ2!$^FTTPkcLgQmNANSNEBdCewHMuUJr;khtcOUQli6oA|wl4UfHNdBZ2bnDNr= z$HP?8MpUuzcKQ>G-*B5 zS6Kh?XW3en@H>ZhDgVFu=u!GI{al{VoSsw6^%)&UxU>*%7ek%te8) z9A|k;`z^NIC-~di)|eVyo^UNn+Tcmgy$=(2YRvflZgGXTyZz%|SHpzOLvK9%?_|20 z&HjCi1zS#Nkzt|Cbr6&(KWv%2 zoSQTI)+OcqGYUJsFZsl=74&8<{BfmurIKp1h1ax$Q(pbKqV`(MM6bRy_faGJfd`NJ e4)Pkwt(`JQ=*~%ftxVOX2EA9VGSgc8HUa?ra8DZm literal 0 HcmV?d00001 diff --git a/src/test/resources/Linux/config/certs/client2.der b/src/test/resources/Linux/config/certs/client2.der new file mode 100755 index 0000000000000000000000000000000000000000..57a2e8dc8491696796dc05b5e82f3f3e6ffcedd3 GIT binary patch literal 1219 zcmV;!1U&mNf&{+;0RS)!1_>&LNQUrsW5^Br2+u}0)hbn0Iow~3aO(N zgjIcar>WM}4PyAus~p2H$UdM8C{#4KaIF5#7?9!G()hjDYeu7jVT%%DDeYE+usl5B z=m}uvOh&&!mZ5JV8RBf3Bo(EBb(KKPl~lWnt+DJLjZ9EMSMc>-nl9uFb0>h8%0+*@ z?fhg1c;v@3eK1e_^t5OmTba5SPoD;Knn85MebHZu$3&^?9=4+qTb0hF91t10P$SGCPa^b>LYbNEl?3UEZ-m%=LUo?k4|R zj$0hV{_nP%kw%^~$93{RfR*OH=_R%^bA(`u{&LI#!X8{q-$XQb!@T}|Vw}2YA(|Hb zdz^Wgr%e1}v_XQ6liqy*RbFH{neLcGZ*A~QysWtQvIufn0V)9c$zC)|AN>IWfq?+y z(NQ}S%HPI(m7zve`d*21M2l=b1=SZe=CPQ0)M7Nu_c z2pfaLK$O`0rZl+6e_TP3;v%~(@-X!Rfq?+S(h*;%mT~|zq@wWdb0hE^T9bqa+>v4L z-IHMl(^9MaJs9%17N}R3y=r9jA&lhaQE5mf#=~l03;RumCJa3mKA!~cY4LoDpv@z8K-PeHXs-XJ>A&zeBkk&Pc2tK^j#vOo+c5KL z$0Xo{aZ>!U;Cc2ub;{8peP9j!FLN$JzJC=0fq?*kleUDh71z}IyZ@nMaE9<|Ew3KR zYO$*{?68o{s+?v4LA=-ExIN(o>4B=asz&i8soxJ-Ca|#W4|L$;$6#*eX(F!c%n94C z7tMXnhE+-jrfcBZBem>;Tbp)996!np5ER{Rox>rUQ?pc*G|LFZi>$SHh zs#?_cf3<$3*S)l-RdSM(eEX( z4XdYLk^7tUv%2TY_hLbfdUfGxqD?-=s#ES;aF?Xc%rn^1_VA|st_%0#edDF4eEzK3 z9VRUCI&`q9NKKagu~9v2xl?DS*&mt8=S>%zz5RI&&c?n zg@u`kX%BLc15+R{$Qc%uZ-i*p8tKq%A?e|ah?66WNNd<_WIJKByZhJr^9oLA9z+py8!@dFG?2x literal 0 HcmV?d00001 diff --git a/src/test/resources/Linux/config/certs/client3.der b/src/test/resources/Linux/config/certs/client3.der new file mode 100755 index 0000000000000000000000000000000000000000..37d96cf5b3870ca2216349a5d81cc9ff3b3ac50f GIT binary patch literal 1219 zcmV;!1U&mNf&{+;0RS)!1_>&LNQUrsW5^Br2+u}0)hbn0F%TmEwTpg z)%S8(i_bb*R`MW_=;kU>K0N^`#Ek{@uMmJKKm(PR6{v-q#4QSE2fmS5&A77c(ZRM9 z(EBNiR4YT%N&^Jkpwx{S5}J@MLe>))m`EU1=nW6S71CMiqQRQE+VE$9*`PJmA8yhI zU_v{I95f6rf3sJ-ioeZG{XZ{l7N6+0{2|ZBytpUxjH+ax#owZ@E4N`KIDL=xJK`>j zrHq9cl0q5!x~hk7=3Y4A9n1Ri5Jvs>T*$S5LM^3mTf<)L)#cJ`fUB3(9{pnZdyMq= za}g+iCli(xf=n|dl;1cDbY+=tFtmo@*&n*l-d{~$8M&kJv`q2xgKPaM2 zv)Zl5ABqs1t6Lk5AZ?SQ0;V(hMkyg!o~LnPI-#%^%!b_vu`9$^sYDW9dq$i*GD*$J zy1K*hLRx{t)-nJJ;7+huZCVq-FzLvMuG2Rs4te!L)+aGgf7yurltUn?=8p4PTWc9u z@$>SMC2k+gY_~%9X$F}MMR}H^?9vCpJYF7qUu>tFq4g**AXW*g_-=LKj5Hl}%u#&V zqx>SqivFs0(*GdqF}O=pPS3e{4#Cw@<^49KwU*}>uvOOUlU6D@lK+0Zwpjv!fdJA9 zPK-rcKOwIB8zB$OC%^ClM$nvj-qgGA=qTE{N&q3+kJRc*!uR9j*rnCd8bNv`PUX|# zeVZ{myyiO&MdT{zU_J!R(dth4zkPhayuhDMXbqqgGieIYJKU)H&edYhv~0*k=2au~ z>ty-zycK-nS{@W7$&h;u}Lq6yO<`*LpS0S~q zf!7d}Gd{We<{eSF-g1yqB&to$tMtz=ze0Qq%ZroC`GPYvfrrC2MOLI=1$%uf zC)_#z%=5lD<0ugt!@Z!+k2{wMRWi!1qO#-9S`EA5I*q>)yYrw5a~ub!cjM zi`19CcH)m8+7blzbwC*>Z&m%EW-lAy9#H~;fdH5fsk7xYXv#ytw2I%J1OW>eub%y9 zu+^`4Hb{k_`aINKyH`1Z9%FL7q?cE zWGQ>69GY5gn1K2NVVdfvi>_|=%Bl2RWVzaXqaa*2{@nF5Hp>1$cmQ>tNNK#pl3Uq# z>Wu<{fdIUA7eZb(NE@6yfA=waqol}0TG0vNx)^{zR$n^t3_%1|A`X?M*U$Ai0A;h` zftKUUG)j@WliDnWd~yIOHCzKp!jR5+iepWicgr$UaY*X5)7HkSnb-v|@~V}SgUm+o hy2!BHI#gLC_pot~x!tK}brGW#p5T=s_3gEoczkG!Sik@P literal 0 HcmV?d00001 diff --git a/src/test/resources/Linux/config/certs/key.sha256 b/src/test/resources/Linux/config/certs/key.sha256 new file mode 100755 index 000000000..9c18187a7 --- /dev/null +++ b/src/test/resources/Linux/config/certs/key.sha256 @@ -0,0 +1 @@ +-%€àg5ãŽÀªûæàªÅ \ No newline at end of file diff --git a/src/test/resources/Linux/config/certs/servercert.cer b/src/test/resources/Linux/config/certs/servercert.cer new file mode 100755 index 0000000000000000000000000000000000000000..36fd3667f9a5e327e319b0aa5bc089acb1005c55 GIT binary patch literal 937 zcmXqLVqR*{#MHZhnTe5!iN$B0P^AGc8>d#AN85K^Mn+av27??!ZUas>=1>+kVJ5dA zLp}o@5Ql?@HNY{*GZ@Bahw+6C1VQp#JY4SiIVq`m?ujL-hEPFnY=X?lf(CNpyoLq_ zmPV$AriSK*#!=$DM&cHe2<*l~b2<$HOGilQ%g^ zK0Wqc%i=ymDroh~s?LQ0b(8C7w`v@yN)vqFWjx1ib=C%DotM)^kAGhkHal96bA#B5 zEX}9q^_uf0x*O{2z4#HdnsLUj$G20ZLcO9HD}HwU?c&wa{PA{S_xZ|tt%Pp<^)4@2 zGB_%uC$tweheYss-Rqij{p{xYpOI_S-vn#Lf4Xe@VNb|3mq?Kw!>E;e(pWG< zw6DMY;Tn}Ym%e`&doHwBfhlO2#{b_lxMrH9JzU4-);nwknsOf&{(-0RS)!1_>&LNQUrs4#*Aqyhl|0)hbn0JI~6G{oH% zre>J00G2EaysJ+%$Fw(O7Vy@TK7>JK`B*&fl=M17T9Y=a_k{^93Ao{670KBMbn@d% ztprDy8d9t2dWoS>ev^Njg($#!W)bg-Gn_`NYOo_L>6aD9_o`N#TP_K(7N}||<*kcV=E zR9Fs5-in;p&9i^`S*$1QQz~Eb(>?IKRF*_p6pS%isl6WaU(zU`m=%tXhvBRw+|u{= z7UvSZAOcdRDF6GI3Yj!!;jRuy6r2oDFSuN`j^VT=u{kJx*Q|OsH39DNb2_ z=dX_)FULidz!a~5rGInBcOPpy`NTTO6A#R6io6#;L+l-Bw-43N!USEmAq82OP52B2 zmDPwEY>!67@1dE;ob5aB!Mf)@Ufvl`d3BOl?d^Gq7R6hnFtRzWdyrHx;J3jo%6(@$ zWkA+d2#qAzVr~#!`ZwE?!Af=J`&gCd@cAps4P0T3S|W$cW8#gWE6IdE5tHC(?XK@X zJYTK)X{(%C4fdJ)D z9Z){+f$~o8;^59V4Q5bNiG5!Uz8aQbf3q5&9?&N$XjXIAHLelZ*AhfTo{JA;yX22B z7s52c@*0qjPQAin9Aqv%x3TU94qY&eCms$yI39feAgdTNH6uqDbOF5T=|Y^$W5(wam$tT;_a5w@EvdZh?S68F|pU5SCmxkUnj zfK%@S3&1^sUgE98X>E~_0tOt-l4=}joawdThx!tX0KAnoBagch7U;=o&vDg!0)kuU zx;y^rb5}%@!A)>x?dBY7FYpZi6U~3Y`Z6xsl99X&W_)rL&k9=ogye6g$BEabdUaz} zg#=r!qcBQ8GTHR4 zam$VE;NSO)30Xw770-Jx9prYN|IrDu#8fPF5=2)bwrP*X$+(I6%IJ!$2DWkT-s2;w&l=QOGYOPTgH4oa gqCMwTGCUPAw4;8FI|KRV=G&h zGCvBHFk#YlZBZ0ix(u@1y7$&`e&=`Y@4rree9!mue!k~>&T~G`^E%J7ySTdu0)fDv zAEv+FEN(;}58q%U2m~k)E*TsGG21Dl;aCs|QVu6W%HU*hauEa!fWb_rg^qYQ7nDst z&M1z-1pv&12$vA%LcrlzBnE*(!QmJOVJ@T^TpfY50V^ z`jAMS9Rv5;>Ze=d(Yq0iDe(<_`fmq*lB;eSWqq$bZC^rf1h;M9>mzSc9}uo@vQkz* zoOY1nrq%WM)D4$Tq?h!pQ+uVtv0I7HdQsUe=68xh&bUx$%9fEK3(oDGh{sDz3*5Yb z_dI4}s^Z!sFa!VrCFXE5__5E6en^H11xG?z6`-Ft4hsbMR)N1&%-<^Lw~7VM{pDvK z0N7(uizU8=ao^x}|cS(}tMz1VZv&E)%c~LU*}`K!}riY*#GWo(=MzBI-$E zb?UV^dU)dEC}`x1v=Ij}_)OCH^0oVNIgAe_VJ3z;ueXLz38>k;oZ8bxw?cK6epZJP zZ2}Pi;&gqnkm~59NJ+146VK-*ED3sHW5-Yq#lh8A?o5lOez?cQ=)}6+=3qPbiYD#% z?C^aPnyC}iKiQ{vV<@IvN+w3#IE$L`ZhPpb_d+OTQpow~ODr9e(Lhfp}Idp>989#NUuvWB(QM;s0vmcc!xsvMLs-z7O(W@jK7v|3Rix)9HCJ zDZ+dNgRwHkuD0!Ma6j;=GO#Ph#bz)FNEGxl46sT+LWSdoLo8R-8{#4~CS?6*s1Q5y zatA*_iF!`d%xsQ52xdRH49WJNcCn|@uOfR$O}Blz;_~`S7@|3&hzMY}ijIA}tFzCE(Tc(>;`J&4o=a$%G~tPp2~o3g>MNet-X?R|RQ7g+OQE5axSnD^G%=G*5>RZCj%h!C`B?{vN&CrH z&e2JeigyAsX?pn!;<5}%1b0BXSf5c=^$175a%1vX^xKz)0Eu>^K@8nV1lOCoGuGu- z0iS*qmS;{4C`*yEt?Cl>!!{O+6Z^wS@@EoNYV_xsyjjB?)8YeTtnIjs#}f+ZefLP4_7vF#D|zSD z7h210)>-=Y2a*sDAXs=q-QyVX);bxxG(0?71k6D9V=ahJ*^}^`4vl3IWkKTrS1jLweuZ z>jv#u>Gy+oF=j;ZCVc4d@l2il2eRtl2Xb8Lzd$Z@%=|GRf4NyBkm#?Fzuc_9#2*ZD zdY6*YUFe5lMxb3{zlOu9)x&9XZ{$yEYXPvXWahOR-e}lyNM^R+oy+-MO6*=N53bqu zHQ!wrq&6NH_ykL|R?vH43}G588cG)B&r4I*9T5=8F*QD}0J zQIAYrJ2tJHSeA5I^t!I-R!c>^-y0|OsY6ep%B2kaU&G{2e=;7KUeO#OTWG zA&DK=&4{Ew7(sk;Bw2whL9(f;OvZ#dN3ch(FT6f(YE-giVBFcvSuEq@N0|hDA)oID zIhstk+sVf3JQ26&lAo&{`67BfUZP_55vpgKr|{6}+sk!#BN;12o1y)D-W1e&v+EHj z-}!MTDrU+UVs&PuY4q1H$ZAx@Z&@drCvUy)-G#s&xjiP>8GCoXdAl>i%qexXu3Bf> zZOm*%UGhV#nyg14E*5tzPlZX0XFMeJ1qKgdWg)jdd*1;hbEj@DZrHa6z4Vg5`@Vy3 z96BHz;Uk|JP8zQ(fMVNEJ{F~qf|pv3W(c+@!X$L*i4<*?0%(j(T1RQS@h`c9+XjM% zS3;lH)EfG`COx{atF@Q!tt!=KdqqY2EmDC8i$rTuwCH87t|m%8x}7(ICQn>+#Jda~ WDhIFSHsBUIBMRy#dN73N4SxdZTuX@n literal 0 HcmV?d00001 diff --git a/src/test/resources/Linux/config/certs/testclient.jks b/src/test/resources/Linux/config/certs/testclient.jks new file mode 100755 index 0000000000000000000000000000000000000000..3c536261bea9aec6d6ac9cb2def718e3f4801aa6 GIT binary patch literal 1003 zcmezO_TO6u1_mY|W(3omC8@@dEtfgnhpi-*fSKPM$M&poju)etJkjZKglSZl`kztE+v&oUWqRY}|tY?^}!?S0# zzsd0}<|$$yu1&FPaZLRgVe@{<7c1we$!4p*w{q%o?s%9adh#Ym$*0HOYgyc9NCmBa zS=G5Ppl)*g>{g8fRcV6nyNu_!tk)`?cyk2wOM0Z1d zy%#@%Rx{4{_4szGRH#=pW5v&|zg@gqnm^ty>^@&vua(fPzux5~O9n?}^n~`J=8y__)nK@KkNya<`OB=V;Hq^uiWSOOBxGii1zijKU|}7=hFA@ zV$X&4Dli2t)A;{;2G>lJw1?~XJVfU31nBRG+1B@Pi|R&8joRyLs?1H9m>C%u7yBFd z8dw7(T~?LF#K4G+Lz@klaM+m{;VdRNixtjdgR|HT_&}QZ85#exurM<*?LiK5UFSCwJv)myL1khrAL$ReA_Lom&|{0zyG^^lJ&JU^Hsjv&;PMe|LOkPUE2H3 z@cmEBXHxA*f3xIL)Uo!a>;6tXMts}NG}N^ox7$b8Z|zUowqmgeON*-NhecNp2+ej3 zc=9wgF4_0fpMKGtBoXZZcg9Ok$*;5e zkzO$Q*3*!@<8P&=um5%SNk%pUr}{^6Q;sED(tZ|b7dFgIY;4|al(FppafZLaF6Wv4 lnfd0(YM+%wt9TOA8rBC^a~efc1nkcGi{83k1OT~bRqp@* literal 0 HcmV?d00001 diff --git a/src/test/resources/Linux/config/certs/testclient1.jks b/src/test/resources/Linux/config/certs/testclient1.jks new file mode 100755 index 0000000000000000000000000000000000000000..926d3dc4e0fd8b82459cf206f0d78f617fe08f2c GIT binary patch literal 2291 zcmcgtS5TAd7R{dmp?3j6k#0hiKcN@F&=Qak1?i%qpfm|B3c{fT3@V^Tq(~8@BZvhM z6i~oWg-Zv)AWb4wDN^)kyqq)VI6mCx`>?G+$1?VNgNsdXBYnM%yj*gg^3cln1PB2XosTPVr*p2En8<3WQcWQHKj7g>-$~fjM|lJHR<`G15}p72gErPf9idLm}&-(ep<4xNNBMfp^a%UG4jkv^p@Je&xGowWN8Tmq+e24Ci2rzr| zO&Q*j(l%w0S?w{f_SKbC0jy}MU_uS|DN{|OOdn)~vz#9ID(pfjB}rD?jWZ0wxM+@1 zb41VHI7>RcglWYSvRZv98CFGjQCEYJ?!;L_{T10H;+DVBjG`_{elE`FiCbH{KVHws?ig8#jgD9{ z6}?gKYuDP{9F;gN<8UFe=&t+o+V7OX-staHc;9(5_2Av;gz&qh%*u*NC2bPshlhLD z5X~b^wZ2jQ8B%h~U=VP&gvJo5p=~m0Zay(%dWOUz_PvX}?U7!!*hycuycx1VWRdM< z*kpL?NfD*G$GIlh?#EZr57Y=*AP&zX`-pu<15SI@?@9#fhOPNmM-xwf{5hpUH zr<7V=5~?axj>?#+MltD=9g4hKn<~^?Wyf;bR)3r}6pjsh{Vsv#l7DA>zzr7{&tdpd z2YRS_r-xgj4t9zhMmeHG_cc45VSue6sqPkKE04U-l&Tqa^ie%le(oM{p;Vg%z7mh& zRVrJXY>1ThpSajoTWcyeV7}yn+R)Sa8XFEyVPofu-es_rZjVx|*zkOrRM;Q4R|blc zpvE0SD_MFL3lV7{-_l;FDxVybs@+@CcE(RAbU{ybIPs=TPG?c5kx5gmaRTJ)QwDg1 z#4X%(^O>#{eLTCq3Fe=VjOhEJ&+#ZB_*UVD^L58PLl$)g8uXWDrmqUvbygSF8Rih0 z=WcVxOTTXv-H#2jF?Rdh*xT#XT7ysW2{Mbfkt@$z35IfZwdqhc&e;@Xk)PTdW+D8K ziCq;}Ic|RZXaB1-k(r!O{U{N|sqVNVIHqdltPppW^TimRqk`#e5}j~eU5wsi{K2wv ze(il^t*yCl+Ypx3!VD{uCwTR;vfPVsgVnc4{)%!{9L}%#9*Rsyr;xXY4mbQ~Pl>JT zmy?%lQ%dB;Xbl5*)E3*eWwTz;C(scL$$HM`7Av_<1X|_OBHuvtt*+I-Pb0$VpcbeH zfxt>Z8mthcL6dS}Pyh;rTj#j$0|mHv&~zewOJL_ZA|Rk2mJj6Ng4x5l#Gn?oSV55g zFM{Mp9L3vO+WpJ9|K(z!$Y1Zg{JaE;pNFSE!9Bzi`;W-?zeL#YBDhyl01JY8IBl$^ zh8|AWMN$B#1L|V2|Iq*QG&DfrcRO~{0!9ObARrCkh0*{3GSZYhk`a4DQpCobRk+15 zax8}S0DqPRG1J}c`+|W42?`<5E?K?_#1Bzz*L17t;rbJ*0Uw%RPPCOqQJVuzzS1Pp z9B(knxo-uQ7BKDZ+%$3x*B(_myn7eedXd8~gYV2Lhh)Ll+B_31!E`-fB^YqkOUg+EPanMToc4`A$QUh zf#8M#zYz2nLi|EpzYzCMBJVT{0l-f<90rBf|8Dut58SaFfF$=tMqTjp;xPU531p#m z{)uBbiQh)N+w`?!w_IxrrVeOCdQ#NCH-@%$(;p%%-f01ORwb;J{gN%Fj7m9bfzP!ugVTquudiwqYU55JxM*9q3g0-Q&b2XKVo;OJLg|g-hVin= zxZ{P4Ivw+y%Q=p+5l>T0SmmW_`e6_IhEhAF@(ZjV^$uD>gi9kR=kzOnyWm$wE zb%RK=AiXLmgboQP50xrQlfYwlb{#*w&+o&XIp_T5&fGcoH}~ut(uz#FetQNj-wT=CH@VGrPt@vS?q)Vk9y7#_?Q5$mxz=k-8xXf4i-T*^ZUr zxf4O^l(8E$aM}e~>r%;+5{}{IjFa1+43=6mt=8AX6Lb<P@w~G33fS@om z3W-Qr9g=-3tLH8A$0UIvqIrHtpSd?ZbV+rXhh;}H!hCCWDM+PuPIJazWSi9~4+N=N z>#4+zkmdh<`QwbNQ1&g{(W(?4lB@FBkQ=a8 z-j82i{3MR_D`}apb&FXMHu7(Dpr&UYf3iOpnk_#)mS*eaF?p-VN;k*N?V;a-v&NRy z{8ZRl{^Oeum@ofWBVP2^I27TCTsIx{qlGxlWy_G;k8n4u85=883Beh5M&70zP#hwKT zb}d@gKz&n^Bfi5x`f-Afd>t-$u$A4syXwMK1A%9_e$>ZH8`=YT;8}|ag59qmzvwzn z=NVt~hvIHqZBwJOQRHJCaFI#>4*=V9h9!ODZHU1KuEvR@$8L5xTFj{P#uBz z-iImf&CS-7vu!Jc76{GUY;few75O57D|wL zRfYf8Nm5L({&R_oUy1xCt>oOwj8`2VMkVUxC?$+9jC$U6&d;+aPDe@7AEC+8MT8gW zwg2)B%9U|F0R8V z>&ohN(&wzYS1TAB=QX3)s0WX=%oet%Q8rt}cf9wH9`_=B=HZl>1!6u@(gIU3){Mkj z)zop5D|6DHT&xS$akXl;bWB@iN5H&Sa)xLMx-6T*h)voMU=E<6>{%!mdUmvBK2mpMNYO$zteO!LE?9* zDR&rZDNMX$_!MA^Ze<0r;8#mOD&5x~9ML7k70R(1)8XTlqw3`#SuT?=ev&X>jvkl3 zH>UJ7u>8E!T}zdL6B+3er8i&tp*=i~uPO-1o32Dcoq>s@i*O6m`Yrs&POkjVUrBZ^WE= zX{_3OpP1eDjO4V!|LvCWG|6mhs)Jam+pudF>WEKKjf4-ymQKkVDcMpHl%fTMlzeT?PB|?7|0hz;SECA@J zYhiIX0MK$ij8@kM@L25M^#42!9W4K|9S3m%rGo`Q03D2i(7|9(g^?SIQFtiEo)%in z7#>2qZM}Ue)dF;$%I8zI!_@_r?e!f=VUG=Ny%_N|DWqRc5Fwvfbcn9f*Ju9+dFhj- z$t#1bf&h7O4&~9YLq$>4%rkwNc8v+;)n8>2Er|w>D}T5?!p!ksJ05wzn-KA0an~IY zHrJs+18jEJYrJJ#9yT1d$%6+!G6-&?u@VYOjiI#DT!MR5MbFMuz*35JRF-zg~RNf^A=heH9P_doO5hu}f3iAW$#}TxbJW0eS~ZmsW(~ z0ChO;LA>(tAfVtM2=W8*{6O#@2yqa}2hD47#mxrss27?*jW;oyEnCxTCeG6&obQGM1!PMBbyxdhMR|>@P&zH42;1 z!#NiOSHzca#FLkp=*<=#axov$cWh80p!aC~*+ENJcwnMW!PbXphP+}l-Xg0xOk2rPPg KBSyj^7ye)Rk>@i2 literal 0 HcmV?d00001 diff --git a/src/test/resources/Linux/config/certs/testclient3.jks b/src/test/resources/Linux/config/certs/testclient3.jks new file mode 100755 index 0000000000000000000000000000000000000000..0591e38e2f6df184f7a111328dda8b5b1d1ad6e5 GIT binary patch literal 2292 zcmcgtc{J4f8=miMwy}jY*|#4?!(c{asbonql0;`m4TgPS#FB4xWYM4HHm zv6m&XX3H932v@?-z31LefBgRb{qdgjJkRI6=e*~6Kj(e+zV3Ymfk5Dc0{$*G7jI8D zqQCk9SHg!eCP5$=1Ve)EV|d`4N^k%Qpuqe900Tiu(8b(~iSftUsIPeTx3Lz}7t@oN z`63>%%9k-k4$hIO>JUd7&(xJd4ctq!^Oey)hhT%R0@A*JK8!v-s$JO1Imzj2n8efO z5TC$&Db1fz0?`QI_^y7%J5v3goXnY&0+PlNznEl704jgI|5E$38#9lqsj@_u-g{C@ zCin4&w+6XIogH~I#3F=LLIlYeL-)0RB0c<7MKF{W74pW?P}s_^cd8$;tT*V+D+@2l zmReX#K7WckO;RItZzq|FNw3|xs`p!7&&;=@aXb|B;K!M7MVC!kXx{G=von1*&Ye>h z-Nm*FrYK=U-szI{er5q^>Yd{bH9QPNf0J?|Vxf>j#%IR(MCOfqMIv4j;8;e}VY`{D z8Av{*6@5|a@7KA^%+`#=Z^C^dnHXW3l%TAY$ag}g7Rr>ka zO~uZ#+1c&_znT-apKAs6UMSOy>#>ZS>#yW116ns;FP6kg&kdD~-$eY#>4h9=KyG^|XfMj` zYP6?j9~MbwINlMqQtN*@FC{xP#LphYF5o^-#B`@n{hQ{esmacUb7c}lh zBYS+B8!Z1Y;*?sJEjMLqVcX){mpezS8m62=&<){VraOwpJ9bqTN4X81ZM>^!#Ds}dF^ivc(fU1jYVM{0xWN~U-yOdRyLE^xeBg%wqkQjvYR<}YbS$0jNw8Z$PAlrRC z3$)&C)(6|Ktakiyfn%J#2;4 zWRpyaagO|zwFC)AH&2@o@#z!QAt#}_h3mlOgU`JH7NZ&?OUpC9A^@y5xe zBz*$o-wG(d${#qfl>HwmO47nx?m&YZ&^lch*D{=SQ*k;zdcW|{3=J@1z6f!KWh01eUrMjcpPWvxC3zcly$z|ZtykqQqNc1?H)j$sRmU?VGmWl&aGnE zaN3}E=y$&m+0lOv&fLzz&WH&ICyPMvfAUulR|c9p@P4O=oP7`LLvN+mNiZX*a?4vP zb#-;944p}tk4^>fHH|A{=(CrL*wSBM&Aqzl2?RClyMj> z5C~F)Awdc-Byb`X0tUcf==of`Gz>SK0~K>NW{dmaJi zp^C+-s^M&fxz&ziG*wmqq5tP;NPzUOb{xb7gaq({FeHEzOacJV?@efQ1$?=G>!wXY z*9qIpYm&+HvnUHaT|luZ5w=mz7pZs(l9nM<82z9L&3TROO^VICnu?{KhHAm?9mRx8 zN@qTtgFr{AeTm3J*~!ZK9|ewNo|Uwk=jLq?>b>$MuOa)@@anb5Au6t4g4oOEsIMI_ zibW_#R9e^GtAA&z}+8X(Fa7|pLW*B8ddrCQ>fEcXXkiTvD@he2g z3#1E?&a2DaAJ^pacgrGTUc^ieNzl8;9LyXS zI(~dP^e70j7G6A(Zc;Pxbg^v@qR4b<#@n3pXqlbcorWQ#<7s6lr(8zOSeg>cuaC>S z-8>z2T02_>D#AN LGSx;z7%cr4LC4M} literal 0 HcmV?d00001 diff --git a/src/test/resources/Linux/config/certs/testsslclient.jks b/src/test/resources/Linux/config/certs/testsslclient.jks new file mode 100755 index 0000000000000000000000000000000000000000..461826fab2520c99936411a689487585fdcb3d36 GIT binary patch literal 609 zcmezO_TO6u1_mY|W(3ph$vK&+c_l_bzP4xm`CSaG5qhQumOv$n22D(|22G4@Oq>j> zR=wO`GG$h-0WTY;R+~rLcV0$DR#pasU_)*LPB!LH7B*ofw;)4410E2ELzp!nu_&|H zP{4o>#OD%bcZS#k6XC`XVTOws$cghB8W>m_85^1#nwgqMiSrtn8(0{aLbYW;3>rI`8XFnrfBuxZDxo$j^7`Mq*?$Ai1T48IZEC^(i_M4Q|Epu^^O%|@ zoZpduJ+S1lMMGhqyt0{Oqwq41zLgD~336J!ft`w56&77w`+1^l+PoLdDs~@iRyy&2 z&ziYD{n05+miJemHXW_2&)9!_iQoUKIc8>JwZUq8CKtURO59C0yDIx(lfP-=a00IK1!M{-~8Ui83(Y~@C(cR{c z3lsCi`$RPpKm3joG(SHI-W;dv$2V5D%)854uQKKYwyZ+bz9{L~!Yu8=+|WnsQJRU> zR~%33wJJ@TM%dy_I&)-j-FRpOO?z)N4Dk!H2EG=HL*E5!87JTpwUeP$ty9-J{T z(aP0ar*3q($;su;2P!9tOG~xn;?A|)eu|K2x(|KoigBOqTLbICg{h(2C^?1Jk%H-c zjv&_5u~G$1R7|kRpv7Tv=ItRXs>6of`~Z+Lhmz8_nY7AJdb_GtcK)8Dsp`uaJ4CVo z10ODdro1uG2`qwe!8u=rM5B+EhlxT~nfVXGOIeNF_t(rn;R1V}%jATq;q#fBGgl)hHt@xOmlo(JDhfx-l32!84lHWcS)^@OwMBdnBMe($ls+Eu$-2u zaEpu9Pb7T2g-ZvCMWBJ9l`x`wY5L&3B3X9}`F`ja8WolmV*o}JgRcmTNPHemHqbK-rdj&iwN;Q}+ia~-*= zXN<#O@6ME~Se4}Ewmf>;h0A1n`Z1RHVTJA1a!q0%zMQ?~Oyae(Oz}0T5y&{7_f_iE z{)G_jsl&6dXZtF_1fw#pju?}d?u{*J^a6&IwQHQzPFqbXZ{X1~P}zaXjOX=m8N0X_ znaRPscs#`Tb)4J2NQ_(k)6~sh%Q6EMFpZMQIdOlSEJZpGqG%{?vDJJSo>-NMbl$Cb?`p4~G%{&UF>E^)*f5v$zaWZ-v`C8DxZ z1@paZB#xWg2Hz(bVPf@LOq+D^BI%xe<7AA+3oDGz=X`loP$8YPnfm#0~a+SU1aKO$(5`K)YeJry$3^5^_SXzd~p8cLg&l#5% zCB9n2l^osacD>6=j^2*z%cHa|>&;`XC+D%mM%QbL@@J>sYr8kJOb?m11#z|-iIIE+ z*ZlDkEq^?OIrE*CbvY@2ZACb(`un)8e)G&E(abVYT34#fJ-@eLJVHdWVAeR~I+~g` z?!R-J>z#ip!!7DDddQX6qk{smk+G-D+;gkx+idqio?s+$Cpbe>-<-7Nr2l;!5q2s> zP!j@y{Q}Zp4?r3;wFm|UpisE!J)Uro9f`&z8YOP9A6!QS1oR_dKr|9|4vyr7lE?%O z5c?NFVG)*kWMk`p`JsO~FUbAZI~$hG@RFa0XMmw=uqWXk5%a%9*v}#;Cdf_zK}}U6 zfk@CGsM!m$t7?G93E)5U|2z#1kowt%?i`lCu^zF0MD>f3)%IM}XH~wxGDtP(p*=o2ULzrAS z6OmkO8I={CpCI2JLE&D!p;kbuq&|{Xnz_T@wNY_C-$4caNZ=t=VX{{xE+E5@fLEE` zBv%5A?XM%A!skpJfU8?Kc5krb6gKCJQ+mUraV{zNT7wz5H!9rWR??L?8#@k@&o>H& zdg`OME>y|QS>v3SKb%@>waGEKz;}~i|4WL6Vah(j>o2ZH`Uh#v^~106a@bfK+W-7^Oj~XX^w@@AR3oA9>x9K1j*DZ#ni|FF|GLUUQ}W_OFs?Ll&oR zs&X``%gf=uCh0gtH>A5YJ}lvb$IHqt-5+S@$=9=-nDlgVH(TCG=l65tQ?xV$hP7kV zmGo_CM@R;&Q2$5ozmHO@mL@t#S#)Q}74e!An_ic*h9_+Ty5@!N)Nc1oc>6-oa^D4s zs8S|n>#|~C%w5;mxO!FZvi&Z|uC+lgbWh#P??@9VbU^pEj%qG^Y+;~GdC~PycU@U{ KlU<&0*na`jHnw^I literal 0 HcmV?d00001 diff --git a/src/test/resources/Linux/config/config-clientA.xml b/src/test/resources/Linux/config/config-clientA.xml new file mode 100755 index 000000000..6a4b477b6 --- /dev/null +++ b/src/test/resources/Linux/config/config-clientA.xml @@ -0,0 +1,41 @@ + + + Example of config file: change its as your need. + + hosta + hostas + src/test/resources/Linux/config/certs/test-key.des + src/test/resources/Linux/config/OpenR66-authent-A.xml + + + + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + src/test/resources/Linux/config/certs/testcert.jks + testcert + False + + + /tmp/R66 + in + out + arch + work + conf + + + True + 4 + True + 10000 + 10000 + 4266 + + + h2 + jdbc:h2:/tmp/openr66;IFEXISTS=TRUE;MODE=PostgreSQL;AUTO_SERVER=TRUE + openr66 + openr66 + + diff --git a/src/test/resources/Linux/config/config-clientB.xml b/src/test/resources/Linux/config/config-clientB.xml new file mode 100755 index 000000000..abbaa91a4 --- /dev/null +++ b/src/test/resources/Linux/config/config-clientB.xml @@ -0,0 +1,40 @@ + + + Example of config file: change its as your need. + + hostb + hostbs + src/test/resources/Linux/config/certs/test-key.des + src/test/resources/Linux/config/OpenR66-authent-A.xml + + + + + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + src/test/resources/Linux/config/certs/testcert.jks + testcert + False + + + /tmp/R66 + in + out + arch + work + conf + + + True + 10000 + 10000 + 4266 + + + h2 + jdbc:h2:/tmp/openr66b;IFEXISTS=TRUE;MODE=PostgreSQL;AUTO_SERVER=TRUE + openr66 + openr66 + + diff --git a/src/test/resources/Linux/config/config-clientNoDB.xml b/src/test/resources/Linux/config/config-clientNoDB.xml new file mode 100755 index 000000000..03e81c8e0 --- /dev/null +++ b/src/test/resources/Linux/config/config-clientNoDB.xml @@ -0,0 +1,36 @@ + + + Example of config file: change its as your need. + + test + tests + src/test/resources/Linux/config/certs/test-key.des + src/test/resources/Linux/config/OpenR66-authent-A.xml + + + True + + + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + src/test/resources/Linux/config/certs/testcert.jks + testcert + False + + + /tmp/R66 + in + out + arch + work + conf + + + True + 4 + True + 10000 + 10000 + + diff --git a/src/test/resources/Linux/config/config-clientNoDB_B.xml b/src/test/resources/Linux/config/config-clientNoDB_B.xml new file mode 100755 index 000000000..eab9adf5d --- /dev/null +++ b/src/test/resources/Linux/config/config-clientNoDB_B.xml @@ -0,0 +1,38 @@ + + + Example of config file: change its as your need. + + hostb + hostbs + src/test/resources/Linux/config/certs/test-key.des + src/test/resources/Linux/config/OpenR66-authent-A.xml + + + True + + + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + src/test/resources/Linux/config/certs/testcert.jks + testcert + False + + + /tmp/R66 + in + out + arch + work + conf + + + True + 4 + True + 10000 + 10000 + 500 + 500 + + diff --git a/src/test/resources/Linux/config/config-clientSubmitA.xml b/src/test/resources/Linux/config/config-clientSubmitA.xml new file mode 100755 index 000000000..176a39de4 --- /dev/null +++ b/src/test/resources/Linux/config/config-clientSubmitA.xml @@ -0,0 +1,23 @@ + + + + hosta + hostas + src/test/resources/Linux/config/certs/test-key.des + + + /tmp/R66 + in + out + arch + work + conf + + + + h2 + jdbc:h2:/tmp/openr66;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE + openr66 + openr66 + + diff --git a/src/test/resources/Linux/config/config-clienttest-spooled-multiple.xml b/src/test/resources/Linux/config/config-clienttest-spooled-multiple.xml new file mode 100755 index 000000000..8a3c63333 --- /dev/null +++ b/src/test/resources/Linux/config/config-clienttest-spooled-multiple.xml @@ -0,0 +1,94 @@ + + + + test + tests + J:\GG\R66\certs\test-key.des + J:\GG\R66\conf\OpenR66-authent-A-2.xml + + + + + J:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + J:\GG\R66\certs\testcert.jks + testcert + False + + + J:/GG/R66 + in + out + arch + work + conf + + + 4 + True + 10000 + 10000 + 10 + 100 + 4000000000 + 0 + 0 + 10000 + 10000 + 5000 + 65536 + 30 + False + False + False + 1.0 + 0 + 0.75 + 0.0 + 0.05 + 1000 + 10000000 + True + + + hosta + hostas + + + J:\GG\R66\test\stopout.txt + False + + direct1 + hostas + rulespooledx + J:\GG\R66\test\statusoutdirect1.json + J:\GG\R66\test\out\example\a1 + .*\.?ar$ + True + 10000 + False + True + 1 + a1 + hostas + 5000 + + + direct2 + hostas + rulespooledx + J:\GG\R66\test\statusoutdirect2.json + J:\GG\R66\test\out\example\a2 + .*\.?ar$ + True + 10000 + False + True + 1 + a2 + hostas + 5000 + + + diff --git a/src/test/resources/Linux/config/config-clienttest.xml b/src/test/resources/Linux/config/config-clienttest.xml new file mode 100755 index 000000000..240e2577b --- /dev/null +++ b/src/test/resources/Linux/config/config-clienttest.xml @@ -0,0 +1,33 @@ + + + Example of config file: change its as your need. + + test + tests + src/test/resources/Linux/config/certs/test-key.des + src/test/resources/Linux/config/OpenR66-authent-A.xml + + + + + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + src/test/resources/Linux/config/certs/testcert.jks + testcert + False + + + /tmp/R66 + in + out + arch + work + conf + + + True + 4 + True + + diff --git a/src/test/resources/Linux/config/config-serverA-minimal.xml b/src/test/resources/Linux/config/config-serverA-minimal.xml new file mode 100755 index 000000000..b7e64d326 --- /dev/null +++ b/src/test/resources/Linux/config/config-serverA-minimal.xml @@ -0,0 +1,101 @@ + + + Example of config file: change its as your need. + + hosta + hostas + src/test/resources/Linux/config/certs/test-key.des + src/test/resources/Linux/config/OpenR66-authent-A.xml + + + monadmin + c5f4876737cf351a + True + True + src/test/resources/Linux/httpadmin + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + src/test/resources/Linux/config/snmpconfig.xml + + + 6666 + 6667 + 8066 + 8067 + + + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + src/test/resources/Linux/config/certs/testcert.jks + testcert + True + + + /tmp/R66 + in + out + arch + work + conf + + + True + 4 + True + 4266 + + 4000000000 + 8388608 + 67108864 + 1000 + 500 + 500 + 5000 + 30000 + 65536 + 30 + False + False + False + 0.9 + 0 + 0.5 + 0.9 + 0.25 + 1000 + 4096 + + + + h2 + jdbc:h2:/tmp/openr66;IFEXISTS=TRUE;MODE=PostgreSQL;AUTO_SERVER=TRUE + openr66 + openr66 + + + hosta + hostas + hostb + hostbs + + + + hosta + CONFIGADMIN|SYSTEM + + + hostb + CONFIGADMIN|SYSTEM + + + hostas + FULLADMIN + + + tests + FULLADMIN + + + diff --git a/src/test/resources/Linux/config/config-serverA.xml b/src/test/resources/Linux/config/config-serverA.xml new file mode 100755 index 000000000..d66c222b6 --- /dev/null +++ b/src/test/resources/Linux/config/config-serverA.xml @@ -0,0 +1,121 @@ + + + Example of config file: change its as your need. + + hosta + hostas + D:\GG\R66\certs\test-key.des + D:\GG\R66\conf\OpenR66-authent-A.xml + + + monadmin + c5f4876737cf351a + True + True + False + False + D:\GG\R66\httpadmin\i18n + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + False + False + 86400000 + 5000 + D:/GG/R66/conf/snmpconfig.xml + + + 6666 + 6667 + 8066 + 8067 + + + D:\GG\R66\certs\testsslnocert.jks + testsslnocert + testalias + D:\GG\R66\certs\testcert.jks + testcert + True + + + d:/GG/R66 + in + out + arch + work + conf + + + True + D:\NEWJARS\gglib\win32\MD5.dll + 10000 + 10000 + 8 + 80 + 4000000000 + 8388608 + 67108864 + 10000 + 10000 + 5000 + 65536 + 30 + False + False + False + 0.9 + 0 + 0.5 + 0.9 + 0.25 + 1000 + 4096 + + + h2 + jdbc:h2:D:/GG/R66/data/openr66;IFEXISTS=TRUE;MODE=Oracle;AUTO_SERVER=TRUE + openr66 + openr66 + + + 127.0.0.1 + 8068 + False + True + 10000 + True + D:/GG/R66/config/certs/key.sha256 + + ALL + CRUD + + + + 8069 + False + False + -1 + False + + DbHostAuth DbRule DbTaskRunner DbHostConfiguration DbConfiguration + R + + + Bandwidth + R + + + Information + R + + + Server + R + + + Control + R + + + diff --git a/src/test/resources/Linux/config/config-serverB.xml b/src/test/resources/Linux/config/config-serverB.xml new file mode 100755 index 000000000..0be236c7d --- /dev/null +++ b/src/test/resources/Linux/config/config-serverB.xml @@ -0,0 +1,79 @@ + + + Example of config file: change its as your need. + + hostb + hostbs + src/test/resources/Linux/config/certs/test-key.des + src/test/resources/Linux/config/OpenR66-authent-A.xml + + + monadmin + c5f4876737cf351a + True + False + False + False + src/test/resources/Linux/httpadmin + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + + + 6676 + 6677 + 8076 + 8077 + + + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + src/test/resources/Linux/config/certs/testcert.jks + testcert + True + + + /tmp/R66 + in + out + arch + work + conf + + + True + 4 + True + + + h2 + jdbc:h2:/tmp/openr66b;IFEXISTS=TRUE;MODE=PostgreSQL;AUTO_SERVER=TRUE + openr66 + openr66 + + + hosta + hostas + hostb + hostbs + + + + hosta + CONFIGADMIN|SYSTEM + + + hostb + CONFIGADMIN|SYSTEM + + + hostbs + FULLADMIN + + + tests + FULLADMIN + + + diff --git a/src/test/resources/Linux/config/config-serverInitA.xml b/src/test/resources/Linux/config/config-serverInitA.xml new file mode 100755 index 000000000..945acfcfc --- /dev/null +++ b/src/test/resources/Linux/config/config-serverInitA.xml @@ -0,0 +1,56 @@ + + + Example of config file: change its as your need. + + hosta + hostas + src/test/resources/Linux/config/certs/test-key.des + src/test/resources/Linux/config/OpenR66-authent-A.xml + + + True + True + True + False + monadmin + c5f4876737cf351a + src/test/resources/Linux/httpadmin/ + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + + + 6666 + 6667 + 8066 + 8067 + + + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + src/test/resources/Linux/config/certs/testcert.jks + testcert + True + + + /tmp/R66 + in + out + arch + work + conf + + + True + 10000 + 10000 + 4266 + + + h2 + jdbc:h2:/tmp/openr66;MODE=PostgreSQL;AUTO_SERVER=TRUE + openr66 + openr66 + + diff --git a/src/test/resources/Linux/config/config-serverInitB.xml b/src/test/resources/Linux/config/config-serverInitB.xml new file mode 100755 index 000000000..dd462614e --- /dev/null +++ b/src/test/resources/Linux/config/config-serverInitB.xml @@ -0,0 +1,58 @@ + + + Example of config file: change its as your need. + + hostb + hostbs + src/test/resources/Linux/config/certs/test-key.des + src/test/resources/Linux/config/OpenR66-authent-A.xml + + + True + True + True + False + monadmin + c5f4876737cf351a + src/test/resources/Linux/httpadmin/ + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + + + 6676 + 6677 + 8076 + 8077 + + + src/test/resources/Linux/config/certs/testsslnocert.jks + testsslnocert + testalias + src/test/resources/Linux/config/certs/testcert.jks + testcert + True + + + /tmp/R66 + in + out + arch + work + conf + + + True + 4 + True + 10000 + 10000 + 4266 + + + h2 + jdbc:h2:/tmp/openr66b;MODE=PostgreSQL;AUTO_SERVER=TRUE + openr66 + openr66 + + diff --git a/src/test/resources/Linux/config/dummyBootCounter.agent b/src/test/resources/Linux/config/dummyBootCounter.agent new file mode 100644 index 0000000000000000000000000000000000000000..c1b6f7e2c4f1563e4efb4c6db0064af8833c68c8 GIT binary patch literal 11983 zcmd5?4QvzF9X~rb315v#%z#izMxh&77dH+Bl727;LP-gQC27(wW7OCeV{mM9J{yP8 z5v^6nC~ZeUDr==dS(y+}M41W|RY$8*y02D3nyRf*8KZ1$OjX%hZHTR6|KB^`J?G`@ zICkRI(%*OY-n;kz`2FASy?b{@K9+1zMY=hx_-mq}-pIW5H6FhlQfmU?ns#|(Ob&Tv zY4zDBU%NVIkyWy^NMoXb&2l0lNm3=fMe$=WIvg#$iS za4dk?F~3rwk)}`RVsfzhsSB@WGMdaI95(`NYNpbR=>R1`d$B;;{EHwbkGOsGDn&}PhMw3w8W3PgsYFi^$BRTSpv?Nv(^ z59JQ(zBKI4$5X$zXq_w4Q~}PGkShCSrOvgqB!2XTalLP_ywp-ai!I%0f#T_=iV+79 zTi{7$707D@7xiW`$Xf||szy`~^2}V%oDtKb=W#upV0T(Oyd7Drba~u#wTtY^dO6ylZ6}F~#LI|% z5uIs(@?JB|4nAtnoMo19P>Q#rd_OA%kiRs}G;mW|hQex~r%$-QDDLtaw}{w_Zr?-- za&fzky9}rw5^TuVhthamif@QQiX%|?O{P%H)@*VMd1o0a8_+0DG7#NjBdmOwX(n(? zO1zQS+F*bqP-NVc;sPrZu>iS1X&s3fCVfWCxgorF?Ti~TIE38j6iX1y=&*x1kxbMF zYDzFQ4WeHlOeDKZf+2;W6e9_esD@9PP2B!sApz1_|76bA3&g-C#^-YGO-L-(+fRnw z8wMmIYi66q31ZS`qG)}QrPH)HN&n2$zHECGY#h%z6VWdxXOJ%aB=}X3VETlU#B}VZ zrxLC)lk6jzN`jEKlPn`~8<}EfdU&Q3wJ&pP1DX?WCMMA9ptUH1pU|PiuE9Edcxma! zm6nlGcT8Qk$`g%l3M;-roj9KP-IaICHp~fp_r8*UTzvX`SM?p$$2Co2h!B!oLxga3 zkTjDZR2^xD6d{nwq?qf4_3bSs`fy_$Cv&6@W*Ga zKELhADrP?<2#Zke@AeZcLqA{NbPQ*3LiGtyznVShGtwkoB9J@YUGq<|=z;?Oz zt?~P3wO!ph^W}9SmS-P)M><+sw(*{^ADvr%`tbv%SWTfA=Q^gcUmDp3+l*xpBl_&P zh|dWkFJMy2)dxHar1FBBu65R~rE{z`7pCQiu{7x1&F!_Wg}EdVrn=l|VoY{n6Cyv^ zusA~o@ow6^3~7YtK2iLVa~2efBDaOL6v>MKixAPTx#96Ir8Df)o<5MG)=(K z1g`-A4hdd^YvjPwpOvvj!juDuu^6Bu+dpG-Z?YV9mb^f0aAg5vgDWG5@BDo4b88yU z@2EOAdFRSG_1XpzXZ)#e-gfHLvO~Sr_jh+a`jWU9{x95TC&3~@=(??scoZHv=$xFhBtlHJR|A|n* z{guU8cV5QjmpSkC7~ues0eInt|P zaV9X0Mw!5L>~MYik;LwWC;wF$-FfZz?u&_gYPBr}o?rI8AC@L&TYl8EA$s@qLofez zU%>$!f?|`N=1#GL0W1*38kT1PWM+zWoSbK!ewXd=g66Foru;Vi^z`Mf&?~~ooZ4UZ z>!tn^zu5E0nFW_iK7VwY<;ZvJ<6nBz2wqejwc+KzxB{u z>4V4qJ?#><_ztm~#H}NJCnR+Zfwcs#?Ic(?2%9|SODlb!8(V!|5^V5bi*GFnw)wD| z&UeYht;(_S+PKTFgp<$uW*aZ!LL3TVS-}+ANEyNcF{T+~jUak7AznvsaOl-Jy@&R( z&}ZY69{TiqI-;JEc-`>gh6gFQF!UzHh^jIoMyjzdGH^d6Z&k=+c$NKQV%{pTM+%k0 zd#Wp#+JTd0LDUYW^bu8?nnIb^b_G*Aia}22ZGJ(fnZWW?&NBgfy40R|DDjhf<03I* zT!57I7g>HfS4i;A6f**52K+E~iVXhbFSNvc_6a?)V6aX0_&NjfCSm5Ah`KH%pvoqd zH=*)=_JY)?&4z?4$S@3QIDl;#{WYMOBVbX}sgBC=vwRU9#Kex3t&R}Tkx8N?c*Bir zHeV;NQRgGU52$71R5_ph(qLD?TcktK!JA~p5ovwhG_5ne$wC~kz`@LpqwsFbYW|r| zwmk~VrV?hJI9PNjdPqA42bM~ZHWGy0LxRwEk^mBvZ6aZv(~%D#@$D(!4&d)iHD1IR z(8@$>CQ%JGH$`i@s7y}^BnYf1j78<72`@xNi|(f~@k5Qif>||gJya}#2|nvO!&gUoL#^y>E=pTx;i75H2&n_w1a|W9C@aC}Sar|w= zUq5R@;iC_e6=}NJCy|TklWsYozWDV$hZps)ucps*>0595o)CqqbhG&J<4XSNwEq2L VigD1%R*=>mOf#=a1{Do<{tuesgx&xE literal 0 HcmV?d00001 diff --git a/src/test/resources/Linux/config/dummyConf.agent b/src/test/resources/Linux/config/dummyConf.agent new file mode 100644 index 0000000000000000000000000000000000000000..d6b38828cc9cf7ed302e62ca8e81a35f72e58c4c GIT binary patch literal 10 RcmZ4UmVvdLg@J*A5daby0viAT literal 0 HcmV?d00001 diff --git a/src/test/resources/Linux/config/limitConfiga.xml b/src/test/resources/Linux/config/limitConfiga.xml new file mode 100755 index 000000000..c449e44f2 --- /dev/null +++ b/src/test/resources/Linux/config/limitConfiga.xml @@ -0,0 +1,15 @@ + + + Example of config file: change its as your need. + + hosta + + + 0 + 0 + 10000 + 10000 + 5000 + 30000 + + diff --git a/src/test/resources/Linux/config/logback-client.xml b/src/test/resources/Linux/config/logback-client.xml new file mode 100755 index 000000000..bb336e662 --- /dev/null +++ b/src/test/resources/Linux/config/logback-client.xml @@ -0,0 +1,35 @@ + + + + /tmp/GG/R66/log/R66Client.log + true + + /tmp/GG/R66/log/R66Client.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + + diff --git a/src/test/resources/Linux/config/logback-clientDebug.xml b/src/test/resources/Linux/config/logback-clientDebug.xml new file mode 100755 index 000000000..89801150e --- /dev/null +++ b/src/test/resources/Linux/config/logback-clientDebug.xml @@ -0,0 +1,35 @@ + + + + /tmp/GG/R66/log/R66Client.log + true + + /tmp/GG/R66/log/R66Client.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + + diff --git a/src/test/resources/Linux/config/logback-service.xml b/src/test/resources/Linux/config/logback-service.xml new file mode 100755 index 000000000..ffbb26521 --- /dev/null +++ b/src/test/resources/Linux/config/logback-service.xml @@ -0,0 +1,34 @@ + + + + /tmp/GG/R66/log/R66Server.log + true + + /tmp/GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + diff --git a/src/test/resources/Linux/config/logback.xml b/src/test/resources/Linux/config/logback.xml new file mode 100755 index 000000000..ffbb26521 --- /dev/null +++ b/src/test/resources/Linux/config/logback.xml @@ -0,0 +1,34 @@ + + + + /tmp/GG/R66/log/R66Server.log + true + + /tmp/GG/R66/log/R66Server.%d{yyyy-MM-dd}.%i.log.zip + 30 + + 10MB + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + %date{dd/MM/yyyy/HH:mm:ss.SSS} %level [%logger] [%thread] %msg%n + + + + + + + + + diff --git a/src/test/resources/Linux/config/rulerecv-any.rule.xml b/src/test/resources/Linux/config/rulerecv-any.rule.xml new file mode 100755 index 000000000..99682b4e3 --- /dev/null +++ b/src/test/resources/Linux/config/rulerecv-any.rule.xml @@ -0,0 +1,86 @@ + + rule4 + 2 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + test + 0 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + mon info + 0 + 0 + + + + + + + LOG + test + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + \ No newline at end of file diff --git a/src/test/resources/Linux/config/rulerecv.rule.xml b/src/test/resources/Linux/config/rulerecv.rule.xml new file mode 100755 index 000000000..3346bc1c8 --- /dev/null +++ b/src/test/resources/Linux/config/rulerecv.rule.xml @@ -0,0 +1,70 @@ + + rule2 + + hosta + hostb + + 2 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + test + 0 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + \ No newline at end of file diff --git a/src/test/resources/Linux/config/rulerecvthrough-any.rule.xml b/src/test/resources/Linux/config/rulerecvthrough-any.rule.xml new file mode 100755 index 000000000..170f3c9f0 --- /dev/null +++ b/src/test/resources/Linux/config/rulerecvthrough-any.rule.xml @@ -0,0 +1,66 @@ + + rule6 + 6 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + petittest + 0 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + \ No newline at end of file diff --git a/src/test/resources/Linux/config/rulesend-any.rule.xml b/src/test/resources/Linux/config/rulesend-any.rule.xml new file mode 100755 index 000000000..5952a0977 --- /dev/null +++ b/src/test/resources/Linux/config/rulesend-any.rule.xml @@ -0,0 +1,66 @@ + + rule3 + 1 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + petittest + 0 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + \ No newline at end of file diff --git a/src/test/resources/Linux/config/rulesend.rule.xml b/src/test/resources/Linux/config/rulesend.rule.xml new file mode 100755 index 000000000..e40b9a0ae --- /dev/null +++ b/src/test/resources/Linux/config/rulesend.rule.xml @@ -0,0 +1,75 @@ + + rule1 + + hosta + hostb + + 1 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + petittest + 0 + 0 + + + RESCHEDULE + -case C,l -delay 1000 -count 5 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + \ No newline at end of file diff --git a/src/test/resources/Linux/config/rulesendthrough-any.rule.xml b/src/test/resources/Linux/config/rulesendthrough-any.rule.xml new file mode 100755 index 000000000..001a8c358 --- /dev/null +++ b/src/test/resources/Linux/config/rulesendthrough-any.rule.xml @@ -0,0 +1,66 @@ + + rule5 + 5 + + + + + + + + LOG + mon info + 0 + 0 + + + LOG + une autre info + 0 + 1 + + + + + + + LOG + petittest + 0 + 0 + + + EXECRENAME + D:/GG/R66/conf/montest.bat #TRUEFULLPATH# D:\GG\FTP\fredo\a\#TRANSFERID#_#ORIGINALFILENAME# #TRUEFILENAME# #ORIGINALFILENAME# #DATE# #HOUR# #REMOTEHOST# #LOCALHOST# #TRANSFERID# #RANKTRANSFER# #BLOCKSIZE# + 20000 + 0 + + + COPYRENAME + D:/GG/FTP/fredo/a/#DATE#_#HOUR#_#TRANSFERID#_#REMOTEHOST#_#LOCALHOST#_#ORIGINALFILENAME#_#TRUEFILENAME#_%s_%s + 0 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + + + + LOG + erreur + 1 + 0 + + + + \ No newline at end of file diff --git a/src/test/resources/Linux/config/snmpconfig.xml b/src/test/resources/Linux/config/snmpconfig.xml new file mode 100755 index 000000000..52c3d732a --- /dev/null +++ b/src/test/resources/Linux/config/snmpconfig.xml @@ -0,0 +1,99 @@ + + + + udp:0.0.0.0/2001 + tcp:0.0.0.0/2002 + 4 + False + True + 4 + + + + notificationV2c + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + True +
+ + notificationV3 + UdpIpv4 +
127.0.0.1/162
+ 200 + 1 + False +
+
+ + + SHADES + SHA + SHADESAuthPassword + PDES + SHADESPrivPassword + + + TEST + SHA + maplesyrup + PDES + maplesyrup + + + SHA + SHA + SHAAuthPassword + + + MD5DES + MD5 + MD5DESAuthPassword + PDES + MD5DESPrivPassword + + + SHAAES128 + SHA + SHAAES128AuthPassword + PAES128 + SHAAES128PrivPassword + + + SHAAES192 + SHA + SHAAES192AuthPassword + PAES192 + SHAAES192PrivPassword + + + SHAAES256 + SHA + SHAAES256AuthPassword + PAES256 + SHAAES256PrivPassword + + + MD5AES128 + MD5 + MD5AES128AuthPassword + PAES128 + MD5AES128PrivPassword + + + MD5AES192 + MD5 + MD5AES192AuthPassword + PAES192 + MD5AES192PrivPassword + + + MD5AES256 + MD5 + MD5AES256AuthPassword + PAES256 + MD5AES256PrivPassword + + +
diff --git a/src/test/resources/h2/clean.sql b/src/test/resources/h2/clean.sql new file mode 100644 index 000000000..98653292f --- /dev/null +++ b/src/test/resources/h2/clean.sql @@ -0,0 +1,8 @@ +DROP SEQUENCE runseq; +DROP TABLE runner; +DROP TABLE rules; +DROP TABLE multiplemonitor; +DROP TABLE hosts; +DROP TABLE hostconfig; +DROP TABLE configuration; + diff --git a/src/test/resources/h2/create.sql b/src/test/resources/h2/create.sql new file mode 100644 index 000000000..ecb9e1118 --- /dev/null +++ b/src/test/resources/h2/create.sql @@ -0,0 +1,130 @@ +-- +-- Name: configuration; Type: TABLE; Schema: public; +-- + +CREATE TABLE configuration ( + readgloballimit bigint NOT NULL, + writegloballimit bigint NOT NULL, + readsessionlimit bigint NOT NULL, + writesessionlimit bigint NOT NULL, + delaylimit bigint NOT NULL, + updatedinfo integer NOT NULL, + hostid character varying(8096) NOT NULL, + PRIMARY KEY (hostid) +); + +-- +-- Name: hostconfig; Type: TABLE; Schema: public; +-- + +CREATE TABLE hostconfig ( + business text NOT NULL, + roles text NOT NULL, + aliases text NOT NULL, + others text NOT NULL, + updatedinfo integer NOT NULL, + hostid character varying(8096) NOT NULL, + PRIMARY KEY (hostid) +); + +-- +-- Name: hosts; Type: TABLE; Schema: public; +-- + +CREATE TABLE hosts ( + address character varying(8096) NOT NULL, + port integer NOT NULL, + isssl boolean NOT NULL, + hostkey bytea(255) NOT NULL, + adminrole boolean NOT NULL, + isclient boolean NOT NULL, + isactive boolean NOT NULL, + isproxified boolean NOT NULL, + updatedinfo integer NOT NULL, + hostid character varying(8096) NOT NULL, + PRIMARY KEY (hostid) +); + +-- +-- Name: multiplemonitor; Type: TABLE; Schema: public; +-- + +CREATE TABLE multiplemonitor ( + countconfig integer NOT NULL, + counthost integer NOT NULL, + countrule integer NOT NULL, + hostid character varying(8096) NOT NULL, + PRIMARY KEY (hostid) +); + +-- +-- Name: rules; Type: TABLE; Schema: public; +-- + +CREATE TABLE rules ( + hostids text, + modetrans integer, + recvpath character varying(8096), + sendpath character varying(8096), + archivepath character varying(8096), + workpath character varying(8096), + rpretasks text, + rposttasks text, + rerrortasks text, + spretasks text, + sposttasks text, + serrortasks text, + updatedinfo integer, + idrule character varying(8096) NOT NULL, + PRIMARY KEY (idrule) +); + +-- +-- Name: runner; Type: TABLE; Schema: public; +-- + +CREATE TABLE runner ( + globalstep integer NOT NULL, + globallaststep integer NOT NULL, + step integer NOT NULL, + rank integer NOT NULL, + stepstatus character(3) NOT NULL, + retrievemode boolean NOT NULL, + filename character varying(8096) NOT NULL, + ismoved boolean NOT NULL, + idrule character varying(8096) NOT NULL, + blocksz integer NOT NULL, + originalname character varying(8096) NOT NULL, + fileinfo text NOT NULL, + transferinfo text NOT NULL, + modetrans integer NOT NULL, + starttrans timestamp without time zone NOT NULL, + stoptrans timestamp without time zone NOT NULL, + infostatus character(3) NOT NULL, + updatedinfo integer NOT NULL, + ownerreq character varying(8096) NOT NULL, + requester character varying(8096) NOT NULL, + requested character varying(8096) NOT NULL, + specialid bigint NOT NULL, + PRIMARY KEY (ownerreq, requester, requested, specialid) +); + +-- +-- Name: runseq; Type: SEQUENCE; Schema: public; +-- + +CREATE SEQUENCE runseq + START WITH -9223372036854775807 + INCREMENT BY 1 + MINVALUE -9223372036854775807 + NO MAXVALUE + NOCACHE; +-- +-- Name: idx_runner; Type: INDEX; Schema: public; +-- + +CREATE INDEX idx_runner ON runner ( + starttrans, ownerreq, stepstatus, updatedinfo, globalstep, infostatus, + specialid); + + diff --git a/src/test/resources/h2/populate.sql b/src/test/resources/h2/populate.sql new file mode 100644 index 000000000..d69fd18f0 --- /dev/null +++ b/src/test/resources/h2/populate.sql @@ -0,0 +1,62 @@ +-- +-- Data for Name: configuration; Type: TABLE DATA; Schema: public; Owner: waarp +-- + +INSERT INTO configuration VALUES (1, 2, 3, 4, 5, 1, 'server1'); +INSERT INTO configuration VALUES (2, 3, 2, 2, 2, 0, 'server2'); +INSERT INTO configuration VALUES (5, 6, 3, 4, 3, 0, 'server3'); + + +-- +-- Data for Name: hostconfig; Type: TABLE DATA; Schema: public; Owner: waarp +-- + +INSERT INTO hostconfig VALUES ('joyaux', 'marchand', 'le borgne', 'misc', 1, 'server1'); +INSERT INTO hostconfig VALUES ('ba', '', '', '3.0.9', 0, 'server2'); +INSERT INTO hostconfig VALUES ('ba', '', '', '3.0.9', 0, 'server3'); +INSERT INTO hostconfig VALUES ('', '', '', '3.0.9', 0, 'server4'); +INSERT INTO hostconfig VALUES ('', '', '', '3.0.9', 0, 'server5'); + + +-- +-- Data for Name: hosts; Type: TABLE DATA; Schema: public; Owner: waarp +-- + +INSERT INTO hosts VALUES ('127.0.0.1', 6666, true, +'303465626439323336346235616136306332396630346461353132616361346265303639646336633661383432653235', false, true, +false, true, 3, 'server1'); +INSERT INTO hosts VALUES ('127.0.0.1', 6667, true, +'303465626439323336346235616136306332396630346461353132616361346265303639646336633661383432653235', false, false, +true, false, 0, 'server1-ssl'); +INSERT INTO hosts VALUES ('127.0.0.3', 6676, false, +'303465626439323336346235616136306332396630346461353132616361346265303639646336633661383432653235', false, false, +true, false, 0, 'server2'); + + +-- +-- Data for Name: multiplemonitor; Type: TABLE DATA; Schema: public; Owner: waarp +-- + +INSERT INTO multiplemonitor VALUES (11, 18, 29, 'server1'); +INSERT INTO multiplemonitor VALUES (1, 2, 3, 'server2'); +INSERT INTO multiplemonitor VALUES (0, 0, 0, 'server3'); +INSERT INTO multiplemonitor VALUES (0, 0, 0, 'server4'); + + +-- +-- Data for Name: rules; Type: TABLE DATA; Schema: public; Owner: waarp +-- + +INSERT INTO rules VALUES ('', 1, '/in', '/out', '/arch', '/work', '', '', '', '', '', '', 0, 'default'); +INSERT INTO rules VALUES ('blablablabla2blabla3', 1, '/in', '/out', '/arch', '/work', '', 'testaa1', 'testaa1testaa1', 'testaa1testaa1testaa1', '', '', 42, 'dummy'); +INSERT INTO rules VALUES ('', 3, '/in', '/out', '/arch', '/work', '', '', '', '', '', '', 0, 'dummy2'); + +-- +-- Data for Name: runner; Type: TABLE DATA; Schema: public; Owner: waarp +-- + +INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'data/server1/log/client.log', false, 'default', 65536, 'data/server1/log/client.log', 'noinfo', '{"ORIGINALSIZE":18391}', 1, '2018-06-27 14:31:37.738', '2018-06-27 14:31:58.042', 'C ', 5, 'server1', 'server1', 'server2', -9223372036854775807); +INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'data/server1/log/client.log', false, 'default', 65536, 'data/server1/log/client.log', 'noinfo', '{"ORIGINALSIZE":52587}', 1, '2018-06-20 14:36:00.116', '2018-06-20 14:36:20.374', 'C ', 4, 'server1', 'server1', 'server2', -9223372036854775806); +INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'tintin', false, 'tintin', 65536, 'tintin', 'noinfo', '{"ORIGINALSIZE":-1}', 1, '2018-06-22 14:39:01.28', '2018-06-22 14:39:21.518', 'C ', 4, 'server1', 'server1', 'server2', -9223372036854775805); +INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'tintin', false, 'default', 65536, 'tintin', 'noinfo', '{"ORIGINALSIZE":-1}', 1, '2018-06-24 14:39:01.28', '2018-06-24 14:39:21.518', 'C ', 4, 'server1', 'server1', 'server2', 0); + diff --git a/src/test/resources/logback-test.xml b/src/test/resources/logback-test.xml index 23f40bbec..1315a0f42 100644 --- a/src/test/resources/logback-test.xml +++ b/src/test/resources/logback-test.xml @@ -1,16 +1,16 @@ - - - %d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n - - + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n + + - - - + + + - - - - + + + + \ No newline at end of file diff --git a/src/test/resources/mariadb/clean.sql b/src/test/resources/mariadb/clean.sql new file mode 100644 index 000000000..654bd1d58 --- /dev/null +++ b/src/test/resources/mariadb/clean.sql @@ -0,0 +1,7 @@ +DROP TABLE Sequences; +DROP TABLE runner; +DROP TABLE rules; +DROP TABLE multiplemonitor; +DROP TABLE hosts; +DROP TABLE hostconfig; +DROP TABLE configuration; diff --git a/src/test/resources/mariadb/create.sql b/src/test/resources/mariadb/create.sql new file mode 100644 index 000000000..3926467fa --- /dev/null +++ b/src/test/resources/mariadb/create.sql @@ -0,0 +1,116 @@ +use test; + +-- +-- Name: configuration; Type: TABLE; +-- + +CREATE TABLE configuration ( + readgloballimit bigint NOT NULL, + writegloballimit bigint NOT NULL, + readsessionlimit bigint NOT NULL, + writesessionlimit bigint NOT NULL, + delaylimit bigint NOT NULL, + updatedinfo integer NOT NULL, + hostid character varying(255) NOT NULL, + PRIMARY KEY (hostid) +); + +-- +-- Name: hostconfig; Type: TABLE; +-- + +CREATE TABLE hostconfig ( + business text NOT NULL, + roles text NOT NULL, + aliases text NOT NULL, + others text NOT NULL, + updatedinfo integer NOT NULL, + hostid character varying(255) NOT NULL, + PRIMARY KEY (hostid) +); + +-- +-- Name: hosts; Type: TABLE; +-- + +CREATE TABLE hosts ( + address character varying(255) NOT NULL, + port integer NOT NULL, + isssl boolean NOT NULL, + hostkey varbinary(255) NOT NULL, + adminrole boolean NOT NULL, + isclient boolean NOT NULL, + isactive boolean NOT NULL, + isproxified boolean NOT NULL, + updatedinfo integer NOT NULL, + hostid character varying(255) NOT NULL, + PRIMARY KEY (hostid) +); + +-- +-- Name: multiplemonitor; Type: TABLE; +-- + +CREATE TABLE multiplemonitor ( + countconfig integer NOT NULL, + counthost integer NOT NULL, + countrule integer NOT NULL, + hostid character varying(255) NOT NULL, + PRIMARY KEY (hostid) +); + +-- +-- Name: rules; Type: TABLE; +-- + +CREATE TABLE rules ( + hostids text, + modetrans integer, + recvpath character varying(255), + sendpath character varying(255), + archivepath character varying(255), + workpath character varying(255), + rpretasks text, + rposttasks text, + rerrortasks text, + spretasks text, + sposttasks text, + serrortasks text, + updatedinfo integer, + idrule character varying(255) NOT NULL, + PRIMARY KEY (idrule) +); + +-- +-- Name: runner; Type: TABLE; +-- + +CREATE TABLE runner ( + globalstep integer NOT NULL, + globallaststep integer NOT NULL, + step integer NOT NULL, + rank integer NOT NULL, + stepstatus character(3) NOT NULL, + retrievemode boolean NOT NULL, + filename character varying(255) NOT NULL, + ismoved boolean NOT NULL, + idrule character varying(255) NOT NULL, + blocksz integer NOT NULL, + originalname character varying(255) NOT NULL, + fileinfo text NOT NULL, + transferinfo text NOT NULL, + modetrans integer NOT NULL, + starttrans timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + stoptrans timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + infostatus character(3) NOT NULL, + updatedinfo integer NOT NULL, + ownerreq character varying(255) NOT NULL, + requester character varying(255) NOT NULL, + requested character varying(255) NOT NULL, + specialid bigint NOT NULL, + PRIMARY KEY (ownerreq, requester, requested, specialid) +); + +CREATE TABLE Sequences (name VARCHAR(22) NOT NULL PRIMARY KEY, seq BIGINT NOT NULL); + +INSERT INTO Sequences (name, seq) VALUES ('RUNSEQ', 1); diff --git a/src/test/resources/mariadb/populate.sql b/src/test/resources/mariadb/populate.sql new file mode 100644 index 000000000..03b83c34b --- /dev/null +++ b/src/test/resources/mariadb/populate.sql @@ -0,0 +1,62 @@ +-- +-- Data for Name: configuration; Type: TABLE DATA; +-- + +INSERT INTO configuration VALUES (1, 2, 3, 4, 5, 1, 'server1'); +INSERT INTO configuration VALUES (2, 3, 2, 2, 2, 0, 'server2'); +INSERT INTO configuration VALUES (5, 6, 3, 4, 3, 1, 'server3'); + + +-- +-- Data for Name: hostconfig; Type: TABLE DATA; +-- + +INSERT INTO hostconfig VALUES ('joyaux', 'marchand', 'le borgne', 'misc', 1, 'server1'); +INSERT INTO hostconfig VALUES ('ba', '', '', '3.0.9', 0, 'server2'); +INSERT INTO hostconfig VALUES ('ba', '', '', '3.0.9', 0, 'server3'); +INSERT INTO hostconfig VALUES ('', '', '', '3.0.9', 0, 'server4'); +INSERT INTO hostconfig VALUES ('', '', '', '3.0.9', 0, 'server5'); + + +-- +-- Data for Name: hosts; Type: TABLE DATA; +-- + +INSERT INTO hosts VALUES ('127.0.0.1', 6666, true, + '\x303465626439323336346235616136306332396630346461353132616361346265303639646336633661383432653235', false, true, + false, true, 3, 'server1'); +INSERT INTO hosts VALUES ('127.0.0.1', 6667, true, +'\x303465626439323336346235616136306332396630346461353132616361346265303639646336633661383432653235', false, false, + true, false, 0, 'server1-ssl'); +INSERT INTO hosts VALUES ('127.0.0.3', 6676, false, +'\x303465626439323336346235616136306332396630346461353132616361346265303639646336633661383432653235', false, false, +true, false, 0, 'server2'); + + +-- +-- Data for Name: multiplemonitor; Type: TABLE DATA; +-- + +INSERT INTO multiplemonitor VALUES (11, 18, 29, 'server1'); +INSERT INTO multiplemonitor VALUES (1, 2, 3, 'server2'); +INSERT INTO multiplemonitor VALUES (0, 0, 0, 'server3'); +INSERT INTO multiplemonitor VALUES (0, 0, 0, 'server4'); + + +-- +-- Data for Name: rules; Type: TABLE DATA; +-- + +INSERT INTO rules VALUES ('', 1, '/in', '/out', '/arch', '/work', '', '', '', '', '', '', 0, 'default'); +INSERT INTO rules VALUES ('blablablabla2blabla3', +1, '/in', '/out', '/arch', '/work', '', 'testaa1', 'testaa1testaa1', 'testaa1testaa1testaa1', '', '', 0, 'dummy'); +INSERT INTO rules VALUES ('', 3, '/in', '/out', '/arch', '/work', '', '', '', '', '', '', 0, 'dummy2'); + +-- +-- Data for Name: runner; Type: TABLE DATA; +-- + +INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'data/server1/log/client.log', false, 'default', 65536, 'data/server1/log/client.log', 'noinfo', '{"ORIGINALSIZE":18391}', 1, '2018-06-27 14:31:37.738', '2018-06-27 14:31:58.042', 'C ', 5, 'server1', 'server1', 'server2', -9223372036854775807); +INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'data/server1/log/client.log', false, 'default', 65536, 'data/server1/log/client.log', 'noinfo', '{"ORIGINALSIZE":52587}', 1, '2018-06-20 14:36:00.116', '2018-06-20 14:36:20.374', 'C ', 4, 'server1', 'server1', 'server2', -9223372036854775806); +INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'tintin', false, 'tintin', 65536, 'tintin', 'noinfo', '{"ORIGINALSIZE":-1}', 1, '2018-06-22 14:39:01.28', '2018-06-22 14:39:21.518', 'C ', 4, 'server1', 'server1', 'server2', -9223372036854775805); +INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'tintin', false, 'default', 65536, 'tintin', 'noinfo', '{"ORIGINALSIZE":-1}', 1, '2018-06-24 14:39:01.28', '2018-06-24 14:39:21.518', 'C ', 4, 'server1', 'server1', 'server2', 0); diff --git a/src/test/resources/mysql/create.sql b/src/test/resources/mysql/create.sql index 00ff12565..394c9bd5a 100644 --- a/src/test/resources/mysql/create.sql +++ b/src/test/resources/mysql/create.sql @@ -100,8 +100,8 @@ CREATE TABLE runner ( fileinfo text NOT NULL, transferinfo text NOT NULL, modetrans integer NOT NULL, - starttrans timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, - stoptrans timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + starttrans timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), + stoptrans timestamp(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3), infostatus character(3) NOT NULL, updatedinfo integer NOT NULL, ownerreq character varying(255) NOT NULL, diff --git a/src/test/resources/oracle/clean.sql b/src/test/resources/oracle/clean.sql index fd16cb941..ce60c0b8d 100644 --- a/src/test/resources/oracle/clean.sql +++ b/src/test/resources/oracle/clean.sql @@ -1,3 +1,4 @@ +DROP SEQUENCE runseq; DROP TABLE configuration PURGE; DROP TABLE hostconfig PURGE; DROP TABLE hosts PURGE; diff --git a/src/test/resources/oracle/create.sql b/src/test/resources/oracle/create.sql index d78c8a210..9b7e222f7 100644 --- a/src/test/resources/oracle/create.sql +++ b/src/test/resources/oracle/create.sql @@ -107,13 +107,12 @@ CREATE TABLE runner ( -- Name: runseq; Type: SEQUENCE; Schema: public; -- - ---CREATE SEQUENCE runseq - -- START WITH -9223372036854775807 - -- INCREMENT BY 1 - -- MINVALUE -9223372036854775807 - -- NO MAXVALUE - -- CACHE 1; +CREATE SEQUENCE runseq + START WITH -9223372036854775807 + INCREMENT BY 1 + MINVALUE -9223372036854775807 + NOMAXVALUE + NOCACHE; -- -- Name: runseq; Type: SEQUENCE SET; Schema: public; diff --git a/src/test/resources/postgresql/clean.sql b/src/test/resources/postgresql/clean.sql index 9efd10265..85f10da63 100644 --- a/src/test/resources/postgresql/clean.sql +++ b/src/test/resources/postgresql/clean.sql @@ -1,8 +1,8 @@ -DROP TABLE public.configuration; -DROP TABLE public.hostconfig; -DROP TABLE public.hosts; -DROP TABLE public.multiplemonitor; -DROP TABLE public.rules; -DROP TABLE public.runner; DROP SEQUENCE public.runseq; +DROP TABLE public.runner; +DROP TABLE public.rules; +DROP TABLE public.multiplemonitor; +DROP TABLE public.hosts; +DROP TABLE public.hostconfig; +DROP TABLE public.configuration; From 944b89e0c9f677c38542724a05527c2f4c1c05a4 Mon Sep 17 00:00:00 2001 From: mro Date: Fri, 19 Jul 2019 15:06:59 +0200 Subject: [PATCH 2/3] Correct database/data InitObject() --- pom.xml | 14 +- .../openr66/client/AbstractTransfer.java | 74 +++ .../client/MultipleDirectTransfer.java | 73 +-- .../client/MultipleSubmitTransfer.java | 12 +- .../waarp/openr66/client/RequestTransfer.java | 275 ++++++---- .../configuration/FileBasedConfiguration.java | 1 + .../RuleFileBasedConfiguration.java | 8 +- .../org/waarp/openr66/dao/BusinessDAO.java | 41 +- .../org/waarp/openr66/dao/DAOFactory.java | 27 +- .../java/org/waarp/openr66/dao/HostDAO.java | 39 +- .../java/org/waarp/openr66/dao/LimitDAO.java | 39 +- .../waarp/openr66/dao/MultipleMonitorDAO.java | 42 +- .../java/org/waarp/openr66/dao/RuleDAO.java | 39 +- .../org/waarp/openr66/dao/TransferDAO.java | 86 +++- .../openr66/dao/database/DBBusinessDAO.java | 54 +- .../openr66/dao/database/DBDAOFactory.java | 29 +- .../waarp/openr66/dao/database/DBHostDAO.java | 55 +- .../openr66/dao/database/DBLimitDAO.java | 54 +- .../dao/database/DBMultipleMonitorDAO.java | 56 ++- .../waarp/openr66/dao/database/DBRuleDAO.java | 65 ++- .../openr66/dao/database/DBTransferDAO.java | 80 +-- .../dao/database/StatementExecutor.java | 2 +- .../dao/database/h2/H2TransferDAO.java | 10 +- .../database/mariadb/MariaDBTransferDAO.java | 10 +- .../database/oracle/OracleTransferDAO.java | 10 +- .../postgres/PostgreSQLTransferDAO.java | 10 +- .../dao/exception/DAOConnectionException.java | 22 + .../openr66/dao/exception/DAOException.java | 6 +- .../dao/exception/DAONoDataException.java | 19 + .../waarp/openr66/dao/xml/XMLBusinessDAO.java | 91 ++-- .../waarp/openr66/dao/xml/XMLDAOFactory.java | 19 +- .../org/waarp/openr66/dao/xml/XMLHostDAO.java | 88 ++-- .../xml/{XMLimitDAO.java => XMLLimitDAO.java} | 92 ++-- .../org/waarp/openr66/dao/xml/XMLRuleDAO.java | 125 ++--- .../waarp/openr66/dao/xml/XMLTransferDAO.java | 163 ++++-- .../database/data/DbConfiguration.java | 90 ++-- .../openr66/database/data/DbHostAuth.java | 74 +-- .../database/data/DbHostConfiguration.java | 108 ++-- .../database/data/DbMultipleMonitor.java | 72 +-- .../waarp/openr66/database/data/DbRule.java | 94 ++-- .../openr66/database/data/DbTaskRunner.java | 143 +++--- .../protocol/http/HttpFormattedHandler.java | 15 +- .../handler/HttpRestAbstractR66Handler.java | 2 +- .../converters/HostConfigConverter.java | 7 +- .../restv2/converters/TransferConverter.java | 15 +- .../restv2/dbhandlers/HostConfigHandler.java | 17 +- .../http/restv2/dbhandlers/HostIdHandler.java | 15 +- .../http/restv2/dbhandlers/HostsHandler.java | 6 +- .../http/restv2/dbhandlers/LimitsHandler.java | 17 +- .../http/restv2/dbhandlers/RuleIdHandler.java | 15 +- .../http/restv2/dbhandlers/RulesHandler.java | 6 +- .../http/restv2/dbhandlers/ServerHandler.java | 19 +- .../restv2/dbhandlers/TransferIdHandler.java | 19 +- .../restv2/dbhandlers/TransfersHandler.java | 6 +- .../restv2/resthandlers/RestHandlerHook.java | 11 +- .../localhandler/ConnectionActions.java | 3 +- .../localhandler/LocalTransaction.java | 2 - .../protocol/localhandler/ServerActions.java | 1 + .../waarp/openr66/protocol/utils/Version.java | 2 +- .../openr66/dao/database/DBAllDAOTest.java | 243 +++++++-- .../openr66/dao/database/h2/DbH2DAOTest.java | 5 +- .../database/mariadb/DbMariadbDAOTest.java | 5 +- ...QLDAOTransfer.java => DBMySQLDAOTest.java} | 6 +- .../database/oracle/DBOracleDBDAOTest.java | 4 +- .../postgres/DBPostgreSQLDAOTest.java | 4 +- .../dao/database/xml/DbXmlDAOTestNo.java | 193 +++++++ .../http/rest/test/HttpTestR66PseudoMain.java | 2 +- .../http/rest/test/HttpTestRestR66Client.java | 10 +- .../openr66/protocol/junit/AllTasksTest.java | 2 +- .../protocol/junit/NetworkClientTest.java | 474 ++++++++++++------ .../openr66/protocol/junit/TestAbstract.java | 123 ++--- .../protocol/junit/TestAbstractMinimal.java | 10 +- .../protocol/test/TestBusinessRequest.java | 109 ++-- .../openr66/protocol/test/TestTasks.java | 5 +- .../protocol/test/TestTransaction.java | 3 +- .../Linux/config/config-clientNoDB_B.xml | 2 +- .../Linux/config/config-serverA-minimal.xml | 2 +- .../resources/Linux/config/config-serverB.xml | 2 +- .../Linux/config/config-serverInitA.xml | 2 +- .../Linux/config/config-serverInitB.xml | 2 +- 80 files changed, 2395 insertions(+), 1402 deletions(-) create mode 100644 src/main/java/org/waarp/openr66/dao/exception/DAOConnectionException.java create mode 100644 src/main/java/org/waarp/openr66/dao/exception/DAONoDataException.java rename src/main/java/org/waarp/openr66/dao/xml/{XMLimitDAO.java => XMLLimitDAO.java} (61%) rename src/test/java/org/waarp/openr66/dao/database/mySQL/{DBMySQLDAOTransfer.java => DBMySQLDAOTest.java} (91%) create mode 100644 src/test/java/org/waarp/openr66/dao/database/xml/DbXmlDAOTestNo.java diff --git a/pom.xml b/pom.xml index e3c745ba7..fbf0b0e47 100644 --- a/pom.xml +++ b/pom.xml @@ -2,7 +2,7 @@ 4.0.0 WaarpR66 Waarp OpenR66 - 3.1.0 + 3.1.1 OpenR66 is a File Transfer Monitor to be used in real production to transfer files between servers. It allows to start/restart a transfer, check the remote MD5, check status, make pre or post @@ -75,7 +75,7 @@ Waarp WaarpCommon - 3.1.0 + 3.1.1 xml-apis @@ -115,13 +115,13 @@ Waarp WaarpExec - 3.0.5 + 3.1.0 true Waarp WaarpSnmp - 3.0.7 + 3.1.0 true @@ -137,7 +137,7 @@ Waarp WaarpThrift - 3.0.7 + 3.1.0 true @@ -167,12 +167,12 @@ Waarp WaarpGatewayKernel - 3.1.0 + 3.1.1 Waarp WaarpFtpClient - 3.0.7 + 3.1.0 junit diff --git a/src/main/java/org/waarp/openr66/client/AbstractTransfer.java b/src/main/java/org/waarp/openr66/client/AbstractTransfer.java index ae449d2a9..4609e01ee 100644 --- a/src/main/java/org/waarp/openr66/client/AbstractTransfer.java +++ b/src/main/java/org/waarp/openr66/client/AbstractTransfer.java @@ -21,7 +21,9 @@ import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; +import java.util.List; import org.waarp.common.command.exception.CommandAbstractException; import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; @@ -34,6 +36,7 @@ import org.waarp.openr66.context.ErrorCode; import org.waarp.openr66.context.R66Result; import org.waarp.openr66.context.R66Session; +import org.waarp.openr66.context.filesystem.R66Dir; import org.waarp.openr66.context.filesystem.R66File; import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; import org.waarp.openr66.database.DbConstant; @@ -43,7 +46,10 @@ import org.waarp.openr66.protocol.configuration.Messages; import org.waarp.openr66.protocol.configuration.PartnerConfiguration; import org.waarp.openr66.protocol.exception.OpenR66DatabaseGlobalException; +import org.waarp.openr66.protocol.localhandler.packet.InformationPacket; import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; +import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; +import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; import org.waarp.openr66.protocol.utils.FileUtils; import org.waarp.openr66.protocol.utils.R66Future; @@ -340,4 +346,72 @@ protected void finalizeInErrorTransferRequest(ClientRunner runner, DbTaskRunner runner.changeUpdatedInfo(UpdatedInfo.INERROR, code, true); } } + + + public List getRemoteFiles(DbRule dbrule, String[] localfilenames, String requested, + NetworkTransaction networkTransaction) { + List files = new ArrayList(); + for (String filename : localfilenames) { + if (!(filename.contains("*") || filename.contains("?") || filename.contains("~"))) { + files.add(filename); + } else { + // remote query + R66Future futureInfo = new R66Future(true); + logger.info(Messages.getString("Transfer.3") + filename + " to " + requested); //$NON-NLS-1$ + RequestInformation info = new RequestInformation( + futureInfo, requested, rulename, filename, + (byte) InformationPacket.ASKENUM.ASKLIST.ordinal(), -1, false, networkTransaction); + info.run(); + futureInfo.awaitUninterruptibly(); + if (futureInfo.isSuccess()) { + ValidPacket valid = (ValidPacket) futureInfo.getResult().getOther(); + if (valid != null) { + String line = valid.getSheader(); + String[] lines = line.split("\n"); + for (String string : lines) { + File tmpFile = new File(string); + files.add(tmpFile.getPath()); + } + } + } else { + logger.error(Messages.getString("Transfer.6") + filename + " to " + requested + ": " + + (futureInfo.getCause() == null ? "" : futureInfo.getCause().getMessage())); //$NON-NLS-1$ + } + } + } + return files; + } + + public List getLocalFiles(DbRule dbrule, String[] localfilenames) { + List files = new ArrayList(); + R66Session session = new R66Session(); + session.getAuth().specialNoSessionAuth(false, Configuration.configuration.getHOST_ID()); + R66Dir dir = new R66Dir(session); + try { + dir.changeDirectory(dbrule.getSendPath()); + } catch (CommandAbstractException e) { + } + if (localfilenames != null) { + for (String filename : localfilenames) { + if (!(filename.contains("*") || filename.contains("?") || filename.contains("~"))) { + logger.info("Direct add: " + filename); + files.add(filename); + } else { + // local: must check + logger.info("Local Ask for " + filename + " from " + dir.getFullPath()); + List list; + try { + list = dir.list(filename); + if (list != null) { + files.addAll(list); + } + } catch (CommandAbstractException e) { + logger.warn(Messages.getString("Transfer.14") + filename + " : " + e.getMessage()); //$NON-NLS-1$ + } + } + } + } + return files; + } + } diff --git a/src/main/java/org/waarp/openr66/client/MultipleDirectTransfer.java b/src/main/java/org/waarp/openr66/client/MultipleDirectTransfer.java index a34dc4978..2ee6350d6 100644 --- a/src/main/java/org/waarp/openr66/client/MultipleDirectTransfer.java +++ b/src/main/java/org/waarp/openr66/client/MultipleDirectTransfer.java @@ -17,11 +17,9 @@ */ package org.waarp.openr66.client; -import java.io.File; import java.util.ArrayList; import java.util.List; -import org.waarp.common.command.exception.CommandAbstractException; import org.waarp.common.database.exception.WaarpDatabaseException; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; @@ -30,14 +28,10 @@ import org.waarp.openr66.client.utils.OutputFormat.FIELDS; import org.waarp.openr66.context.ErrorCode; import org.waarp.openr66.context.R66Result; -import org.waarp.openr66.context.R66Session; -import org.waarp.openr66.context.filesystem.R66Dir; import org.waarp.openr66.database.DbConstant; import org.waarp.openr66.database.data.DbRule; import org.waarp.openr66.protocol.configuration.Configuration; import org.waarp.openr66.protocol.configuration.Messages; -import org.waarp.openr66.protocol.localhandler.packet.InformationPacket; -import org.waarp.openr66.protocol.localhandler.packet.ValidPacket; import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; import org.waarp.openr66.protocol.utils.ChannelUtils; import org.waarp.openr66.protocol.utils.R66Future; @@ -72,71 +66,6 @@ public MultipleDirectTransfer(R66Future future, String remoteHost, super(future, remoteHost, filename, rulename, fileinfo, isMD5, blocksize, id, networkTransaction); } - public static List getRemoteFiles(DbRule dbrule, String[] localfilenames, String requested, - NetworkTransaction networkTransaction) { - List files = new ArrayList(); - for (String filename : localfilenames) { - if (!(filename.contains("*") || filename.contains("?") || filename.contains("~"))) { - files.add(filename); - } else { - // remote query - R66Future futureInfo = new R66Future(true); - logger.info(Messages.getString("Transfer.3") + filename + " to " + requested); //$NON-NLS-1$ - RequestInformation info = new RequestInformation(futureInfo, requested, rule, filename, - (byte) InformationPacket.ASKENUM.ASKLIST.ordinal(), -1, false, networkTransaction); - info.run(); - futureInfo.awaitUninterruptibly(); - if (futureInfo.isSuccess()) { - ValidPacket valid = (ValidPacket) futureInfo.getResult().getOther(); - if (valid != null) { - String line = valid.getSheader(); - String[] lines = line.split("\n"); - for (String string : lines) { - File tmpFile = new File(string); - files.add(tmpFile.getPath()); - } - } - } else { - logger.error(Messages.getString("Transfer.6") + filename + " to " + requested + ": " + - (futureInfo.getCause() == null ? "" : futureInfo.getCause().getMessage())); //$NON-NLS-1$ - } - } - } - return files; - } - - public static List getLocalFiles(DbRule dbrule, String[] localfilenames) { - List files = new ArrayList(); - R66Session session = new R66Session(); - session.getAuth().specialNoSessionAuth(false, Configuration.configuration.getHOST_ID()); - R66Dir dir = new R66Dir(session); - try { - dir.changeDirectory(dbrule.getSendPath()); - } catch (CommandAbstractException e) { - } - if (localfilenames != null) { - for (String filename : localfilenames) { - if (!(filename.contains("*") || filename.contains("?") || filename.contains("~"))) { - logger.info("Direct add: " + filename); - files.add(filename); - } else { - // local: must check - logger.info("Local Ask for " + filename + " from " + dir.getFullPath()); - List list; - try { - list = dir.list(filename); - if (list != null) { - files.addAll(list); - } - } catch (CommandAbstractException e) { - logger.warn(Messages.getString("Transfer.14") + filename + " : " + e.getMessage()); //$NON-NLS-1$ - } - } - } - } - return files; - } - @Override public void run() { String[] localfilenames = filename.split(","); @@ -169,7 +98,7 @@ public void run() { long time1 = System.currentTimeMillis(); R66Future future = new R66Future(true); DirectTransfer transaction = new DirectTransfer(future, - host, filename, rule, fileInfo, ismd5, block, idt, + host, filename, rulename, fileinfo, isMD5, blocksize, id, networkTransaction); transaction.normalInfoAsWarn = normalInfoAsWarn; logger.debug("rhost: " + host + ":" + transaction.remoteHost); diff --git a/src/main/java/org/waarp/openr66/client/MultipleSubmitTransfer.java b/src/main/java/org/waarp/openr66/client/MultipleSubmitTransfer.java index 722ffed14..6d2feee0b 100644 --- a/src/main/java/org/waarp/openr66/client/MultipleSubmitTransfer.java +++ b/src/main/java/org/waarp/openr66/client/MultipleSubmitTransfer.java @@ -83,7 +83,7 @@ public void run() { try { dbrule = new DbRule(rulename); } catch (WaarpDatabaseException e) { - logger.error(Messages.getString("SubmitTransfer.2") + rule); //$NON-NLS-1$ + logger.error(Messages.getString("SubmitTransfer.2") + rulename); //$NON-NLS-1$ if (DetectionUtils.isJunit()) { return; } @@ -100,7 +100,7 @@ public void run() { } List files = null; if (dbrule.isSendMode()) { - files = MultipleDirectTransfer.getLocalFiles(dbrule, localfilenames); + files = getLocalFiles(dbrule, localfilenames); } else if (submit) { files = new ArrayList(); for (String string : localfilenames) { @@ -111,15 +111,15 @@ public void run() { host = host.trim(); if (host != null && !host.isEmpty()) { if (!submit && dbrule.isRecvMode()) { - files = MultipleDirectTransfer.getRemoteFiles(dbrule, localfilenames, host, networkTransaction); + files = getRemoteFiles(dbrule, localfilenames, host, networkTransaction); } for (String filename : files) { filename = filename.trim(); if (filename != null && !filename.isEmpty()) { R66Future future = new R66Future(true); - SubmitTransfer transaction = new SubmitTransfer(future, - host, filename, rule, fileInfo, ismd5, block, idt, - ttimestart); + SubmitTransfer transaction = new SubmitTransfer( + future, host, filename, rulename, fileinfo, + isMD5, blocksize, id, startTime); transaction.normalInfoAsWarn = normalInfoAsWarn; transaction.run(); future.awaitUninterruptibly(); diff --git a/src/main/java/org/waarp/openr66/client/RequestTransfer.java b/src/main/java/org/waarp/openr66/client/RequestTransfer.java index 5dca54fee..03e82d48f 100644 --- a/src/main/java/org/waarp/openr66/client/RequestTransfer.java +++ b/src/main/java/org/waarp/openr66/client/RequestTransfer.java @@ -231,148 +231,223 @@ public RequestTransfer(R66Future future, long specialId, String requested, Strin } public void run() { - if (logger == null) { - logger = WaarpLoggerFactory.getLogger(RequestTransfer.class); - } DbTaskRunner runner = null; try { - runner = new DbTaskRunner(null, null, - specialId, requester, requested); - logger.info("Found previous Runner: " + runner.toString()); - } catch (WaarpDatabaseException e) { - // Maybe we can ask to the remote - R66Future futureInfo = new R66Future(true); - RequestInformation requestInformation = new RequestInformation(futureInfo, requested, null, null, - (byte) -1, specialId, true, networkTransaction); - requestInformation.normalInfoAsWarn = normalInfoAsWarn; - requestInformation.run(); - futureInfo.awaitUninterruptibly(); - if (futureInfo.isSuccess()) { - R66Result r66result = futureInfo.getResult(); - ValidPacket info = (ValidPacket) r66result.getOther(); - String xml = info.getSheader(); - try { - runner = DbTaskRunner.fromStringXml(xml, true); - runner.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); - // useful ? - CommanderNoDb.todoList.add(runner); + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(RequestTransfer.class); + } + try { + runner = new DbTaskRunner(null, null, + specialId, requester, requested); + logger.info("Found previous Runner: " + runner.toString()); + } catch (WaarpDatabaseException e) { + // Maybe we can ask to the remote + R66Future futureInfo = new R66Future(true); + RequestInformation requestInformation = + new RequestInformation(futureInfo, requested, null, null, + (byte) -1, specialId, true, + networkTransaction); + requestInformation.normalInfoAsWarn = normalInfoAsWarn; + requestInformation.run(); + futureInfo.awaitUninterruptibly(); + if (futureInfo.isSuccess()) { + R66Result r66result = futureInfo.getResult(); + ValidPacket info = (ValidPacket) r66result.getOther(); + String xml = info.getSheader(); + try { + runner = DbTaskRunner.fromStringXml(xml, true); + runner.changeUpdatedInfo(UpdatedInfo.TOSUBMIT); + // useful ? + CommanderNoDb.todoList.add(runner); - logger.info("Get Runner from remote: " + runner.toString()); - if (runner.getSpecialId() == DbConstant.ILLEGALVALUE || !runner.isSender()) { - logger.error(Messages.getString("RequestTransfer.18")); //$NON-NLS-1$ - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + logger.info( + "Get Runner from remote: " + runner.toString()); + if (runner.getSpecialId() == DbConstant.ILLEGALVALUE || + !runner.isSender()) { + logger.error(Messages.getString( + "RequestTransfer.18")); //$NON-NLS-1$ + future.setResult(new R66Result( + new OpenR66DatabaseGlobalException(e), null, + true, ErrorCode.Internal, null)); - future.setFailure(e); - return; - } - if (runner.isAllDone()) { - logger.error(Messages.getString("RequestTransfer.21")); //$NON-NLS-1$ - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, + future.setFailure(e); + return; + } + if (runner.isAllDone()) { + logger.error(Messages.getString( + "RequestTransfer.21")); //$NON-NLS-1$ + future.setResult(new R66Result( + new OpenR66DatabaseGlobalException(e), null, + true, ErrorCode.Internal, null)); + future.setFailure(e); + return; + } + } catch (OpenR66ProtocolBusinessException e1) { + logger.error(Messages.getString( + "RequestTransfer.18")); //$NON-NLS-1$ + future.setResult(new R66Result( + new OpenR66DatabaseGlobalException(e1), null, true, + ErrorCode.Internal, null)); future.setFailure(e); return; } - } catch (OpenR66ProtocolBusinessException e1) { - logger.error(Messages.getString("RequestTransfer.18")); //$NON-NLS-1$ - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e1), null, true, - ErrorCode.Internal, null)); + } else { + logger.error( + Messages.getString("RequestTransfer.18")); //$NON-NLS-1$ + future.setResult( + new R66Result(new OpenR66DatabaseGlobalException(e), + null, true, + ErrorCode.Internal, null)); future.setFailure(e); return; } - } else { - logger.error(Messages.getString("RequestTransfer.18")); //$NON-NLS-1$ - future.setResult(new R66Result(new OpenR66DatabaseGlobalException(e), null, true, - ErrorCode.Internal, null)); - future.setFailure(e); - return; } - } - if (cancel || stop || restart) { - if (cancel) { - // Cancel the task and delete any file if in retrieve - if (runner.isAllDone()) { - // nothing to do since already finished - setDone(runner); - logger.info("Transfer already finished: " + runner.toString()); - future.setResult(new R66Result(null, true, ErrorCode.TransferOk, runner)); - future.getResult().setRunner(runner); - future.setSuccess(); - return; - } else { - // Send a request of cancel - ErrorCode code = sendStopOrCancel(runner, LocalPacketFactory.CANCELPACKET); - switch (code) { + if (cancel || stop || restart) { + if (cancel) { + // Cancel the task and delete any file if in retrieve + if (runner.isAllDone()) { + // nothing to do since already finished + setDone(runner); + logger.info( + "Transfer already finished: " + runner.toString()); + future.setResult( + new R66Result(null, true, ErrorCode.TransferOk, + runner)); + future.getResult().setRunner(runner); + future.setSuccess(); + return; + } else { + // Send a request of cancel + ErrorCode code = sendStopOrCancel(runner, + LocalPacketFactory.CANCELPACKET); + future.setResult( + new R66Result(null, true, code, + runner)); + future.getResult().setRunner(runner); + switch (code) { case CompleteOk: - logger.info("Transfer cancel requested and done: {}", - runner); + logger + .info("Transfer cancel requested and done: {}", + runner); + future.setSuccess(); break; case TransferOk: - logger.info("Transfer cancel requested but already finished: {}", - runner); + logger.info( + "Transfer cancel requested but already finished: {}", + runner); + future.setSuccess(); break; default: - logger.info("Transfer cancel requested but internal error: {}", - runner); + logger.info( + "Transfer cancel requested but internal error: {}", + runner); + future.setFailure(new WaarpDatabaseException("Transfer cancel requested but internal error")); break; + } } - } - } else if (stop) { - // Just stop the task - // Send a request - ErrorCode code = sendStopOrCancel(runner, LocalPacketFactory.STOPPACKET); - switch (code) { + } else if (stop) { + // Just stop the task + // Send a request + ErrorCode code = + sendStopOrCancel(runner, LocalPacketFactory.STOPPACKET); + future.setResult( + new R66Result(null, true, code, + runner)); + future.getResult().setRunner(runner); + switch (code) { case CompleteOk: - logger.info("Transfer stop requested and done: {}", runner); + logger.info("Transfer stop requested and done: {}", + runner); + future.setSuccess(); break; case TransferOk: - logger.info("Transfer stop requested but already finished: {}", - runner); + logger.info( + "Transfer stop requested but already finished: {}", + runner); + future.setSuccess(); break; default: - logger.info("Transfer stop requested but internal error: {}", - runner); + logger.info( + "Transfer stop requested but internal error: {}", + runner); + future.setFailure(new WaarpDatabaseException("Transfer stop requested but internal error")); break; - } - } else if (restart) { - // Restart if already stopped and not finished - ErrorCode code = sendValid(runner, LocalPacketFactory.VALIDPACKET); - switch (code) { + } + } else if (restart) { + // Restart if already stopped and not finished + ErrorCode code = + sendValid(runner, LocalPacketFactory.VALIDPACKET); + future.setResult( + new R66Result(null, true, code, + runner)); + future.getResult().setRunner(runner); + switch (code) { case QueryStillRunning: logger.info( - "Transfer restart requested but already active and running: {}", - runner); + "Transfer restart requested but already active and running: {}", + runner); + future.setSuccess(); break; case Running: - logger.info("Transfer restart requested but already running: {}", - runner); + logger.info( + "Transfer restart requested but already running: {}", + runner); + future.setSuccess(); break; case PreProcessingOk: - logger.info("Transfer restart requested and restarted: {}", - runner); + logger.info( + "Transfer restart requested and restarted: {}", + runner); + future.setSuccess(); break; case CompleteOk: - logger.info("Transfer restart requested but already finished: {}", - runner); + logger.info( + "Transfer restart requested but already finished: {}", + runner); + future.setSuccess(); break; case RemoteError: - logger.info("Transfer restart requested but remote error: {}", - runner); + logger.info( + "Transfer restart requested but remote error: {}", + runner); + future.setSuccess(); break; case PassThroughMode: - logger.info("Transfer not restarted since it is in PassThrough mode: {}", - runner); + logger.info( + "Transfer not restarted since it is in PassThrough mode: {}", + runner); + future.setSuccess(); break; default: - logger.info("Transfer restart requested but internal error: {}", - runner); + logger.info( + "Transfer restart requested but internal error: {}", + runner); + future.setFailure(new WaarpDatabaseException("Transfer restart requested but internal error")); break; + } + } + } else { + // Only request + logger.info( + "Transfer information: {} " + runner.toShortString(), + future.isDone()); + future.setResult( + new R66Result(null, true, runner.getErrorInfo(), runner)); + future.setSuccess(); + } + } finally { + if (!future.isDone()) { + if (runner != null) { + // Default set to success + future.setResult( + new R66Result(null, true, runner.getErrorInfo(), + runner)); + future.setSuccess(); + } else { + future.setFailure(new WaarpDatabaseException("Transfer requested but internal error")); } } - } else { - // Only request - logger.info("Transfer information: " + runner.toShortString()); - future.setResult(new R66Result(null, true, runner.getErrorInfo(), runner)); - future.setSuccess(); } } diff --git a/src/main/java/org/waarp/openr66/configuration/FileBasedConfiguration.java b/src/main/java/org/waarp/openr66/configuration/FileBasedConfiguration.java index 500b4f9f7..95b72c54b 100644 --- a/src/main/java/org/waarp/openr66/configuration/FileBasedConfiguration.java +++ b/src/main/java/org/waarp/openr66/configuration/FileBasedConfiguration.java @@ -1801,6 +1801,7 @@ private static boolean loadDatabase(Configuration config, boolean initdb) { } DbConstant.admin = new DbAdmin(); // no database support DbConstant.noCommitAdmin = DbConstant.admin; + DAOFactory.initialize(); } else { String dbdriver = value.getString(); value = hashConfig.get(XML_DBSERVER); diff --git a/src/main/java/org/waarp/openr66/configuration/RuleFileBasedConfiguration.java b/src/main/java/org/waarp/openr66/configuration/RuleFileBasedConfiguration.java index 348ee767d..7b9174c12 100644 --- a/src/main/java/org/waarp/openr66/configuration/RuleFileBasedConfiguration.java +++ b/src/main/java/org/waarp/openr66/configuration/RuleFileBasedConfiguration.java @@ -150,6 +150,7 @@ public static void importRules(File configDirectory) File[] files = FileUtils.getFiles(configDirectory, new ExtensionFilter(EXT_RULE)); for (File file : files) { + logger.info("Load rule from {}", file.getAbsolutePath()); DbRule rule = getFromFile(file); logger.debug(rule.toString()); } @@ -238,7 +239,8 @@ public static String[] getHostIds(XmlValue value) { String[] idsArray = new String[0]; if (value == null || (value.getList() == null) || value.getList().isEmpty()) { logger - .info("Unable to find the Hostid for Rule, setting to the default"); + .debug("Unable to find the Hostid for Rule, setting to " + + "the default"); } else { @SuppressWarnings("unchecked") List ids = (List) value.getList(); @@ -588,7 +590,9 @@ private static void addToElement(Element element, DbRule rule) { task.add(newElement(DbRule.TASK_TYPE, array[rank][0])); task.add(newElement(DbRule.TASK_PATH, array[rank][1])); task.add(newElement(DbRule.TASK_DELAY, array[rank][2])); - task.add(newElement(DbRule.TASK_COMMENT, array[rank][3])); + if (array[rank].length > 3) { + task.add(newElement(DbRule.TASK_COMMENT, array[rank][3])); + } roottasks.add(task); } } diff --git a/src/main/java/org/waarp/openr66/dao/BusinessDAO.java b/src/main/java/org/waarp/openr66/dao/BusinessDAO.java index bdbc7d027..c09bcf9c8 100644 --- a/src/main/java/org/waarp/openr66/dao/BusinessDAO.java +++ b/src/main/java/org/waarp/openr66/dao/BusinessDAO.java @@ -2,7 +2,8 @@ import java.util.List; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Business; /** @@ -13,27 +14,29 @@ public interface BusinessDAO { /** * Retrieve all Business objects in a List from the persistance layer * - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List getAll() throws DAOException; + List getAll() throws DAOConnectionException; /** * Retrieve all Business objects corresponding to the given filters * in a List from the persistance layer * * @param filters List of filter - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List find(List filters) throws DAOException; + List find(List filters) throws DAOConnectionException; /** * Retrieve the Business object with the specified hostid from the * persistance layer * * @param hostid Hostid of the Business object requested - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - Business select(String hostid) throws DAOException; + Business select(String hostid) + throws DAOConnectionException, DAONoDataException; /** * Verify if a Business object with the specified hostid exists in @@ -42,40 +45,44 @@ public interface BusinessDAO { * @param hostid Hostid of the Business object verified * @return true if a Business object with the specified hostid exist; false * if no Business object correspond to the specified hostid. - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - boolean exist(String hostid) throws DAOException; + boolean exist(String hostid) throws DAOConnectionException; /** * Insert the specified Business object in the persistance layer * * @param business Business object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void insert(Business business) throws DAOException; + void insert(Business business) throws DAOConnectionException; /** * Update the specified Business object in the persistance layer * * @param business Business object to update - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void update(Business business) throws DAOException; + void update(Business business) + throws DAOConnectionException, DAONoDataException; /** * Remove the specified Business object from the persistance layer * * @param business Business object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void delete(Business business) throws DAOException; + void delete(Business business) + throws DAOConnectionException, DAONoDataException; /** * Remove all Business objects from the persistance layer * - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void deleteAll() throws DAOException; + void deleteAll() throws DAOConnectionException; void close(); } diff --git a/src/main/java/org/waarp/openr66/dao/DAOFactory.java b/src/main/java/org/waarp/openr66/dao/DAOFactory.java index 707155054..91cf827b7 100644 --- a/src/main/java/org/waarp/openr66/dao/DAOFactory.java +++ b/src/main/java/org/waarp/openr66/dao/DAOFactory.java @@ -1,8 +1,9 @@ package org.waarp.openr66.dao; import org.waarp.common.database.ConnectionFactory; +import org.waarp.common.utility.DetectionUtils; import org.waarp.openr66.dao.database.DBDAOFactory; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import org.waarp.openr66.dao.xml.XMLDAOFactory; @@ -33,48 +34,48 @@ public static DAOFactory getInstance() { * Return a BusinessDAO * * @return a ready to use BusinessDAO - * @throws DAOException if cannot create the DAO + * @throws DAOConnectionException if cannot create the DAO */ - public abstract BusinessDAO getBusinessDAO() throws DAOException; + public abstract BusinessDAO getBusinessDAO() throws DAOConnectionException; /** * Return a HostDAO * * @return a ready to use HostDAO - * @throws DAOException if cannot create the DAO + * @throws DAOConnectionException if cannot create the DAO */ - public abstract HostDAO getHostDAO() throws DAOException; + public abstract HostDAO getHostDAO() throws DAOConnectionException; /** * Return a LimitDAO * * @return a ready to use LimitDAO - * @throws DAOException if cannot create the DAO + * @throws DAOConnectionException if cannot create the DAO */ - public abstract LimitDAO getLimitDAO() throws DAOException; + public abstract LimitDAO getLimitDAO() throws DAOConnectionException; /** * Return a MultipleMonitorDAO * * @return a ready to use MultipleMonitorDAO - * @throws DAOException if cannot create the DAO + * @throws DAOConnectionException if cannot create the DAO */ public abstract MultipleMonitorDAO getMultipleMonitorDAO() - throws DAOException; + throws DAOConnectionException; /** * Return a RuleDAO * * @return a ready to use RuleDAO - * @throws DAOException if cannot create the DAO + * @throws DAOConnectionException if cannot create the DAO */ - public abstract RuleDAO getRuleDAO() throws DAOException; + public abstract RuleDAO getRuleDAO() throws DAOConnectionException; /** * Return a TransferDAO * * @return a ready to use TramsferDAO - * @throws DAOException if cannot create the DAO + * @throws DAOConnectionException if cannot create the DAO */ - public abstract TransferDAO getTransferDAO() throws DAOException; + public abstract TransferDAO getTransferDAO() throws DAOConnectionException; } diff --git a/src/main/java/org/waarp/openr66/dao/HostDAO.java b/src/main/java/org/waarp/openr66/dao/HostDAO.java index 845847bdb..52006466b 100644 --- a/src/main/java/org/waarp/openr66/dao/HostDAO.java +++ b/src/main/java/org/waarp/openr66/dao/HostDAO.java @@ -2,7 +2,8 @@ import java.util.List; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Host; /** @@ -13,25 +14,27 @@ public interface HostDAO { /** * Retrieve all Host objects in a List from the persistance layer * - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List getAll() throws DAOException; + List getAll() throws DAOConnectionException; /** * Retrieve all Host objects corresponding to the given filters * in a List from the persistance lsayer * * @param filters List of filter - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List find(List filters) throws DAOException; + List find(List filters) throws DAOConnectionException; /** * Retrieve the Host object with the specified hostid from the persistance layer * * @param hostid Hostid of the Host object requested - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - Host select(String hostid) throws DAOException; + Host select(String hostid) throws DAOConnectionException, + DAONoDataException; /** * Verify if a Host object with the specified hostid exists in @@ -40,40 +43,42 @@ public interface HostDAO { * @param hostid Hostid of the Host object verified * @return true if a Host object with the specified hostid exist; false * if no Host object correspond to the specified hostid. - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - boolean exist(String hostid) throws DAOException; + boolean exist(String hostid) throws DAOConnectionException; /** * Insert the specified Host object in the persistance layer * * @param host Host object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void insert(Host host) throws DAOException; + void insert(Host host) throws DAOConnectionException; /** * Update the specified Host object in the persistance layer * * @param host Host object to update - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void update(Host host) throws DAOException; + void update(Host host) throws DAOConnectionException, DAONoDataException; /** * Remove the specified Host object from the persistance layer * * @param host Host object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void delete(Host host) throws DAOException; + void delete(Host host) throws DAOConnectionException, DAONoDataException; /** * Remove all Host objects from the persistance layer * - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void deleteAll() throws DAOException; + void deleteAll() throws DAOConnectionException; void close(); } diff --git a/src/main/java/org/waarp/openr66/dao/LimitDAO.java b/src/main/java/org/waarp/openr66/dao/LimitDAO.java index d9e3fbb63..212953eca 100644 --- a/src/main/java/org/waarp/openr66/dao/LimitDAO.java +++ b/src/main/java/org/waarp/openr66/dao/LimitDAO.java @@ -2,7 +2,8 @@ import java.util.List; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Limit; /** @@ -13,25 +14,27 @@ public interface LimitDAO { /** * Retrieve all Limit objects in a List from the persistance layer * - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List getAll() throws DAOException; + List getAll() throws DAOConnectionException; /** * Retrieve all Limit objects correspondig to the given filters * in a List from the persistance layer * * @param filters List of filter - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List find(List filters) throws DAOException; + List find(List filters) throws DAOConnectionException; /** * Retrieve the Limit object with the specified hostid from the persistance layer * * @param hostid Hostid of the Limit object requested - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - Limit select(String hostid) throws DAOException; + Limit select(String hostid) + throws DAOConnectionException, DAONoDataException; /** * Verify if a Limit object with the specified hostid exists in @@ -40,40 +43,42 @@ public interface LimitDAO { * @param hostid Hostid of the Limit object verified * @return true if a Limit object with the specified hostid exist; false * if no Limit object correspond to the specified hostid. - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - boolean exist(String hostid) throws DAOException; + boolean exist(String hostid) throws DAOConnectionException; /** * Insert the specified Limit object in the persistance layer * * @param limit Limit object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void insert(Limit limit) throws DAOException; + void insert(Limit limit) throws DAOConnectionException; /** * Update the specified Limit object in the persistance layer * * @param limit Limit object to update - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void update(Limit limit) throws DAOException; + void update(Limit limit) throws DAOConnectionException, DAONoDataException; /** * Remove the specified Limit object from the persistance layer * * @param limit Limit object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void delete(Limit limit) throws DAOException; + void delete(Limit limit) throws DAOConnectionException, DAONoDataException; /** * Remove all Limit objects from the persistance layer * - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void deleteAll() throws DAOException; + void deleteAll() throws DAOConnectionException; void close(); } diff --git a/src/main/java/org/waarp/openr66/dao/MultipleMonitorDAO.java b/src/main/java/org/waarp/openr66/dao/MultipleMonitorDAO.java index d3e634a19..34196cf17 100644 --- a/src/main/java/org/waarp/openr66/dao/MultipleMonitorDAO.java +++ b/src/main/java/org/waarp/openr66/dao/MultipleMonitorDAO.java @@ -2,7 +2,8 @@ import java.util.List; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.MultipleMonitor; /** @@ -13,26 +14,29 @@ public interface MultipleMonitorDAO { /** * Retrieve all MultipleMonitor objects in a List from the persistance layer * - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List getAll() throws DAOException; + List getAll() throws DAOConnectionException; /** * Retrieve all MultipleMonitor objects corresponding to the given filters * in a List from the persistance layer * * @param filters List of filter - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List find(List filters) throws DAOException; + List find(List filters) throws + DAOConnectionException; /** * Retrieve the MultipleMonitor object with the specified hostid from the persistance layer * * @param hostid Hostid of the MultipleMonitor object requested - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - MultipleMonitor select(String hostid) throws DAOException; + MultipleMonitor select(String hostid) + throws DAOConnectionException, DAONoDataException; /** * Verify if a MultipleMonitor object with the specified hostid exists in @@ -41,40 +45,44 @@ public interface MultipleMonitorDAO { * @param hostid Hostid of the MultipleMonitor object verified * @return true if a MultipleMonitor object with the specified hostid exist; false * if no MultipleMonitor object correspond to the specified hostid. - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - boolean exist(String hostid) throws DAOException; + boolean exist(String hostid) throws DAOConnectionException; /** * Insert the specified MultipleMonitor object in the persistance layer * * @param multipleMonitor MultipleMonitor object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void insert(MultipleMonitor multipleMonitor) throws DAOException; + void insert(MultipleMonitor multipleMonitor) throws DAOConnectionException; /** * Update the specified MultipleMonitor object in the persistance layer * * @param multipleMonitor MultipleMonitor object to update - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void update(MultipleMonitor multipleMonitor) throws DAOException; + void update(MultipleMonitor multipleMonitor) + throws DAOConnectionException, DAONoDataException; /** * Remove the specified MultipleMonitor object from the persistance layer * * @param multipleMonitor MultipleMonitor object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void delete(MultipleMonitor multipleMonitor) throws DAOException; + void delete(MultipleMonitor multipleMonitor) + throws DAOConnectionException, DAONoDataException; /** * Remove all MultipleMonitor objects from the persistance layer * - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void deleteAll() throws DAOException; + void deleteAll() throws DAOConnectionException; void close(); } diff --git a/src/main/java/org/waarp/openr66/dao/RuleDAO.java b/src/main/java/org/waarp/openr66/dao/RuleDAO.java index f054c1d58..77d86b435 100644 --- a/src/main/java/org/waarp/openr66/dao/RuleDAO.java +++ b/src/main/java/org/waarp/openr66/dao/RuleDAO.java @@ -2,7 +2,8 @@ import java.util.List; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Rule; /** @@ -13,27 +14,29 @@ public interface RuleDAO { /** * Retrieve all Rule objects in a List from the persistance layer * - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List getAll() throws DAOException; + List getAll() throws DAOConnectionException; /** * Retrieve all Rule objects corresponding to the given filters * a List from the persistance layer * * @param filters List of filter - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List find(List filters) throws DAOException; + List find(List filters) throws DAOConnectionException; /** * Retrieve the Rule object with the specified Rulename from the * persistance layer * * @param rulename rulename of the Rule object requested - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - Rule select(String rulename) throws DAOException; + Rule select(String rulename) + throws DAOConnectionException, DAONoDataException; /** * Verify if a Rule object with the specified Rulename exists in @@ -42,40 +45,42 @@ public interface RuleDAO { * @param rulename rulename of the Rule object verified * @return true if a Rule object with the specified Rulename exist; false * if no Rule object correspond to the specified Rulename. - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - boolean exist(String rulename) throws DAOException; + boolean exist(String rulename) throws DAOConnectionException; /** * Insert the specified Rule object in the persistance layer * * @param rule Rule object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void insert(Rule rule) throws DAOException; + void insert(Rule rule) throws DAOConnectionException; /** * Update the specified Rule object in the persistance layer * * @param rule Rule object to update - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void update(Rule rule) throws DAOException; + void update(Rule rule) throws DAOConnectionException, DAONoDataException; /** * Remove the specified Rule object from the persistance layer * * @param rule Rule object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void delete(Rule rule) throws DAOException; + void delete(Rule rule) throws DAOConnectionException, DAONoDataException; /** * Remove all Rule objects from the persistance layer * - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void deleteAll() throws DAOException; + void deleteAll() throws DAOConnectionException; void close(); } diff --git a/src/main/java/org/waarp/openr66/dao/TransferDAO.java b/src/main/java/org/waarp/openr66/dao/TransferDAO.java index 711f110b0..68a43ebd8 100644 --- a/src/main/java/org/waarp/openr66/dao/TransferDAO.java +++ b/src/main/java/org/waarp/openr66/dao/TransferDAO.java @@ -2,7 +2,8 @@ import java.util.List; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Transfer; /** @@ -13,43 +14,80 @@ public interface TransferDAO { /** * Retrieve all Transfer objects in a List from the persistance layer * - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List getAll() throws DAOException; + List getAll() throws DAOConnectionException; /** * Retrieve all Transfer objects to the given filters * in a List from the persistance layer * * @param filters List of filter - * @throws DAOException If data access error occurs + * @throws DAOConnectionException If data access error occurs */ - List find(List filters) throws DAOException; + List find(List filters) throws DAOConnectionException; - List find(List filters, int limit) throws DAOException; + /** + * Retrieve all Transfer objects to the given filters + * in a List from the persistance layer + * + * @param filters List of filter + * @throws DAOConnectionException If data access error occurs + */ + List find(List filters, int limit) throws + DAOConnectionException; + /** + * Retrieve all Transfer objects to the given filters + * in a List from the persistance layer + * + * @param filters List of filter + * @throws DAOConnectionException If data access error occurs + */ List find(List filters, int limit, int offset) - throws DAOException; + throws DAOConnectionException; + /** + * Retrieve all Transfer objects to the given filters + * in a List from the persistance layer + * + * @param filters List of filter + * @throws DAOConnectionException If data access error occurs + */ List find(List filters, String column, boolean ascend) - throws DAOException; + throws DAOConnectionException; + /** + * Retrieve all Transfer objects to the given filters + * in a List from the persistance layer + * + * @param filters List of filter + * @throws DAOConnectionException If data access error occurs + */ List find(List filters, String column, boolean ascend, - int limit) throws DAOException; + int limit) throws DAOConnectionException; + /** + * Retrieve all Transfer objects to the given filters + * in a List from the persistance layer + * + * @param filters List of filter + * @throws DAOConnectionException If data access error occurs + */ List find(List filters, String column, boolean ascend, - int limit, int offset) throws DAOException; + int limit, int offset) throws DAOConnectionException; /** * Retrieve the Transfer object with the specified Special ID from the persistance layer * * @param id special ID of the Transfer object requested - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ Transfer select(long id, String requester, String requested, String owner) - throws DAOException; + throws DAOConnectionException, DAONoDataException; /** * Verify if a Transfer object with the specified Special ID exists in @@ -58,41 +96,45 @@ Transfer select(long id, String requester, String requested, String owner) * @param id special ID of the Transfer object verified * @return true if a Transfer object with the specified Special ID exist; false * if no Transfer object correspond to the specified Special ID. - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ boolean exist(long id, String requester, String requested, String owner) - throws DAOException; + throws DAOConnectionException; /** * Insert the specified Transfer object in the persistance layer * * @param transfer Transfer object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void insert(Transfer transfer) throws DAOException; + void insert(Transfer transfer) throws DAOConnectionException; /** * Update the specified Transfer object in the persistance layer * * @param transfer Transfer object to update - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void update(Transfer transfer) throws DAOException; + void update(Transfer transfer) + throws DAOConnectionException, DAONoDataException; /** * Remove the specified Transfer object from the persistance layer * * @param transfer Transfer object to insert - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs + * @throws DAONoDataException if no data are available */ - void delete(Transfer transfer) throws DAOException; + void delete(Transfer transfer) + throws DAOConnectionException, DAONoDataException; /** * Remove all Transfer objects from the persistance layer * - * @throws DAOException If a data access error occurs + * @throws DAOConnectionException If a data access error occurs */ - void deleteAll() throws DAOException; + void deleteAll() throws DAOConnectionException; void close(); } diff --git a/src/main/java/org/waarp/openr66/dao/database/DBBusinessDAO.java b/src/main/java/org/waarp/openr66/dao/database/DBBusinessDAO.java index 78dd2d2b8..18e1440a8 100644 --- a/src/main/java/org/waarp/openr66/dao/database/DBBusinessDAO.java +++ b/src/main/java/org/waarp/openr66/dao/database/DBBusinessDAO.java @@ -12,7 +12,8 @@ import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.openr66.dao.BusinessDAO; import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Business; import org.waarp.openr66.pojo.UpdatedInfo; @@ -71,34 +72,39 @@ public void close() { } @Override - public void delete(Business business) throws DAOException { + public void delete(Business business) + throws DAOConnectionException, DAONoDataException { PreparedStatement stm = null; try { stm = connection.prepareStatement(SQL_DELETE); setParameters(stm, business.getHostid()); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void deleteAll() throws DAOException { + public void deleteAll() throws DAOConnectionException { PreparedStatement stm = null; try { stm = connection.prepareStatement(SQL_DELETE_ALL); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public List getAll() throws DAOException { + public List getAll() throws DAOConnectionException { ArrayList businesses = new ArrayList(); PreparedStatement stm = null; ResultSet res = null; @@ -109,7 +115,7 @@ public List getAll() throws DAOException { businesses.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -118,7 +124,8 @@ public List getAll() throws DAOException { } @Override - public List find(List filters) throws DAOException { + public List find(List filters) throws + DAOConnectionException { ArrayList businesses = new ArrayList(); // Create the SQL query StringBuilder query = new StringBuilder(SQL_GET_ALL); @@ -148,7 +155,7 @@ public List find(List filters) throws DAOException { businesses.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -157,7 +164,7 @@ public List find(List filters) throws DAOException { } @Override - public boolean exist(String hostid) throws DAOException { + public boolean exist(String hostid) throws DAOConnectionException { PreparedStatement stm = null; ResultSet res = null; try { @@ -166,7 +173,7 @@ public boolean exist(String hostid) throws DAOException { res = executeQuery(stm); return res.next(); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -174,7 +181,8 @@ public boolean exist(String hostid) throws DAOException { } @Override - public Business select(String hostid) throws DAOException { + public Business select(String hostid) + throws DAOConnectionException, DAONoDataException { PreparedStatement stm = null; ResultSet res = null; try { @@ -183,18 +191,19 @@ public Business select(String hostid) throws DAOException { res = executeQuery(stm); if (res.next()) { return getFromResultSet(res); + } else { + throw new DAONoDataException(("No " + getClass().getName() + " found")); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); } - return null; } @Override - public void insert(Business business) throws DAOException { + public void insert(Business business) throws DAOConnectionException { Object[] params = { business.getHostid(), business.getBusiness(), @@ -210,14 +219,15 @@ public void insert(Business business) throws DAOException { setParameters(stm, params); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void update(Business business) throws DAOException { + public void update(Business business) + throws DAOConnectionException, DAONoDataException { Object[] params = { business.getHostid(), business.getBusiness(), @@ -232,9 +242,13 @@ public void update(Business business) throws DAOException { try { stm = connection.prepareStatement(SQL_UPDATE); setParameters(stm, params); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } diff --git a/src/main/java/org/waarp/openr66/dao/database/DBDAOFactory.java b/src/main/java/org/waarp/openr66/dao/database/DBDAOFactory.java index 5ad8c3dd7..929de96f8 100644 --- a/src/main/java/org/waarp/openr66/dao/database/DBDAOFactory.java +++ b/src/main/java/org/waarp/openr66/dao/database/DBDAOFactory.java @@ -11,7 +11,7 @@ import org.waarp.openr66.dao.database.mariadb.MariaDBTransferDAO; import org.waarp.openr66.dao.database.oracle.OracleTransferDAO; import org.waarp.openr66.dao.database.postgres.PostgreSQLTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; /** * DAOFactory for standard SQL databases @@ -27,52 +27,53 @@ public DBDAOFactory(ConnectionFactory factory) { } @Override - public DBBusinessDAO getBusinessDAO() throws DAOException { + public DBBusinessDAO getBusinessDAO() throws DAOConnectionException { try { return new DBBusinessDAO(connectionFactory.getConnection()); } catch (SQLException e) { - throw new DAOException("data access error", e); + throw new DAOConnectionException("data access error", e); } } @Override - public DBHostDAO getHostDAO() throws DAOException { + public DBHostDAO getHostDAO() throws DAOConnectionException { try { return new DBHostDAO(connectionFactory.getConnection()); } catch (SQLException e) { - throw new DAOException("data access error", e); + throw new DAOConnectionException("data access error", e); } } @Override - public DBLimitDAO getLimitDAO() throws DAOException { + public DBLimitDAO getLimitDAO() throws DAOConnectionException { try { return new DBLimitDAO(connectionFactory.getConnection()); } catch (SQLException e) { - throw new DAOException("data access error", e); + throw new DAOConnectionException("data access error", e); } } @Override - public DBMultipleMonitorDAO getMultipleMonitorDAO() throws DAOException { + public DBMultipleMonitorDAO getMultipleMonitorDAO() throws + DAOConnectionException { try { return new DBMultipleMonitorDAO(connectionFactory.getConnection()); } catch (SQLException e) { - throw new DAOException("data access error", e); + throw new DAOConnectionException("data access error", e); } } @Override - public DBRuleDAO getRuleDAO() throws DAOException { + public DBRuleDAO getRuleDAO() throws DAOConnectionException { try { return new DBRuleDAO(connectionFactory.getConnection()); } catch (SQLException e) { - throw new DAOException("data access error", e); + throw new DAOConnectionException("data access error", e); } } @Override - public DBTransferDAO getTransferDAO() throws DAOException { + public DBTransferDAO getTransferDAO() throws DAOConnectionException { try { DbProperties prop = connectionFactory.getProperties(); if (prop instanceof H2Properties) { @@ -86,10 +87,10 @@ public DBTransferDAO getTransferDAO() throws DAOException { } else if (prop instanceof PostgreSQLProperties) { return new PostgreSQLTransferDAO(connectionFactory.getConnection()); } else { - throw new DAOException("Unsupported database"); + throw new DAOConnectionException("Unsupported database"); } } catch (SQLException e) { - throw new DAOException("data access error", e); + throw new DAOConnectionException("data access error", e); } } diff --git a/src/main/java/org/waarp/openr66/dao/database/DBHostDAO.java b/src/main/java/org/waarp/openr66/dao/database/DBHostDAO.java index 53b0ac058..9d6a41c78 100644 --- a/src/main/java/org/waarp/openr66/dao/database/DBHostDAO.java +++ b/src/main/java/org/waarp/openr66/dao/database/DBHostDAO.java @@ -12,7 +12,8 @@ import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.openr66.dao.HostDAO; import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Host; import org.waarp.openr66.pojo.UpdatedInfo; @@ -69,7 +70,7 @@ public class DBHostDAO extends StatementExecutor implements HostDAO { protected Connection connection; - public DBHostDAO(Connection con) throws DAOException { + public DBHostDAO(Connection con) throws DAOConnectionException { this.connection = con; } @@ -83,34 +84,39 @@ public void close() { } @Override - public void delete(Host host) throws DAOException { + public void delete(Host host) + throws DAOConnectionException, DAONoDataException { PreparedStatement stm = null; try { stm = connection.prepareStatement(SQL_DELETE); setParameters(stm, host.getHostid()); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void deleteAll() throws DAOException { + public void deleteAll() throws DAOConnectionException { PreparedStatement stm = null; try { stm = connection.prepareStatement(SQL_DELETE_ALL); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public List getAll() throws DAOException { + public List getAll() throws DAOConnectionException { ArrayList hosts = new ArrayList(); PreparedStatement stm = null; ResultSet res = null; @@ -121,7 +127,7 @@ public List getAll() throws DAOException { hosts.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -130,7 +136,7 @@ public List getAll() throws DAOException { } @Override - public List find(List filters) throws DAOException { + public List find(List filters) throws DAOConnectionException { ArrayList hosts = new ArrayList(); // Create the SQL query StringBuilder query = new StringBuilder(SQL_GET_ALL); @@ -160,7 +166,7 @@ public List find(List filters) throws DAOException { hosts.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -169,7 +175,7 @@ public List find(List filters) throws DAOException { } @Override - public boolean exist(String hostid) throws DAOException { + public boolean exist(String hostid) throws DAOConnectionException { PreparedStatement stm = null; ResultSet res = null; try { @@ -178,7 +184,7 @@ public boolean exist(String hostid) throws DAOException { res = executeQuery(stm); return res.next(); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -186,7 +192,8 @@ public boolean exist(String hostid) throws DAOException { } @Override - public Host select(String hostid) throws DAOException { + public Host select(String hostid) + throws DAOConnectionException, DAONoDataException { PreparedStatement stm = null; ResultSet res = null; try { @@ -195,18 +202,19 @@ public Host select(String hostid) throws DAOException { res = executeQuery(stm); if (res.next()) { return getFromResultSet(res); + } else { + throw new DAONoDataException(("No " + getClass().getName() + " found")); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); } - return null; } @Override - public void insert(Host host) throws DAOException { + public void insert(Host host) throws DAOConnectionException { Object[] params = { host.getHostid(), host.getAddress(), @@ -226,14 +234,15 @@ public void insert(Host host) throws DAOException { setParameters(stm, params); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void update(Host host) throws DAOException { + public void update(Host host) + throws DAOConnectionException, DAONoDataException { Object[] params = { host.getHostid(), host.getAddress(), @@ -252,9 +261,13 @@ public void update(Host host) throws DAOException { try { stm = connection.prepareStatement(SQL_UPDATE); setParameters(stm, params); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } diff --git a/src/main/java/org/waarp/openr66/dao/database/DBLimitDAO.java b/src/main/java/org/waarp/openr66/dao/database/DBLimitDAO.java index 9d4e4f922..8ffd69519 100644 --- a/src/main/java/org/waarp/openr66/dao/database/DBLimitDAO.java +++ b/src/main/java/org/waarp/openr66/dao/database/DBLimitDAO.java @@ -12,7 +12,8 @@ import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.openr66.dao.LimitDAO; import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Limit; import org.waarp.openr66.pojo.UpdatedInfo; @@ -76,34 +77,39 @@ public void close() { } @Override - public void delete(Limit limit) throws DAOException { + public void delete(Limit limit) + throws DAOConnectionException, DAONoDataException { PreparedStatement stm = null; try { stm = connection.prepareStatement(SQL_DELETE); setParameters(stm, limit.getHostid()); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void deleteAll() throws DAOException { + public void deleteAll() throws DAOConnectionException { PreparedStatement stm = null; try { stm = connection.prepareStatement(SQL_DELETE_ALL); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public List getAll() throws DAOException { + public List getAll() throws DAOConnectionException { ArrayList limits = new ArrayList(); ResultSet res = null; PreparedStatement stm = null; @@ -114,7 +120,7 @@ public List getAll() throws DAOException { limits.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); closeResultSet(res); @@ -123,7 +129,8 @@ public List getAll() throws DAOException { } @Override - public List find(List filters) throws DAOException { + public List find(List filters) throws + DAOConnectionException { ArrayList limits = new ArrayList(); // Create the SQL query StringBuilder query = new StringBuilder(SQL_GET_ALL); @@ -153,7 +160,7 @@ public List find(List filters) throws DAOException { limits.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); closeResultSet(res); @@ -162,7 +169,7 @@ public List find(List filters) throws DAOException { } @Override - public boolean exist(String hostid) throws DAOException { + public boolean exist(String hostid) throws DAOConnectionException { PreparedStatement stm = null; ResultSet res = null; try { @@ -171,7 +178,7 @@ public boolean exist(String hostid) throws DAOException { res = executeQuery(stm); return res.next(); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); closeResultSet(res); @@ -179,7 +186,8 @@ public boolean exist(String hostid) throws DAOException { } @Override - public Limit select(String hostid) throws DAOException { + public Limit select(String hostid) + throws DAOConnectionException, DAONoDataException { PreparedStatement stm = null; ResultSet res = null; try { @@ -188,18 +196,19 @@ public Limit select(String hostid) throws DAOException { res = executeQuery(stm); if (res.next()) { return getFromResultSet(res); + } else { + throw new DAONoDataException(("No " + getClass().getName() + " found")); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); closeResultSet(res); } - return null; } @Override - public void insert(Limit limit) throws DAOException { + public void insert(Limit limit) throws DAOConnectionException { Object[] params = { limit.getHostid(), limit.getReadGlobalLimit(), @@ -216,14 +225,15 @@ public void insert(Limit limit) throws DAOException { setParameters(stm, params); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void update(Limit limit) throws DAOException { + public void update(Limit limit) + throws DAOConnectionException, DAONoDataException { Object[] params = { limit.getHostid(), limit.getReadGlobalLimit(), @@ -239,9 +249,13 @@ public void update(Limit limit) throws DAOException { try { stm = connection.prepareStatement(SQL_UPDATE); setParameters(stm, params); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } diff --git a/src/main/java/org/waarp/openr66/dao/database/DBMultipleMonitorDAO.java b/src/main/java/org/waarp/openr66/dao/database/DBMultipleMonitorDAO.java index 3aff4b635..17aa71207 100644 --- a/src/main/java/org/waarp/openr66/dao/database/DBMultipleMonitorDAO.java +++ b/src/main/java/org/waarp/openr66/dao/database/DBMultipleMonitorDAO.java @@ -12,7 +12,8 @@ import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.openr66.dao.MultipleMonitorDAO; import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.MultipleMonitor; /** @@ -66,34 +67,40 @@ public void close() { } @Override - public void delete(MultipleMonitor multipleMonitor) throws DAOException { + public void delete(MultipleMonitor multipleMonitor) throws + DAOConnectionException, + DAONoDataException { PreparedStatement stm = null; try { stm = connection.prepareStatement(SQL_DELETE); setParameters(stm, multipleMonitor.getHostid()); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void deleteAll() throws DAOException { + public void deleteAll() throws DAOConnectionException { PreparedStatement stm = null; try { stm = connection.prepareStatement(SQL_DELETE_ALL); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public List getAll() throws DAOException { + public List getAll() throws DAOConnectionException { ArrayList monitors = new ArrayList(); PreparedStatement stm = null; ResultSet res = null; @@ -104,7 +111,7 @@ public List getAll() throws DAOException { monitors.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -114,7 +121,7 @@ public List getAll() throws DAOException { @Override public List find(List filters) - throws DAOException { + throws DAOConnectionException { ArrayList monitors = new ArrayList(); // Create the SQL query StringBuilder query = new StringBuilder(SQL_GET_ALL); @@ -144,7 +151,7 @@ public List find(List filters) monitors.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -153,7 +160,7 @@ public List find(List filters) } @Override - public boolean exist(String hostid) throws DAOException { + public boolean exist(String hostid) throws DAOConnectionException { PreparedStatement stm = null; ResultSet res = null; try { @@ -162,7 +169,7 @@ public boolean exist(String hostid) throws DAOException { res = executeQuery(stm); return res.next(); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -170,7 +177,8 @@ public boolean exist(String hostid) throws DAOException { } @Override - public MultipleMonitor select(String hostid) throws DAOException { + public MultipleMonitor select(String hostid) + throws DAOConnectionException, DAONoDataException { PreparedStatement stm = null; ResultSet res = null; try { @@ -179,18 +187,20 @@ public MultipleMonitor select(String hostid) throws DAOException { res = executeQuery(stm); if (res.next()) { return getFromResultSet(res); + } else { + throw new DAONoDataException(("No " + getClass().getName() + " found")); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); } - return null; } @Override - public void insert(MultipleMonitor multipleMonitor) throws DAOException { + public void insert(MultipleMonitor multipleMonitor) throws + DAOConnectionException { Object[] params = { multipleMonitor.getHostid(), multipleMonitor.getCountConfig(), @@ -204,14 +214,16 @@ public void insert(MultipleMonitor multipleMonitor) throws DAOException { setParameters(stm, params); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void update(MultipleMonitor multipleMonitor) throws DAOException { + public void update(MultipleMonitor multipleMonitor) throws + DAOConnectionException, + DAONoDataException { Object[] params = { multipleMonitor.getHostid(), multipleMonitor.getCountConfig(), @@ -224,9 +236,13 @@ public void update(MultipleMonitor multipleMonitor) throws DAOException { try { stm = connection.prepareStatement(SQL_UPDATE); setParameters(stm, params); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } diff --git a/src/main/java/org/waarp/openr66/dao/database/DBRuleDAO.java b/src/main/java/org/waarp/openr66/dao/database/DBRuleDAO.java index 8f2cb3dd7..aac93621a 100644 --- a/src/main/java/org/waarp/openr66/dao/database/DBRuleDAO.java +++ b/src/main/java/org/waarp/openr66/dao/database/DBRuleDAO.java @@ -17,13 +17,14 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.UpdatedInfo; import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.openr66.dao.RuleDAO; import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import org.waarp.openr66.pojo.Rule; import org.waarp.openr66.pojo.RuleTask; @@ -107,34 +108,39 @@ public void close() { } @Override - public void delete(Rule rule) throws DAOException { + public void delete(Rule rule) + throws DAOConnectionException, DAONoDataException { PreparedStatement stm = null; try { stm = connection.prepareStatement(SQL_DELETE); setParameters(stm, rule.getName()); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void deleteAll() throws DAOException { + public void deleteAll() throws DAOConnectionException { PreparedStatement stm = null; try { stm = connection.prepareStatement(SQL_DELETE_ALL); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public List getAll() throws DAOException { + public List getAll() throws DAOConnectionException { ArrayList rules = new ArrayList(); PreparedStatement stm = null; ResultSet res = null; @@ -145,7 +151,7 @@ public List getAll() throws DAOException { rules.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -154,7 +160,7 @@ public List getAll() throws DAOException { } @Override - public List find(List filters) throws DAOException { + public List find(List filters) throws DAOConnectionException { ArrayList rules = new ArrayList(); // Create the SQL query StringBuilder query = new StringBuilder(SQL_GET_ALL); @@ -184,7 +190,7 @@ public List find(List filters) throws DAOException { rules.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -193,7 +199,7 @@ public List find(List filters) throws DAOException { } @Override - public boolean exist(String ruleName) throws DAOException { + public boolean exist(String ruleName) throws DAOConnectionException { PreparedStatement stm = null; ResultSet res = null; try { @@ -202,7 +208,7 @@ public boolean exist(String ruleName) throws DAOException { res = executeQuery(stm); return res.next(); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -210,7 +216,8 @@ public boolean exist(String ruleName) throws DAOException { } @Override - public Rule select(String ruleName) throws DAOException { + public Rule select(String ruleName) + throws DAOConnectionException, DAONoDataException { PreparedStatement stm = null; ResultSet res = null; try { @@ -219,18 +226,19 @@ public Rule select(String ruleName) throws DAOException { res = executeQuery(stm); if (res.next()) { return getFromResultSet(res); + } else { + throw new DAONoDataException(("No " + getClass().getName() + " found")); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); } - return null; } @Override - public void insert(Rule rule) throws DAOException { + public void insert(Rule rule) throws DAOConnectionException { Object[] params = { rule.getName(), rule.getXMLHostids(), @@ -254,14 +262,15 @@ public void insert(Rule rule) throws DAOException { setParameters(stm, params); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void update(Rule rule) throws DAOException { + public void update(Rule rule) + throws DAOConnectionException, DAONoDataException { Object[] params = { rule.getName(), rule.getXMLHostids(), @@ -284,16 +293,20 @@ public void update(Rule rule) throws DAOException { try { stm = connection.prepareStatement(SQL_UPDATE); setParameters(stm, params); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } protected Rule getFromResultSet(ResultSet set) throws SQLException, - DAOException { + DAOConnectionException { return new Rule( set.getString(ID_FIELD), set.getInt(MODE_TRANS_FIELD), @@ -311,7 +324,8 @@ protected Rule getFromResultSet(ResultSet set) throws SQLException, UpdatedInfo.valueOf(set.getInt(UPDATED_INFO_FIELD))); } - private List retrieveHostids(String xml) throws DAOException { + private List retrieveHostids(String xml) throws + DAOConnectionException { ArrayList res = new ArrayList(); if ((xml == null) || xml.equals("")) { return res; @@ -322,7 +336,7 @@ private List retrieveHostids(String xml) throws DAOException { document = DocumentBuilderFactory.newInstance(). newDocumentBuilder().parse(stream); } catch (Exception e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } document.getDocumentElement().normalize(); @@ -333,7 +347,8 @@ private List retrieveHostids(String xml) throws DAOException { return res; } - private List retrieveTasks(String xml) throws DAOException { + private List retrieveTasks(String xml) throws + DAOConnectionException { ArrayList res = new ArrayList(); if ((xml == null) || xml.equals("")) { return res; @@ -344,7 +359,7 @@ private List retrieveTasks(String xml) throws DAOException { document = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(stream); } catch (Exception e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } document.getDocumentElement().normalize(); diff --git a/src/main/java/org/waarp/openr66/dao/database/DBTransferDAO.java b/src/main/java/org/waarp/openr66/dao/database/DBTransferDAO.java index d115ed145..759f5d9e9 100644 --- a/src/main/java/org/waarp/openr66/dao/database/DBTransferDAO.java +++ b/src/main/java/org/waarp/openr66/dao/database/DBTransferDAO.java @@ -4,7 +4,6 @@ import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.Statement; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -12,13 +11,13 @@ import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.openr66.context.ErrorCode; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.database.DbConstant; import org.waarp.openr66.dao.TransferDAO; import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import org.waarp.openr66.pojo.Transfer; import org.waarp.openr66.pojo.UpdatedInfo; -import org.waarp.openr66.protocol.configuration.Configuration; /** * Implementation of TransferDAO for a standard SQL database @@ -159,7 +158,8 @@ public DBTransferDAO(Connection con) { } @Override - public void delete(Transfer transfer) throws DAOException { + public void delete(Transfer transfer) + throws DAOConnectionException, DAONoDataException { PreparedStatement stm = null; Object[] params = { transfer.getId(), @@ -170,29 +170,33 @@ public void delete(Transfer transfer) throws DAOException { try { stm = connection.prepareStatement(getDeleteRequest()); setParameters(stm, params); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void deleteAll() throws DAOException { + public void deleteAll() throws DAOConnectionException { PreparedStatement stm = null; try { stm = connection.prepareStatement(getDeleteAllRequest()); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public List getAll() throws DAOException { + public List getAll() throws DAOConnectionException { ArrayList transfers = new ArrayList(); PreparedStatement stm = null; ResultSet res = null; @@ -203,7 +207,7 @@ public List getAll() throws DAOException { transfers.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -231,7 +235,8 @@ private String prepareFindQuery(List filters, Object[] params) { } @Override - public List find(List filters) throws DAOException { + public List find(List filters) throws + DAOConnectionException { ArrayList transfers = new ArrayList(); // Create the SQL query Object[] params = new Object[filters.size()]; @@ -247,7 +252,7 @@ public List find(List filters) throws DAOException { transfers.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -256,7 +261,8 @@ public List find(List filters) throws DAOException { } @Override - public List find(List filters, int limit) throws DAOException { + public List find(List filters, int limit) throws + DAOConnectionException { ArrayList transfers = new ArrayList(); // Create the SQL query Object[] params = new Object[filters.size()]; @@ -277,7 +283,7 @@ public List find(List filters, int limit) throws DAOException transfers.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -287,7 +293,7 @@ public List find(List filters, int limit) throws DAOException @Override public List find(List filters, int limit, int offset) - throws DAOException { + throws DAOConnectionException { ArrayList transfers = new ArrayList(); // Create the SQL query Object[] params = new Object[filters.size()]; @@ -312,7 +318,7 @@ public List find(List filters, int limit, int offset) transfers.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -322,7 +328,7 @@ public List find(List filters, int limit, int offset) @Override public List find(List filters, String column, - boolean ascend) throws DAOException { + boolean ascend) throws DAOConnectionException { ArrayList transfers = new ArrayList(); // Create the SQL query Object[] params = new Object[filters.size()]; @@ -347,7 +353,7 @@ public List find(List filters, String column, transfers.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -357,7 +363,8 @@ public List find(List filters, String column, @Override public List find(List filters, String column, - boolean ascend, int limit) throws DAOException { + boolean ascend, int limit) throws + DAOConnectionException { ArrayList transfers = new ArrayList(); // Create the SQL query Object[] params = new Object[filters.size()]; @@ -385,7 +392,7 @@ public List find(List filters, String column, transfers.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -396,7 +403,7 @@ public List find(List filters, String column, @Override public List find(List filters, String column, boolean ascend, int limit, int offset) - throws DAOException { + throws DAOConnectionException { ArrayList transfers = new ArrayList(); // Create the SQL query Object[] params = new Object[filters.size()]; @@ -426,7 +433,7 @@ public List find(List filters, String column, transfers.add(getFromResultSet(res)); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -436,7 +443,7 @@ public List find(List filters, String column, @Override public boolean exist(long id, String requester, String requested, - String owner) throws DAOException { + String owner) throws DAOConnectionException { PreparedStatement stm = null; ResultSet res = null; Object[] params = { @@ -451,7 +458,7 @@ public boolean exist(long id, String requester, String requested, res = executeQuery(stm); return res.next(); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); @@ -460,7 +467,8 @@ public boolean exist(long id, String requester, String requested, @Override public Transfer select(long id, String requester, String requested, - String owner) throws DAOException { + String owner) + throws DAOConnectionException, DAONoDataException { PreparedStatement stm = null; ResultSet res = null; Object[] params = { @@ -475,20 +483,21 @@ public Transfer select(long id, String requester, String requested, res = executeQuery(stm); if (res.next()) { return getFromResultSet(res); + } else { + throw new DAONoDataException(("No " + getClass().getName() + " found")); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeResultSet(res); closeStatement(stm); } - return null; } - abstract protected long getNextId() throws DAOException; + abstract protected long getNextId() throws DAOConnectionException; @Override - public void insert(Transfer transfer) throws DAOException { + public void insert(Transfer transfer) throws DAOConnectionException { if (transfer.getId() == DbConstant.ILLEGALVALUE) { transfer.setId(getNextId()); } @@ -524,14 +533,15 @@ public void insert(Transfer transfer) throws DAOException { setParameters(stm, params); executeUpdate(stm); } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } } @Override - public void update(Transfer transfer) throws DAOException { + public void update(Transfer transfer) + throws DAOConnectionException, DAONoDataException { Object[] params = { transfer.getId(), transfer.getGlobalStep().ordinal(), @@ -565,9 +575,13 @@ public void update(Transfer transfer) throws DAOException { try { stm = connection.prepareStatement(getUpdateRequest()); setParameters(stm, params); - executeUpdate(stm); + try { + executeUpdate(stm); + } catch (SQLException e2) { + throw new DAONoDataException(e2); + } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(stm); } diff --git a/src/main/java/org/waarp/openr66/dao/database/StatementExecutor.java b/src/main/java/org/waarp/openr66/dao/database/StatementExecutor.java index 681cc2570..67938c053 100644 --- a/src/main/java/org/waarp/openr66/dao/database/StatementExecutor.java +++ b/src/main/java/org/waarp/openr66/dao/database/StatementExecutor.java @@ -26,7 +26,7 @@ public void executeUpdate(PreparedStatement stm) throws SQLException { if (res < 1) { logger.warn("Update failed, no record updated."); } else { - logger.info(res + " records updated."); + logger.debug(res + " records updated."); } } diff --git a/src/main/java/org/waarp/openr66/dao/database/h2/H2TransferDAO.java b/src/main/java/org/waarp/openr66/dao/database/h2/H2TransferDAO.java index 32bd9cff0..b1ff75a0e 100644 --- a/src/main/java/org/waarp/openr66/dao/database/h2/H2TransferDAO.java +++ b/src/main/java/org/waarp/openr66/dao/database/h2/H2TransferDAO.java @@ -6,18 +6,18 @@ import java.sql.SQLException; import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; public class H2TransferDAO extends DBTransferDAO { protected static String SQL_GET_ID = "SELECT NEXTVAL('RUNSEQ')"; - public H2TransferDAO(Connection con) throws DAOException { + public H2TransferDAO(Connection con) throws DAOConnectionException { super(con); } @Override - protected long getNextId() throws DAOException { + protected long getNextId() throws DAOConnectionException { PreparedStatement ps = null; try { ps = connection.prepareStatement(SQL_GET_ID); @@ -25,11 +25,11 @@ protected long getNextId() throws DAOException { if (rs.next()) { return rs.getLong(1); } else { - throw new DAOException( + throw new DAOConnectionException( "Error no id available, you should purge the database."); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(ps); } diff --git a/src/main/java/org/waarp/openr66/dao/database/mariadb/MariaDBTransferDAO.java b/src/main/java/org/waarp/openr66/dao/database/mariadb/MariaDBTransferDAO.java index 2b01364a7..3460ab6a5 100644 --- a/src/main/java/org/waarp/openr66/dao/database/mariadb/MariaDBTransferDAO.java +++ b/src/main/java/org/waarp/openr66/dao/database/mariadb/MariaDBTransferDAO.java @@ -1,7 +1,7 @@ package org.waarp.openr66.dao.database.mariadb; import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import java.sql.Connection; import java.sql.PreparedStatement; @@ -15,12 +15,12 @@ public class MariaDBTransferDAO extends DBTransferDAO { private static String SQL_UPDATE_ID = "UPDATE Sequences SET seq = ? " + "WHERE name='RUNSEQ'"; - public MariaDBTransferDAO(Connection con) throws DAOException { + public MariaDBTransferDAO(Connection con) throws DAOConnectionException { super(con); } @Override - protected long getNextId() throws DAOException { + protected long getNextId() throws DAOConnectionException { PreparedStatement ps = null; PreparedStatement ps2 = null; try { @@ -34,11 +34,11 @@ protected long getNextId() throws DAOException { ps2.executeUpdate(); return res; } else { - throw new DAOException( + throw new DAOConnectionException( "Error no id available, you should purge the database."); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(ps); closeStatement(ps2); diff --git a/src/main/java/org/waarp/openr66/dao/database/oracle/OracleTransferDAO.java b/src/main/java/org/waarp/openr66/dao/database/oracle/OracleTransferDAO.java index d8e49d089..e577c4c1e 100644 --- a/src/main/java/org/waarp/openr66/dao/database/oracle/OracleTransferDAO.java +++ b/src/main/java/org/waarp/openr66/dao/database/oracle/OracleTransferDAO.java @@ -6,18 +6,18 @@ import java.sql.SQLException; import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; public class OracleTransferDAO extends DBTransferDAO { protected static String SQL_GET_ID = "SELECT runseq.nextval FROM DUAL"; - public OracleTransferDAO(Connection con) throws DAOException { + public OracleTransferDAO(Connection con) throws DAOConnectionException { super(con); } @Override - protected long getNextId() throws DAOException { + protected long getNextId() throws DAOConnectionException { PreparedStatement ps = null; try { ps = connection.prepareStatement(SQL_GET_ID); @@ -25,11 +25,11 @@ protected long getNextId() throws DAOException { if (rs.next()) { return rs.getLong(1); } else { - throw new DAOException( + throw new DAOConnectionException( "Error no id available, you should purge the database."); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(ps); } diff --git a/src/main/java/org/waarp/openr66/dao/database/postgres/PostgreSQLTransferDAO.java b/src/main/java/org/waarp/openr66/dao/database/postgres/PostgreSQLTransferDAO.java index 05b7895de..a9fd834d2 100644 --- a/src/main/java/org/waarp/openr66/dao/database/postgres/PostgreSQLTransferDAO.java +++ b/src/main/java/org/waarp/openr66/dao/database/postgres/PostgreSQLTransferDAO.java @@ -6,18 +6,18 @@ import java.sql.SQLException; import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; public class PostgreSQLTransferDAO extends DBTransferDAO { protected static String SQL_GET_ID = "SELECT NEXTVAL('runseq')"; - public PostgreSQLTransferDAO(Connection con) throws DAOException { + public PostgreSQLTransferDAO(Connection con) throws DAOConnectionException { super(con); } @Override - protected long getNextId() throws DAOException { + protected long getNextId() throws DAOConnectionException { PreparedStatement ps = null; try { ps = connection.prepareStatement(SQL_GET_ID); @@ -25,11 +25,11 @@ protected long getNextId() throws DAOException { if (rs.next()) { return rs.getLong(1); } else { - throw new DAOException( + throw new DAOConnectionException( "Error no id available, you should purge the database."); } } catch (SQLException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { closeStatement(ps); } diff --git a/src/main/java/org/waarp/openr66/dao/exception/DAOConnectionException.java b/src/main/java/org/waarp/openr66/dao/exception/DAOConnectionException.java new file mode 100644 index 000000000..038a1723c --- /dev/null +++ b/src/main/java/org/waarp/openr66/dao/exception/DAOConnectionException.java @@ -0,0 +1,22 @@ +package org.waarp.openr66.dao.exception; + +import java.lang.Exception; +import java.lang.Throwable; + +/** + * Connection DAO Exception + */ +public class DAOConnectionException extends DAOException { + + public DAOConnectionException(String message) { + super(message); + } + + public DAOConnectionException(Throwable cause) { + super(cause); + } + + public DAOConnectionException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/org/waarp/openr66/dao/exception/DAOException.java b/src/main/java/org/waarp/openr66/dao/exception/DAOException.java index 2f4b9a811..2b9ab21f7 100644 --- a/src/main/java/org/waarp/openr66/dao/exception/DAOException.java +++ b/src/main/java/org/waarp/openr66/dao/exception/DAOException.java @@ -1,8 +1,8 @@ package org.waarp.openr66.dao.exception; -import java.lang.Exception; -import java.lang.Throwable; - +/** + * Parent Exception of DAO + */ public class DAOException extends Exception { public DAOException(String message) { diff --git a/src/main/java/org/waarp/openr66/dao/exception/DAONoDataException.java b/src/main/java/org/waarp/openr66/dao/exception/DAONoDataException.java new file mode 100644 index 000000000..ca6122ec5 --- /dev/null +++ b/src/main/java/org/waarp/openr66/dao/exception/DAONoDataException.java @@ -0,0 +1,19 @@ +package org.waarp.openr66.dao.exception; + +/** + * Exception when no data found in select or update + */ +public class DAONoDataException extends DAOException { + + public DAONoDataException(String message) { + super(message); + } + + public DAONoDataException(Throwable cause) { + super(cause); + } + + public DAONoDataException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/src/main/java/org/waarp/openr66/dao/xml/XMLBusinessDAO.java b/src/main/java/org/waarp/openr66/dao/xml/XMLBusinessDAO.java index 9216af623..5cab3efdf 100644 --- a/src/main/java/org/waarp/openr66/dao/xml/XMLBusinessDAO.java +++ b/src/main/java/org/waarp/openr66/dao/xml/XMLBusinessDAO.java @@ -1,15 +1,16 @@ package org.waarp.openr66.dao.xml; import org.w3c.dom.Document; -import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.openr66.dao.BusinessDAO; import org.waarp.openr66.dao.Filter; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Business; +import org.waarp.openr66.pojo.Host; import org.xml.sax.SAXException; import javax.xml.namespace.QName; @@ -17,16 +18,23 @@ import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.*; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ConcurrentHashMap; //TODO public class XMLBusinessDAO implements BusinessDAO { private static final WaarpLogger logger = WaarpLoggerFactory.getLogger(XMLBusinessDAO.class); + /** + * HashTable in case of lack of database + */ + private static final ConcurrentHashMap + dbR66BusinessHashMap = + new ConcurrentHashMap(); + public static final String HOSTID_FIELD = "hostid"; private static final String XML_SELECT = "/authent/entry[hostid=$hostid]"; @@ -34,23 +42,23 @@ public class XMLBusinessDAO implements BusinessDAO { private File file; - public XMLBusinessDAO(String filePath) throws DAOException { + public XMLBusinessDAO(String filePath) throws DAOConnectionException { this.file = new File(filePath); } public void close() {} - public void delete(Business business) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void delete(Business business) throws DAOConnectionException { + dbR66BusinessHashMap.remove(business.getHostid()); } - public void deleteAll() throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void deleteAll() throws DAOConnectionException { + dbR66BusinessHashMap.clear(); } - public List getAll() throws DAOException { + public List getAll() throws DAOConnectionException { if (!file.exists()) { - throw new DAOException("File doesn't exist"); + throw new DAOConnectionException("File doesn't exist"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -64,23 +72,28 @@ public List getAll() throws DAOException { List res = new ArrayList(listNode.getLength()); for (int i = 0; i < listNode.getLength(); i++) { Node node = listNode.item(i); - res.add(getFromNode(node)); + Business business = getFromNode(node); + res.add(business); + dbR66BusinessHashMap.put(business.getHostid(), business); } return res; } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } - public boolean exist(String hostid) throws DAOException { + public boolean exist(String hostid) throws DAOConnectionException { + if (dbR66BusinessHashMap.containsKey(hostid)) { + return true; + } if (!file.exists()) { - throw new DAOException("File doesn't exist"); + throw new DAOConnectionException("File doesn't exist"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -95,27 +108,33 @@ public boolean exist(String hostid) throws DAOException { // Query will return "" if nothing is found return(!"".equals(xpe.evaluate(document))); } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } - public List find(List fitlers) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public List find(List fitlers) throws + DAOConnectionException { + throw new DAOConnectionException("Operation not supported on XML DAO"); } - public void insert(Business business) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void insert(Business business) throws DAOConnectionException { + dbR66BusinessHashMap.put(business.getHostid(), business); } - public Business select(String hostid) throws DAOException { + public Business select(String hostid) + throws DAOConnectionException, DAONoDataException { + Business business = dbR66BusinessHashMap.get(hostid); + if (business != null) { + return business; + } if (!file.exists()) { - throw new DAOException("File doesn't exist"); + throw new DAOConnectionException("File doesn't exist"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -130,22 +149,24 @@ public Business select(String hostid) throws DAOException { // Retrieve node and instantiate object Node node = (Node) xpe.evaluate(document, XPathConstants.NODE); if (node != null) { - return getFromNode(node); + business = getFromNode(node); + dbR66BusinessHashMap.put(business.getHostid(), business); + return business; } - return null; + throw new DAONoDataException("Business not found"); } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } - public void update(Business business) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void update(Business business) throws DAOConnectionException { + dbR66BusinessHashMap.put(business.getHostid(), business); } private Business getFromNode(Node parent) { diff --git a/src/main/java/org/waarp/openr66/dao/xml/XMLDAOFactory.java b/src/main/java/org/waarp/openr66/dao/xml/XMLDAOFactory.java index cbe480714..77ad26e5b 100644 --- a/src/main/java/org/waarp/openr66/dao/xml/XMLDAOFactory.java +++ b/src/main/java/org/waarp/openr66/dao/xml/XMLDAOFactory.java @@ -1,7 +1,7 @@ package org.waarp.openr66.dao.xml; import org.waarp.openr66.dao.*; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import org.waarp.openr66.protocol.configuration.Configuration; public class XMLDAOFactory extends DAOFactory { @@ -18,32 +18,33 @@ public XMLDAOFactory() {} @Override - public BusinessDAO getBusinessDAO() throws DAOException { + public BusinessDAO getBusinessDAO() throws DAOConnectionException { return new XMLBusinessDAO(businessFile); } @Override - public HostDAO getHostDAO() throws DAOException { + public HostDAO getHostDAO() throws DAOConnectionException { return new XMLHostDAO(hostFile); } @Override - public LimitDAO getLimitDAO() throws DAOException { - return new XMLimitDAO(limitFile); + public LimitDAO getLimitDAO() throws DAOConnectionException { + return new XMLLimitDAO(limitFile); } @Override - public MultipleMonitorDAO getMultipleMonitorDAO() throws DAOException { - throw new DAOException("MultipleMonitor is not supported on XML DAO"); + public MultipleMonitorDAO getMultipleMonitorDAO() throws + DAOConnectionException { + throw new DAOConnectionException("MultipleMonitor is not supported on XML DAO"); } @Override - public RuleDAO getRuleDAO() throws DAOException { + public RuleDAO getRuleDAO() throws DAOConnectionException { return new XMLRuleDAO(ruleFile); } @Override - public TransferDAO getTransferDAO() throws DAOException { + public TransferDAO getTransferDAO() throws DAOConnectionException { return new XMLTransferDAO(transferFile); } } diff --git a/src/main/java/org/waarp/openr66/dao/xml/XMLHostDAO.java b/src/main/java/org/waarp/openr66/dao/xml/XMLHostDAO.java index bc85b788e..879d980ab 100644 --- a/src/main/java/org/waarp/openr66/dao/xml/XMLHostDAO.java +++ b/src/main/java/org/waarp/openr66/dao/xml/XMLHostDAO.java @@ -1,14 +1,15 @@ package org.waarp.openr66.dao.xml; import org.w3c.dom.Document; -import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.HostDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; +import org.waarp.openr66.database.data.DbHostAuth; import org.waarp.openr66.pojo.Host; import org.xml.sax.SAXException; @@ -17,16 +18,23 @@ import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.*; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ConcurrentHashMap; public class XMLHostDAO implements HostDAO { private static final WaarpLogger logger = WaarpLoggerFactory.getLogger(XMLHostDAO.class); + /** + * HashTable in case of lack of database + */ + private static final ConcurrentHashMap + dbR66HostAuthHashMap = + new ConcurrentHashMap(); + public static final String HOSTID_FIELD = "hostid"; public static final String ADDRESS_FIELD = "address"; public static final String PORT_FIELD = "port"; @@ -48,17 +56,17 @@ public XMLHostDAO(String filePath) { public void close() {} - public void delete(Host host) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void delete(Host host) throws DAOConnectionException { + dbR66HostAuthHashMap.remove(host.getHostid()); } - public void deleteAll() throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void deleteAll() throws DAOConnectionException { + dbR66HostAuthHashMap.clear(); } - public List getAll() throws DAOException { + public List getAll() throws DAOConnectionException { if (!file.exists()) { - throw new DAOException("File doesn't exist"); + throw new DAOConnectionException("File doesn't exist"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -72,23 +80,28 @@ public List getAll() throws DAOException { List res = new ArrayList(listNode.getLength()); for (int i = 0; i < listNode.getLength(); i++) { Node node = listNode.item(i); - res.add(getFromNode(node)); + Host host = getFromNode(node); + res.add(host); + dbR66HostAuthHashMap.put(host.getHostid(), host); } return res; } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } - public boolean exist(String hostid) throws DAOException { + public boolean exist(String hostid) throws DAOConnectionException { + if (dbR66HostAuthHashMap.containsKey(hostid)) { + return true; + } if (!file.exists()) { - throw new DAOException("File doesn't exist"); + throw new DAOConnectionException("File doesn't exist"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -103,27 +116,32 @@ public boolean exist(String hostid) throws DAOException { // Query will return "" if nothing is found return(!"".equals(xpe.evaluate(document))); } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } - public List find(List fitlers) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public List find(List fitlers) throws DAOConnectionException { + throw new DAOConnectionException("Operation not supported on XML DAO"); } - public void insert(Host host) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void insert(Host host) throws DAOConnectionException { + dbR66HostAuthHashMap.put(host.getHostid(), host); } - public Host select(String hostid) throws DAOException { + public Host select(String hostid) + throws DAOConnectionException, DAONoDataException { + Host host = dbR66HostAuthHashMap.get(hostid); + if (host != null) { + return host; + } if (!file.exists()) { - throw new DAOException("File " + file.getPath() + " doesn't exist"); + throw new DAOConnectionException("File " + file.getPath() + " doesn't exist"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -138,22 +156,24 @@ public Host select(String hostid) throws DAOException { // Retrieve node and instantiate object Node node = (Node) xpe.evaluate(document, XPathConstants.NODE); if (node != null) { - return getFromNode(node); + host = getFromNode(node); + dbR66HostAuthHashMap.put(host.getHostid(), host); + return host; } - return null; + throw new DAONoDataException("Host not found"); } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } - public void update(Host host) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void update(Host host) throws DAOConnectionException { + dbR66HostAuthHashMap.put(host.getHostid(), host); } private Host getFromNode(Node parent) { diff --git a/src/main/java/org/waarp/openr66/dao/xml/XMLimitDAO.java b/src/main/java/org/waarp/openr66/dao/xml/XMLLimitDAO.java similarity index 61% rename from src/main/java/org/waarp/openr66/dao/xml/XMLimitDAO.java rename to src/main/java/org/waarp/openr66/dao/xml/XMLLimitDAO.java index cd2f2f347..0074bc9c8 100644 --- a/src/main/java/org/waarp/openr66/dao/xml/XMLimitDAO.java +++ b/src/main/java/org/waarp/openr66/dao/xml/XMLLimitDAO.java @@ -1,14 +1,14 @@ package org.waarp.openr66.dao.xml; import org.w3c.dom.Document; -import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.LimitDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Limit; import org.xml.sax.SAXException; @@ -17,15 +17,22 @@ import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.*; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; +import java.util.concurrent.ConcurrentHashMap; //TODO -public class XMLimitDAO implements LimitDAO { +public class XMLLimitDAO implements LimitDAO { - private static final WaarpLogger logger = WaarpLoggerFactory.getLogger(XMLimitDAO.class); + private static final WaarpLogger logger = WaarpLoggerFactory.getLogger( + XMLLimitDAO.class); + + /** + * HashTable in case of lack of database + */ + private static final ConcurrentHashMap dbR66ConfigurationHashMap = + new ConcurrentHashMap(); public static final String HOSTID_FIELD = "hostid"; public static final String SESSION_LIMIT_FILED = "sessionlimit"; @@ -39,44 +46,49 @@ public class XMLimitDAO implements LimitDAO { private File file; - public XMLimitDAO(String filePath) throws DAOException { + public XMLLimitDAO(String filePath) throws DAOConnectionException { this.file = new File(filePath); } public void close() {} - public void delete(Limit limit) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void delete(Limit limit) throws DAOConnectionException { + dbR66ConfigurationHashMap.remove(limit.getHostid()); } - public void deleteAll() throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void deleteAll() throws DAOConnectionException { + dbR66ConfigurationHashMap.clear(); } - public List getAll() throws DAOException { + public List getAll() throws DAOConnectionException { if (!file.exists()) { - throw new DAOException("File doesn't exist"); + throw new DAOConnectionException("File doesn't exist"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document document = dbf.newDocumentBuilder().parse(file); // File contains only 1 entry List res = new ArrayList(1); - res.add(getFromNode(document.getDocumentElement())); + Limit limit = getFromNode(document.getDocumentElement()); + res.add(limit); + dbR66ConfigurationHashMap.put(limit.getHostid(), limit); // Iterate through all found nodes return res; } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } - public boolean exist(String hostid) throws DAOException { + public boolean exist(String hostid) throws DAOConnectionException { + if (dbR66ConfigurationHashMap.containsKey(hostid)) { + return true; + } if (!file.exists()) { - throw new DAOException("File doesn't exist"); + throw new DAOConnectionException("File doesn't exist"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -91,27 +103,33 @@ public boolean exist(String hostid) throws DAOException { // Query will return "" if nothing is found return(!"".equals(xpe.evaluate(document))); } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } - public List find(List fitlers) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public List find(List fitlers) throws + DAOConnectionException { + throw new DAOConnectionException("Operation not supported on XML DAO"); } - public void insert(Limit limit) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void insert(Limit limit) throws DAOConnectionException { + dbR66ConfigurationHashMap.put(limit.getHostid(), limit); } - public Limit select(String hostid) throws DAOException { + public Limit select(String hostid) + throws DAOConnectionException, DAONoDataException { + Limit limit = dbR66ConfigurationHashMap.get(hostid); + if (limit != null) { + return limit; + } if (!file.exists()) { - throw new DAOException("File doesn't exist"); + throw new DAOConnectionException("File doesn't exist"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -126,22 +144,24 @@ public Limit select(String hostid) throws DAOException { // Retrieve node and instantiate object Node node = (Node) xpe.evaluate(document, XPathConstants.NODE); if (node != null) { - return getFromNode(document.getDocumentElement()); + limit = getFromNode(document.getDocumentElement()); + dbR66ConfigurationHashMap.put(limit.getHostid(), limit); + return limit; } - return null; + throw new DAONoDataException("Limit not found"); } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } - public void update(Limit limit) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void update(Limit limit) throws DAOConnectionException { + dbR66ConfigurationHashMap.put(limit.getHostid(), limit); } private Limit getFromNode(Node parent) { diff --git a/src/main/java/org/waarp/openr66/dao/xml/XMLRuleDAO.java b/src/main/java/org/waarp/openr66/dao/xml/XMLRuleDAO.java index 97e2d5b89..6f486c096 100644 --- a/src/main/java/org/waarp/openr66/dao/xml/XMLRuleDAO.java +++ b/src/main/java/org/waarp/openr66/dao/xml/XMLRuleDAO.java @@ -7,15 +7,15 @@ import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.openr66.configuration.ExtensionFilter; -import org.waarp.openr66.dao.DAOFactory; import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.RuleDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; +import org.waarp.openr66.database.data.DbRule; import org.waarp.openr66.pojo.Rule; import org.waarp.openr66.pojo.RuleTask; import org.waarp.openr66.protocol.configuration.Configuration; import org.xml.sax.SAXException; -import sun.security.krb5.Config; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; @@ -25,11 +25,18 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.concurrent.ConcurrentHashMap; public class XMLRuleDAO implements RuleDAO { private static final WaarpLogger logger = WaarpLoggerFactory.getLogger(XMLRuleDAO.class); + /** + * HashTable in case of lack of database + */ + private static final ConcurrentHashMap dbR66RuleHashMap = + new ConcurrentHashMap(); + public static final String ROOT_LIST = "rules"; public static final String ROOT_ELEMENT = "rule"; @@ -74,15 +81,15 @@ private File[] getRuleFiles() { return res.toArray(new File[0]); } - public void delete(Rule rule) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void delete(Rule rule) throws DAOConnectionException { + dbR66RuleHashMap.remove(rule.getName()); } - public void deleteAll() throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void deleteAll() throws DAOConnectionException { + dbR66RuleHashMap.clear(); } - public List getAll() throws DAOException { + public List getAll() throws DAOConnectionException { List res = new ArrayList(); File[] files = getRuleFiles(); @@ -99,96 +106,48 @@ public List getAll() throws DAOException { for (int i = 0; i < listNode.getLength(); i++) { Node node = listNode.item(i); - res.add(getFromNode(node)); + Rule rule = getFromNode(node); + res.add(rule); + dbR66RuleHashMap.put(rule.getName(), rule); } } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } return res; } - public boolean exist(String rulename) throws DAOException { - File[] files = getRuleFiles(); - for (File ruleFile : files) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - Document document = dbf.newDocumentBuilder().parse(ruleFile); - // Setup XPath variable - SimpleVariableResolver resolver = new SimpleVariableResolver(); - resolver.addVariable(new QName(null, "idrule"), rulename); - // Setup XPath query - XPath xPath = XPathFactory.newInstance().newXPath(); - xPath.setXPathVariableResolver(resolver); - XPathExpression xpe = xPath.compile(XML_SELECT); - // Query will return "" if nothing is found - if (!"".equals(xpe.evaluate(document))) { - return true; - } - } catch (SAXException e) { - throw new DAOException(e); - } catch (XPathExpressionException e) { - throw new DAOException(e); - } catch (ParserConfigurationException e) { - throw new DAOException(e); - } catch (IOException e) { - throw new DAOException(e); - } - } - return false; + public boolean exist(String rulename) throws DAOConnectionException { + return dbR66RuleHashMap.containsKey(rulename); } - public List find(List fitlers) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public List find(List fitlers) throws DAOConnectionException { + throw new DAOConnectionException("Operation not supported on XML DAO"); } - public void insert(Rule rule) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void insert(Rule rule) throws DAOConnectionException { + dbR66RuleHashMap.put(rule.getName(), rule); } - public Rule select(String rulename) throws DAOException { - File[] files = getRuleFiles(); - for (File ruleFile : files) { - try { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - Document document = dbf.newDocumentBuilder().parse(ruleFile); - // Setup XPath variable - SimpleVariableResolver resolver = new SimpleVariableResolver(); - resolver.addVariable(new QName(null, "idrule"), rulename); - // Setup XPath query - XPath xPath = XPathFactory.newInstance().newXPath(); - xPath.setXPathVariableResolver(resolver); - XPathExpression xpe = xPath.compile(XML_SELECT); - // Retrieve node and instantiate object - Node node = (Node) xpe.evaluate(document, XPathConstants.NODE); - if (node != null) { - return getFromNode(node); - } - return null; - } catch (SAXException e) { - throw new DAOException(e); - } catch (XPathExpressionException e) { - throw new DAOException(e); - } catch (ParserConfigurationException e) { - throw new DAOException(e); - } catch (IOException e) { - throw new DAOException(e); - } + public Rule select(String rulename) + throws DAOConnectionException, DAONoDataException { + if (exist(rulename)) { + return dbR66RuleHashMap.get(rulename); } - return null; + throw new DAONoDataException("Rule cannot be found"); } - public void update(Rule rule) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void update(Rule rule) throws DAOConnectionException { + dbR66RuleHashMap.put(rule.getName(), rule); } - private Rule getFromNode(Node parent) throws DAOException { + private Rule getFromNode(Node parent) throws DAOConnectionException { Rule res = new Rule(); NodeList children = parent.getChildNodes(); @@ -259,7 +218,8 @@ private Node getNode(Document doc, Rule rule) { public static final String HOSTID_FIELD = "hostid"; - private List retrieveHostids(String xml) throws DAOException { + private List retrieveHostids(String xml) throws + DAOConnectionException { ArrayList res = new ArrayList(); if ((xml == null) || xml.equals("")) { return res; @@ -271,11 +231,11 @@ private List retrieveHostids(String xml) throws DAOException { document = DocumentBuilderFactory.newInstance(). newDocumentBuilder().parse(stream); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } finally { if (stream != null) { try { @@ -299,7 +259,8 @@ private List retrieveHostids(String xml) throws DAOException { public static final String PATH_FIELD = "path"; public static final String DELAY_FIELD = "delay"; - private List retrieveTasks(Node src) throws DAOException { + private List retrieveTasks(Node src) throws + DAOConnectionException { List res = new ArrayList(); NodeList feed = src.getChildNodes(); for (int i = 0; i < feed.getLength(); i++) { diff --git a/src/main/java/org/waarp/openr66/dao/xml/XMLTransferDAO.java b/src/main/java/org/waarp/openr66/dao/xml/XMLTransferDAO.java index af695a58d..5adf59a44 100644 --- a/src/main/java/org/waarp/openr66/dao/xml/XMLTransferDAO.java +++ b/src/main/java/org/waarp/openr66/dao/xml/XMLTransferDAO.java @@ -6,22 +6,23 @@ import org.w3c.dom.NodeList; import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; +import org.waarp.common.lru.SynchronizedLruCache; import org.waarp.common.utility.LongUuid; import org.waarp.openr66.context.ErrorCode; import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.TransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; +import org.waarp.openr66.database.data.DbTaskRunner; import org.waarp.openr66.pojo.Transfer; import org.waarp.openr66.protocol.configuration.Configuration; import org.xml.sax.SAXException; import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.*; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; import java.sql.Timestamp; import java.util.ArrayList; @@ -60,6 +61,65 @@ public class XMLTransferDAO implements TransferDAO { "requested='$requested' and ownerreq='ownerreq']"; private static final String XML_GET_ALL= "runner"; + + /** + * HashTable in case of lack of database using LRU mode with + * 20 000 items maximum (< 200 MB?) for 180s + */ + private static SynchronizedLruCache dbR66TaskHashMap; + + /** + * Create the LRU cache + * + * @param limit + * limit of number of entries in the cache + * @param ttl + * time to leave used + */ + public static void createLruCache(int limit, long ttl) { + dbR66TaskHashMap = new SynchronizedLruCache(limit, ttl); + } + + public static String hashStatus() { + return "DbTaskRunner: [dbR66TaskHashMap: " + dbR66TaskHashMap.size() + "] "; + } + + /** + * To enable clear of oldest entries in the cache + * + * @return the number of elements removed + */ + public static int clearCache() { + return dbR66TaskHashMap.forceClearOldest(); + } + + /** + * To update the TTL for the cache (to 10xTIMEOUT) + * + * @param ttl + */ + public static void updateLruCacheTimeout(long ttl) { + dbR66TaskHashMap.setNewTtl(ttl); + } + + /** + * To allow to remove specifically one SpecialId from MemoryHashmap + * + * @param specialId + */ + public static final void removeNoDbSpecialId(long specialId) { + dbR66TaskHashMap.remove(specialId); + } + + /** + * To update the usage TTL of the associated object + * + * @param specialId + */ + public static final void updateUsed(long specialId) { + dbR66TaskHashMap.updateTtl(specialId); + } + private File file; public XMLTransferDAO(String filePath) { @@ -78,15 +138,16 @@ private File getFile(String requester, String requested, long id) { + id + XMLEXTENSION); } - public void delete(Transfer transfer) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void delete(Transfer transfer) throws DAOConnectionException { + removeNoDbSpecialId(transfer.getId()); } - public void deleteAll() throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public void deleteAll() throws DAOConnectionException { + dbR66TaskHashMap.clear(); + throw new DAOConnectionException("Operation not supported on XML DAO"); } - public List getAll() throws DAOException { + public List getAll() throws DAOConnectionException { File arch = new File(Configuration.configuration.getArchivePath()); File[] runnerFiles = arch.listFiles(); List res = new ArrayList(); @@ -102,64 +163,75 @@ public List getAll() throws DAOException { // Iterate through all found nodes for (int i = 0; i < listNode.getLength(); i++) { Node node = listNode.item(i); - res.add(getFromNode(node)); + Transfer transfer = getFromNode(node); + res.add(transfer); + dbR66TaskHashMap.put(transfer.getId(), transfer); } } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } return res; } public boolean exist(long id, String requester, String requested, - String owner) throws DAOException { + String owner) throws DAOConnectionException { + if (dbR66TaskHashMap.contains(id)) { + return true; + } file = getFile(requester, requested, id); return file.exists(); } - public List find(List fitlers) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public List find(List fitlers) throws + DAOConnectionException { + throw new DAOConnectionException("Operation not supported on XML DAO"); } @Override - public List find(List filters, int limit) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public List find(List filters, int limit) throws + DAOConnectionException { + throw new DAOConnectionException("Operation not supported on XML DAO"); } @Override - public List find(List filters, int limit, int offset) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public List find(List filters, int limit, int offset) throws + DAOConnectionException { + throw new DAOConnectionException("Operation not supported on XML DAO"); } @Override - public List find(List filters, String column, boolean ascend) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public List find(List filters, String column, boolean ascend) throws + DAOConnectionException { + throw new DAOConnectionException("Operation not supported on XML DAO"); } @Override - public List find(List filters, String column, boolean ascend, int limit) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public List find(List filters, String column, boolean ascend, int limit) throws + DAOConnectionException { + throw new DAOConnectionException("Operation not supported on XML DAO"); } @Override - public List find(List filters, String column, boolean ascend, int limit, int offset) throws DAOException { - throw new DAOException("Operation not supported on XML DAO"); + public List find(List filters, String column, boolean ascend, int limit, int offset) throws + DAOConnectionException { + throw new DAOConnectionException("Operation not supported on XML DAO"); } - public void insert(Transfer transfer) throws DAOException { + public void insert(Transfer transfer) throws DAOConnectionException { //Set unique Id transfer.setId(new LongUuid().getLong()); - + dbR66TaskHashMap.put(transfer.getId(), transfer); file = getFile(transfer.getRequester(), transfer.getRequested(), transfer.getId()); if (file.exists()) { - throw new DAOException("File already exist"); + throw new DAOConnectionException("File already exist"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -170,15 +242,19 @@ public void insert(Transfer transfer) throws DAOException { // Write document in file XMLUtils.writeToFile(file, document); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } public Transfer select(long id, String requester, String requested, - String owner) throws DAOException { + String owner) + throws DAOConnectionException, DAONoDataException { + if (dbR66TaskHashMap.contains(id)) { + return dbR66TaskHashMap.get(id); + } file = getFile(requester, requested, id); if (!file.exists()) { - return null; + throw new DAONoDataException("Transfer cannot be found"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -198,23 +274,23 @@ public Transfer select(long id, String requester, String requested, if (node != null) { return getFromNode(node); } - return null; + throw new DAONoDataException("Transfer cannot be found"); } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } - public void update(Transfer transfer) throws DAOException { + public void update(Transfer transfer) throws DAOConnectionException { file = getFile(transfer.getRequester(), transfer.getRequested(), transfer.getId()); if (!file.exists()) { - throw new DAOException("File doesn't exist"); + throw new DAOConnectionException("File doesn't exist"); } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); @@ -241,14 +317,15 @@ public void update(Transfer transfer) throws DAOException { root.appendChild(getNode(document, transfer)); // Write document in file XMLUtils.writeToFile(file, document); + dbR66TaskHashMap.put(transfer.getId(), transfer); } catch (SAXException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (XPathExpressionException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (ParserConfigurationException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } catch (IOException e) { - throw new DAOException(e); + throw new DAOConnectionException(e); } } diff --git a/src/main/java/org/waarp/openr66/database/data/DbConfiguration.java b/src/main/java/org/waarp/openr66/database/data/DbConfiguration.java index 6a5de998d..6810f0212 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbConfiguration.java +++ b/src/main/java/org/waarp/openr66/database/data/DbConfiguration.java @@ -1,17 +1,17 @@ /** * This file is part of Waarp Project. - * + * * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * + * * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. - * + * * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. - * + * * You should have received a copy of the GNU General Public License along with Waarp . If not, see * . */ @@ -28,13 +28,15 @@ import org.waarp.common.database.data.DbValue; import org.waarp.common.database.exception.WaarpDatabaseException; import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; import org.waarp.common.database.exception.WaarpDatabaseSqlException; import org.waarp.openr66.commander.CommanderNoDb; import org.waarp.openr66.dao.DAOFactory; import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.LimitDAO; import org.waarp.openr66.dao.database.DBLimitDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Limit; import org.waarp.openr66.protocol.configuration.Configuration; @@ -42,9 +44,9 @@ /** * Configuration Table object - * + * * @author Frederic Bregier - * + * */ public class DbConfiguration extends AbstractDbData { public static enum Columns { @@ -69,12 +71,6 @@ public static enum Columns { public static final String table = " CONFIGURATION "; - /** - * HashTable in case of lack of database - */ - private static final ConcurrentHashMap dbR66ConfigurationHashMap = - new ConcurrentHashMap(); - private Limit limit = null; // ALL TABLE SHOULD IMPLEMENT THIS @@ -101,21 +97,18 @@ public static enum Columns { @Override protected void initObject() { - /* - primaryKey = new DbValue[] { new DbValue(limit.getHostid(), - Columns.HOSTID.name()) }; + primaryKey = new DbValue[] { new DbValue("", Columns.HOSTID.name()) }; otherFields = new DbValue[] { - new DbValue(limit.getReadGlobalLimit(), Columns.READGLOBALLIMIT.name()), - new DbValue(limit.getWriteGlobalLimit(), Columns.WRITEGLOBALLIMIT.name()), - new DbValue(limit.getReadSessionLimit(), Columns.READSESSIONLIMIT.name()), - new DbValue(limit.getWriteSessionLimit(), Columns.WRITESESSIONLIMIT.name()), - new DbValue(limit.getDelayLimit(), Columns.DELAYLIMIT.name()), - new DbValue(limit.getUpdatedInfo().ordinal(), Columns.UPDATEDINFO.name()) }; + new DbValue(0l, Columns.READGLOBALLIMIT.name()), + new DbValue(0l, Columns.WRITEGLOBALLIMIT.name()), + new DbValue(0l, Columns.READSESSIONLIMIT.name()), + new DbValue(0l, Columns.WRITESESSIONLIMIT.name()), + new DbValue(0l, Columns.DELAYLIMIT.name()), + new DbValue(0, Columns.UPDATEDINFO.name()) }; allFields = new DbValue[] { otherFields[0], otherFields[1], otherFields[2], otherFields[3], otherFields[4], otherFields[5], primaryKey[0] }; - */ } @Override @@ -146,7 +139,7 @@ protected void setToArray() { allFields[Columns.READSESSIONLIMIT.ordinal()].setValue(limit.getReadSessionLimit()); allFields[Columns.WRITESESSIONLIMIT.ordinal()].setValue(limit.getWriteSessionLimit()); allFields[Columns.DELAYLIMIT.ordinal()].setValue(limit.getDelayLimit()); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(limit.getUpdatedInfo()); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(limit.getUpdatedInfo().ordinal()); } @Override @@ -172,7 +165,6 @@ protected void setPrimaryKey() { } /** - * @param dbSession * @param hostid * @param rg * Read Global Limit @@ -189,17 +181,22 @@ public DbConfiguration(String hostid, long rg, long wg, long rs, long ws, long del) { super(); this.limit = new Limit(hostid, rg, wg, rs, ws, del); + setToArray(); } public DbConfiguration(Limit limit) { super(); + if (limit == null) { + throw new IllegalArgumentException( + "Argument in constructor cannot be null"); + } this.limit = limit; + setToArray(); } /** * Constructor from Json - * - * @param dbSession + * * @param source * @throws WaarpDatabaseSqlException */ @@ -210,6 +207,7 @@ public DbConfiguration(ObjectNode source) throws WaarpDatabaseSqlException { if (limit.getHostid() == null || limit.getHostid().isEmpty()) { throw new WaarpDatabaseSqlException("Not enough argument to create the object"); } + setToArray(); } /** @@ -227,7 +225,6 @@ public void setFromJson(ObjectNode node, boolean ignorePrimaryKey) throws WaarpD } /** - * @param dbSession * @param hostid * @throws WaarpDatabaseException */ @@ -237,16 +234,16 @@ public DbConfiguration(String hostid) throws WaarpDatabaseException { try { limitAccess = DAOFactory.getInstance().getLimitDAO(); this.limit = limitAccess.select(hostid); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + this.limit = new Limit(hostid, 0l); } finally { if (limitAccess != null) { limitAccess.close(); } } - if (this.limit == null) { - this.limit = new Limit(hostid, 0l); - } + setToArray(); } @Override @@ -255,8 +252,11 @@ public void delete() throws WaarpDatabaseException { try { limitAccess = DAOFactory.getInstance().getLimitDAO(); limitAccess.delete(limit); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Cannot find " + + "Configuration", e); } finally { if (limitAccess != null) { limitAccess.close(); @@ -273,7 +273,7 @@ public void insert() throws WaarpDatabaseException { try { limitAccess = DAOFactory.getInstance().getLimitDAO(); limitAccess.insert(limit); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (limitAccess != null) { @@ -288,7 +288,7 @@ public boolean exist() throws WaarpDatabaseException { try { limitAccess = DAOFactory.getInstance().getLimitDAO(); return limitAccess.exist(limit.getHostid()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (limitAccess != null) { @@ -303,8 +303,11 @@ public void select() throws WaarpDatabaseException { try { limitAccess = DAOFactory.getInstance().getLimitDAO(); limit = limitAccess.select(limit.getHostid()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Cannot find " + + "Configuration", e); } finally { if (limitAccess != null) { limitAccess.close(); @@ -321,8 +324,11 @@ public void update() throws WaarpDatabaseException { try { limitAccess = DAOFactory.getInstance().getLimitDAO(); limitAccess.update(limit); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Cannot find " + + "Configuration", e); } finally { if (limitAccess != null) { limitAccess.close(); @@ -342,13 +348,13 @@ public static DbConfiguration getFromStatement(DbPreparedStatement preparedState throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { DbConfiguration dbConfiguration = new DbConfiguration(); dbConfiguration.getValues(preparedStatement, dbConfiguration.allFields); - dbConfiguration.setFromArray(); + dbConfiguration.setToArray(); dbConfiguration.isSaved = true; return dbConfiguration; } /** - * + * * @return the DbPreparedStatement for getting Updated Object * @throws WaarpDatabaseNoConnectionException * @throws WaarpDatabaseSqlException @@ -366,7 +372,7 @@ public static DbConfiguration[] getUpdatedPrepareStament() try { limitAccess = DAOFactory.getInstance().getLimitDAO(); limits = limitAccess.find(filters); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseNoConnectionException(e); } finally { if (limitAccess != null) { @@ -443,7 +449,7 @@ public void updateConfiguration() { } /** - * + * * @return True if this Configuration refers to the current host */ public boolean isOwnConfiguration() { @@ -452,7 +458,7 @@ public boolean isOwnConfiguration() { } /** - * + * * @return the DbValue associated with this table */ public static DbValue[] getAllType() { diff --git a/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java b/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java index e840e3b43..a95467b31 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java +++ b/src/main/java/org/waarp/openr66/database/data/DbHostAuth.java @@ -44,7 +44,8 @@ import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.HostDAO; import org.waarp.openr66.dao.database.DBHostDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Host; import org.waarp.openr66.protocol.configuration.Configuration; import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessException; @@ -96,12 +97,6 @@ public static enum Columns { public static final String table = " HOSTS "; - /** - * HashTable in case of lack of database - */ - private static final ConcurrentHashMap dbR66HostAuthHashMap = - new ConcurrentHashMap(); - private Host host; // ALL TABLE SHOULD IMPLEMENT THIS @@ -134,26 +129,21 @@ public static enum Columns { @Override protected void initObject() { - /* - primaryKey = new DbValue[] { new DbValue(host.getHostid(), Columns.HOSTID - .name()) }; + primaryKey = new DbValue[] { new DbValue("", Columns.HOSTID.name()) }; otherFields = new DbValue[] { - new DbValue(host.getAddress(), Columns.ADDRESS.name()), - new DbValue(host.getPort(), Columns.PORT.name()), - new DbValue(host.isSSL(), Columns.ISSSL.name()), - new DbValue(host.getHostkey(), Columns.HOSTKEY.name()), - new DbValue(host.isAdmin(), Columns.ADMINROLE.name()), - new DbValue(host.isClient(), Columns.ISCLIENT.name()), - new DbValue(host.isActive(), Columns.ISACTIVE.name()), - new DbValue(host.isProxified(), Columns.ISPROXIFIED.name()), - new DbValue(host.getUpdatedInfo().ordinal(), - Columns.UPDATEDINFO.name()) }; + new DbValue("", Columns.ADDRESS.name()), + new DbValue(0, Columns.PORT.name()), + new DbValue(false, Columns.ISSSL.name()), + new DbValue(new byte[0], Columns.HOSTKEY.name()), + new DbValue(false, Columns.ADMINROLE.name()), + new DbValue(false, Columns.ISCLIENT.name()), + new DbValue(false, Columns.ISACTIVE.name()), + new DbValue(false, Columns.ISPROXIFIED.name()), + new DbValue(0, Columns.UPDATEDINFO.name()) }; allFields = new DbValue[] { otherFields[0], otherFields[1], otherFields[2], otherFields[3], otherFields[4], otherFields[5], otherFields[6], otherFields[7], otherFields[8], primaryKey[0] }; - - */ } @Override @@ -186,7 +176,7 @@ protected void setToArray() { allFields[Columns.ISCLIENT.ordinal()].setValue(host.isClient()); allFields[Columns.ISACTIVE.ordinal()].setValue(host.isActive()); allFields[Columns.ISPROXIFIED.ordinal()].setValue(host.isProxified()); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(host.getUpdatedInfo()); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(host.getUpdatedInfo().ordinal()); allFields[Columns.HOSTID.ordinal()].setValue(host.getHostid()); } @@ -248,13 +238,19 @@ public DbHostAuth(String hostid, String address, int port, private DbHostAuth(Host host) { super(); + if (host == null) { + throw new IllegalArgumentException( + "Argument in constructor cannot be null"); + } this.host = host; + setToArray(); } public DbHostAuth(ObjectNode source) throws WaarpDatabaseSqlException { super(); this.host = new Host(); setFromJson(source, false); + setToArray(); } @Override @@ -293,16 +289,16 @@ public DbHostAuth(String hostid) throws WaarpDatabaseException { try { hostAccess = DAOFactory.getInstance().getHostDAO(); host = hostAccess.select(hostid); - } catch (DAOException e) { + setToArray(); + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Cannot find host", e); } finally { if (hostAccess != null) { hostAccess.close(); } } - if (host == null) { - throw new WaarpDatabaseNoDataException("Cannot find host"); - } } /** @@ -319,7 +315,7 @@ public static DbHostAuth[] deleteAll() throws WaarpDatabaseException { hostAccess = DAOFactory.getInstance().getHostDAO(); hosts = hostAccess.getAll(); hostAccess.deleteAll(); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (hostAccess != null) { @@ -338,8 +334,10 @@ public void delete() throws WaarpDatabaseException { try { hostAccess = DAOFactory.getInstance().getHostDAO(); hostAccess.delete(host); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Cannot find host", e); } finally { if (hostAccess != null) { hostAccess.close(); @@ -353,7 +351,7 @@ public void insert() throws WaarpDatabaseException { try { hostAccess = DAOFactory.getInstance().getHostDAO(); hostAccess.insert(host); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (hostAccess != null) { @@ -368,7 +366,7 @@ public boolean exist() throws WaarpDatabaseException { try { hostAccess = DAOFactory.getInstance().getHostDAO(); return hostAccess.exist(host.getHostid()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (hostAccess != null) { @@ -383,8 +381,10 @@ public void select() throws WaarpDatabaseException { try { hostAccess = DAOFactory.getInstance().getHostDAO(); host = hostAccess.select(host.getHostid()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Cannot find host", e); } finally { if (hostAccess != null) { hostAccess.close(); @@ -398,8 +398,10 @@ public void update() throws WaarpDatabaseException { try { hostAccess = DAOFactory.getInstance().getHostDAO(); hostAccess.update(host); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Cannot find host", e); } finally { if (hostAccess != null) { hostAccess.close(); @@ -430,7 +432,7 @@ public static DbHostAuth[] getAllHosts() try { hostAccess = DAOFactory.getInstance().getHostDAO(); hosts = hostAccess.getAll(); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseNoConnectionException(e); } finally { if (hostAccess != null) { @@ -470,7 +472,7 @@ public static DbHostAuth[] getUpdatedPreparedStatement() try { hostAccess = DAOFactory.getInstance().getHostDAO(); hosts = hostAccess.find(filters); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseNoConnectionException(e); } finally { if (hostAccess != null) { @@ -871,7 +873,7 @@ public static boolean hasProxifiedHosts() { try { hostAccess = DAOFactory.getInstance().getHostDAO(); return hostAccess.find(filters).size() > 0; - } catch (DAOException e) { + } catch (DAOConnectionException e) { logger.error("DAO Access error", e); return false; } finally { diff --git a/src/main/java/org/waarp/openr66/database/data/DbHostConfiguration.java b/src/main/java/org/waarp/openr66/database/data/DbHostConfiguration.java index ae40be0f7..878300ba8 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbHostConfiguration.java +++ b/src/main/java/org/waarp/openr66/database/data/DbHostConfiguration.java @@ -1,17 +1,17 @@ /** * This file is part of Waarp Project. - * + * * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * + * * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. - * + * * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. - * + * * You should have received a copy of the GNU General Public License along with Waarp . If not, see * . */ @@ -52,7 +52,8 @@ import org.waarp.openr66.dao.DAOFactory; import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.database.DBBusinessDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Business; import org.waarp.openr66.protocol.configuration.Configuration; import org.waarp.openr66.protocol.configuration.Messages; @@ -62,9 +63,9 @@ /** * Configuration Table object - * + * * @author Frederic Bregier - * + * */ public class DbHostConfiguration extends AbstractDbData { /** @@ -92,12 +93,6 @@ public static enum Columns { public static final String table = " HOSTCONFIG "; - /** - * HashTable in case of lack of database - */ - private static final ConcurrentHashMap dbR66HostConfigurationHashMap = - new ConcurrentHashMap(); - private Business business; @@ -195,20 +190,17 @@ public static enum OtherFields { @Override protected void initObject() { - /* primaryKey = new DbValue[] { - new DbValue(business.getHostid(), Columns.HOSTID.name()) }; + new DbValue("", Columns.HOSTID.name()) }; otherFields = new DbValue[] { - new DbValue(business.getBusiness(), Columns.BUSINESS.name(), true), - new DbValue(business.getRoles(), Columns.ROLES.name(), true), - new DbValue(business.getAliases(), Columns.ALIASES.name(), true), - new DbValue(business.getOthers(), Columns.OTHERS.name(), true), - new DbValue(business.getUpdatedInfo().ordinal(), Columns.UPDATEDINFO.name()) }; + new DbValue("", Columns.BUSINESS.name(), true), + new DbValue("", Columns.ROLES.name(), true), + new DbValue("", Columns.ALIASES.name(), true), + new DbValue("", Columns.OTHERS.name(), true), + new DbValue(0, Columns.UPDATEDINFO.name()) }; allFields = new DbValue[] { otherFields[0], otherFields[1], otherFields[2], otherFields[3], otherFields[4], primaryKey[0] }; - - */ } @Override @@ -274,7 +266,7 @@ protected void setToArray() { } while (len != business.getOthers().length()); } allFields[Columns.OTHERS.ordinal()].setValue(business.getOthers()); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(business.getUpdatedInfo()); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(business.getUpdatedInfo().ordinal()); } @Override @@ -299,7 +291,6 @@ protected void setPrimaryKey() { } /** - * @param dbSession * @param hostid * @param business Business configuration * @param roles Roles configuration @@ -310,17 +301,22 @@ public DbHostConfiguration(String hostid, String business, String roles, String String others) { super(); this.business = new Business(hostid, business, roles, aliases, others); + setToArray(); } public DbHostConfiguration(Business business) { super(); + if (business == null) { + throw new IllegalArgumentException( + "Argument in constructor cannot be null"); + } this.business = business; + setToArray(); } /** * Constructor from Json - * - * @param dbSession + * * @param source * @throws WaarpDatabaseSqlException */ @@ -336,7 +332,6 @@ public DbHostConfiguration(ObjectNode source) throws WaarpDatabaseSqlException { } /** - * @param dbSession * @param hostid * @throws WaarpDatabaseException */ @@ -346,8 +341,12 @@ public DbHostConfiguration(String hostid) throws WaarpDatabaseException { try { businessAccess = DAOFactory.getInstance().getBusinessDAO(); this.business = businessAccess.select(hostid); - } catch (DAOException e) { + setToArray(); + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("DbHostConfiguration not " + + "found", e); } finally { if (businessAccess != null) { businessAccess.close(); @@ -554,7 +553,7 @@ public void setOthers(String others) { } /** - * + * * @return the element for the content of the other part */ public Element getOtherElement() { @@ -572,7 +571,7 @@ public Element getOtherElement() { } /** - * + * * @param element * the element to set as XML string to other part */ @@ -586,8 +585,11 @@ public void delete() throws WaarpDatabaseException { try { businessAccess = DAOFactory.getInstance().getBusinessDAO(); businessAccess.delete(business); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("DbHostConfiguration not " + + "found", e); } finally { if (businessAccess != null) { businessAccess.close(); @@ -601,7 +603,7 @@ public void insert() throws WaarpDatabaseException { try { businessAccess = DAOFactory.getInstance().getBusinessDAO(); businessAccess.insert(business); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (businessAccess != null) { @@ -616,7 +618,7 @@ public boolean exist() throws WaarpDatabaseException { try { businessAccess = DAOFactory.getInstance().getBusinessDAO(); return businessAccess.exist(business.getHostid()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (businessAccess != null) { @@ -631,8 +633,11 @@ public void select() throws WaarpDatabaseException { try { businessAccess = DAOFactory.getInstance().getBusinessDAO(); this.business = businessAccess.select(business.getHostid()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("DbHostConfiguration not " + + "found", e); } finally { if (businessAccess != null) { businessAccess.close(); @@ -646,8 +651,11 @@ public void update() throws WaarpDatabaseException { try { businessAccess = DAOFactory.getInstance().getBusinessDAO(); businessAccess.update(business); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("DbHostConfiguration not " + + "found", e); } finally { if (businessAccess != null) { businessAccess.close(); @@ -665,7 +673,7 @@ private DbHostConfiguration() { /** * For instance from Commander when getting updated information - * + * * @param preparedStatement * @return the next updated Configuration * @throws WaarpDatabaseNoConnectionException @@ -675,13 +683,13 @@ public static DbHostConfiguration getFromStatement(DbPreparedStatement preparedS throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { DbHostConfiguration dbConfiguration = new DbHostConfiguration(); dbConfiguration.getValues(preparedStatement, dbConfiguration.allFields); - dbConfiguration.setFromArray(); + dbConfiguration.setToArray(); dbConfiguration.isSaved = true; return dbConfiguration; } /** - * + * * @return the DbPreparedStatement for getting Updated Object * @throws WaarpDatabaseNoConnectionException * @throws WaarpDatabaseSqlException @@ -699,7 +707,7 @@ public static DbHostConfiguration[] getUpdatedPrepareStament() try { businessAccess = DAOFactory.getInstance().getBusinessDAO(); businesses = businessAccess.find(filters); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseNoConnectionException(e); } finally { if (businessAccess != null) { @@ -716,7 +724,7 @@ public static DbHostConfiguration[] getUpdatedPrepareStament() } /** - * + * * @param session * @param hostid * @param business @@ -787,7 +795,7 @@ public void updateConfiguration() { } /** - * + * * @return True if this Configuration refers to the current host */ public boolean isOwnConfiguration() { @@ -796,7 +804,7 @@ public boolean isOwnConfiguration() { /** * Shortcut to add all paths element from source into set - * + * * @param source * @param path * @param set @@ -847,7 +855,7 @@ private boolean updateSet(String source, String path, HashSet set) { /** * update Business with possible purge and new or added content, and updating in memory information - * + * * @param config * @param newbusiness * @param purged @@ -892,7 +900,7 @@ public boolean updateBusiness(Configuration config, String newbusiness, boolean /** * Shortcut to add all paths element with key and value from source into map - * + * * @param source * @param path * @param keypath @@ -963,7 +971,7 @@ private boolean updateMap(String source, String path, String keypath, String val /** * update Alias with possible purge and new or added content, and updating in memory information - * + * * @param config * @param newalias * @param purged @@ -1044,7 +1052,7 @@ public boolean updateAlias(Configuration config, String newalias, boolean purged /** * update Roles with possible purge and new or added content, and updating in memory information - * + * * @param config * @param newroles * @param purged @@ -1136,8 +1144,7 @@ public static void updateHostConfiguration(Configuration config, DbHostConfigura } /** - * - * @param dbSession + * * @param hostid * @return the version of the database from HostConfiguration table */ @@ -1177,8 +1184,7 @@ public boolean isSeeAllId(String id) { /** * Update the version for this HostId - * - * @param dbSession + * * @param hostid * @param version */ @@ -1223,7 +1229,7 @@ public static void updateVersionDb(String hostid, String version) { } /** - * + * * @return the DbValue associated with this table */ public static DbValue[] getAllType() { diff --git a/src/main/java/org/waarp/openr66/database/data/DbMultipleMonitor.java b/src/main/java/org/waarp/openr66/database/data/DbMultipleMonitor.java index f4ecfd12f..681377fb9 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbMultipleMonitor.java +++ b/src/main/java/org/waarp/openr66/database/data/DbMultipleMonitor.java @@ -1,17 +1,17 @@ /** * This file is part of Waarp Project. - * + * * Copyright 2009, Frederic Bregier, and individual contributors by the @author tags. See the * COPYRIGHT.txt in the distribution for a full listing of individual contributors. - * + * * All Waarp Project is free software: you can redistribute it and/or modify it under the terms of * the GNU General Public License as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. - * + * * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. - * + * * You should have received a copy of the GNU General Public License along with Waarp . If not, see * . */ @@ -26,18 +26,20 @@ import org.waarp.common.database.data.DbValue; import org.waarp.common.database.exception.WaarpDatabaseException; import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; import org.waarp.common.database.exception.WaarpDatabaseSqlException; import org.waarp.openr66.dao.DAOFactory; import org.waarp.openr66.dao.MultipleMonitorDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.MultipleMonitor; import org.waarp.openr66.protocol.configuration.Configuration; /** * Configuration Table object - * + * * @author Frederic Bregier - * + * */ public class DbMultipleMonitor extends AbstractDbData { public static enum Columns { @@ -56,12 +58,6 @@ public static enum Columns { public static final String table = " MULTIPLEMONITOR "; - /** - * HashTable in case of lack of database - */ - private static final ConcurrentHashMap dbR66MMHashMap = - new ConcurrentHashMap(); - private MultipleMonitor multipleMonitor; // ALL TABLE SHOULD IMPLEMENT THIS @@ -82,16 +78,13 @@ public static enum Columns { @Override protected void initObject() { - /* - primaryKey = new DbValue[] { new DbValue(multipleMonitor.getHostid(), - Columns.HOSTID.name()) }; + primaryKey = new DbValue[] { new DbValue("", Columns.HOSTID.name()) }; otherFields = new DbValue[] { - new DbValue(getCountConfig(), Columns.COUNTCONFIG.name()), - new DbValue(getCountHost(), Columns.COUNTHOST.name()), - new DbValue(getCountRule(), Columns.COUNTRULE.name()) }; + new DbValue(0, Columns.COUNTCONFIG.name()), + new DbValue(0, Columns.COUNTHOST.name()), + new DbValue(0, Columns.COUNTRULE.name()) }; allFields = new DbValue[] { otherFields[0], otherFields[1], otherFields[2], primaryKey[0] }; - */ } @Override @@ -141,7 +134,6 @@ protected void setPrimaryKey() { } /** - * @param dbSession * @param hostid * @param cc * count for Config @@ -156,7 +148,6 @@ public DbMultipleMonitor(String hostid, int cc, int ch, int cr) { } /** - * @param dbSession * @param hostid * @throws WaarpDatabaseException */ @@ -166,8 +157,12 @@ public DbMultipleMonitor(String hostid) throws WaarpDatabaseException { try { monitorAccess = DAOFactory.getInstance().getMultipleMonitorDAO(); multipleMonitor = monitorAccess.select(hostid); - } catch (DAOException e) { + setToArray(); + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Cannot find " + + "MultipleMonitor", e); } finally { if (monitorAccess != null) { monitorAccess.close(); @@ -181,8 +176,11 @@ public void delete() throws WaarpDatabaseException { try { monitorAccess = DAOFactory.getInstance().getMultipleMonitorDAO(); monitorAccess.delete(multipleMonitor); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Cannot find " + + "MultipleMonitor", e); } finally { if (monitorAccess != null) { monitorAccess.close(); @@ -196,7 +194,7 @@ public void insert() throws WaarpDatabaseException { try { monitorAccess = DAOFactory.getInstance().getMultipleMonitorDAO(); monitorAccess.insert(multipleMonitor); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (monitorAccess != null) { @@ -211,7 +209,7 @@ public boolean exist() throws WaarpDatabaseException { try { monitorAccess = DAOFactory.getInstance().getMultipleMonitorDAO(); return monitorAccess.exist(multipleMonitor.getHostid()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (monitorAccess != null) { @@ -226,8 +224,11 @@ public void select() throws WaarpDatabaseException { try { monitorAccess = DAOFactory.getInstance().getMultipleMonitorDAO(); multipleMonitor = monitorAccess.select(multipleMonitor.getHostid()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Cannot find " + + "MultipleMonitor", e); } finally { if (monitorAccess != null) { monitorAccess.close(); @@ -241,8 +242,11 @@ public void update() throws WaarpDatabaseException { try { monitorAccess = DAOFactory.getInstance().getMultipleMonitorDAO(); monitorAccess.update(multipleMonitor); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Cannot find " + + "MultipleMonitor", e); } finally { if (monitorAccess != null) { monitorAccess.close(); @@ -260,7 +264,7 @@ private DbMultipleMonitor() { /** * For instance from Commander when getting updated information - * + * * @param preparedStatement * @return the next updated Configuration * @throws WaarpDatabaseNoConnectionException @@ -270,13 +274,13 @@ public static DbMultipleMonitor getFromStatement(DbPreparedStatement preparedSta throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { DbMultipleMonitor dbMm = new DbMultipleMonitor(); dbMm.getValues(preparedStatement, dbMm.allFields); - dbMm.setFromArray(); + dbMm.setToArray(); dbMm.isSaved = true; return dbMm; } /** - * + * * @return the DbPreparedStatement for getting Updated Object in "FOR UPDATE" mode * @throws WaarpDatabaseNoConnectionException * @throws WaarpDatabaseSqlException @@ -302,7 +306,7 @@ public static DbPreparedStatement getUpdatedPrepareStament(DbSession session) /** * On Commander side - * + * * @return True if this is the last update */ public boolean checkUpdateConfig() { @@ -319,7 +323,7 @@ public boolean checkUpdateConfig() { /** * On Commander side - * + * * @return True if this is the last update */ public boolean checkUpdateHost() { @@ -336,7 +340,7 @@ public boolean checkUpdateHost() { /** * On Commander side - * + * * @return True if this is the last update */ public boolean checkUpdateRule() { diff --git a/src/main/java/org/waarp/openr66/database/data/DbRule.java b/src/main/java/org/waarp/openr66/database/data/DbRule.java index 5a0f16fbc..815311149 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbRule.java +++ b/src/main/java/org/waarp/openr66/database/data/DbRule.java @@ -50,7 +50,8 @@ import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.RuleDAO; import org.waarp.openr66.dao.database.DBRuleDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; import org.waarp.openr66.pojo.Rule; import org.waarp.openr66.pojo.RuleTask; @@ -110,12 +111,6 @@ public static enum Columns { public static final String table = " RULES "; - /** - * HashTable in case of lack of database - */ - private static final ConcurrentHashMap dbR66RuleHashMap = - new ConcurrentHashMap(); - /** * Internal context XML fields */ @@ -234,31 +229,28 @@ public static enum Columns { @Override protected void initObject() { - /* - primaryKey = new DbValue[] { new DbValue(getIdRule(), - Columns.IDRULE.name()) }; + primaryKey = new DbValue[] { new DbValue("", Columns.IDRULE.name()) }; otherFields = new DbValue[] { // HOSTIDS, MODETRANS, RECVPATH, SENDPATH, ARCHIVEPATH, WORKPATH, // PRETASKS, POSTTASKS, ERRORTASKS - new DbValue(rule.getXMLHostids(), Columns.HOSTIDS.name(), true), - new DbValue(rule.getMode(), Columns.MODETRANS.name()), - new DbValue(rule.getRecvPath(), Columns.RECVPATH.name()), - new DbValue(rule.getSendPath(), Columns.SENDPATH.name()), - new DbValue(rule.getArchivePath(), Columns.ARCHIVEPATH.name()), - new DbValue(rule.getWorkPath(), Columns.WORKPATH.name()), - new DbValue(rule.getXMLRPreTasks(), Columns.RPRETASKS.name(), true), - new DbValue(rule.getXMLRPostTasks(), Columns.RPOSTTASKS.name(), true), - new DbValue(rule.getXMLRErrorTasks(), Columns.RERRORTASKS.name(), true), - new DbValue(rule.getXMLSPreTasks(), Columns.SPRETASKS.name(), true), - new DbValue(rule.getXMLSPostTasks(), Columns.SPOSTTASKS.name(), true), - new DbValue(rule.getXMLSErrorTasks(), Columns.SERRORTASKS.name(), true), - new DbValue(rule.getUpdatedInfo().ordinal(), Columns.UPDATEDINFO.name()) }; + new DbValue("", Columns.HOSTIDS.name(), true), + new DbValue(0, Columns.MODETRANS.name()), + new DbValue("", Columns.RECVPATH.name()), + new DbValue("", Columns.SENDPATH.name()), + new DbValue("", Columns.ARCHIVEPATH.name()), + new DbValue("", Columns.WORKPATH.name()), + new DbValue("", Columns.RPRETASKS.name(), true), + new DbValue("", Columns.RPOSTTASKS.name(), true), + new DbValue("", Columns.RERRORTASKS.name(), true), + new DbValue("", Columns.SPRETASKS.name(), true), + new DbValue("", Columns.SPOSTTASKS.name(), true), + new DbValue("", Columns.SERRORTASKS.name(), true), + new DbValue(0, Columns.UPDATEDINFO.name()) }; allFields = new DbValue[] { otherFields[0], otherFields[1], otherFields[2], otherFields[3], otherFields[4], otherFields[5], otherFields[6], otherFields[7], otherFields[8], otherFields[9], otherFields[10], otherFields[11], otherFields[12], primaryKey[0] }; - */ } @Override @@ -315,7 +307,7 @@ protected void setToArray() { allFields[Columns.SPRETASKS.ordinal()].setValue(rule.getXMLSPreTasks()); allFields[Columns.SPOSTTASKS.ordinal()].setValue(rule.getXMLSPostTasks()); allFields[Columns.SERRORTASKS.ordinal()].setValue(rule.getXMLSErrorTasks()); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(rule.getUpdatedInfo()); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(rule.getUpdatedInfo().ordinal()); allFields[Columns.IDRULE.ordinal()].setValue(getIdRule()); } @@ -378,7 +370,6 @@ protected void setPrimaryKey() { } /** - * @param dbSession * @param idRule * @param ids * @param mode @@ -406,10 +397,10 @@ public DbRule(String idRule, String ids, int mode, String recvPath, fromLegacyTasks(getTasksRule(spreTasks)), fromLegacyTasks(getTasksRule(spostTasks)), fromLegacyTasks(getTasksRule(serrorTasks))); + setToArray(); } /** - * @param dbSession * @param idRule * @throws WaarpDatabaseException */ @@ -419,27 +410,31 @@ public DbRule(String idRule) throws WaarpDatabaseException { try { ruleAccess = DAOFactory.getInstance().getRuleDAO(); rule = ruleAccess.select(idRule); - } catch (DAOException e) { + setToArray(); + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Rule not found", e); } finally { if (ruleAccess != null) { ruleAccess.close(); } } - if (rule == null) { - throw new WaarpDatabaseNoDataException("Rule not found"); - } } public DbRule(Rule rule) { super(); - rule = rule; + if (rule == null) { + throw new IllegalArgumentException( + "Argument in constructor cannot be null"); + } + this.rule = rule; + setToArray(); } /** * Constructor used from XML file * - * @param dbSession * @param idrule * @param idsArrayRef * @param recvpath @@ -470,12 +465,12 @@ public DbRule(String idrule, String[] idsArrayRef, int mode, fromLegacyTasks(spretasksArray), fromLegacyTasks(sposttasksArray), fromLegacyTasks(serrortasksArray)); + setToArray(); } /** * Constructor from Json * - * @param dbSession * @param source * @throws WaarpDatabaseSqlException */ @@ -486,6 +481,7 @@ public DbRule(ObjectNode source) throws WaarpDatabaseSqlException { if (getIdRule() == null || getIdRule().isEmpty()) { throw new WaarpDatabaseSqlException("Not enough argument to create the object"); } + setToArray(); } @Override @@ -496,7 +492,6 @@ public void setFromJson(ObjectNode node, boolean ignorePrimaryKey) throws WaarpD /** * Delete all entries (used when purge and reload) * - * @param dbSession * @return the previous existing array of DbRule * @throws WaarpDatabaseException */ @@ -507,7 +502,7 @@ public static DbRule[] deleteAll() throws WaarpDatabaseException { ruleAccess = DAOFactory.getInstance().getRuleDAO(); rules = ruleAccess.getAll(); ruleAccess.deleteAll(); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (ruleAccess != null) { @@ -529,8 +524,10 @@ public void delete() throws WaarpDatabaseException { try { ruleAccess = DAOFactory.getInstance().getRuleDAO(); ruleAccess.delete(rule); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Rule not found", e); } finally { if (ruleAccess != null) { ruleAccess.close(); @@ -544,7 +541,7 @@ public void insert() throws WaarpDatabaseException { try { ruleAccess = DAOFactory.getInstance().getRuleDAO(); ruleAccess.insert(rule); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (ruleAccess != null) { @@ -559,7 +556,7 @@ public boolean exist() throws WaarpDatabaseException { try { ruleAccess = DAOFactory.getInstance().getRuleDAO(); return ruleAccess.exist(rule.getName()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (ruleAccess != null) { @@ -574,8 +571,11 @@ public void select() throws WaarpDatabaseException { try { ruleAccess = DAOFactory.getInstance().getRuleDAO(); rule = ruleAccess.select(rule.getName()); - } catch (DAOException e) { + setToArray(); + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Rule not found", e); } finally { if (ruleAccess != null) { ruleAccess.close(); @@ -589,8 +589,11 @@ public void update() throws WaarpDatabaseException { try { ruleAccess = DAOFactory.getInstance().getRuleDAO(); ruleAccess.update(rule); - } catch (DAOException e) { + setToArray(); + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Rule not found", e); } finally { if (ruleAccess != null) { ruleAccess.close(); @@ -609,8 +612,6 @@ private DbRule() { /** * Get All DbRule from database or from internal hashMap in case of no database support * - * @param dbSession - * may be null * @return the array of DbRule * @throws WaarpDatabaseNoConnectionException * @throws WaarpDatabaseSqlException @@ -622,7 +623,7 @@ public static DbRule[] getAllRules() try { ruleAccess = DAOFactory.getInstance().getRuleDAO(); rules = ruleAccess.getAll(); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseNoConnectionException(e); } finally { if (ruleAccess != null) { @@ -650,10 +651,9 @@ public static DbRule getFromStatement(DbPreparedStatement preparedStatement) throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { DbRule dbRule = new DbRule(); dbRule.getValues(preparedStatement, dbRule.allFields); - dbRule.setFromArray(); + dbRule.setToArray(); dbRule.isSaved = true; logger.debug("Get one Rule from Db: " + dbRule.getIdRule()); - dbR66RuleHashMap.put(dbRule.getIdRule(), dbRule); return dbRule; } @@ -673,7 +673,7 @@ public static DbRule[] getUpdatedPrepareStament() try { ruleAccess = DAOFactory.getInstance().getRuleDAO(); rules = ruleAccess.find(filters); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseNoConnectionException(e); } finally { if (ruleAccess != null) { diff --git a/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java b/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java index 262bfd272..74352b9aa 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java +++ b/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java @@ -69,7 +69,9 @@ import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.TransferDAO; import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; +import org.waarp.openr66.dao.xml.XMLTransferDAO; import org.waarp.openr66.database.DbConstant; import org.waarp.openr66.pojo.Transfer; import org.waarp.openr66.protocol.configuration.Configuration; @@ -111,12 +113,6 @@ public class DbTaskRunner extends AbstractDbData { private static final WaarpLogger logger = WaarpLoggerFactory .getLogger(DbTaskRunner.class); - /** - * HashTable in case of lack of database using LRU mode with - * 20 000 items maximum (< 200 MB?) for 180s - */ - private static SynchronizedLruCache dbR66TaskHashMap; - /** * Create the LRU cache * @@ -126,11 +122,11 @@ public class DbTaskRunner extends AbstractDbData { * time to leave used */ public static void createLruCache(int limit, long ttl) { - dbR66TaskHashMap = new SynchronizedLruCache(limit, ttl); + XMLTransferDAO.createLruCache(limit, ttl); } public static String hashStatus() { - return "DbTaskRunner: [dbR66TaskHashMap: " + dbR66TaskHashMap.size() + "] "; + return XMLTransferDAO.hashStatus(); } /** @@ -139,7 +135,7 @@ public static String hashStatus() { * @return the number of elements removed */ public static int clearCache() { - return dbR66TaskHashMap.forceClearOldest(); + return XMLTransferDAO.clearCache(); } /** @@ -148,7 +144,7 @@ public static int clearCache() { * @param ttl */ public static void updateLruCacheTimeout(long ttl) { - dbR66TaskHashMap.setNewTtl(ttl); + XMLTransferDAO.updateLruCacheTimeout(ttl); } public static enum Columns { @@ -299,34 +295,34 @@ protected void initObject() { // empty transfer for initObject transfer = new Transfer(); primaryKey = new DbValue[] { - new DbValue(transfer.getOwnerRequest(), Columns.OWNERREQ.name()), - new DbValue(transfer.getRequester(), Columns.REQUESTER.name()), - new DbValue(transfer.getRequested(), Columns.REQUESTED.name()), - new DbValue(transfer.getId(), Columns.SPECIALID.name()) }; + new DbValue("", Columns.OWNERREQ.name()), + new DbValue("", Columns.REQUESTER.name()), + new DbValue("", Columns.REQUESTED.name()), + new DbValue(0l, Columns.SPECIALID.name()) }; otherFields = new DbValue[] { // GLOBALSTEP, GLOBALLASTSTEP, STEP, RANK, STEPSTATUS, RETRIEVEMODE, // FILENAME, ISMOVED, IDRULE, // BLOCKSZ, ORIGINALNAME, FILEINFO, MODETRANS, // STARTTRANS, STOPTRANS // INFOSTATUS, UPDATEDINFO - new DbValue(transfer.getGlobalStep().ordinal(), Columns.GLOBALSTEP.name()), - new DbValue(transfer.getLastGlobalStep().ordinal(), Columns.GLOBALLASTSTEP.name()), - new DbValue(transfer.getStep(), Columns.STEP.name()), - new DbValue(transfer.getRank(), Columns.RANK.name()), - new DbValue(ErrorCode.Unknown.getCode(), Columns.STEPSTATUS.name()), // status.getCode() - new DbValue(transfer.getRetrieveMode(), Columns.RETRIEVEMODE.name()), - new DbValue(transfer.getFilename(), Columns.FILENAME.name()), - new DbValue(transfer.getIsMoved(), Columns.ISMOVED.name()), - new DbValue(transfer.getRule(), Columns.IDRULE.name()), - new DbValue(transfer.getBlockSize(), Columns.BLOCKSZ.name()), - new DbValue(transfer.getOriginalName(), Columns.ORIGINALNAME.name()), - new DbValue(transfer.getFileInfo(), Columns.FILEINFO.name(), true), - new DbValue(transfer.getTransferInfo(), Columns.TRANSFERINFO.name(), true), - new DbValue(transfer.getTransferMode(), Columns.MODETRANS.name()), - new DbValue(transfer.getStart(), Columns.STARTTRANS.name()), - new DbValue(transfer.getStop(), Columns.STOPTRANS.name()), - new DbValue(ErrorCode.Unknown.getCode(), Columns.INFOSTATUS.name()),// infostatus.getCode() - new DbValue(transfer.getUpdatedInfo().ordinal(), Columns.UPDATEDINFO.name()) }; + new DbValue(0, Columns.GLOBALSTEP.name()), + new DbValue(0, Columns.GLOBALLASTSTEP.name()), + new DbValue(0, Columns.STEP.name()), + new DbValue(0, Columns.RANK.name()), + new DbValue("", Columns.STEPSTATUS.name()), // status.getCode() + new DbValue(false, Columns.RETRIEVEMODE.name()), + new DbValue("", Columns.FILENAME.name()), + new DbValue(false, Columns.ISMOVED.name()), + new DbValue("", Columns.IDRULE.name()), + new DbValue(0, Columns.BLOCKSZ.name()), + new DbValue("", Columns.ORIGINALNAME.name()), + new DbValue("", Columns.FILEINFO.name(), true), + new DbValue("", Columns.TRANSFERINFO.name(), true), + new DbValue(0, Columns.MODETRANS.name()), + new DbValue(new Timestamp(0l), Columns.STARTTRANS.name()), + new DbValue(new Timestamp(0l), Columns.STOPTRANS.name()), + new DbValue("", Columns.INFOSTATUS.name()),// infostatus.getCode() + new DbValue(0, Columns.UPDATEDINFO.name()) }; allFields = new DbValue[] { otherFields[0], otherFields[1], otherFields[2], otherFields[3], @@ -359,8 +355,8 @@ protected String getUpdateAllFields() { @Override protected void setToArray() { - allFields[Columns.GLOBALSTEP.ordinal()].setValue(transfer.getGlobalStep()); - allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(transfer.getLastGlobalStep()); + allFields[Columns.GLOBALSTEP.ordinal()].setValue(transfer.getGlobalStep().ordinal()); + allFields[Columns.GLOBALLASTSTEP.ordinal()].setValue(transfer.getLastGlobalStep().ordinal()); allFields[Columns.STEP.ordinal()].setValue(transfer.getStep()); allFields[Columns.RANK.ordinal()].setValue(transfer.getRank()); allFields[Columns.STEPSTATUS.ordinal()].setValue(transfer.getStepStatus().getCode()); @@ -377,7 +373,7 @@ protected void setToArray() { transfer.setStop(new Timestamp(System.currentTimeMillis())); allFields[Columns.STOPTRANS.ordinal()].setValue(transfer.getStop()); allFields[Columns.INFOSTATUS.ordinal()].setValue(transfer.getInfoStatus().getCode()); - allFields[Columns.UPDATEDINFO.ordinal()].setValue(transfer.getUpdatedInfo()); + allFields[Columns.UPDATEDINFO.ordinal()].setValue(transfer.getUpdatedInfo().ordinal()); allFields[Columns.OWNERREQ.ordinal()].setValue(transfer.getOwnerRequest()); allFields[Columns.REQUESTER.ordinal()].setValue(transfer.getRequester()); allFields[Columns.REQUESTED.ordinal()].setValue(transfer.getRequested()); @@ -513,7 +509,12 @@ public void checkThroughMode() { public DbTaskRunner(Transfer transfer) { super(); + if (transfer == null) { + throw new IllegalArgumentException( + "Argument in constructor cannot be null"); + } this.transfer = transfer; + setToArray(); } /** @@ -568,6 +569,7 @@ public DbTaskRunner(DbRule rule, boolean isSender, checkThroughMode(); insert(); requestPacket.setSpecialId(transfer.getId()); + setToArray(); } /** @@ -598,6 +600,7 @@ public DbTaskRunner(R66Session session, DbRule rule, setOriginalSizeTransferMap(originalSize); checkThroughMode(); + setToArray(); insert(); requestPacket.setSpecialId(transfer.getId()); } @@ -622,16 +625,15 @@ public DbTaskRunner(R66Session session, DbRule rule, transferAccess = DAOFactory.getInstance().getTransferDAO(); transfer = transferAccess.select(id, requester, requested, Configuration.configuration.getHOST_ID()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Transfer not found", e); } finally { if (transferAccess != null) { transferAccess.close(); } } - if (transfer == null) { - throw new WaarpDatabaseNoDataException("Transfer not found"); - } this.rule = new DbRule(getRuleId()); if (rule != null) { if (!transfer.getRule().equals(rule.getIdRule())) { @@ -639,6 +641,7 @@ public DbTaskRunner(R66Session session, DbRule rule, "Rule does not correspond"); } } + setToArray(); } /** @@ -657,14 +660,17 @@ public DbTaskRunner(long id, String requester, String requested) transferAccess = DAOFactory.getInstance().getTransferDAO(); transfer = transferAccess.select(id, requester, requested, Configuration.configuration.getHOST_ID()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Transfer not found", e); } finally { if (transferAccess != null) { transferAccess.close(); } } this.rule = new DbRule(getRuleId()); + setToArray(); } /** @@ -683,6 +689,7 @@ public DbTaskRunner(long id, String requester, String requested, String owner) } else { transfer.setOwnerRequest(owner); } + setToArray(); } /** @@ -695,6 +702,7 @@ public DbTaskRunner(ObjectNode source) throws WaarpDatabaseException { super(); transfer = new Transfer(); setFromJson(source, false); + setToArray(); } @Override @@ -851,8 +859,11 @@ public DbTaskRunner(long id, String requested) transfer = transferAccess.select(id, Configuration.configuration.getHOST_ID(), requested, Configuration.configuration.getHOST_ID()); - } catch (DAOException e) { + setToArray(); + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Transfer not found", e); } finally { if (transferAccess != null) { transferAccess.close(); @@ -874,17 +885,6 @@ private static String getLimitWhereCondition() { private void createNoDbSpecialId() { transfer.setId(new LongUuid().getLong()); setPrimaryKey(); - /*synchronized (clientNoDbSpecialIdLast) { - // New SpecialId is not possible with No Database Model - specialId = System.currentTimeMillis(); - if (clientNoDbSpecialIdLast.get() >= specialId) { - specialId = clientNoDbSpecialIdLast.incrementAndGet(); - } else { - clientNoDbSpecialIdLast.set(specialId); - } - setPrimaryKey(); - return; - }*/ } /** @@ -900,7 +900,7 @@ private final void removeNoDbSpecialId() { * @param specialId */ public static final void removeNoDbSpecialId(long specialId) { - dbR66TaskHashMap.remove(specialId); + XMLTransferDAO.removeNoDbSpecialId(specialId); } /** @@ -909,7 +909,7 @@ public static final void removeNoDbSpecialId(long specialId) { * @param specialId */ public static final void updateUsed(long specialId) { - dbR66TaskHashMap.updateTtl(specialId); + XMLTransferDAO.updateUsed(specialId); } @Override @@ -918,8 +918,10 @@ public void delete() throws WaarpDatabaseException { try { transferAccess = DAOFactory.getInstance().getTransferDAO(); transferAccess.delete(transfer); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Transfer not found", e); } finally { if (transferAccess != null) { transferAccess.close(); @@ -953,7 +955,7 @@ public void insert() throws WaarpDatabaseException { try { transferAccess = DAOFactory.getInstance().getTransferDAO(); transferAccess.insert(transfer); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (transferAccess != null) { @@ -979,7 +981,7 @@ public boolean exist() throws WaarpDatabaseException { return transferAccess.exist(transfer.getId(), transfer.getRequester(), transfer.getRequested(), Configuration.configuration.getHOST_ID()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); } finally { if (transferAccess != null) { @@ -1011,16 +1013,15 @@ public void select() throws WaarpDatabaseException { transfer = transferAccess.select(transfer.getId(), transfer.getRequester(), transfer.getRequested(), Configuration.configuration.getHOST_ID()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseNoConnectionException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Transfer not found", e); } finally { if (transferAccess != null) { transferAccess.close(); } } - if (transfer == null) { - throw new WaarpDatabaseNoConnectionException("No Transfer found"); - } this.rule = new DbRule(getRuleId()); checkThroughMode(); } @@ -1067,8 +1068,10 @@ protected void optimizedUpdate() throws WaarpDatabaseException { try { transferAccess = DAOFactory.getInstance().getTransferDAO(); transferAccess.update(transfer); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoDataException("Transfer not found", e); } finally { if (transferAccess != null) { transferAccess.close(); @@ -1157,8 +1160,7 @@ public static DbTaskRunner getFromStatement( throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException { DbTaskRunner dbTaskRunner = new DbTaskRunner(); dbTaskRunner.getValues(preparedStatement, dbTaskRunner.allFields); - dbTaskRunner.setFromArray(); - if (dbTaskRunner.rule == null) { + if (dbTaskRunner.rule == null && dbTaskRunner.transfer.getRule() != null) { try { dbTaskRunner.rule = new DbRule(dbTaskRunner.getRuleId()); } catch (WaarpDatabaseException e) { @@ -1167,6 +1169,7 @@ public static DbTaskRunner getFromStatement( } } dbTaskRunner.checkThroughMode(); + dbTaskRunner.setToArray(); dbTaskRunner.isSaved = true; return dbTaskRunner; } @@ -1185,6 +1188,7 @@ public static DbTaskRunner getFromStatementNoDbRule( DbTaskRunner dbTaskRunner = new DbTaskRunner(); dbTaskRunner.getValues(preparedStatement, dbTaskRunner.allFields); dbTaskRunner.setFromArray(); + dbTaskRunner.setToArray(); if (dbTaskRunner.rule == null) { try { dbTaskRunner.rule = new DbRule(dbTaskRunner.getRuleId()); @@ -1559,7 +1563,7 @@ public static DbTaskRunner[] getSelectFromInfoPrepareStatement( } else { transfers = transferAccess.find(filters, limit); } - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseNoConnectionException(e); } finally { if (transferAccess != null) { @@ -2084,8 +2088,10 @@ public static void changeFinishedToDone() transfer.setUpdatedInfo(org.waarp.openr66.pojo.UpdatedInfo.DONE); transferAccess.update(transfer); } - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new WaarpDatabaseNoConnectionException(e); + } catch (DAONoDataException e) { + throw new WaarpDatabaseNoConnectionException("Transfer not found"); } finally { transferAccess.close(); } @@ -3875,6 +3881,7 @@ public String asXML() throws OpenR66ProtocolBusinessException { @Override public ObjectNode getJson() { + setToArray(); ObjectNode node = super.getJson(); if (rescheduledTransfer) { node.put(JSON_RESCHEDULE, true); @@ -3955,6 +3962,7 @@ public static DbTaskRunner fromStringXml(String xml, boolean reverse) throws Ope setRunnerFromElementNoException(runner, document.getRootElement()); try { runner.setFromArray(); + runner.setToArray(); } catch (WaarpDatabaseSqlException e) { logger.error("Cannot read XML", e); throw new OpenR66ProtocolBusinessException("Cannot read XML: " + e.getMessage()); @@ -4129,6 +4137,7 @@ public static void loadXml(File logsFile) throws OpenR66ProtocolBusinessExceptio try { setRunnerFromElement(runnerlog, element); runnerlog.setFromArray(); + runnerlog.setToArray(); runnerlog.insertOrUpdateForLogsImport(); } catch (WaarpDatabaseSqlException e) { error = true; diff --git a/src/main/java/org/waarp/openr66/protocol/http/HttpFormattedHandler.java b/src/main/java/org/waarp/openr66/protocol/http/HttpFormattedHandler.java index 6de1e7cdc..bcc05a11c 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/HttpFormattedHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/HttpFormattedHandler.java @@ -45,9 +45,7 @@ import io.netty.handler.traffic.TrafficCounter; import org.waarp.common.database.DbAdmin; -import org.waarp.common.database.DbPreparedStatement; import org.waarp.common.database.DbSession; -import org.waarp.common.database.exception.WaarpDatabaseException; import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; import org.waarp.common.database.exception.WaarpDatabaseSqlException; import org.waarp.common.exception.FileTransferException; @@ -63,7 +61,7 @@ import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.TransferDAO; import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import org.waarp.openr66.database.DbConstant; import org.waarp.openr66.database.data.DbTaskRunner; import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; @@ -75,7 +73,6 @@ import org.waarp.openr66.protocol.exception.OpenR66ExceptionTrappedFactory; import org.waarp.openr66.protocol.exception.OpenR66ProtocolBusinessNoWriteBackException; import org.waarp.openr66.protocol.localhandler.LocalChannelReference; -import org.waarp.openr66.protocol.localhandler.packet.RequestPacket; /** * Handler for HTTP information support @@ -520,7 +517,7 @@ private void active(ChannelHandlerContext ctx, int nb) { transfers = transferAccess.find(filters, DBTransferDAO.TRANSFER_START_FIELD, false, nb); addRunners(transfers, ErrorCode.PostProcessingOk.getMesg(), nb); - } catch (DAOException e) { + } catch (DAOConnectionException e) { logger.warn("OpenR66 Web Error {}", e.getMessage()); sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); return; @@ -582,7 +579,7 @@ private void error(ChannelHandlerContext ctx, int nb) { transfers = transferAccess.find(filters, DBTransferDAO.TRANSFER_START_FIELD, false, nb/4); addRunners(transfers, TASKSTEP.ERRORTASK.name(), nb/4); - } catch (DAOException e) { + } catch (DAOConnectionException e) { logger.warn("OpenR66 Web Error {}", e.getMessage()); sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); return; @@ -617,7 +614,7 @@ private void done(ChannelHandlerContext ctx, int nb) { transfers = transferAccess.find(filters, DBTransferDAO.TRANSFER_START_FIELD, false, nb); addRunners(transfers, "ALL RUNNERS: " + nb, nb); - } catch (DAOException e) { + } catch (DAOConnectionException e) { logger.warn("OpenR66 Web Error {}", e.getMessage()); sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); return; @@ -650,7 +647,7 @@ private void all(ChannelHandlerContext ctx, int nb) { transfers = transferAccess.find(filters, DBTransferDAO.TRANSFER_START_FIELD, false, nb); addRunners(transfers, "ALL RUNNERS: " + nb, nb); - } catch (DAOException e) { + } catch (DAOConnectionException e) { logger.warn("OpenR66 Web Error {}", e.getMessage()); sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); return; @@ -719,7 +716,7 @@ private void status(ChannelHandlerContext ctx, int nb) { responseContent.append("

Some Transfers are in ERRORTASK


"); status = HttpResponseStatus.INTERNAL_SERVER_ERROR; } - } catch (DAOException e) { + } catch (DAOConnectionException e) { logger.warn("OpenR66 Web Error {}", e.getMessage()); sendError(ctx, HttpResponseStatus.SERVICE_UNAVAILABLE); return; diff --git a/src/main/java/org/waarp/openr66/protocol/http/rest/handler/HttpRestAbstractR66Handler.java b/src/main/java/org/waarp/openr66/protocol/http/rest/handler/HttpRestAbstractR66Handler.java index 35cfe6e15..890e47567 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/rest/handler/HttpRestAbstractR66Handler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/rest/handler/HttpRestAbstractR66Handler.java @@ -148,7 +148,7 @@ public ChannelFuture sendResponse(HttpRestHandler handler, ChannelHandlerContext logger.debug("Will write: {}", body); ChannelFuture future = ctx.writeAndFlush(response); if (handler.isWillClose()) { - System.err.println("Will close session in HttpRestAbstractR66Handler"); + logger.debug("Will close session in HttpRestAbstractR66Handler"); return future; } return null; diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/converters/HostConfigConverter.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/converters/HostConfigConverter.java index 69c1ebbd2..5af0629b6 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/converters/HostConfigConverter.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/converters/HostConfigConverter.java @@ -26,7 +26,8 @@ import com.fasterxml.jackson.databind.node.JsonNodeFactory; import com.fasterxml.jackson.databind.node.ObjectNode; import org.waarp.openr66.dao.BusinessDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Business; import org.waarp.openr66.protocol.http.restv2.errors.RestError; import org.waarp.openr66.protocol.http.restv2.errors.RestErrorException; @@ -198,7 +199,9 @@ public static List getRoles(String hostName) { businessDAO = DAO_FACTORY.getBusinessDAO(); Business config = businessDAO.select(SERVER_NAME); array = getRolesArray(config); - } catch (DAOException e) { + } catch (DAOConnectionException e) { + throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { throw new InternalServerErrorException(e); } finally { if (businessDAO != null) { diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/converters/TransferConverter.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/converters/TransferConverter.java index 569ec0f44..7fb1abf76 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/converters/TransferConverter.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/converters/TransferConverter.java @@ -27,7 +27,8 @@ import org.joda.time.DateTime; import org.waarp.openr66.dao.HostDAO; import org.waarp.openr66.dao.RuleDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Rule; import org.waarp.openr66.pojo.Transfer; import org.waarp.openr66.pojo.UpdatedInfo; @@ -156,7 +157,9 @@ public static Transfer nodeToNewTransfer(ObjectNode object) { ruleDAO = DAO_FACTORY.getRuleDAO(); Rule rule = ruleDAO.select(transfer.getRule()); mode = ModeTrans.fromCode(rule.getMode()); - } catch (DAOException e) { + } catch (DAOConnectionException e) { + throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { throw new InternalServerErrorException(e); } finally { if (ruleDAO != null) { @@ -187,7 +190,7 @@ private static boolean ruleExists(String rule) { try { ruleDAO = DAO_FACTORY.getRuleDAO(); return ruleDAO.exist(rule); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); } finally { if (ruleDAO != null) { @@ -207,7 +210,7 @@ private static boolean hostExists(String host) { try { hostDAO = DAO_FACTORY.getHostDAO(); return hostDAO.exist(host); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); } finally { if (hostDAO != null) { @@ -230,7 +233,9 @@ private static boolean canUseRule(String host, String rule) { ruleDAO = DAO_FACTORY.getRuleDAO(); List hostIds = ruleDAO.select(rule).getHostids(); return !hostIds.isEmpty() && !hostIds.contains(host); - } catch (DAOException e) { + } catch (DAOConnectionException e) { + throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { throw new InternalServerErrorException(e); } finally { if (ruleDAO != null) { diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostConfigHandler.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostConfigHandler.java index 084dbc36e..0d36697fc 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostConfigHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostConfigHandler.java @@ -28,7 +28,8 @@ import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import org.waarp.openr66.dao.BusinessDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Business; import org.waarp.openr66.protocol.http.restv2.converters.HostConfigConverter; import org.waarp.openr66.protocol.http.restv2.errors.RestErrorException; @@ -107,8 +108,10 @@ public void getConfig(HttpRequest request, HttpResponder responder) { } else { responder.sendStatus(NOT_FOUND); } - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (businessDAO != null) { businessDAO.close(); @@ -143,7 +146,7 @@ public void initializeConfig(HttpRequest request, HttpResponder responder) { } else { throw new RestErrorException(ALREADY_EXISTING(SERVER_NAME)); } - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); } finally { if (businessDAO != null) { @@ -180,8 +183,10 @@ public void updateConfig(HttpRequest request, HttpResponder responder) { ObjectNode responseObject = HostConfigConverter.businessToNode(newConfig); String responseText = JsonUtils.nodeToString(responseObject); responder.sendJson(CREATED, responseText); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (businessDAO != null) { businessDAO.close(); @@ -209,8 +214,10 @@ public void deleteConfig(HttpRequest request, HttpResponder responder) { } else { responder.sendStatus(NOT_FOUND); } - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (businessDAO != null) { businessDAO.close(); diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostIdHandler.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostIdHandler.java index 391ce30fb..e07e6c5ee 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostIdHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostIdHandler.java @@ -28,7 +28,8 @@ import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import org.waarp.openr66.dao.HostDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Host; import org.waarp.openr66.protocol.http.restv2.converters.HostConverter; import org.waarp.openr66.protocol.http.restv2.utils.JsonUtils; @@ -109,8 +110,10 @@ public void getHost(HttpRequest request, HttpResponder responder, ObjectNode responseObject = HostConverter.hostToNode(host); String responseText = JsonUtils.nodeToString(responseObject); responder.sendJson(OK, responseText); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (hostDAO != null) { hostDAO.close(); @@ -151,8 +154,10 @@ public void updateHost(HttpRequest request, HttpResponder responder, String responseText = JsonUtils.nodeToString(responseObject); responder.sendJson(CREATED, responseText); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (hostDAO != null) { hostDAO.close(); @@ -183,8 +188,10 @@ public void deleteHost(HttpRequest request, HttpResponder responder, hostDAO.delete(host); responder.sendStatus(NO_CONTENT); } - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (hostDAO != null) { hostDAO.close(); diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostsHandler.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostsHandler.java index 6e3b8e61c..c8e91cc1b 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostsHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/HostsHandler.java @@ -32,7 +32,7 @@ import org.waarp.common.role.RoleDefault.ROLE; import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.HostDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import org.waarp.openr66.pojo.Host; import org.waarp.openr66.protocol.http.restv2.RestConstants; import org.waarp.openr66.protocol.http.restv2.converters.HostConverter; @@ -193,7 +193,7 @@ public void filterHosts(HttpRequest request, HttpResponder responder, try { hostDAO = DAO_FACTORY.getHostDAO(); hosts = hostDAO.find(filters); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); } finally { if (hostDAO != null) { @@ -241,7 +241,7 @@ public void addHost(HttpRequest request, HttpResponder responder) { } hostDAO.insert(host); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); } finally { if (hostDAO != null) { diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/LimitsHandler.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/LimitsHandler.java index 7f5caee3b..61446661f 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/LimitsHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/LimitsHandler.java @@ -28,7 +28,8 @@ import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import org.waarp.openr66.dao.LimitDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Limit; import org.waarp.openr66.protocol.http.restv2.converters.LimitsConverter; import org.waarp.openr66.protocol.http.restv2.errors.RestErrorException; @@ -111,8 +112,10 @@ public void getLimits(HttpRequest request, HttpResponder responder) { } else { responder.sendStatus(NOT_FOUND); } - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (limitDAO != null) { limitDAO.close(); @@ -152,7 +155,7 @@ public void initializeLimits(HttpRequest request, HttpResponder responder) { } else { throw new RestErrorException(ALREADY_EXISTING(SERVER_NAME)); } - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); } finally { if (limitDAO != null) { @@ -197,8 +200,10 @@ public void updateLimits(HttpRequest request, HttpResponder responder) { String responseText = JsonUtils.nodeToString(responseObject); responder.sendJson(CREATED, responseText); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (limitDAO != null) { limitDAO.close(); @@ -228,8 +233,10 @@ public void deleteLimits(HttpRequest request, HttpResponder responder) { } else { responder.sendStatus(NOT_FOUND); } - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (limitDAO != null) { limitDAO.close(); diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/RuleIdHandler.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/RuleIdHandler.java index dac0c12b8..50890384a 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/RuleIdHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/RuleIdHandler.java @@ -28,7 +28,8 @@ import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import org.waarp.openr66.dao.RuleDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Rule; import org.waarp.openr66.protocol.http.restv2.converters.RuleConverter; import org.waarp.openr66.protocol.http.restv2.utils.JsonUtils; @@ -110,8 +111,10 @@ public void getRule(HttpRequest request, HttpResponder responder, ObjectNode responseObject = RuleConverter.ruleToNode(rule); String responseText = JsonUtils.nodeToString(responseObject); responder.sendJson(OK, responseText); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (ruleDAO != null) { ruleDAO.close(); @@ -150,8 +153,10 @@ public void updateRule(HttpRequest request, HttpResponder responder, ObjectNode responseObject = RuleConverter.ruleToNode(newRule); String responseText = JsonUtils.nodeToString(responseObject); responder.sendJson(CREATED, responseText); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (ruleDAO != null) { ruleDAO.close(); @@ -182,8 +187,10 @@ public void deleteRule(HttpRequest request, HttpResponder responder, ruleDAO.delete(rule); responder.sendStatus(NO_CONTENT); } - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (ruleDAO != null) { ruleDAO.close(); diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/RulesHandler.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/RulesHandler.java index 23a020d32..1fac76a24 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/RulesHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/RulesHandler.java @@ -32,7 +32,7 @@ import org.waarp.common.role.RoleDefault.ROLE; import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.RuleDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import org.waarp.openr66.pojo.Rule; import org.waarp.openr66.protocol.http.restv2.converters.RuleConverter.ModeTrans; import org.waarp.openr66.protocol.http.restv2.converters.RuleConverter.Order; @@ -165,7 +165,7 @@ public void filterRules(HttpRequest request, HttpResponder responder, try { ruleDAO = DAO_FACTORY.getRuleDAO(); rules = ruleDAO.find(filters); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); } finally { if (ruleDAO != null) { @@ -213,7 +213,7 @@ public void addRule(HttpRequest request, HttpResponder responder) { } ruleDAO.insert(rule); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); } finally { if (ruleDAO != null) { diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/ServerHandler.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/ServerHandler.java index 14bad3831..eaaf5d053 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/ServerHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/ServerHandler.java @@ -37,7 +37,8 @@ import org.waarp.openr66.dao.HostDAO; import org.waarp.openr66.dao.RuleDAO; import org.waarp.openr66.dao.TransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Business; import org.waarp.openr66.pojo.Host; import org.waarp.openr66.pojo.Rule; @@ -237,8 +238,10 @@ public void deactivate(HttpRequest request, HttpResponder responder) { DefaultHttpHeaders headers = new DefaultHttpHeaders(); headers.add("active", host.isActive()); responder.sendStatus(NO_CONTENT, headers); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (hostDAO != null) { hostDAO.close(); @@ -432,8 +435,10 @@ public void getLogs(HttpRequest request, HttpResponder responder, String responseText = JsonUtils.nodeToString(responseObject); responder.sendJson(OK, responseText); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (transferDAO != null) { transferDAO.close(); @@ -566,8 +571,10 @@ public void getConfig(HttpRequest request, HttpResponder responder, String responseText = JsonUtils.nodeToString(responseObject); responder.sendJson(OK, responseText); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (hostDAO != null) { hostDAO.close(); } if (ruleDAO != null) { ruleDAO.close(); } @@ -731,8 +738,10 @@ public void setConfig(HttpRequest request, HttpResponder responder, throw new RestErrorException(errors); } - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (hostDAO != null) { hostDAO.close(); } if (ruleDAO != null) { ruleDAO.close(); } diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/TransferIdHandler.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/TransferIdHandler.java index 5e944cc5e..462537203 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/TransferIdHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/TransferIdHandler.java @@ -28,7 +28,8 @@ import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import org.waarp.openr66.dao.TransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Transfer; import org.waarp.openr66.protocol.http.restv2.converters.TransferConverter; import org.waarp.openr66.protocol.http.restv2.utils.JsonUtils; @@ -117,8 +118,10 @@ public void getTransfer(HttpRequest request, HttpResponder responder, } } catch (NumberFormatException e) { responder.sendStatus(NOT_FOUND); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (transferDAO != null) { transferDAO.close(); @@ -176,8 +179,10 @@ public void restartTransfer(HttpRequest request, HttpResponder responder, } } catch (NumberFormatException e) { responder.sendStatus(NOT_FOUND); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (transferDAO != null) { transferDAO.close(); @@ -234,8 +239,10 @@ public void stopTransfer(HttpRequest request, HttpResponder responder, } } catch (NumberFormatException e) { responder.sendStatus(NOT_FOUND); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (transferDAO != null) { transferDAO.close(); @@ -291,8 +298,10 @@ public void cancelTransfer(HttpRequest request, HttpResponder responder, } } catch (NumberFormatException e) { responder.sendStatus(NOT_FOUND); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { + responder.sendStatus(NOT_FOUND); } finally { if (transferDAO != null) { transferDAO.close(); diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/TransfersHandler.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/TransfersHandler.java index 9f2f7c177..935d67958 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/TransfersHandler.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/dbhandlers/TransfersHandler.java @@ -33,7 +33,7 @@ import org.waarp.common.role.RoleDefault.ROLE; import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.TransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import org.waarp.openr66.pojo.Transfer; import org.waarp.openr66.protocol.http.restv2.converters.TransferConverter; import org.waarp.openr66.protocol.http.restv2.errors.RestError; @@ -200,7 +200,7 @@ public void filterTransfer(HttpRequest request, HttpResponder responder, transferDAO = DAO_FACTORY.getTransferDAO(); transferList = transferDAO.find(filters, order.column, order.ascend, limit, offset); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); } finally { if (transferDAO != null) { @@ -238,7 +238,7 @@ public void createTransfer(HttpRequest request, HttpResponder responder) { try { transferDAO = DAO_FACTORY.getTransferDAO(); transferDAO.insert(transfer); - } catch (DAOException e) { + } catch (DAOConnectionException e) { throw new InternalServerErrorException(e); } finally { if (transferDAO != null) { diff --git a/src/main/java/org/waarp/openr66/protocol/http/restv2/resthandlers/RestHandlerHook.java b/src/main/java/org/waarp/openr66/protocol/http/restv2/resthandlers/RestHandlerHook.java index ee0b2fe43..1f66dfe58 100644 --- a/src/main/java/org/waarp/openr66/protocol/http/restv2/resthandlers/RestHandlerHook.java +++ b/src/main/java/org/waarp/openr66/protocol/http/restv2/resthandlers/RestHandlerHook.java @@ -33,7 +33,8 @@ import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.utility.Base64; import org.waarp.openr66.dao.HostDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Host; import org.waarp.openr66.protocol.http.restv2.RestServiceInitializer; import org.waarp.openr66.protocol.http.restv2.converters.HostConfigConverter; @@ -288,7 +289,9 @@ private String checkCredentials(HttpRequest request) { throw new NotAllowedException("User does not exist."); } host = hostDAO.select(user); - } catch (DAOException e) { + } catch (DAOConnectionException e) { + throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { throw new InternalServerErrorException(e); } finally { if (hostDAO != null) { @@ -338,7 +341,9 @@ private String checkCredentials(HttpRequest request) { throw new NotAllowedException("User does not exist."); } host = hostDAO.select(authUser); - } catch (DAOException e) { + } catch (DAOConnectionException e) { + throw new InternalServerErrorException(e); + } catch (DAONoDataException e) { throw new InternalServerErrorException(e); } finally { if (hostDAO != null) { diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/ConnectionActions.java b/src/main/java/org/waarp/openr66/protocol/localhandler/ConnectionActions.java index d0318f608..9e631679b 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/ConnectionActions.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/ConnectionActions.java @@ -369,7 +369,8 @@ public void authent(Channel channel, AuthentPacket packet, boolean isSsl) session.newState(AUTHENTR); } - System.err.println(localChannelReference == null); + logger.debug("LocalChannelReference null? {}", + localChannelReference == null); if (localChannelReference.getDbSession() != null) { localChannelReference.getDbSession().useConnection(); } diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java index 89231c8d5..aeade7362 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/LocalTransaction.java @@ -102,8 +102,6 @@ public LocalTransaction() { serverBootstrap.channel(LocalServerChannel.class); serverBootstrap.group(Configuration.configuration.getLocalBossGroup(), Configuration.configuration.getLocalWorkerGroup()); - serverBootstrap.option(ChannelOption.TCP_NODELAY, true); - serverBootstrap.option(ChannelOption.SO_REUSEADDR, true); serverBootstrap.childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) Configuration.configuration.getTIMEOUTCON()); serverBootstrap.childHandler(new LocalServerInitializer()); try { diff --git a/src/main/java/org/waarp/openr66/protocol/localhandler/ServerActions.java b/src/main/java/org/waarp/openr66/protocol/localhandler/ServerActions.java index 0d63a853c..e41ebf47c 100644 --- a/src/main/java/org/waarp/openr66/protocol/localhandler/ServerActions.java +++ b/src/main/java/org/waarp/openr66/protocol/localhandler/ServerActions.java @@ -2373,6 +2373,7 @@ public final ValidPacket informationRequest(long id, boolean isTo, String remote } DbTaskRunner runner = null; if (isTo) { + logger.info("{} {} {}", id, remote, local); try { runner = new DbTaskRunner(session, null, id, remote, local); } catch (WaarpDatabaseException e) { diff --git a/src/main/java/org/waarp/openr66/protocol/utils/Version.java b/src/main/java/org/waarp/openr66/protocol/utils/Version.java index 5eafe65e8..a4fa803b6 100644 --- a/src/main/java/org/waarp/openr66/protocol/utils/Version.java +++ b/src/main/java/org/waarp/openr66/protocol/utils/Version.java @@ -3,7 +3,7 @@ /** Provides the version information of Waarp OpenR66. */ public final class Version { /** The version identifier. */ - public static final String ID = "3.1.0"; + public static final String ID = "3.1.1"; /** Prints out the version identifier to stdout. */ public static void main(String[] args) { System.out.println(ID); } private Version() { super(); } diff --git a/src/test/java/org/waarp/openr66/dao/database/DBAllDAOTest.java b/src/test/java/org/waarp/openr66/dao/database/DBAllDAOTest.java index 9e1ae1fab..0c016dda7 100644 --- a/src/test/java/org/waarp/openr66/dao/database/DBAllDAOTest.java +++ b/src/test/java/org/waarp/openr66/dao/database/DBAllDAOTest.java @@ -25,13 +25,15 @@ import org.junit.Test; import org.waarp.openr66.context.ErrorCode; import org.waarp.openr66.dao.BusinessDAO; +import org.waarp.openr66.dao.DAOFactory; import org.waarp.openr66.dao.Filter; import org.waarp.openr66.dao.HostDAO; import org.waarp.openr66.dao.LimitDAO; import org.waarp.openr66.dao.MultipleMonitorDAO; import org.waarp.openr66.dao.RuleDAO; import org.waarp.openr66.dao.TransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; import org.waarp.openr66.pojo.Business; import org.waarp.openr66.pojo.Host; import org.waarp.openr66.pojo.Limit; @@ -54,6 +56,75 @@ public abstract class DBAllDAOTest { private Connection con; + private DAOFactoryTest factoryTest = new DAOFactoryTest(); + + public DAOFactory getDaoFactory() { + return factoryTest; + } + + class DAOFactoryTest extends DAOFactory { + + @Override + public BusinessDAO getBusinessDAO() throws DAOConnectionException { + try { + return new DBBusinessDAO(getConnection()); + } catch (SQLException e) { + fail(e.getMessage()); + return null; + } + } + + @Override + public HostDAO getHostDAO() throws DAOConnectionException { + try { + return new DBHostDAO(getConnection()); + } catch (SQLException e) { + fail(e.getMessage()); + return null; + } + } + + @Override + public LimitDAO getLimitDAO() throws DAOConnectionException { + try { + return new DBLimitDAO(getConnection()); + } catch (SQLException e) { + fail(e.getMessage()); + return null; + } + } + + @Override + public MultipleMonitorDAO getMultipleMonitorDAO() + throws DAOConnectionException { + try { + return new DBMultipleMonitorDAO(getConnection()); + } catch (SQLException e) { + fail(e.getMessage()); + return null; + } + } + + @Override + public RuleDAO getRuleDAO() throws DAOConnectionException { + try { + return new DBRuleDAO(getConnection()); + } catch (SQLException e) { + fail(e.getMessage()); + return null; + } + } + + @Override + public TransferDAO getTransferDAO() throws DAOConnectionException { + try { + return getDAO(getConnection()); + } catch (SQLException e) { + fail(e.getMessage()); + return null; + } + } + } public void runScript(String script) { try { @@ -84,7 +155,9 @@ public void setUp() { public void wrapUp() { try { cleanDB(); - con.close(); + if (con != null) { + con.close(); + } } catch (Exception e) { fail(e.getMessage()); } @@ -92,13 +165,14 @@ public void wrapUp() { public abstract void cleanDB() throws SQLException; + /******************* * BUSINESS *******************/ @Test public void testDeleteAllBusiness() { try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); + BusinessDAO dao = getDaoFactory().getBusinessDAO(); dao.deleteAll(); ResultSet res = con.createStatement() @@ -112,7 +186,7 @@ public void testDeleteAllBusiness() { @Test public void testDeleteBusiness() { try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); + BusinessDAO dao = getDaoFactory().getBusinessDAO(); dao.delete(new Business("server1", "", "", "", "")); ResultSet res = con.createStatement() @@ -127,7 +201,7 @@ public void testDeleteBusiness() { @Test public void testGetAllBusiness() { try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); + BusinessDAO dao = getDaoFactory().getBusinessDAO(); assertEquals(5, dao.getAll().size()); } catch (Exception e) { fail(e.getMessage()); @@ -137,16 +211,21 @@ public void testGetAllBusiness() { @Test public void testSelectBusiness() { try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); + BusinessDAO dao = getDaoFactory().getBusinessDAO(); Business business = dao.select("server1"); - Business business2 = dao.select("ghost"); assertEquals("joyaux", business.getBusiness()); assertEquals("marchand", business.getRoles()); assertEquals("le borgne", business.getAliases()); assertEquals("misc", business.getOthers()); assertEquals(UpdatedInfo.NOTUPDATED, business.getUpdatedInfo()); - assertEquals(null, business2); + + try { + dao.select("ghost"); + fail("Should raised an exception"); + } catch (DAONoDataException e) { + // Ignore since OK + } } catch (Exception e) { fail(e.getMessage()); } @@ -155,7 +234,7 @@ public void testSelectBusiness() { @Test public void testExistBusiness() { try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); + BusinessDAO dao = getDaoFactory().getBusinessDAO(); assertEquals(true, dao.exist("server1")); assertEquals(false, dao.exist("ghost")); } catch (Exception e) { @@ -167,7 +246,7 @@ public void testExistBusiness() { @Test public void testInsertBusiness() { try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); + BusinessDAO dao = getDaoFactory().getBusinessDAO(); dao.insert(new Business("chacha", "lolo", "lala", "minou", "ect", UpdatedInfo.TOSUBMIT)); @@ -196,7 +275,7 @@ public void testInsertBusiness() { @Test public void testUpdateBusiness() { try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); + BusinessDAO dao = getDaoFactory().getBusinessDAO(); dao.update(new Business("server2", "lolo", "lala", "minou", "ect", UpdatedInfo.RUNNING)); @@ -222,7 +301,7 @@ public void testFindBusiness() { ArrayList map = new ArrayList(); map.add(new Filter(DBBusinessDAO.BUSINESS_FIELD, "=", "ba")); try { - BusinessDAO dao = new DBBusinessDAO(getConnection()); + BusinessDAO dao = getDaoFactory().getBusinessDAO(); assertEquals(2, dao.find(map).size()); } catch (Exception e) { fail(e.getMessage()); @@ -236,7 +315,7 @@ public void testFindBusiness() { @Test public void testDeleteAllHost() { try { - HostDAO dao = new DBHostDAO(getConnection()); + HostDAO dao = getDaoFactory().getHostDAO(); dao.deleteAll(); ResultSet res = con.createStatement() @@ -250,7 +329,7 @@ public void testDeleteAllHost() { @Test public void testDeleteHost() { try { - HostDAO dao = new DBHostDAO(getConnection()); + HostDAO dao = getDaoFactory().getHostDAO(); dao.delete(new Host("server1", "", 666, null, false, false)); ResultSet res = con.createStatement() @@ -265,7 +344,7 @@ public void testDeleteHost() { @Test public void testGetAllHost() { try { - HostDAO dao = new DBHostDAO(getConnection()); + HostDAO dao = getDaoFactory().getHostDAO(); assertEquals(3, dao.getAll().size()); } catch (Exception e) { fail(e.getMessage()); @@ -275,9 +354,8 @@ public void testGetAllHost() { @Test public void testSelectHost() { try { - HostDAO dao = new DBHostDAO(getConnection()); + HostDAO dao = getDaoFactory().getHostDAO(); Host host = dao.select("server1"); - Host host2 = dao.select("ghost"); assertEquals("server1", host.getHostid()); assertEquals("127.0.0.1", host.getAddress()); @@ -290,7 +368,12 @@ public void testSelectHost() { assertEquals(false, host.isActive()); assertEquals(UpdatedInfo.TOSUBMIT, host.getUpdatedInfo()); - assertEquals(null, host2); + try { + dao.select("ghost"); + fail("Should raised an exception"); + } catch (DAONoDataException e) { + // Ignore since OK + } } catch (Exception e) { fail(e.getMessage()); } @@ -299,7 +382,7 @@ public void testSelectHost() { @Test public void testExistHost() { try { - HostDAO dao = new DBHostDAO(getConnection()); + HostDAO dao = getDaoFactory().getHostDAO(); assertEquals(true, dao.exist("server1")); assertEquals(false, dao.exist("ghost")); } catch (Exception e) { @@ -311,7 +394,7 @@ public void testExistHost() { @Test public void testInsertHost() { try { - HostDAO dao = new DBHostDAO(getConnection()); + HostDAO dao = getDaoFactory().getHostDAO(); dao.insert( new Host("chacha", "address", 666, "aaa".getBytes("utf-8"), false, false)); @@ -343,7 +426,7 @@ public void testInsertHost() { @Test public void testUpdateHost() { try { - HostDAO dao = new DBHostDAO(getConnection()); + HostDAO dao = getDaoFactory().getHostDAO(); dao.update( new Host("server2", "address", 666, "password".getBytes("utf-8"), false, false)); @@ -373,7 +456,7 @@ public void testFindHost() { ArrayList map = new ArrayList(); map.add(new Filter(DBHostDAO.ADDRESS_FIELD, "=", "127.0.0.1")); try { - HostDAO dao = new DBHostDAO(getConnection()); + HostDAO dao = getDaoFactory().getHostDAO(); assertEquals(2, dao.find(map).size()); } catch (Exception e) { e.printStackTrace(); @@ -389,7 +472,7 @@ public void testFindHost() { @Test public void testDeleteAllLimit() { try { - LimitDAO dao = new DBLimitDAO(getConnection()); + LimitDAO dao = getDaoFactory().getLimitDAO(); dao.deleteAll(); ResultSet res = con.createStatement() @@ -403,7 +486,7 @@ public void testDeleteAllLimit() { @Test public void testDeleteLimit() { try { - LimitDAO dao = new DBLimitDAO(getConnection()); + LimitDAO dao = getDaoFactory().getLimitDAO(); dao.delete(new Limit("server1", 0l)); ResultSet res = con.createStatement() @@ -418,7 +501,7 @@ public void testDeleteLimit() { @Test public void testGetAllLimit() { try { - LimitDAO dao = new DBLimitDAO(getConnection()); + LimitDAO dao = getDaoFactory().getLimitDAO(); assertEquals(3, dao.getAll().size()); } catch (Exception e) { fail(e.getMessage()); @@ -428,9 +511,8 @@ public void testGetAllLimit() { @Test public void testSelectLimit() { try { - LimitDAO dao = new DBLimitDAO(getConnection()); + LimitDAO dao = getDaoFactory().getLimitDAO(); Limit limit = dao.select("server1"); - Limit limit2 = dao.select("ghost"); assertEquals("server1", limit.getHostid()); assertEquals(1, limit.getReadGlobalLimit()); @@ -439,7 +521,13 @@ public void testSelectLimit() { assertEquals(4, limit.getWriteSessionLimit()); assertEquals(5, limit.getDelayLimit()); assertEquals(UpdatedInfo.NOTUPDATED, limit.getUpdatedInfo()); - assertEquals(null, limit2); + + try { + dao.select("ghost"); + fail("Should raised an exception"); + } catch (DAONoDataException e) { + // Ignore since OK + } } catch (Exception e) { fail(e.getMessage()); } @@ -448,7 +536,7 @@ public void testSelectLimit() { @Test public void testExistLimit() { try { - LimitDAO dao = new DBLimitDAO(getConnection()); + LimitDAO dao = getDaoFactory().getLimitDAO(); assertEquals(true, dao.exist("server1")); assertEquals(false, dao.exist("ghost")); } catch (Exception e) { @@ -460,7 +548,7 @@ public void testExistLimit() { @Test public void testInsertLimit() { try { - LimitDAO dao = new DBLimitDAO(getConnection()); + LimitDAO dao = getDaoFactory().getLimitDAO(); dao.insert(new Limit("chacha", 4l, 1l, 5l, 13l, 12, UpdatedInfo.TOSUBMIT)); @@ -490,7 +578,7 @@ public void testInsertLimit() { @Test public void testUpdateLimit() { try { - LimitDAO dao = new DBLimitDAO(getConnection()); + LimitDAO dao = getDaoFactory().getLimitDAO(); dao.update(new Limit("server2", 4l, 1l, 5l, 13l, 12l, UpdatedInfo.RUNNING)); @@ -517,7 +605,7 @@ public void testFindLimit() { ArrayList map = new ArrayList(); map.add(new Filter(DBLimitDAO.READ_SESSION_LIMIT_FIELD, ">", 2)); try { - LimitDAO dao = new DBLimitDAO(getConnection()); + LimitDAO dao = getDaoFactory().getLimitDAO(); assertEquals(2, dao.find(map).size()); } catch (Exception e) { fail(e.getMessage()); @@ -533,7 +621,11 @@ public void testFindLimit() { @Test public void testDeleteAllMultipleMonitor() { try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + MultipleMonitorDAO dao = getDaoFactory().getMultipleMonitorDAO(); + if (dao == null) { + // ignore since XML + return; + } dao.deleteAll(); ResultSet res = con.createStatement() @@ -547,7 +639,11 @@ public void testDeleteAllMultipleMonitor() { @Test public void testDeleteMultipleMonitor() { try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + MultipleMonitorDAO dao = getDaoFactory().getMultipleMonitorDAO(); + if (dao == null) { + // ignore since XML + return; + } dao.delete(new MultipleMonitor("server1", 0, 0, 0)); ResultSet res = con.createStatement() @@ -562,7 +658,11 @@ public void testDeleteMultipleMonitor() { @Test public void testGetAllMultipleMonitor() { try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + MultipleMonitorDAO dao = getDaoFactory().getMultipleMonitorDAO(); + if (dao == null) { + // ignore since XML + return; + } assertEquals(4, dao.getAll().size()); } catch (Exception e) { fail(e.getMessage()); @@ -572,15 +672,23 @@ public void testGetAllMultipleMonitor() { @Test public void testSelectMultipleMonitor() { try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + MultipleMonitorDAO dao = getDaoFactory().getMultipleMonitorDAO(); + if (dao == null) { + // ignore since XML + return; + } MultipleMonitor multiple = dao.select("server1"); - MultipleMonitor multiple2 = dao.select("ghost"); assertEquals("server1", multiple.getHostid()); assertEquals(11, multiple.getCountConfig()); assertEquals(29, multiple.getCountRule()); assertEquals(18, multiple.getCountHost()); - assertEquals(null, multiple2); + try { + dao.select("ghost"); + fail("Should raised an exception"); + } catch (DAONoDataException e) { + // Ignore since OK + } } catch (Exception e) { fail(e.getMessage()); } @@ -589,7 +697,11 @@ public void testSelectMultipleMonitor() { @Test public void testExistMultipleMonitor() { try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + MultipleMonitorDAO dao = getDaoFactory().getMultipleMonitorDAO(); + if (dao == null) { + // ignore since XML + return; + } assertEquals(true, dao.exist("server1")); assertEquals(false, dao.exist("ghost")); } catch (Exception e) { @@ -601,7 +713,11 @@ public void testExistMultipleMonitor() { @Test public void testInsertMultipleMonitor() { try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + MultipleMonitorDAO dao = getDaoFactory().getMultipleMonitorDAO(); + if (dao == null) { + // ignore since XML + return; + } dao.insert(new MultipleMonitor("chacha", 31, 19, 98)); ResultSet res = con.createStatement() @@ -626,7 +742,11 @@ public void testInsertMultipleMonitor() { @Test public void testUpdateMultipleMonitor() { try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + MultipleMonitorDAO dao = getDaoFactory().getMultipleMonitorDAO(); + if (dao == null) { + // ignore since XML + return; + } dao.update(new MultipleMonitor("server2", 31, 19, 98)); ResultSet res = con.createStatement() @@ -648,7 +768,11 @@ public void testFindMultipleMonitor() { ArrayList map = new ArrayList(); map.add(new Filter(DBMultipleMonitorDAO.COUNT_CONFIG_FIELD, "=", 0)); try { - MultipleMonitorDAO dao = new DBMultipleMonitorDAO(getConnection()); + MultipleMonitorDAO dao = getDaoFactory().getMultipleMonitorDAO(); + if (dao == null) { + // ignore since XML + return; + } assertEquals(2, dao.find(map).size()); } catch (Exception e) { fail(e.getMessage()); @@ -664,7 +788,7 @@ public void testFindMultipleMonitor() { @Test public void testDeleteAllRule() { try { - RuleDAO dao = new DBRuleDAO(getConnection()); + RuleDAO dao = getDaoFactory().getRuleDAO(); dao.deleteAll(); ResultSet res = con.createStatement() @@ -678,7 +802,7 @@ public void testDeleteAllRule() { @Test public void testDeleteRule() { try { - RuleDAO dao = new DBRuleDAO(getConnection()); + RuleDAO dao = getDaoFactory().getRuleDAO(); dao.delete(new Rule("default", 1)); ResultSet res = con.createStatement() @@ -693,7 +817,7 @@ public void testDeleteRule() { @Test public void testGetAllRule() { try { - RuleDAO dao = new DBRuleDAO(getConnection()); + RuleDAO dao = getDaoFactory().getRuleDAO(); assertEquals(3, dao.getAll().size()); } catch (Exception e) { fail(e.getMessage()); @@ -703,9 +827,8 @@ public void testGetAllRule() { @Test public void testSelectRule() { try { - RuleDAO dao = new DBRuleDAO(getConnection()); + RuleDAO dao = getDaoFactory().getRuleDAO(); Rule rule = dao.select("dummy"); - Rule rule2 = dao.select("ghost"); assertEquals("dummy", rule.getName()); assertEquals(1, rule.getMode()); @@ -721,7 +844,12 @@ public void testSelectRule() { assertEquals(0, rule.getSPostTasks().size()); assertEquals(0, rule.getSErrorTasks().size()); assertEquals(UpdatedInfo.UNKNOWN, rule.getUpdatedInfo()); - assertEquals(null, rule2); + try { + dao.select("ghost"); + fail("Should raised an exception"); + } catch (DAONoDataException e) { + // Ignore since OK + } } catch (Exception e) { fail(e.getMessage()); } @@ -730,7 +858,7 @@ public void testSelectRule() { @Test public void testExistRule() { try { - RuleDAO dao = new DBRuleDAO(getConnection()); + RuleDAO dao = getDaoFactory().getRuleDAO(); assertEquals(true, dao.exist("dummy")); assertEquals(false, dao.exist("ghost")); } catch (Exception e) { @@ -742,7 +870,7 @@ public void testExistRule() { @Test public void testInsertRule() { try { - RuleDAO dao = new DBRuleDAO(getConnection()); + RuleDAO dao = getDaoFactory().getRuleDAO(); dao.insert(new Rule("chacha", 2)); ResultSet res = con.createStatement() @@ -780,7 +908,7 @@ public void testInsertRule() { @Test public void testUpdateRule() { try { - RuleDAO dao = new DBRuleDAO(getConnection()); + RuleDAO dao = getDaoFactory().getRuleDAO(); dao.update(new Rule("dummy", 2)); ResultSet res = con.createStatement() @@ -816,7 +944,7 @@ public void testFindRule() { ArrayList map = new ArrayList(); map.add(new Filter(DBRuleDAO.MODE_TRANS_FIELD, "=", 1)); try { - RuleDAO dao = new DBRuleDAO(getConnection()); + RuleDAO dao = getDaoFactory().getRuleDAO(); assertEquals(2, dao.find(map).size()); } catch (Exception e) { fail(e.getMessage()); @@ -838,7 +966,8 @@ public void testDeleteAllTransfer() throws Exception { assertEquals(false, res.next()); } - public abstract TransferDAO getDAO(Connection con) throws DAOException; + public abstract TransferDAO getDAO(Connection con) throws + DAOConnectionException; @Test public void testDeleteTransfer() throws Exception { @@ -866,10 +995,14 @@ public void testGetAllTransfer() throws Exception { public void testSelectTransfer() throws Exception { TransferDAO dao = getDAO(getConnection()); Transfer transfer = dao.select(0l, "server1", "server2", "server1"); - Transfer transfer2 = dao.select(1l, "server1", "server2", "server1"); assertEquals(0, transfer.getId()); - assertEquals(null, transfer2); + try { + dao.select(1l, "server1", "server2", "server1"); + fail("Should raised an exception"); + } catch (DAONoDataException e) { + // Ignore since OK + } } @Test diff --git a/src/test/java/org/waarp/openr66/dao/database/h2/DbH2DAOTest.java b/src/test/java/org/waarp/openr66/dao/database/h2/DbH2DAOTest.java index fd302e063..656bd11c0 100644 --- a/src/test/java/org/waarp/openr66/dao/database/h2/DbH2DAOTest.java +++ b/src/test/java/org/waarp/openr66/dao/database/h2/DbH2DAOTest.java @@ -22,12 +22,13 @@ import org.waarp.openr66.dao.database.DBAllDAOTest; import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; + public class DbH2DAOTest extends DBAllDAOTest { private String createScript = "h2/create.sql"; @@ -54,7 +55,7 @@ public void cleanDB() { } @Override - public DBTransferDAO getDAO(Connection con) throws DAOException { + public DBTransferDAO getDAO(Connection con) throws DAOConnectionException { return new H2TransferDAO(con); } diff --git a/src/test/java/org/waarp/openr66/dao/database/mariadb/DbMariadbDAOTest.java b/src/test/java/org/waarp/openr66/dao/database/mariadb/DbMariadbDAOTest.java index d28cddd55..b85ef5650 100644 --- a/src/test/java/org/waarp/openr66/dao/database/mariadb/DbMariadbDAOTest.java +++ b/src/test/java/org/waarp/openr66/dao/database/mariadb/DbMariadbDAOTest.java @@ -24,8 +24,7 @@ import org.testcontainers.containers.MariaDBContainer; import org.waarp.openr66.dao.database.DBAllDAOTest; import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.database.h2.H2TransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import java.sql.Connection; import java.sql.DriverManager; @@ -40,7 +39,7 @@ public class DbMariadbDAOTest extends DBAllDAOTest { private String cleanScript = "mariadb/clean.sql"; @Override - public DBTransferDAO getDAO(Connection con) throws DAOException { + public DBTransferDAO getDAO(Connection con) throws DAOConnectionException { return new MariaDBTransferDAO(con); } diff --git a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBMySQLDAOTransfer.java b/src/test/java/org/waarp/openr66/dao/database/mySQL/DBMySQLDAOTest.java similarity index 91% rename from src/test/java/org/waarp/openr66/dao/database/mySQL/DBMySQLDAOTransfer.java rename to src/test/java/org/waarp/openr66/dao/database/mySQL/DBMySQLDAOTest.java index 075a5c07a..022291faf 100644 --- a/src/test/java/org/waarp/openr66/dao/database/mySQL/DBMySQLDAOTransfer.java +++ b/src/test/java/org/waarp/openr66/dao/database/mySQL/DBMySQLDAOTest.java @@ -25,13 +25,13 @@ import org.waarp.openr66.dao.database.DBAllDAOTest; import org.waarp.openr66.dao.database.DBTransferDAO; import org.waarp.openr66.dao.database.mariadb.MariaDBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; -public class DBMySQLDAOTransfer extends DBAllDAOTest { +public class DBMySQLDAOTest extends DBAllDAOTest { @ClassRule public static MySQLContainer db = new MySQLContainer(); @@ -40,7 +40,7 @@ public class DBMySQLDAOTransfer extends DBAllDAOTest { private String cleanScript = "mysql/clean.sql"; @Override - public DBTransferDAO getDAO(Connection con) throws DAOException { + public DBTransferDAO getDAO(Connection con) throws DAOConnectionException { return new MariaDBTransferDAO(con); } diff --git a/src/test/java/org/waarp/openr66/dao/database/oracle/DBOracleDBDAOTest.java b/src/test/java/org/waarp/openr66/dao/database/oracle/DBOracleDBDAOTest.java index 1fe786fdb..4c483022a 100644 --- a/src/test/java/org/waarp/openr66/dao/database/oracle/DBOracleDBDAOTest.java +++ b/src/test/java/org/waarp/openr66/dao/database/oracle/DBOracleDBDAOTest.java @@ -24,7 +24,7 @@ import org.testcontainers.containers.OracleContainer; import org.waarp.openr66.dao.database.DBAllDAOTest; import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import java.sql.Connection; import java.sql.DriverManager; @@ -40,7 +40,7 @@ public class DBOracleDBDAOTest extends DBAllDAOTest { private String cleanScript = "oracle/clean.sql"; @Override - public DBTransferDAO getDAO(Connection con) throws DAOException { + public DBTransferDAO getDAO(Connection con) throws DAOConnectionException { return new OracleTransferDAO(con); } diff --git a/src/test/java/org/waarp/openr66/dao/database/postgres/DBPostgreSQLDAOTest.java b/src/test/java/org/waarp/openr66/dao/database/postgres/DBPostgreSQLDAOTest.java index 30471c6dc..e2d6e6c3b 100644 --- a/src/test/java/org/waarp/openr66/dao/database/postgres/DBPostgreSQLDAOTest.java +++ b/src/test/java/org/waarp/openr66/dao/database/postgres/DBPostgreSQLDAOTest.java @@ -24,7 +24,7 @@ import org.testcontainers.containers.PostgreSQLContainer; import org.waarp.openr66.dao.database.DBAllDAOTest; import org.waarp.openr66.dao.database.DBTransferDAO; -import org.waarp.openr66.dao.exception.DAOException; +import org.waarp.openr66.dao.exception.DAOConnectionException; import java.sql.Connection; import java.sql.DriverManager; @@ -39,7 +39,7 @@ public class DBPostgreSQLDAOTest extends DBAllDAOTest { private String cleanScript = "postgresql/clean.sql"; @Override - public DBTransferDAO getDAO(Connection con) throws DAOException { + public DBTransferDAO getDAO(Connection con) throws DAOConnectionException { return new PostgreSQLTransferDAO(con); } diff --git a/src/test/java/org/waarp/openr66/dao/database/xml/DbXmlDAOTestNo.java b/src/test/java/org/waarp/openr66/dao/database/xml/DbXmlDAOTestNo.java new file mode 100644 index 000000000..1501a720b --- /dev/null +++ b/src/test/java/org/waarp/openr66/dao/database/xml/DbXmlDAOTestNo.java @@ -0,0 +1,193 @@ +/******************************************************************************* + * This file is part of Waarp Project (named also Waarp or GG). + * + * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + * + * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + * + * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + ******************************************************************************/ + +package org.waarp.openr66.dao.database.xml; + +import org.waarp.openr66.dao.BusinessDAO; +import org.waarp.openr66.dao.DAOFactory; +import org.waarp.openr66.dao.HostDAO; +import org.waarp.openr66.dao.LimitDAO; +import org.waarp.openr66.dao.MultipleMonitorDAO; +import org.waarp.openr66.dao.RuleDAO; +import org.waarp.openr66.dao.TransferDAO; +import org.waarp.openr66.dao.database.DBAllDAOTest; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.xml.XMLBusinessDAO; +import org.waarp.openr66.dao.xml.XMLHostDAO; +import org.waarp.openr66.dao.xml.XMLRuleDAO; +import org.waarp.openr66.dao.xml.XMLTransferDAO; +import org.waarp.openr66.dao.xml.XMLLimitDAO; +import org.waarp.openr66.pojo.Host; +import org.waarp.openr66.pojo.Limit; +import org.waarp.openr66.pojo.Rule; +import org.waarp.openr66.pojo.Transfer; +import org.waarp.openr66.pojo.UpdatedInfo; + +import java.sql.Connection; +import java.sql.SQLException; + +import static org.junit.Assert.*; + +/** + * Not ready for tests + */ +public abstract class DbXmlDAOTestNo extends DBAllDAOTest { + static final String path = "/tmp/R66/arch"; + DAOFactoryTest factoryTest = new DAOFactoryTest(); + + @Override + public DAOFactory getDaoFactory() { + return factoryTest; + } + + class DAOFactoryTest extends DAOFactory { + + @Override + public BusinessDAO getBusinessDAO() throws DAOConnectionException { + return new XMLBusinessDAO(path); + } + + @Override + public HostDAO getHostDAO() throws DAOConnectionException { + return new XMLHostDAO(path); + } + + @Override + public LimitDAO getLimitDAO() throws DAOConnectionException { + return new XMLLimitDAO(path); + } + + @Override + public MultipleMonitorDAO getMultipleMonitorDAO() + throws DAOConnectionException { + return null; + } + + @Override + public RuleDAO getRuleDAO() throws DAOConnectionException { + return new XMLRuleDAO(path); + } + + @Override + public TransferDAO getTransferDAO() throws DAOConnectionException { + try { + return getDAO(getConnection()); + } catch (SQLException e) { + fail(e.getMessage()); + return null; + } + } + } + + @Override + public Connection getConnection() throws SQLException { + // No connection + return null; + } + + @Override + public void initDB() { + // Init through Map + try { + XMLLimitDAO dao = new XMLLimitDAO(path); + dao.deleteAll(); + dao.insert(new Limit("server1", 1, 2, 3, 4, 5, + UpdatedInfo.valueOf(1))); + dao.insert(new Limit("server2", 2, 3, 2, 2, 2, + UpdatedInfo.valueOf(0))); + dao.insert(new Limit("server3", 5, 6, 3, 4, 3, + UpdatedInfo.valueOf(0))); + } catch (DAOConnectionException e) { + e.printStackTrace(); + } + try { + XMLBusinessDAO dao = new XMLBusinessDAO(path); + dao.deleteAll(); + } catch (DAOConnectionException e) { + e.printStackTrace(); + } + /* + INSERT INTO hostconfig VALUES ('joyaux', 'marchand', 'le borgne', 'misc', 1, 'server1'); + INSERT INTO hostconfig VALUES ('ba', '', '', '3.0.9', 0, 'server2'); + INSERT INTO hostconfig VALUES ('ba', '', '', '3.0.9', 0, 'server3'); + INSERT INTO hostconfig VALUES ('', '', '', '3.0.9', 0, 'server4'); + INSERT INTO hostconfig VALUES ('', '', '', '3.0.9', 0, 'server5'); +*/ + + try { + XMLHostDAO dao = new XMLHostDAO(path); + dao.deleteAll(); + dao.insert(new Host("server1", "127.0.0.1", 6666, + "303465626439323336346235616136306332396630346461353132616361346265303639646336633661383432653235".getBytes(), + true,false, true, + false,true, + UpdatedInfo.valueOf(3))); + dao.insert(new Host("server1-ssl", "127.0.0.1", 6666, + "303465626439323336346235616136306332396630346461353132616361346265303639646336633661383432653235".getBytes(), + true,false, false, + true,false, + UpdatedInfo.valueOf(0))); + dao.insert(new Host("server2", "127.0.0.1", 6666, + "303465626439323336346235616136306332396630346461353132616361346265303639646336633661383432653235".getBytes(), + false,false, false, + true,false, + UpdatedInfo.valueOf(0))); + } catch (DAOConnectionException e) { + e.printStackTrace(); + } + + try { + XMLRuleDAO dao = new XMLRuleDAO(path); + dao.deleteAll(); + } catch (DAOConnectionException e) { + e.printStackTrace(); + } + /* + INSERT INTO rules VALUES ('', 1, '/in', '/out', '/arch', '/work', '', '', '', '', '', '', 0, 'default'); + INSERT INTO rules VALUES ('blablablabla2blabla3', 1, '/in', '/out', '/arch', '/work', '', 'testaa1', 'testaa1testaa1', 'testaa1testaa1testaa1', '', '', 42, 'dummy'); + INSERT INTO rules VALUES ('', 3, '/in', '/out', '/arch', '/work', '', '', '', '', '', '', 0, 'dummy2'); + */ + + try { + XMLTransferDAO dao = new XMLTransferDAO(path); + dao.deleteAll(); + } catch (DAOConnectionException e) { + e.printStackTrace(); + } + /* + INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'data/server1/log/client.log', false, 'default', 65536, 'data/server1/log/client.log', 'noinfo', '{"ORIGINALSIZE":18391}', 1, '2018-06-27 14:31:37.738', '2018-06-27 14:31:58.042', 'C ', 5, 'server1', 'server1', 'server2', -9223372036854775807); + INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'data/server1/log/client.log', false, 'default', 65536, 'data/server1/log/client.log', 'noinfo', '{"ORIGINALSIZE":52587}', 1, '2018-06-20 14:36:00.116', '2018-06-20 14:36:20.374', 'C ', 4, 'server1', 'server1', 'server2', -9223372036854775806); + INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'tintin', false, 'tintin', 65536, 'tintin', 'noinfo', '{"ORIGINALSIZE":-1}', 1, '2018-06-22 14:39:01.28', '2018-06-22 14:39:21.518', 'C ', 4, 'server1', 'server1', 'server2', -9223372036854775805); + INSERT INTO runner VALUES (5, 0, 0, 0, 'C ', true, 'tintin', false, 'default', 65536, 'tintin', 'noinfo', '{"ORIGINALSIZE":-1}', 1, '2018-06-24 14:39:01.28', '2018-06-24 14:39:21.518', 'C ', 4, 'server1', 'server1', 'server2', 0); +*/ + + } + + @Override + public void cleanDB() { + // No Clean + } + + @Override + public TransferDAO getDAO(Connection con) throws DAOConnectionException { + return new XMLTransferDAO(path); + } + +} diff --git a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestR66PseudoMain.java b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestR66PseudoMain.java index fb6c8cd48..4c1b90a1e 100644 --- a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestR66PseudoMain.java +++ b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestR66PseudoMain.java @@ -92,7 +92,7 @@ public static RestConfiguration getTestConfiguration() configuration.RESTHANDLERS_CRUD[i] = RestConfiguration.CRUD.ALL.mask; } configuration.REST_AUTHENTICATED = true; - configuration.initializeKey(new File("/opt/R66/certs/key.sha256")); + configuration.initializeKey(new File(HttpTestRestR66Client.keydesfilename)); configuration.REST_TIME_LIMIT = 10000; configuration.REST_SIGNATURE = true; configuration.REST_ADDRESS = "127.0.0.1"; diff --git a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestR66Client.java b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestR66Client.java index eacce413d..148ef4eb0 100644 --- a/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestR66Client.java +++ b/src/test/java/org/waarp/openr66/protocol/http/rest/test/HttpTestRestR66Client.java @@ -24,6 +24,7 @@ import io.netty.handler.codec.http.HttpMethod; import org.joda.time.DateTime; import org.waarp.common.crypto.Des; +import org.waarp.common.crypto.HmacSha256; import org.waarp.common.crypto.ssl.WaarpSslUtility; import org.waarp.common.database.data.AbstractDbData; import org.waarp.common.database.exception.WaarpDatabaseException; @@ -83,6 +84,7 @@ import java.util.concurrent.atomic.AtomicLong; import static org.junit.Assert.*; +import static org.mockito.Mockito.*; /** * @author "Frederic Bregier" @@ -90,11 +92,11 @@ public class HttpTestRestR66Client implements Runnable { public static String keydesfilename = "/opt/R66/certs/test-key.des"; private static final String baseURI = "/"; - private static final String userAuthent = "admin2"; - private static final String keyAuthent = "test"; + public static String userAuthent = "admin2"; + private static String keyAuthent = "test"; private static final long limit = 10000000; private static final long delaylimit = 5000; - private static final String hostid = "hostZZ"; + private static String hostid = "hostZZ"; private static final String address = "10.10.10.10"; private static final String hostkey = "ABCDEFGH"; private static final String business = @@ -147,7 +149,7 @@ public static void main(String[] args) { try { HttpTestR66PseudoMain.config = - HttpTestR66PseudoMain.getTestConfiguration2(); + HttpTestR66PseudoMain.getTestConfiguration(); } catch (CryptoException e2) { // TODO Auto-generated catch block e2.printStackTrace(); diff --git a/src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java b/src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java index 70348e0f4..78fefdc5d 100644 --- a/src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java +++ b/src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java @@ -49,7 +49,7 @@ public static void setUpBeforeClass() throws Exception { } @Test - public void test2_Tasks() throws IOException, OpenR66RunnerErrorException, + public void test_Tasks() throws IOException, OpenR66RunnerErrorException, CommandAbstractException { System.err.println("Start Tasks"); File totest = new File("/tmp/R66/in/testTask.txt"); diff --git a/src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java b/src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java index 09c735337..d5bc6f5b4 100644 --- a/src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java +++ b/src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java @@ -1,22 +1,22 @@ -/******************************************************************************* +/** * This file is part of Waarp Project (named also Waarp or GG). - * - * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author - * tags. See the COPYRIGHT.txt in the distribution for a full listing of - * individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - * A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * Waarp . If not, see . - ******************************************************************************/ + *

+ * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + *

+ * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + *

+ * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + */ /** * @@ -125,7 +125,7 @@ public static void setUpBeforeClass() throws Exception { // setUpBeforeClassServer("Linux/config/config-serverInitB.xml", "config-serverB.xml", false); setUpBeforeClassServer("Linux/config/config-serverInitA.xml", "config-serverA-minimal.xml", true); - setUpBeforeClassClient("config-clientB.xml"); + setUpBeforeClassClient("config-clientA.xml"); } /** @@ -181,8 +181,9 @@ private static void sendInformation(AbstractLocalPacket informationPacket, R66FiniteDualStates state, boolean isSsl) throws OpenR66ProtocolPacketException { - logger.warn("Start connection for Extra commands {}", - informationPacket.getClass().getSimpleName()); + logger.warn("Start connection for Extra commands {} \n\t{}", + informationPacket.getClass().getSimpleName(), + informationPacket); LocalChannelReference localChannelReference = networkTransaction .createConnectionWithRetry(socketServerAddress, isSsl, future); @@ -290,12 +291,12 @@ public void test1_PingPongPacket() throws WaarpDatabaseException { } @Test - public void test8_BusinessRequest() throws WaarpDatabaseException { + public void test83_BusinessRequest() throws WaarpDatabaseException { logger.warn("Start Test of BusinessRequest"); DbHostAuth host = new DbHostAuth("hostas"); assertEquals("Error should be at 0", 0, - TestBusinessRequest.runTest(networkTransaction, host, 5)); + TestBusinessRequest.runTest(networkTransaction, host, 3)); } @Test @@ -494,6 +495,7 @@ public void test6_SendUsingTrafficShaping() throws IOException { R66Result result = future.getResult(); checkFinalResult(future, result, delay, size); totestBig.delete(); + bandwidth = 0; } @Test @@ -670,19 +672,18 @@ public void test1_JsonGenerator() { assertFalse("Json should not be empty", tasks.isEmpty()); } catch (WaarpDatabaseNoConnectionException e) { e.printStackTrace(); - assertEquals("Json in Error", true, false); + fail("Json in Error"); } catch (WaarpDatabaseSqlException e) { e.printStackTrace(); - assertEquals("Json in Error", true, false); + fail("Json in Error"); } catch (OpenR66ProtocolBusinessException e) { e.printStackTrace(); - assertEquals("Json in Error", true, false); + fail("Json in Error"); } } @Test public void test1_JsonGeneratorDbHostAuth() { - // FIXME SHOULD BE POSSIBLE !! int nb = 11; logger.warn("Start Test Json"); DbPreparedStatement preparedStatement; @@ -708,7 +709,6 @@ public void test1_JsonGeneratorDbHostAuth() { @Test public void test1_JsonGeneratorDbRule() { - // FIXME SHOULD BE POSSIBLE !! int nb = 11; logger.warn("Start Test Json"); DbPreparedStatement preparedStatement; @@ -733,10 +733,10 @@ public void test1_JsonGeneratorDbRule() { } @Test - public void test9_ExtraCommands() - throws WaarpDatabaseException, IOException, InterruptedException, - OpenR66ProtocolPacketException { + public void test91_ExtraCommandsInformationPacket() + throws Exception { File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); + setUpBeforeClassClient("config-clientB.xml"); DbHostAuth host = new DbHostAuth("hostas"); final SocketAddress socketServerAddress; @@ -770,6 +770,7 @@ public void test9_ExtraCommands() false, R66FiniteDualStates.INFORMATION, true); + logger.warn("Start Extra commands: ASKEXIST"); future = new R66Future(true); scode = (byte) InformationPacket.ASKENUM.ASKEXIST.ordinal(); informationPacket = @@ -778,6 +779,7 @@ public void test9_ExtraCommands() true, R66FiniteDualStates.INFORMATION, true); + logger.warn("Start Extra commands: ASKLIST"); future = new R66Future(true); scode = (byte) InformationPacket.ASKENUM.ASKLIST.ordinal(); informationPacket = @@ -786,6 +788,7 @@ public void test9_ExtraCommands() true, R66FiniteDualStates.INFORMATION, true); + logger.warn("Start Extra commands: ASKMLSDETAIL"); future = new R66Future(true); scode = (byte) InformationPacket.ASKENUM.ASKMLSDETAIL.ordinal(); informationPacket = @@ -794,6 +797,7 @@ public void test9_ExtraCommands() true, R66FiniteDualStates.INFORMATION, true); + logger.warn("Start Extra commands: ASKMLSLIST"); future = new R66Future(true); scode = (byte) InformationPacket.ASKENUM.ASKMLSLIST.ordinal(); informationPacket = @@ -803,35 +807,57 @@ public void test9_ExtraCommands() true); // ValidPacket BANDWIDTH + logger.warn("Start Extra commands: BANDWIDTHPACKET)"); future = new R66Future(true); ValidPacket valid = new ValidPacket("-1", "-1", LocalPacketFactory.BANDWIDTHPACKET); sendInformation(valid, socketServerAddress, future, scode, true, R66FiniteDualStates.VALIDOTHER, true); - // MultipleDirectTransfer - logger.warn("Start MultipleDirectTransfer"); - future = new R66Future(true); - MultipleDirectTransfer multipleDirectTransfer = - new MultipleDirectTransfer(future, "hostas,hostas", - "testTask.txt,testTask.txt", "rule3", - "MultipleDirectTransfer", true, 1024, - DbConstant.ILLEGALVALUE, - networkTransaction); - multipleDirectTransfer.run(); - future.awaitForDoneOrInterruptible(); - assertTrue("All sends should be OK", future.isSuccess()); + setUpBeforeClassClient("config-clientA.xml"); + totest.delete(); + } + + @Test + public void test93_ExtraCommandsOnTransfer() + throws Exception { + setUpBeforeClassClient("config-clientB.xml"); + ValidPacket valid; + byte scode = -1; + File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); + DbHostAuth host = + new DbHostAuth("hostas"); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + R66Future futureTransfer = new R66Future(true); + TestTransferNoDb transaction = + new TestTransferNoDb(futureTransfer, "hostas", "testTask.txt", + "rule3", + "Test SendDirect Small", true, 8192, + DbConstant.ILLEGALVALUE, + networkTransaction); + transaction.run(); + futureTransfer.await(); + assertTrue("File transfer not ok", futureTransfer.isSuccess()); + long id = futureTransfer.getRunner().getSpecialId(); + logger.warn("Remote Task: {}", id); // RequestTransfer logger.warn("Start RequestTransfer check"); - future = new R66Future(true); + R66Future future = new R66Future(true); RequestTransfer requestTransfer = - new RequestTransfer(future, id, "hostas", "hostas", false, + new RequestTransfer(future, id, "hostbs", "hostbs", false, false, false, networkTransaction); requestTransfer.run(); future.awaitForDoneOrInterruptible(); - assertFalse("Request of Transfer should be OK", future.isSuccess()); + assertTrue("Request of Transfer should be OK", future.isSuccess()); // RequestTransfer logger.warn("Start RequestTransfer stop"); @@ -864,6 +890,53 @@ public void test9_ExtraCommands() future.awaitForDoneOrInterruptible(); assertTrue("Request of information should be OK", future.isSuccess()); + + // ValidPacket VALID + logger.warn("Start Valid VALID"); + future = new R66Future(true); + valid = new ValidPacket(null, "hostas hostas " + id, + LocalPacketFactory.VALIDPACKET); + sendInformation(valid, socketServerAddress, future, scode, false, + R66FiniteDualStates.VALIDOTHER, true); + + // ValidPacket STOP + logger.warn("Start Valid STOP"); + future = new R66Future(true); + valid = new ValidPacket(null, "hostas hostas " + id, + LocalPacketFactory.STOPPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + + // ValidPacket CANCEL + logger.warn("Start Valid CANCEL"); + future = new R66Future(true); + valid = new ValidPacket(null, "hostas hostas " + id, + LocalPacketFactory.CANCELPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + + setUpBeforeClassClient("config-clientA.xml"); + totest.delete(); + } + + @Test + public void test92_ExtraCommandsOther() + throws Exception { + setUpBeforeClassClient("config-clientB.xml"); + ValidPacket valid; + byte scode = -1; + DbHostAuth host = + new DbHostAuth("hostas"); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + R66Future future; + // Message logger.warn("Start Message"); future = new R66Future(true); @@ -918,30 +991,6 @@ public void test9_ExtraCommands() sendInformation(valid, socketServerAddress, future, scode, false, R66FiniteDualStates.VALIDOTHER, true); - // ValidPacket VALID - logger.warn("Start Valid VALID"); - future = new R66Future(true); - valid = new ValidPacket(null, "hostas hostas " + id, - LocalPacketFactory.VALIDPACKET); - sendInformation(valid, socketServerAddress, future, scode, false, - R66FiniteDualStates.VALIDOTHER, true); - - // ValidPacket STOP - logger.warn("Start Valid STOP"); - future = new R66Future(true); - valid = new ValidPacket(null, "hostas hostas " + id, - LocalPacketFactory.STOPPACKET); - sendInformation(valid, socketServerAddress, future, scode, true, - R66FiniteDualStates.VALIDOTHER, true); - - // ValidPacket CANCEL - logger.warn("Start Valid CANCEL"); - future = new R66Future(true); - valid = new ValidPacket(null, "hostas hostas " + id, - LocalPacketFactory.CANCELPACKET); - sendInformation(valid, socketServerAddress, future, scode, true, - R66FiniteDualStates.VALIDOTHER, true); - // NoOpPacket logger.warn("Start NoOp"); long timeout = Configuration.configuration.getTIMEOUTCON(); @@ -960,12 +1009,12 @@ public void test9_ExtraCommands() true); Configuration.configuration.setTIMEOUTCON(timeout); - totest.delete(); + setUpBeforeClassClient("config-clientA.xml"); } @Test - public void test8_JsonCommands() - throws IOException, WaarpDatabaseException, InterruptedException, + public void test91_MultipleDirectTransfer() + throws WaarpDatabaseException, IOException, InterruptedException, OpenR66ProtocolPacketException { File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); DbHostAuth host = @@ -988,9 +1037,75 @@ public void test8_JsonCommands() transaction.run(); futureTransfer.await(); assertTrue("File transfer not ok", futureTransfer.isSuccess()); - long id = futureTransfer.getResult().getRunner().getSpecialId(); - logger.warn("Remote Task: {}", - futureTransfer.getResult().getRunner().getSpecialId()); + long id = futureTransfer.getRunner().getSpecialId(); + logger.warn("Remote Task: {}", id); + + // MultipleDirectTransfer + logger.warn("Start MultipleDirectTransfer"); + R66Future future = new R66Future(true); + MultipleDirectTransfer multipleDirectTransfer = + new MultipleDirectTransfer(future, "hostas,hostas", + "testTask.txt,testTask.txt", "rule3", + "MultipleDirectTransfer", true, 1024, + DbConstant.ILLEGALVALUE, + networkTransaction); + multipleDirectTransfer.run(); + future.awaitForDoneOrInterruptible(); + assertTrue("All sends should be OK", future.isSuccess()); + + totest.delete(); + } + + + @Test + public void test81_JsonCommandsLogs() + throws IOException, WaarpDatabaseException, InterruptedException, + OpenR66ProtocolPacketException { + DbHostAuth host = + new DbHostAuth("hosta"); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + + byte scode = -1; + AbstractLocalPacket valid = null; + + logger.warn("Log"); + R66Future future = new R66Future(true); + LogJsonPacket node6 = new LogJsonPacket(); + node6.setClean(true); + node6.setPurge(false); + valid = new JsonCommandPacket(node6, LocalPacketFactory.LOGPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + logger.warn("Log2"); + future = new R66Future(true); + node6.setPurge(true); + valid = new JsonCommandPacket(node6, LocalPacketFactory.LOGPURGEPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + } + + @Test + public void test82_JsonCommandsOthers() + throws IOException, WaarpDatabaseException, InterruptedException, + OpenR66ProtocolPacketException { + DbHostAuth host = + new DbHostAuth("hosta"); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } byte scode = -1; @@ -1009,65 +1124,15 @@ public void test8_JsonCommands() node = new BandwidthJsonPacket(); // will ask current values instead node.setSetter(true); - node.setWriteglobal(0); - node.setReadglobal(0); - node.setWritesession(0); - node.setReadsession(0); + node.setWriteglobal(1000000000); + node.setReadglobal(1000000000); + node.setWritesession(1000000000); + node.setReadsession(1000000000); valid = new JsonCommandPacket(node, LocalPacketFactory.BANDWIDTHPACKET); sendInformation(valid, socketServerAddress, future, scode, true, R66FiniteDualStates.VALIDOTHER, false); - logger.warn("Information"); - future = new R66Future(true); - InformationJsonPacket node4 = - new InformationJsonPacket(id, true, "hostas"); - valid = new JsonCommandPacket(node4, - LocalPacketFactory.INFORMATIONPACKET); - sendInformation(valid, socketServerAddress, future, scode, true, - R66FiniteDualStates.VALIDOTHER, false); - - logger.warn("Information2"); - future = new R66Future(true); - node4 = new InformationJsonPacket( - (byte) InformationPacket.ASKENUM.ASKMLSDETAIL.ordinal(), - "rule3", - "testTask.txt"); - valid = new JsonCommandPacket(node4, - LocalPacketFactory.INFORMATIONPACKET); - sendInformation(valid, socketServerAddress, future, scode, true, - R66FiniteDualStates.VALIDOTHER, false); - - logger.warn("Stop"); - future = new R66Future(true); - StopOrCancelJsonPacket node5 = new StopOrCancelJsonPacket(); - node5.setRequested("hostas"); - node5.setRequester("hostas"); - node5.setSpecialid(id); - valid = new JsonCommandPacket(node5, LocalPacketFactory.STOPPACKET); - sendInformation(valid, socketServerAddress, future, scode, true, - R66FiniteDualStates.VALIDOTHER, false); - logger.warn("Cancel"); - future = new R66Future(true); - valid = new JsonCommandPacket(node5, LocalPacketFactory.CANCELPACKET); - sendInformation(valid, socketServerAddress, future, scode, true, - R66FiniteDualStates.VALIDOTHER, false); - - logger.warn("Log"); - future = new R66Future(true); - LogJsonPacket node6 = new LogJsonPacket(); - node6.setClean(true); - node6.setPurge(false); - valid = new JsonCommandPacket(node6, LocalPacketFactory.LOGPACKET); - sendInformation(valid, socketServerAddress, future, scode, true, - R66FiniteDualStates.VALIDOTHER, false); - logger.warn("Log2"); - future = new R66Future(true); - node6.setPurge(true); - valid = new JsonCommandPacket(node6, LocalPacketFactory.LOGPURGEPACKET); - sendInformation(valid, socketServerAddress, future, scode, true, - R66FiniteDualStates.VALIDOTHER, false); - - logger.warn("Config"); + logger.warn("Config Export"); future = new R66Future(true); ConfigExportJsonPacket node7 = new ConfigExportJsonPacket(); node7.setHost(true); @@ -1083,19 +1148,23 @@ public void test8_JsonCommands() logger.warn("Config Import"); future = new R66Future(true); ConfigImportJsonPacket node8 = new ConfigImportJsonPacket(); - node8.setHost("/tmp/R66/arch/hostb_Authentications.xml"); - node8.setRule("/tmp/R66/arch/hostb.rules.xml"); + node8.setHost("/tmp/R66/arch/hosta_Authentications.xml"); + node8.setRule("/tmp/R66/arch/hosta.rules.xml"); valid = new JsonCommandPacket(node8, LocalPacketFactory.CONFIMPORTPACKET); sendInformation(valid, socketServerAddress, future, scode, true, R66FiniteDualStates.VALIDOTHER, false); - logger.warn("Test"); + logger.warn("BandwidthUnlimit 2"); future = new R66Future(true); - JsonPacket node9 = new JsonPacket(); - node9.setComment("Test Message"); - node9.setRequestUserPacket(LocalPacketFactory.TESTPACKET); - valid = new JsonCommandPacket(node9, LocalPacketFactory.TESTPACKET); + node = new BandwidthJsonPacket(); + // will ask current values instead + node.setSetter(true); + node.setWriteglobal(1000000000); + node.setReadglobal(1000000000); + node.setWritesession(1000000000); + node.setReadsession(1000000000); + valid = new JsonCommandPacket(node, LocalPacketFactory.BANDWIDTHPACKET); sendInformation(valid, socketServerAddress, future, scode, true, R66FiniteDualStates.VALIDOTHER, false); @@ -1111,8 +1180,28 @@ public void test8_JsonCommands() sendInformation(valid, socketServerAddress, future, scode, true, R66FiniteDualStates.VALIDOTHER, false); + } + + @Ignore("Information not OK at the end") + @Test + public void test80_JsonCommandsBusiness() + throws IOException, WaarpDatabaseException, InterruptedException, + OpenR66ProtocolPacketException { + DbHostAuth host = + new DbHostAuth("hosta"); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + + byte scode = -1; logger.warn("Business"); - future = new R66Future(true); + R66Future future = new R66Future(true); + AbstractLocalPacket valid = null; BusinessRequestJsonPacket node3 = new BusinessRequestJsonPacket(); node3.setClassName(TestExecJavaTask.class.getName()); node3.setArguments(" business 0"); @@ -1123,6 +1212,107 @@ public void test8_JsonCommands() sendInformation(valid, socketServerAddress, future, scode, true, R66FiniteDualStates.VALIDOTHER, false); + } + + @Ignore("Information not OK at the end") + @Test + public void test80_JsonCommandsTest() + throws IOException, WaarpDatabaseException, InterruptedException, + OpenR66ProtocolPacketException { + DbHostAuth host = + new DbHostAuth("hosta"); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + + byte scode = -1; + logger.warn("Test"); + R66Future future = new R66Future(true); + AbstractLocalPacket valid = null; + JsonPacket node9 = new JsonPacket(); + node9.setComment("Test Message"); + node9.setRequestUserPacket(LocalPacketFactory.TESTPACKET); + valid = new JsonCommandPacket(node9, LocalPacketFactory.TESTPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, false); + + logger.warn("End Json"); + } + + @Test + public void test81_JsonCommandsWithTransferId() + throws IOException, WaarpDatabaseException, InterruptedException, + OpenR66ProtocolPacketException { + File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); + DbHostAuth host = + new DbHostAuth("hostas"); + final SocketAddress socketServerAddress; + try { + socketServerAddress = host.getSocketAddress(); + } catch (IllegalArgumentException e) { + logger.error( + "Needs a correct configuration file as first argument"); + return; + } + R66Future futureTransfer = new R66Future(true); + TestTransferNoDb transaction = + new TestTransferNoDb(futureTransfer, "hostas", "testTask.txt", + "rule3", + "Test SendDirect Small", true, 8192, + DbConstant.ILLEGALVALUE, + networkTransaction); + transaction.run(); + futureTransfer.await(); + assertTrue("File transfer not ok", futureTransfer.isSuccess()); + long id = futureTransfer.getResult().getRunner().getSpecialId(); + logger.warn("Remote Task: {}", + futureTransfer.getResult().getRunner().getSpecialId()); + + byte scode = -1; + + R66Future future; + AbstractLocalPacket valid; + + logger.warn("Information"); + future = new R66Future(true); + InformationJsonPacket node4 = + new InformationJsonPacket(id, true, "hostas"); + valid = new JsonCommandPacket(node4, + LocalPacketFactory.INFORMATIONPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + + logger.warn("Information2"); + future = new R66Future(true); + node4 = new InformationJsonPacket( + (byte) InformationPacket.ASKENUM.ASKMLSDETAIL.ordinal(), + "rule3", + "testTask.txt"); + valid = new JsonCommandPacket(node4, + LocalPacketFactory.INFORMATIONPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + + logger.warn("Stop"); + future = new R66Future(true); + StopOrCancelJsonPacket node5 = new StopOrCancelJsonPacket(); + node5.setRequested("hostas"); + node5.setRequester("hostas"); + node5.setSpecialid(id); + valid = new JsonCommandPacket(node5, LocalPacketFactory.STOPPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + logger.warn("Cancel"); + future = new R66Future(true); + valid = new JsonCommandPacket(node5, LocalPacketFactory.CANCELPACKET); + sendInformation(valid, socketServerAddress, future, scode, true, + R66FiniteDualStates.VALIDOTHER, true); + logger.warn("End Json"); totest.delete(); } @@ -1131,7 +1321,7 @@ public void test8_JsonCommands() public void test1_ThriftClient() throws IOException { logger.warn("Start Test Thrift Client"); int PORT = 4266; - int tries = 10000; + int tries = 1000; TTransport transport = null; try { File totest = generateOutFile("/tmp/R66/out/testTask.txt", 10); @@ -1229,10 +1419,12 @@ public void test1_ThriftClient() throws IOException { transport.close(); } + @Ignore("Issue on checkBaseAuthent") @Test - public void test9_RestR66() throws Exception { + public void test90_RestR66() throws Exception { HttpTestRestR66Client.keydesfilename = new File(dir, "certs/test-key.des").getAbsolutePath(); + logger.info("Key filename: {}", HttpTestRestR66Client.keydesfilename); HttpTestRestR66Client.main(new String[] { "1" }); } } diff --git a/src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java b/src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java index 0880851ef..d75e4d095 100644 --- a/src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java +++ b/src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java @@ -1,22 +1,22 @@ -/******************************************************************************* +/** * This file is part of Waarp Project (named also Waarp or GG). - * - * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author - * tags. See the COPYRIGHT.txt in the distribution for a full listing of - * individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - * A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * Waarp . If not, see . - ******************************************************************************/ + *

+ * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author + * tags. See the COPYRIGHT.txt in the distribution for a full listing of + * individual contributors. + *

+ * All Waarp Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or (at your + * option) any later version. + *

+ * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR + * A PARTICULAR PURPOSE. See the GNU General Public License for more details. + *

+ * You should have received a copy of the GNU General Public License along with + * Waarp . If not, see . + */ /** * @@ -30,8 +30,19 @@ import org.apache.tools.ant.types.Path; import org.junit.After; import org.junit.Before; +import org.waarp.common.database.DbPreparedStatement; +import org.waarp.common.database.data.AbstractDbData.UpdatedInfo; +import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.database.exception.WaarpDatabaseNoDataException; import org.waarp.common.utility.DetectionUtils; import org.waarp.openr66.configuration.FileBasedConfiguration; +import org.waarp.openr66.dao.DAOFactory; +import org.waarp.openr66.dao.TransferDAO; +import org.waarp.openr66.dao.exception.DAOConnectionException; +import org.waarp.openr66.dao.exception.DAONoDataException; +import org.waarp.openr66.database.data.DbTaskRunner; +import org.waarp.openr66.database.data.DbTaskRunner.Columns; +import org.waarp.openr66.database.data.DbTaskRunner.TASKSTEP; import org.waarp.openr66.protocol.configuration.Configuration; import org.waarp.openr66.protocol.networkhandler.NetworkTransaction; import org.waarp.openr66.protocol.utils.ChannelUtils; @@ -39,6 +50,7 @@ import org.waarp.openr66.server.ServerInitDatabase; import java.io.File; +import java.io.FileFilter; /** * @author frederic @@ -51,6 +63,7 @@ public abstract class TestAbstract extends TestAbstractMinimal { private static File homeDir; public static void setUpDbBeforeClass() throws Exception { + deleteBase(); String serverInit = "Linux/config/config-serverInitB.xml"; setUpBeforeClassMinimal(serverInit); @@ -75,38 +88,18 @@ public static void setUpDbBeforeClass() throws Exception { listener.setMessageOutputLevel(Project.MSG_WARN); project.fireBuildStarted(); - initiateDbB(); - initiateDbA(); + serverInit = "config-serverInitB.xml"; + initiateDb(serverInit); + serverInit = "config-serverInitA.xml"; + initiateDb(serverInit); project.log("finished"); project.fireBuildFinished(null); } - public static void initiateDbB() { + public static void initiateDb(String serverInit) { DetectionUtils.setJunit(true); - String serverInit = "config-serverInitB.xml"; - File file = new File(dir, serverInit); - logger.warn("File {} exists? {}", file, file.isFile()); - File fileAuth = new File(dir, "OpenR66-authent-A.xml"); - File fileLimit = new File(dir, "limitConfiga.xml"); - logger.warn("File {} exists? {}", fileAuth, fileAuth.isFile()); - logger.warn("File {} exists? {}", fileLimit, fileLimit.isFile()); - - String[] args = { - file.getAbsolutePath(), "-initdb", "-dir", - dir.getAbsolutePath(), "-auth", - new File(dir, "OpenR66-authent-A.xml").getAbsolutePath(), - "-limit", - new File(dir, "limitConfiga.xml").getAbsolutePath() - }; - executeJvm(homeDir, ServerInitDatabase.class, args); - } - - public static void initiateDbA() { - DetectionUtils.setJunit(true); - String serverInit = "config-serverInitA.xml"; - File file = new File(dir, serverInit); logger.warn("File {} exists? {}", file, file.isFile()); File fileAuth = new File(dir, "OpenR66-authent-A.xml"); @@ -201,16 +194,24 @@ public static void setUpBeforeClassServer(String serverInit, } } - /** - * @throws java.lang.Exception - */ public static void tearDownAfterClassServer() throws Exception { ChannelUtils.exit(); + deleteBase(); + } + + public static void deleteBase() { + File tmp = new File("/tmp"); + File[] files = tmp.listFiles(new FileFilter() { + @Override + public boolean accept(File file) { + return file.getName().startsWith("openr66"); + } + }); + for (File file : files) { + file.delete(); + } } - /** - * @throws java.lang.Exception - */ public static void setUpBeforeClassClient(String clientConfig) throws Exception { File clientConfigFile = new File(dir, clientConfig); @@ -233,26 +234,32 @@ public static void setUpBeforeClassClient(String clientConfig) } Configuration.configuration.pipelineInit(); networkTransaction = new NetworkTransaction(); + DbTaskRunner.clearCache(); + TransferDAO transferAccess = null; + try { + transferAccess = DAOFactory.getInstance().getTransferDAO(); + transferAccess.deleteAll(); + } catch (DAOConnectionException e) { + throw new WaarpDatabaseException(e); + } finally { + if (transferAccess != null) { + transferAccess.close(); + } + } } - /** - * @throws java.lang.Exception - */ public static void tearDownAfterClassClient() throws Exception { networkTransaction.closeAll(); } - /** - * @throws java.lang.Exception - */ @Before public void setUp() throws Exception { Configuration.configuration.setTIMEOUTCON(10000); + Configuration.configuration + .changeNetworkLimit(1000000000, 1000000000, 1000000000, 1000000000, + 1000); } - /** - * @throws java.lang.Exception - */ @After public void tearDown() throws Exception { Configuration.configuration.setTIMEOUTCON(100); diff --git a/src/test/java/org/waarp/openr66/protocol/junit/TestAbstractMinimal.java b/src/test/java/org/waarp/openr66/protocol/junit/TestAbstractMinimal.java index fa74b526b..4a690844e 100644 --- a/src/test/java/org/waarp/openr66/protocol/junit/TestAbstractMinimal.java +++ b/src/test/java/org/waarp/openr66/protocol/junit/TestAbstractMinimal.java @@ -24,6 +24,7 @@ package org.waarp.openr66.protocol.junit; import org.waarp.common.file.FileUtils; +import org.waarp.common.logging.WaarpLogLevel; import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; @@ -49,7 +50,8 @@ public abstract class TestAbstractMinimal { */ public static void setUpBeforeClassMinimal(String serverInit) throws Exception { - WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory(null)); + WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( + WaarpLogLevel.WARN)); if (logger == null) { logger = WaarpLoggerFactory.getLogger(TestAbstractMinimal.class); } @@ -67,12 +69,6 @@ public static void setUpBeforeClassMinimal(String serverInit) new File(tmp, "work").mkdir(); File conf = new File(tmp, "conf"); conf.mkdir(); - File[] files = dir.listFiles(new FileFilter() { - @Override - public boolean accept(File file) { - return file.isFile(); - } - }); File [] copied = FileUtils.copyRecursive(dir, conf, false); for (File fileCopied : copied) { System.out.print(fileCopied.getAbsolutePath() + " "); diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java b/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java index 0653d759c..53f07120c 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestBusinessRequest.java @@ -19,6 +19,7 @@ ******************************************************************************/ package org.waarp.openr66.protocol.test; +import org.waarp.common.logging.WaarpLogLevel; import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; @@ -55,7 +56,7 @@ public TestBusinessRequest(NetworkTransaction networkTransaction, public static void main(String[] args) { WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); + WaarpLogLevel.WARN)); if (logger == null) { logger = WaarpLoggerFactory.getLogger(TestBusinessRequest.class); } @@ -72,19 +73,19 @@ public static void main(String[] args) { } Configuration.configuration.pipelineInit(); - NetworkTransaction networkTransaction = new NetworkTransaction(); - DbHostAuth host = Configuration.configuration.getHOST_AUTH(); - runTest(networkTransaction, host, 1); - networkTransaction.closeAll(); - } + NetworkTransaction networkTransaction = new NetworkTransaction(); + DbHostAuth host = Configuration.configuration.getHOST_AUTH(); + runTest(networkTransaction, host, 1); + networkTransaction.closeAll(); + } - public static int runTest(NetworkTransaction networkTransaction, - DbHostAuth host, int nbToDo) { - if (logger == null) { - logger = WaarpLoggerFactory.getLogger(TestBusinessRequest.class); - } - ExecutorService executorService = Executors.newCachedThreadPool(); - int nb = nbToDo; + public static int runTest(NetworkTransaction networkTransaction, + DbHostAuth host, int nbToDo) { + if (logger == null) { + logger = WaarpLoggerFactory.getLogger(TestBusinessRequest.class); + } + ExecutorService executorService = Executors.newCachedThreadPool(); + int nb = nbToDo; R66Future[] arrayFuture = new R66Future[nb]; logger.info("Start Test of Transaction"); @@ -154,47 +155,47 @@ public static int runTest(NetworkTransaction networkTransaction, "Simple ExecJava Success: " + success + " Error: " + error + " NB/s: " + 1000 / (time4 - time3)); - logger.info("Start Test of Increasing Transaction"); - time1 = System.currentTimeMillis(); - String argsAdd = - "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; - String value = " business 0 "; - int lastnb = nb; - for (int i = 0; i < nb; i++) { - arrayFuture[i] = new R66Future(true); - try { - value += argsAdd + argsAdd + argsAdd + argsAdd + argsAdd + - argsAdd + argsAdd + argsAdd + argsAdd - + argsAdd; - } catch (OutOfMemoryError e) { - logger.warn("Send size: " + value.length()); - lastnb = i; - break; - } - packet = new BusinessRequestPacket( - TestExecJavaTask.class.getName() + value, 0); - TestBusinessRequest transaction2 = - new TestBusinessRequest(networkTransaction, arrayFuture[i], - host.getHostid(), packet); - executorService.execute(transaction2); - } - int success2 = 0; - int error2 = 0; - for (int i = 0; i < lastnb; i++) { - arrayFuture[i].awaitForDoneOrInterruptible(); - if (arrayFuture[i].isSuccess()) { - success2++; - } else { - error2++; - } - } - time2 = System.currentTimeMillis(); - logger.warn( - "Simple TestExecJavaTask with increasing argument size Success: " + - success2 + " Error: " + error2 - + " NB/s: " + success2 * nb * 1000 / (time2 - time1)); - executorService.shutdown(); - return error + error2; + logger.info("Start Test of Increasing Transaction"); + time1 = System.currentTimeMillis(); + String argsAdd = + "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789"; + String value = " business 0 "; + int lastnb = nb; + for (int i = 0; i < nb; i++) { + arrayFuture[i] = new R66Future(true); + try { + value += argsAdd + argsAdd + argsAdd + argsAdd + argsAdd + + argsAdd + argsAdd + argsAdd + argsAdd + + argsAdd; + } catch (OutOfMemoryError e) { + logger.warn("Send size: " + value.length()); + lastnb = i; + break; + } + packet = new BusinessRequestPacket( + TestExecJavaTask.class.getName() + value, 0); + TestBusinessRequest transaction2 = + new TestBusinessRequest(networkTransaction, arrayFuture[i], + host.getHostid(), packet); + executorService.execute(transaction2); } + int success2 = 0; + int error2 = 0; + for (int i = 0; i < lastnb; i++) { + arrayFuture[i].awaitForDoneOrInterruptible(); + if (arrayFuture[i].isSuccess()) { + success2++; + } else { + error2++; + } + } + time2 = System.currentTimeMillis(); + logger.warn( + "Simple TestExecJavaTask with increasing argument size Success: " + + success2 + " Error: " + error2 + + " NB/s: " + success2 * nb * 1000 / (time2 - time1)); + executorService.shutdown(); + return error + error2; + } } diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestTasks.java b/src/test/java/org/waarp/openr66/protocol/test/TestTasks.java index 03efe8843..86ef52921 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestTasks.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestTasks.java @@ -22,6 +22,7 @@ import org.waarp.common.command.exception.CommandAbstractException; import org.waarp.common.database.DbAdmin; import org.waarp.common.database.exception.WaarpDatabaseException; +import org.waarp.common.logging.WaarpLogLevel; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; import org.waarp.openr66.configuration.FileBasedConfiguration; @@ -69,14 +70,14 @@ public class TestTasks { */ public static void main(String[] args) { WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); + WaarpLogLevel.WARN)); if (args.length < 4) { System.err.println( "Need config inDirectory outDirectory filename (in inDirectory)"); return; } if (!FileBasedConfiguration - .setClientConfigurationFromXml(Configuration.configuration, args[0])) { + .setSubmitClientConfigurationFromXml(Configuration.configuration, args[0])) { System.err .println("Needs a correct configuration file as first argument"); return; diff --git a/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java b/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java index 4dde925c0..40fec852b 100644 --- a/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java +++ b/src/test/java/org/waarp/openr66/protocol/test/TestTransaction.java @@ -19,6 +19,7 @@ ******************************************************************************/ package org.waarp.openr66.protocol.test; +import org.waarp.common.logging.WaarpLogLevel; import org.waarp.common.logging.WaarpLogger; import org.waarp.common.logging.WaarpLoggerFactory; import org.waarp.common.logging.WaarpSlf4JLoggerFactory; @@ -70,7 +71,7 @@ public TestTransaction(NetworkTransaction networkTransaction, public static void main(String[] args) { WaarpLoggerFactory.setDefaultFactory(new WaarpSlf4JLoggerFactory( - null)); + WaarpLogLevel.WARN)); if (logger == null) { logger = WaarpLoggerFactory.getLogger(TestTransaction.class); } diff --git a/src/test/resources/Linux/config/config-clientNoDB_B.xml b/src/test/resources/Linux/config/config-clientNoDB_B.xml index eab9adf5d..222922f05 100755 --- a/src/test/resources/Linux/config/config-clientNoDB_B.xml +++ b/src/test/resources/Linux/config/config-clientNoDB_B.xml @@ -1,5 +1,5 @@ - + Example of config file: change its as your need. hostb diff --git a/src/test/resources/Linux/config/config-serverA-minimal.xml b/src/test/resources/Linux/config/config-serverA-minimal.xml index b7e64d326..3ee62ee2b 100755 --- a/src/test/resources/Linux/config/config-serverA-minimal.xml +++ b/src/test/resources/Linux/config/config-serverA-minimal.xml @@ -12,7 +12,7 @@ c5f4876737cf351a True True - src/test/resources/Linux/httpadmin + src/main/httpadmin src/test/resources/Linux/config/certs/testsslnocert.jks testsslnocert testalias diff --git a/src/test/resources/Linux/config/config-serverB.xml b/src/test/resources/Linux/config/config-serverB.xml index 0be236c7d..6353105c8 100755 --- a/src/test/resources/Linux/config/config-serverB.xml +++ b/src/test/resources/Linux/config/config-serverB.xml @@ -14,7 +14,7 @@ False False False - src/test/resources/Linux/httpadmin + src/main/httpadmin src/test/resources/Linux/config/certs/testsslnocert.jks testsslnocert testalias diff --git a/src/test/resources/Linux/config/config-serverInitA.xml b/src/test/resources/Linux/config/config-serverInitA.xml index 945acfcfc..2c68cce57 100755 --- a/src/test/resources/Linux/config/config-serverInitA.xml +++ b/src/test/resources/Linux/config/config-serverInitA.xml @@ -14,7 +14,7 @@ False monadmin c5f4876737cf351a - src/test/resources/Linux/httpadmin/ + src/main/httpadmin/ src/test/resources/Linux/config/certs/testsslnocert.jks testsslnocert testalias diff --git a/src/test/resources/Linux/config/config-serverInitB.xml b/src/test/resources/Linux/config/config-serverInitB.xml index dd462614e..2f0cdc5f6 100755 --- a/src/test/resources/Linux/config/config-serverInitB.xml +++ b/src/test/resources/Linux/config/config-serverInitB.xml @@ -14,7 +14,7 @@ False monadmin c5f4876737cf351a - src/test/resources/Linux/httpadmin/ + src/main/httpadmin/ src/test/resources/Linux/config/certs/testsslnocert.jks testsslnocert testalias From 515a94d1e85982e72e17547b94dc7b6c1962b3c3 Mon Sep 17 00:00:00 2001 From: Frederic Bregier Date: Sat, 10 Aug 2019 13:02:14 +0200 Subject: [PATCH 3/3] Fix Shutdown through SigTerm - Fix Shutdown through Sigterm (add Junit too) - Fix Commander incorrect request to get Submitted tasks --- pom.xml | 29 +++++++- .../openr66/database/data/DbTaskRunner.java | 2 +- .../openr66/protocol/junit/AllTasksTest.java | 68 ------------------- .../protocol/junit/NetworkClientTest.java | 44 ++++++++++++ .../openr66/protocol/junit/TestAbstract.java | 2 +- 5 files changed, 74 insertions(+), 71 deletions(-) delete mode 100644 src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java diff --git a/pom.xml b/pom.xml index fbf0b0e47..14bce770f 100644 --- a/pom.xml +++ b/pom.xml @@ -236,7 +236,34 @@ 1.10.6 test - + + com.github.jnr + jnr-posix + 3.0.50 + + test + + + org.apache.ant + ant + 1.10.6 + + test + + + com.sun + tools + + + + + Waarp + WaarpCommon + tests + test-jar + 3.1.1 + test + diff --git a/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java b/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java index 74352b9aa..c5054fb39 100644 --- a/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java +++ b/src/main/java/org/waarp/openr66/database/data/DbTaskRunner.java @@ -1550,7 +1550,7 @@ public static DbTaskRunner[] getSelectFromInfoPrepareStatement( List filters = new ArrayList(3); filters.add(new Filter(DBTransferDAO.UPDATED_INFO_FIELD, "=", org.waarp.openr66.pojo.UpdatedInfo.fromLegacy(info).ordinal())); - filters.add(new Filter(DBTransferDAO.TRANSFER_START_FIELD, "=", + filters.add(new Filter(DBTransferDAO.TRANSFER_START_FIELD, "<=", new Timestamp(System.currentTimeMillis()))); filters.add(new Filter(DBTransferDAO.OWNER_REQUEST_FIELD, "=", Configuration.configuration.getHOST_ID())); diff --git a/src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java b/src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java deleted file mode 100644 index 78fefdc5d..000000000 --- a/src/test/java/org/waarp/openr66/protocol/junit/AllTasksTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/******************************************************************************* - * This file is part of Waarp Project (named also Waarp or GG). - * - * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author - * tags. See the COPYRIGHT.txt in the distribution for a full listing of - * individual contributors. - * - * All Waarp Project is free software: you can redistribute it and/or - * modify it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or (at your - * option) any later version. - * - * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - * A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * Waarp . If not, see . - ******************************************************************************/ - -/** - * - */ -package org.waarp.openr66.protocol.junit; - -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; -import org.waarp.common.command.exception.CommandAbstractException; -import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; -import org.waarp.openr66.protocol.test.TestTasks; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; - -/** - * @author frederic - * - */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -public class AllTasksTest extends TestAbstract { - - @BeforeClass - public static void setUpBeforeClass() throws Exception { - setUpBeforeClassMinimal("Linux/config/config-serverInitB.xml"); - setUpDbBeforeClass(); - } - - @Test - public void test_Tasks() throws IOException, OpenR66RunnerErrorException, - CommandAbstractException { - System.err.println("Start Tasks"); - File totest = new File("/tmp/R66/in/testTask.txt"); - FileWriter fileWriter = new FileWriter(totest); - fileWriter.write("Test content"); - fileWriter.flush(); - fileWriter.close(); - TestTasks.main(new String[] { - new File(dir, "config-serverA-minimal.xml").getAbsolutePath(), - "/tmp/R66/in", - "/tmp/R66/out", totest.getName() - }); - System.err.println("End Tasks"); - } - -} diff --git a/src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java b/src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java index d5bc6f5b4..26bdcf200 100644 --- a/src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java +++ b/src/test/java/org/waarp/openr66/protocol/junit/NetworkClientTest.java @@ -29,17 +29,20 @@ import org.apache.thrift.transport.TSocket; import org.apache.thrift.transport.TTransport; import org.apache.thrift.transport.TTransportException; +import org.apache.tools.ant.Project; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; import org.junit.runners.MethodSorters; +import org.waarp.common.command.exception.CommandAbstractException; import org.waarp.common.database.DbPreparedStatement; import org.waarp.common.database.exception.WaarpDatabaseException; import org.waarp.common.database.exception.WaarpDatabaseNoConnectionException; import org.waarp.common.database.exception.WaarpDatabaseSqlException; import org.waarp.common.digest.FilesystemBasedDigest; +import org.waarp.common.utility.Processes; import org.waarp.openr66.client.Message; import org.waarp.openr66.client.MultipleDirectTransfer; import org.waarp.openr66.client.MultipleSubmitTransfer; @@ -50,6 +53,7 @@ import org.waarp.openr66.context.ErrorCode; import org.waarp.openr66.context.R66FiniteDualStates; import org.waarp.openr66.context.R66Result; +import org.waarp.openr66.context.task.exception.OpenR66RunnerErrorException; import org.waarp.openr66.context.task.test.TestExecJavaTask; import org.waarp.openr66.database.DbConstant; import org.waarp.openr66.database.data.DbHostAuth; @@ -83,10 +87,12 @@ import org.waarp.openr66.protocol.test.TestRecvThroughClient; import org.waarp.openr66.protocol.test.TestRecvThroughClient.TestRecvThroughHandler; import org.waarp.openr66.protocol.test.TestSendThroughClient; +import org.waarp.openr66.protocol.test.TestTasks; import org.waarp.openr66.protocol.test.TestTransaction; import org.waarp.openr66.protocol.test.TestTransferNoDb; import org.waarp.openr66.protocol.utils.ChannelUtils; import org.waarp.openr66.protocol.utils.R66Future; +import org.waarp.openr66.server.R66Server; import org.waarp.thrift.r66.Action; import org.waarp.thrift.r66.R66Request; import org.waarp.thrift.r66.R66Service; @@ -1427,4 +1433,42 @@ public void test90_RestR66() throws Exception { logger.info("Key filename: {}", HttpTestRestR66Client.keydesfilename); HttpTestRestR66Client.main(new String[] { "1" }); } + + @Test + public void test98_Tasks() throws IOException, OpenR66RunnerErrorException, + CommandAbstractException { + System.err.println("Start Tasks"); + File totest = new File("/tmp/R66/in/testTask.txt"); + FileWriter fileWriter = new FileWriter(totest); + fileWriter.write("Test content"); + fileWriter.flush(); + fileWriter.close(); + TestTasks.main(new String[] { + new File(dir, "config-serverA-minimal.xml").getAbsolutePath(), + "/tmp/R66/in", + "/tmp/R66/out", totest.getName() + }); + System.err.println("End Tasks"); + } + + @Test + public void test99_SigTermR66() throws InterruptedException { + // global ant project settings + final Project project = Processes.getProject(homeDir); + final String[] argsServer = { + new File(dir, "config-serverA-minimal.xml").getAbsolutePath() + }; + int pid = Processes.executeJvm(project, homeDir, R66Server.class, + argsServer, true); + Thread.sleep(1000); + logger.warn("PID found is {}", pid); + logger.warn("PID is running: {}", Processes.exists(pid)); + assertTrue("Process should still exists... " + pid, Processes.exists(pid)); + Processes.kill(pid, true); + while (Processes.exists(pid)) { + logger.warn("{} still running", pid); + Thread.sleep(1000); + } + Processes.finalizeProject(project); + } } diff --git a/src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java b/src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java index d75e4d095..8da673185 100644 --- a/src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java +++ b/src/test/java/org/waarp/openr66/protocol/junit/TestAbstract.java @@ -60,7 +60,7 @@ public abstract class TestAbstract extends TestAbstractMinimal { protected static NetworkTransaction networkTransaction = null; private static Project project; - private static File homeDir; + static File homeDir; public static void setUpDbBeforeClass() throws Exception { deleteBase();