From 067276ef6a2a18a894d1f03160b743871aed8fa1 Mon Sep 17 00:00:00 2001 From: Michal Date: Sat, 8 Feb 2025 16:39:16 +0100 Subject: [PATCH] --- build.xml | 73 + config.properties | 13 + log | 7 + log.log | 222 +++ manifest.mf | 3 + nbproject/build-impl.xml | 1789 ++++++++++++++++++++ nbproject/genfiles.properties | 8 + nbproject/project.properties | 118 ++ nbproject/project.xml | 25 + src/jnet/server/Database.java | 710 ++++++++ src/jnet/server/Server.java | 149 ++ src/jnet/server/ServerMessageParser.java | 336 ++++ src/jnet/server/network/NettyServer.java | 61 + src/jnet/server/network/ServerHandler.java | 40 + src/jnet/server/network/ServerSsl.java | 88 + src/jnet/server/probe/Ping.java | 136 ++ src/jnet/server/probe/Ping2.java | 78 + src/jnet/server/probe/PingTestResult.java | 91 + 18 files changed, 3947 insertions(+) create mode 100644 build.xml create mode 100644 config.properties create mode 100644 log create mode 100644 log.log create mode 100644 manifest.mf create mode 100644 nbproject/build-impl.xml create mode 100644 nbproject/genfiles.properties create mode 100644 nbproject/project.properties create mode 100644 nbproject/project.xml create mode 100644 src/jnet/server/Database.java create mode 100644 src/jnet/server/Server.java create mode 100644 src/jnet/server/ServerMessageParser.java create mode 100644 src/jnet/server/network/NettyServer.java create mode 100644 src/jnet/server/network/ServerHandler.java create mode 100644 src/jnet/server/network/ServerSsl.java create mode 100644 src/jnet/server/probe/Ping.java create mode 100644 src/jnet/server/probe/Ping2.java create mode 100644 src/jnet/server/probe/PingTestResult.java diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..0e27a76 --- /dev/null +++ b/build.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + Builds, tests, and runs the project jNetServer. + + + diff --git a/config.properties b/config.properties new file mode 100644 index 0000000..fcf2420 --- /dev/null +++ b/config.properties @@ -0,0 +1,13 @@ +#Sat Jan 19 23:43:37 CET 2019 +mysql_server=cucky.cz +mysql_port=8658 +mysql_user=jnet +mysql_password=Michal2407 +mysql_database=jnet +server_port=1225 +debug=true +ping_attempt=2 +ping_timeout=2000 +instability_attempt=2 +instability_limit=1000 + diff --git a/log b/log new file mode 100644 index 0000000..70fe9c1 --- /dev/null +++ b/log @@ -0,0 +1,7 @@ +03.02.25 16:34:13 I --------------------------------------------- +03.02.25 16:34:13 I jNet Server +03.02.25 16:34:13 I Version: 1 (Mon Feb 03 16:33:44 CET 2025) +03.02.25 16:34:13 I --------------------------------------------- +03.02.25 16:34:13 I +03.02.25 16:34:13 I Loading config ... +03.02.25 16:34:13 E fail. Soubor konfigurace nenalezen config.properties (Systém nemůže nalézt uvedený soubor) diff --git a/log.log b/log.log new file mode 100644 index 0000000..41e6fc8 --- /dev/null +++ b/log.log @@ -0,0 +1,222 @@ +04.02.25 18:20:10 I --------------------------------------------- +04.02.25 18:20:10 I jNet Server +04.02.25 18:20:10 I Version: 1 (Tue Feb 04 17:54:52 CET 2025) +04.02.25 18:20:10 I --------------------------------------------- +04.02.25 18:20:10 I +04.02.25 18:20:10 I Loading config ... +04.02.25 18:20:10 I successfully +04.02.25 18:20:10 D Debug mode on +04.02.25 18:20:10 I Connecting to a selected database ... +04.02.25 18:20:10 I successfully +04.02.25 18:20:10 I Loading user list ... +04.02.25 18:20:10 I load 2 user(s) +04.02.25 18:20:10 I Loading map list ... +04.02.25 18:20:10 I load 6 map(s) +04.02.25 18:20:10 I Loading object list ... +04.02.25 18:20:10 I load 5 object(s) +04.02.25 18:20:10 I Loading object type ... +04.02.25 18:20:10 I load 12 type(s) +04.02.25 18:20:10 I Loading SNMP profile ... +04.02.25 18:20:10 I load 2 profile(s) +04.02.25 18:20:10 I Loading events ... +04.02.25 18:20:11 I load 259 event(s) +04.02.25 18:20:11 I Ping start ... +04.02.25 18:20:11 I Server is ready and listening on port 1225 +04.02.25 18:20:13 D -> Message type: 1 +04.02.25 18:20:13 I Authorization request send (kubernetes.docker.internal) +04.02.25 18:20:13 D <- Message type: 3 +04.02.25 18:20:13 D -> Message type: 4 +04.02.25 18:20:13 I User: michal logged in (kubernetes.docker.internal) +04.02.25 18:20:13 D <- Message type: 5 +04.02.25 18:20:13 D <- Message type: 9 +04.02.25 18:20:13 D <- For all. Message type: 7 +04.02.25 18:20:13 D <- Message type: 13 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 8 +04.02.25 18:20:13 D <- Message type: 11 +04.02.25 18:20:13 D <- Message type: 11 +04.02.25 18:20:13 D <- Message type: 100 +04.02.25 18:20:13 D <- Message type: 100 +04.02.25 18:20:13 D <- Message type: 100 +04.02.25 18:20:13 D <- Message type: 100 +04.02.25 18:20:13 D <- Message type: 100 +04.02.25 18:20:13 D <- Message type: 100 +04.02.25 18:20:13 D <- Message type: 14 +04.02.25 18:20:13 D <- Message type: 110 +04.02.25 18:20:13 D <- Message type: 107 +04.02.25 18:20:13 D <- Message type: 107 +04.02.25 18:28:05 D <- For all. Message type: 108 +04.02.25 18:28:05 D <- For all. Message type: 101 +04.02.25 18:28:05 D <- For all. Message type: 101 +04.02.25 18:29:45 D <- For all. Message type: 108 +04.02.25 18:29:45 D <- For all. Message type: 101 +04.02.25 18:29:45 D <- For all. Message type: 101 +04.02.25 18:34:14 D <- For all. Message type: 108 +04.02.25 18:34:14 D <- For all. Message type: 101 +04.02.25 18:34:14 D <- For all. Message type: 101 +04.02.25 18:35:53 D <- For all. Message type: 108 +04.02.25 18:35:53 D <- For all. Message type: 101 +04.02.25 18:35:54 D <- For all. Message type: 101 +04.02.25 18:38:18 D <- For all. Message type: 108 +04.02.25 18:38:18 D <- For all. Message type: 101 +04.02.25 18:38:18 D <- For all. Message type: 101 +04.02.25 18:39:31 D <- For all. Message type: 108 +04.02.25 18:39:31 D <- For all. Message type: 101 +04.02.25 18:39:31 D <- For all. Message type: 101 +04.02.25 18:40:31 D <- For all. Message type: 108 +04.02.25 18:40:31 D <- For all. Message type: 101 +04.02.25 18:40:31 D <- For all. Message type: 101 +04.02.25 18:44:12 D <- For all. Message type: 108 +04.02.25 18:44:12 D <- For all. Message type: 101 +04.02.25 18:44:13 D <- For all. Message type: 101 +04.02.25 18:44:43 D <- For all. Message type: 108 +04.02.25 18:44:43 D <- For all. Message type: 101 +04.02.25 18:44:44 D <- For all. Message type: 101 +04.02.25 18:46:19 D <- For all. Message type: 108 +04.02.25 18:46:19 D <- For all. Message type: 101 +04.02.25 18:46:20 D <- For all. Message type: 101 +04.02.25 18:48:13 D <- For all. Message type: 108 +04.02.25 18:48:13 D <- For all. Message type: 101 +04.02.25 18:48:14 D <- For all. Message type: 101 +04.02.25 18:49:37 D <- For all. Message type: 108 +04.02.25 18:49:37 D <- For all. Message type: 101 +04.02.25 18:49:37 D <- For all. Message type: 101 +04.02.25 18:54:18 D <- For all. Message type: 108 +04.02.25 18:54:18 D <- For all. Message type: 101 +04.02.25 18:54:18 D <- For all. Message type: 101 +04.02.25 18:59:24 D <- For all. Message type: 108 +04.02.25 18:59:24 D <- For all. Message type: 101 +04.02.25 18:59:27 D <- For all. Message type: 101 +04.02.25 18:59:56 D <- For all. Message type: 108 +04.02.25 18:59:56 D <- For all. Message type: 101 +04.02.25 18:59:56 D <- For all. Message type: 101 +04.02.25 19:11:38 D <- For all. Message type: 108 +04.02.25 19:11:38 D <- For all. Message type: 101 +04.02.25 19:11:39 D <- For all. Message type: 101 +04.02.25 19:14:33 D <- For all. Message type: 108 +04.02.25 19:14:33 D <- For all. Message type: 101 +04.02.25 19:14:33 D <- For all. Message type: 101 +04.02.25 19:20:55 D <- For all. Message type: 108 +04.02.25 19:20:55 D <- For all. Message type: 101 +04.02.25 19:20:55 D <- For all. Message type: 101 +04.02.25 19:24:30 D <- For all. Message type: 108 +04.02.25 19:24:30 D <- For all. Message type: 101 +04.02.25 19:24:30 D <- For all. Message type: 101 +04.02.25 19:29:23 D <- For all. Message type: 108 +04.02.25 19:29:23 D <- For all. Message type: 101 +04.02.25 19:29:24 D <- For all. Message type: 101 +04.02.25 19:34:17 D <- For all. Message type: 108 +04.02.25 19:34:17 D <- For all. Message type: 101 +04.02.25 19:34:18 D <- For all. Message type: 101 +04.02.25 19:44:31 D <- For all. Message type: 108 +04.02.25 19:44:31 D <- For all. Message type: 101 +04.02.25 19:44:31 D <- For all. Message type: 101 +04.02.25 19:48:14 D <- For all. Message type: 108 +04.02.25 19:48:14 D <- For all. Message type: 101 +04.02.25 19:48:14 D <- For all. Message type: 101 +04.02.25 19:59:37 D <- For all. Message type: 108 +04.02.25 19:59:37 D <- For all. Message type: 101 +04.02.25 19:59:38 D <- For all. Message type: 101 +04.02.25 20:0:02 D <- For all. Message type: 108 +04.02.25 20:0:02 D <- For all. Message type: 101 +04.02.25 20:0:03 D <- For all. Message type: 101 +04.02.25 20:8:49 D <- For all. Message type: 108 +04.02.25 20:8:49 D <- For all. Message type: 101 +04.02.25 20:8:50 D <- For all. Message type: 101 +04.02.25 20:9:35 D <- For all. Message type: 108 +04.02.25 20:9:35 D <- For all. Message type: 101 +04.02.25 20:9:35 D <- For all. Message type: 101 +04.02.25 20:17:35 D <- For all. Message type: 108 +04.02.25 20:17:35 D <- For all. Message type: 101 +04.02.25 20:17:35 D <- For all. Message type: 101 +04.02.25 20:19:33 D <- For all. Message type: 108 +04.02.25 20:19:33 D <- For all. Message type: 101 +04.02.25 20:19:33 D <- For all. Message type: 101 +04.02.25 20:19:47 D <- For all. Message type: 108 +04.02.25 20:19:47 D <- For all. Message type: 101 +04.02.25 20:19:47 D <- For all. Message type: 101 +04.02.25 20:23:18 D <- For all. Message type: 108 +04.02.25 20:23:18 D <- For all. Message type: 101 +04.02.25 20:23:19 D <- For all. Message type: 101 +04.02.25 20:24:28 D <- For all. Message type: 108 +04.02.25 20:24:28 D <- For all. Message type: 101 +04.02.25 20:24:29 D <- For all. Message type: 101 +04.02.25 20:24:31 D <- For all. Message type: 108 +04.02.25 20:24:31 D <- For all. Message type: 101 +04.02.25 20:24:31 D <- For all. Message type: 101 +04.02.25 20:26:06 D <- For all. Message type: 108 +04.02.25 20:26:06 D <- For all. Message type: 101 +04.02.25 20:26:06 D <- For all. Message type: 101 +04.02.25 20:34:17 D <- For all. Message type: 108 +04.02.25 20:34:17 D <- For all. Message type: 101 +04.02.25 20:34:18 D <- For all. Message type: 101 +04.02.25 20:44:50 D <- For all. Message type: 108 +04.02.25 20:44:50 D <- For all. Message type: 101 +04.02.25 20:44:53 D <- For all. Message type: 108 +04.02.25 20:44:53 D <- For all. Message type: 101 +04.02.25 20:44:53 D <- For all. Message type: 101 +04.02.25 20:44:53 D <- For all. Message type: 101 +04.02.25 20:52:08 D <- For all. Message type: 108 +04.02.25 20:52:08 D <- For all. Message type: 101 +04.02.25 20:52:09 D <- For all. Message type: 101 +04.02.25 20:54:29 D <- For all. Message type: 108 +04.02.25 20:54:29 D <- For all. Message type: 101 +04.02.25 20:54:30 D <- For all. Message type: 101 +04.02.25 21:8:32 D <- For all. Message type: 108 +04.02.25 21:8:32 D <- For all. Message type: 101 +04.02.25 21:8:32 D <- For all. Message type: 101 +04.02.25 21:13:54 D <- For all. Message type: 108 +04.02.25 21:13:54 D <- For all. Message type: 101 +04.02.25 21:13:55 D <- For all. Message type: 101 +04.02.25 21:29:31 D <- For all. Message type: 108 +04.02.25 21:29:31 D <- For all. Message type: 101 +04.02.25 21:29:31 D <- For all. Message type: 101 +04.02.25 21:30:11 D <- For all. Message type: 108 +04.02.25 21:30:11 D <- For all. Message type: 101 +04.02.25 21:30:12 D <- For all. Message type: 101 +04.02.25 21:30:18 D <- For all. Message type: 108 +04.02.25 21:30:18 D <- For all. Message type: 101 +04.02.25 21:30:19 D <- For all. Message type: 101 +04.02.25 21:39:31 D <- For all. Message type: 108 +04.02.25 21:39:31 D <- For all. Message type: 101 +04.02.25 21:39:31 D <- For all. Message type: 101 +04.02.25 21:40:04 D <- For all. Message type: 108 +04.02.25 21:40:04 D <- For all. Message type: 101 +04.02.25 21:40:05 D <- For all. Message type: 101 +04.02.25 21:41:08 D <- For all. Message type: 108 +04.02.25 21:41:08 D <- For all. Message type: 101 +04.02.25 21:41:08 D <- For all. Message type: 101 +04.02.25 21:53:54 D <- For all. Message type: 108 +04.02.25 21:53:54 D <- For all. Message type: 101 +04.02.25 21:53:55 D <- For all. Message type: 101 +04.02.25 21:54:05 D <- For all. Message type: 108 +04.02.25 21:54:05 D <- For all. Message type: 101 +04.02.25 21:54:05 D <- For all. Message type: 101 +04.02.25 21:54:38 D <- For all. Message type: 108 +04.02.25 21:54:38 D <- For all. Message type: 101 +04.02.25 21:54:38 D <- For all. Message type: 101 +04.02.25 22:4:46 D <- For all. Message type: 108 +04.02.25 22:4:46 D <- For all. Message type: 101 +04.02.25 22:4:47 D <- For all. Message type: 101 +04.02.25 22:10:03 D <- For all. Message type: 108 +04.02.25 22:10:03 D <- For all. Message type: 101 +04.02.25 22:10:03 D <- For all. Message type: 101 +04.02.25 22:39:33 D <- For all. Message type: 108 +04.02.25 22:39:33 D <- For all. Message type: 101 +04.02.25 22:39:34 D <- For all. Message type: 101 +04.02.25 22:52:23 D <- For all. Message type: 108 +04.02.25 22:52:23 D <- For all. Message type: 101 +04.02.25 22:52:24 D <- For all. Message type: 101 +04.02.25 22:54:16 D <- For all. Message type: 108 +04.02.25 22:54:16 D <- For all. Message type: 101 +04.02.25 22:54:16 D <- For all. Message type: 101 diff --git a/manifest.mf b/manifest.mf new file mode 100644 index 0000000..328e8e5 --- /dev/null +++ b/manifest.mf @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +X-COMMENT: Main-Class will be added automatically by build + diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml new file mode 100644 index 0000000..9fbc901 --- /dev/null +++ b/nbproject/build-impl.xml @@ -0,0 +1,1789 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No tests executed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + Must select one file in the IDE or set profile.class + This target only works when run from inside the NetBeans IDE. + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + Must select some files in the IDE or set test.includes + + + + + Must select one file in the IDE or set run.class + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + Must select some files in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + Must select one file in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties new file mode 100644 index 0000000..48fd8e1 --- /dev/null +++ b/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=36922983 +build.xml.script.CRC32=49bb365f +build.xml.stylesheet.CRC32=f85dc8f2@1.113.0.48 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=36922983 +nbproject/build-impl.xml.script.CRC32=233b34c8 +nbproject/build-impl.xml.stylesheet.CRC32=12e0a6c2@1.113.0.48 diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 0000000..689f904 --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,118 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=jNetServer +application.vendor=cucky +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.modulepath=\ + ${run.modulepath} +debug.test.classpath=\ + ${run.test.classpath} +debug.test.modulepath=\ + ${run.test.modulepath} +# Files in build.classes.dir which should be excluded from distribution jar +dist.archive.excludes= +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/jNetServer.jar +dist.javadoc.dir=${dist.dir}/javadoc +dist.jlink.dir=${dist.dir}/jlink +dist.jlink.output=${dist.jlink.dir}/jNetServer +endorsed.classpath= +excludes= +file.reference.apache-commons-lang3-3.12.0.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\apache-commons-lang3-3.12.0.jar +file.reference.apache-commons-logging-1.2.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\apache-commons-logging-1.2.jar +file.reference.apache-commons-text-1.10.0.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\apache-commons-text-1.10.0.jar +file.reference.icmp4j-all.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\icmp4j-all.jar +file.reference.jna-5.3.1.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\jna-5.3.1.jar +file.reference.jna-platform-5.9.0.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\jna-platform-5.9.0.jar +file.reference.mysql-connector-java-8.0.15.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\mysql-connector-java-8.0.15.jar +file.reference.netty-all-4.1.68.Final.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\netty-all-4.1.68.Final.jar +file.reference.spring-security-crypto-5.8.0.jar=C:\\Users\\cucky\\Documents\\NetBeansProjects\\jar_files\\spring-security-crypto-5.8.0.jar +includes=** +jar.compress=false +javac.classpath=\ + ${file.reference.mysql-connector-java-8.0.15.jar}:\ + ${reference.jNetLib.jar}:\ + ${file.reference.apache-commons-lang3-3.12.0.jar}:\ + ${file.reference.netty-all-4.1.68.Final.jar}:\ + ${file.reference.icmp4j-all.jar}:\ + ${file.reference.apache-commons-logging-1.2.jar}:\ + ${file.reference.apache-commons-text-1.10.0.jar}:\ + ${file.reference.jna-5.3.1.jar}:\ + ${file.reference.jna-platform-5.9.0.jar}:\ + ${file.reference.spring-security-crypto-5.8.0.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.external.vm=true +javac.modulepath= +javac.processormodulepath= +javac.processorpath=\ + ${javac.classpath} +javac.source=23 +javac.target=23 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.modulepath=\ + ${javac.modulepath} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.html5=false +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +# The jlink additional root modules to resolve +jlink.additionalmodules= +# The jlink additional command line parameters +jlink.additionalparam= +jlink.launcher=true +jlink.launcher.name=jNetServer +main.class=jnet.server.Server +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +project.jNetLib=../jNetLib +reference.jNetLib.jar=${project.jNetLib}/dist/jNetLib.jar +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs= +run.modulepath=\ + ${javac.modulepath} +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +run.test.modulepath=\ + ${javac.test.modulepath} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 0000000..2e8bb54 --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,25 @@ + + + org.netbeans.modules.java.j2seproject + + + jNetServer + + + + + + + + + + jNetLib + jar + + jar + clean + jar + + + + diff --git a/src/jnet/server/Database.java b/src/jnet/server/Database.java new file mode 100644 index 0000000..70c00fa --- /dev/null +++ b/src/jnet/server/Database.java @@ -0,0 +1,710 @@ +package jnet.server; + +import java.sql.Timestamp; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import jnet.lib.LogFile; +import jnet.lib.object.Event; +import jnet.lib.object.Map; +import jnet.lib.object.MapObject; +import jnet.lib.object.ObjectType; +import jnet.lib.object.SnmpProbe; +import jnet.lib.object.SnmpProfile; +import jnet.lib.object.User; + +public class Database { + + private static Connection connection = null; + private static String host; + private static String port; + private static String database; + private static String user; + private static String password; + + + public void connect(String host, String port, String database, String user, String password) { + this.host = host; + this.port = port; + this.database = database; + this.user = user; + this.password = password; + + connection = connect(); + } + + private static Connection connect() { + try { + LogFile.printInfo("Connecting to a selected database ..."); + Connection connection = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database + "" + + "?useUnicode=true" + + "&characterEncoding=UTF-8" + + "&autoReconnect=true" + + "&serverTimezone=UTC", user, password); + LogFile.printInfo(" successfully"); + return connection; + } catch (SQLException ex) { + LogFile.printErr("MySQL connection exception: " + ex.getMessage()); + LogFile.printErr("MySQL host: " + host + " port: " + port + " database: " + database + " user: " + user); + System.exit(0); + } + return null; + } + + /** + * vrati aktualni spojeni + * + * @return + * @throws SQLException + */ + public static Connection getCurrentConnection() throws SQLException { + if (connection != null || connection.isClosed()) { + return connection; + } else { + connection = connect(); + } + return null; + } + + /** + * insert + * + * @param sql dotaz + * @return pri uspesnem vlozeni vrati posledni vlozeny id + */ + public static int insert(String sqlQuery) { + long id = -1; + try { + Statement statement = getCurrentConnection().createStatement(); + statement.executeUpdate(sqlQuery, Statement.RETURN_GENERATED_KEYS); + + PreparedStatement getLastInsertId = getCurrentConnection().prepareStatement("SELECT LAST_INSERT_ID()"); + ResultSet rs = getLastInsertId.executeQuery(); + if (rs.next()) { + id = rs.getLong("last_insert_id()"); + } + } catch (SQLException ex) { + LogFile.printErr("MySQL exception: " + ex.getMessage() + " SQL: " + sqlQuery); + } + return (int) id; + } + + /** + * update + * + * @param sql sql dotaz + */ + public static void update(String sql) { + try { + Statement statement = getCurrentConnection().createStatement(); + statement.executeUpdate(sql); + statement.close(); + } catch (SQLException ex) { + LogFile.printErr("MySQL exception: " + ex.getMessage() + " SQL: " + sql); + } + } + + /** + * smaze zaznam z tabulky + * + * @param table nazev tabulky + * @param id id rádku + * @return + */ + static boolean remove(String table, int id) { + try { + String sql = "DELETE FROM " + table + " WHERE id = ?"; + + PreparedStatement stmt = getCurrentConnection().prepareStatement(sql); + + stmt.setInt(1, id); + + int affectedRows = stmt.executeUpdate(); + if (affectedRows > 0) { + return true; + } else { + return false; + } + } catch (SQLException ex) { + LogFile.printErr("Database error: " + ex.getMessage()); + } + return false; + } + + /** + * vytvoří tabulku + * + * @param sql string + */ + public static void createTable(String sql) { + try { + Statement statement = getCurrentConnection().createStatement(); + statement.executeUpdate(sql); + } catch (SQLException e) { + System.out.println("An error has occured on Table Creation: " + e.getMessage()); + } + } + + /** + * vráti seznam vsech map + * + * @return ArrayList + */ + public static ArrayList getMapList() { + String sql = "SELECT * FROM maps"; + ArrayList list = new ArrayList(); + try { + Statement statement = getCurrentConnection().createStatement(); + ResultSet rs = statement.executeQuery(sql); + while (rs.next()) { + Map m = new Map( + rs.getInt("id"), + rs.getString("name"), + rs.getBoolean("locked")); + list.add(m); + } + rs.close(); + } catch (SQLException ex) { + LogFile.printErr("MySQL exception: " + ex.getMessage() + "query: " + sql); + } + return list; + } + + /** + * vrati seznam objektu odpovidajici mape + * + * @param mapId id mapy + * @return ArrayList + */ + public static ArrayList getMapObject(int mapId) { + ArrayList list = new ArrayList<>(); + String sql = "SELECT * FROM objects WHERE map = " + mapId; + try { + Statement statement = getCurrentConnection().createStatement(); + ResultSet r = statement.executeQuery(sql); + while (r.next()) { + int objId = r.getInt("id"); + list.add(new MapObject( + objId, + r.getString("name"), + r.getInt("map"), + r.getInt("objectType"), + r.getString("ip"), + r.getInt("x"), + r.getInt("y"), + r.getString("user"), + r.getString("password"), + r.getString("description"), + r.getString("location"), + r.getInt("snmpProfile"), + getSnmpProbe(objId), + (boolean) (r.getInt("active") == 1), + (r.getInt("winbox") == 1), + r.getString("winboxPort"), + (boolean) (r.getInt("ssh") == 1), + r.getString("sshPort"), + (boolean) (r.getInt("web") == 1), + r.getString("webPort"), + r.getInt("webVerze"), + (boolean) (r.getInt("telnet") == 1), + r.getString("telnetPort"), + (boolean) (r.getInt("sms") == 1), + r.getString("smsPort"), + r.getInt("smsVerze") + )); + } + r.close(); + statement.close(); + } catch (SQLException ex) { + LogFile.printErr("MySQL exception: " + ex.getMessage() + "query: " + sql); + } + return list; + } + + /** + * vrati seznam objektu + * + * @return ArrayList + */ + public static ArrayList getAllMapObject() { + ArrayList list = new ArrayList<>(); + String sql = "SELECT * FROM objects"; + try { + Statement statement = getCurrentConnection().createStatement(); + ResultSet r = statement.executeQuery(sql); + while (r.next()) { + int objId = r.getInt("id"); + list.add(new MapObject( + objId, + r.getString("name"), + r.getInt("map"), + r.getInt("objectType"), + r.getString("ip"), + r.getInt("x"), + r.getInt("y"), + r.getString("user"), + r.getString("password"), + r.getString("description"), + r.getString("location"), + r.getInt("snmpProfile"), + getSnmpProbe(objId), + (boolean) (r.getInt("active") == 1), + (r.getInt("winbox") == 1), + r.getString("winboxPort"), + (boolean) (r.getInt("ssh") == 1), + r.getString("sshPort"), + (boolean) (r.getInt("web") == 1), + r.getString("webPort"), + r.getInt("webVerze"), + (boolean) (r.getInt("telnet") == 1), + r.getString("telnetPort"), + (boolean) (r.getInt("sms") == 1), + r.getString("smsPort"), + r.getInt("smsVerze") + )); + } + r.close(); + statement.close(); + } catch (SQLException ex) { + LogFile.printErr("MySQL exception: " + ex.getMessage() + "query: " + sql); + } + return list; + } + + /** + * vrati seznam SNMP probe + * + * @return ArrayList + */ + public static ArrayList getSnmpProbe(int objId) { + ArrayList list = new ArrayList<>(); + String sql = "SELECT * FROM snmpProbe WHERE object = " + objId; + try { + Statement statement = getCurrentConnection().createStatement(); + ResultSet r = statement.executeQuery(sql); + while (r.next()) { + list.add(new SnmpProbe( + r.getInt("id"), + r.getString("name"), + r.getInt("object") + )); + } + r.close(); + statement.close(); + } catch (SQLException ex) { + LogFile.printErr("MySQL exception: " + ex.getMessage() + "query: " + sql); + } + return list; + } + + /** + * vrati informace o uzivateli podle jmena + * + * @param username + * @return User + */ + static User getUserInfo(String username) { + User u = null; + try { + Statement statement = getCurrentConnection().createStatement(); + ResultSet r_con = statement.executeQuery("SELECT * FROM users WHERE username = '" + username + "'"); + while (r_con.next()) { + u = new User(r_con.getInt("id"), + username, + r_con.getString("password"), + r_con.getBoolean("add_map"), + r_con.getBoolean("remove_map"), + r_con.getBoolean("edit_map"), + r_con.getBoolean("add_object"), + r_con.getBoolean("remove_object"), + r_con.getBoolean("edit_object"), + r_con.getBoolean("edit_server") + ); + } + r_con.close(); + } catch (SQLException ex) { + LogFile.printErr("MySQL exception: " + ex.getMessage()); + + } + return u; + } + + /** + * vrati seznam object type + * + * @return ArrayList + */ + static ArrayList getObjectType() { + ArrayList objectType = new ArrayList<>(); + try { + Statement statement = getCurrentConnection().createStatement(); + ResultSet so = statement.executeQuery("SELECT * FROM objectType"); + while (so.next()) { + objectType.add(new ObjectType( + so.getInt("id"), + so.getString("name"), + so.getString("image") + )); + } + so.close(); + } catch (SQLException ex) { + System.out.println("MySQL exception: " + ex.getMessage()); + } + return objectType; + } + + /** + * vrati seznam uzivatelu + * + * @return ArrayList + */ + static ArrayList getUsers() { + ArrayList users = new ArrayList<>(); + try { + Statement statement = getCurrentConnection().createStatement(); + ResultSet su = statement.executeQuery("SELECT * FROM users"); + while (su.next()) { + users.add(new User( + su.getInt("id"), + su.getString("username"), + "", + su.getBoolean("add_map"), + su.getBoolean("remove_map"), + su.getBoolean("edit_map"), + su.getBoolean("add_object"), + su.getBoolean("remove_object"), + su.getBoolean("edit_object"), + su.getBoolean("edit_server") + )); + } + su.close(); + } catch (SQLException ex) { + System.out.println("MySQL exception: " + ex.getMessage()); + } + return users; + } + + /** + * vrati snmp profily + * + * @return ArrayList + */ + static ArrayList getSnmpProfile() { + ArrayList snmpProfile = new ArrayList<>(); + try { + Statement statement = getCurrentConnection().createStatement(); + ResultSet rs = statement.executeQuery("SELECT * FROM snmpProfile"); + while (rs.next()) { + snmpProfile.add(new SnmpProfile( + rs.getInt("id"), + rs.getString("name"), + rs.getInt("version"), + rs.getString("port"), + rs.getString("communityRead"), + rs.getString("communityRead") + )); + } + rs.close(); + } catch (SQLException ex) { + System.out.println("MySQL exception: " + ex.getMessage()); + } + return snmpProfile; + } + + /** + * vrati seznam udalosti + * + * @param + * @return ArrayList + */ + public static ArrayList getEvents() { + ArrayList list = new ArrayList<>(); + String sql = "SELECT * FROM events"; + try { + Statement statement = getCurrentConnection().createStatement(); + ResultSet r = statement.executeQuery(sql); + while (r.next()) { + list.add(new Event( + r.getInt("id"), + r.getInt("object"), + r.getLong("start"), + r.getLong("finish"), + r.getString("description"), + r.getInt("type") + )); + } + r.close(); + statement.close(); + } catch (SQLException ex) { + LogFile.printErr("MySQL exception: " + ex.getMessage() + "query: " + sql); + } + return list; + } + + /** + * pridá objekt + * + * @param mo MapObject + * @return + */ + static MapObject addMapObject(MapObject mo) { + String query = "INSERT INTO objects (" + + "name," + + "ip," + + "x," + + "y," + + "map," + + "objectType," + + "active," + + "user," + + "password," + + "description," + + "location," + + "snmpProfile," + + "winbox," + + "winboxPort," + + "ssh," + + "sshPort," + + "web," + + "webPort," + + "webVerze," + + "telnet," + + "telnetPort," + + "sms," + + "smsPort," + + "smsVerze" + + ") VALUES (" + + "'" + mo.getName() + "'," + + "'" + mo.getIp() + "'," + + "'" + mo.getX() + "'," + + "'" + mo.getY() + "'," + + "'" + mo.getMap() + "'," + + "'" + mo.getObjectType() + "'," + + "'" + (mo.isActive() ? 1 : 0) + "'," + + "'" + mo.getUser() + "'," + + "'" + mo.getPassword() + "'," + + "'" + mo.getDescription() + "'," + + "'" + mo.getLocation() + "'," + + "'" + mo.getSnmpProfile() + "'," + + "'" + (mo.isWinbox() ? 1 : 0) + "'," + + "'" + mo.getWinboxPort() + "'," + + "'" + (mo.isSsh() ? 1 : 0) + "'," + + "'" + mo.getSshPort() + "'," + + "'" + (mo.isWeb() ? 1 : 0) + "'," + + "'" + mo.getWebPort() + "'," + + "'" + mo.getWebVerze() + "'," + + "'" + (mo.isTelnet() ? 1 : 0) + "'," + + "'" + mo.getTelnetPort() + "'," + + "'" + (mo.isSms() ? 1 : 0) + "'," + + "'" + mo.getSmsPort() + "'," + + "'" + mo.getSmsVerze() + "'" + + ")"; + mo.setId(insert(query)); + return mo; + } + + /** + * nastaví stav zámku mapy + * + * @param state stav + * @param map map id + */ + static void mapLock(int state, int map) { + update("UPDATE maps SET locked='" + state + "' WHERE id=" + map); + } + + /** + * pridá typ objektu + * + * @param ot ObjectType + * @return + */ + static int addObjectType(ObjectType ot) { + return insert("INSERT INTO objectType (name, image) VALUES ('" + ot.getName() + "', '" + ot.getImgStr() + "')"); + } + + /** + * odebere objekt z databaze + * + * @param id + */ + static void removeObject(int id) { + if (remove("objects", id)) { + LogFile.printInfo("Obejct ID " + id + " removed from database"); + } else { + LogFile.printErr("Obejct ID " + id + " not removed from database"); + } + } + + /** + * odebere mapu z databaze + * + * @param id + */ + static void removeMap(int id) { + if (remove("maps", id)) { + LogFile.printInfo("Map ID " + id + " removed from database"); + } else { + LogFile.printErr("Map ID " + id + " not removed from database"); + } + } + + /** + * pridani mapy + * + * @param name nazev mapy + * @return + */ + static int addMap(String name) { + return insert("INSERT INTO maps (name) VALUES ('" + name + "')"); + } + + /** + * zmeni pozici objektu + * + * @param id id objektu + * @param x pozice x + * @param y pozice y + */ + static void objectMove(int id, int x, int y) { + update("UPDATE objects SET x='" + x + "', y='" + y + "' WHERE id=" + id); + } + + /** + * upravi object + * + * @param mo MapObject + */ + static void updateObject(MapObject mo) { + update("UPDATE objects SET " + + "name='" + mo.getName() + "', " + + "ip='" + mo.getIp() + "', " + + "x='" + mo.getX() + "', " + + "y='" + mo.getY() + "'," + + "map='" + mo.getMap() + "', " + + "objectType='" + mo.getObjectType() + "', " + + "active='" + (mo.isActive() ? 1 : 0) + "', " + + "user='" + mo.getUser() + "', " + + "password='" + mo.getPassword() + "', " + + "description='" + mo.getDescription() + "', " + + "location='" + mo.getLocation() + "', " + + "snmpProfile='" + mo.getSnmpProfile() + "', " + + "winbox='" + (mo.isWinbox() ? 1 : 0) + "', " + + "winboxPort='" + mo.getWinboxPort() + "', " + + "ssh='" + (mo.isSsh() ? 1 : 0) + "', " + + "sshPort='" + mo.getSshPort() + "', " + + "web='" + (mo.isWeb() ? 1 : 0) + "', " + + "webPort='" + mo.getWebPort() + "', " + + "webVerze='" + mo.getWebVerze() + "', " + + "telnet='" + (mo.isTelnet() ? 1 : 0) + "', " + + "telnetPort='" + mo.getTelnetPort() + "', " + + "sms='" + (mo.isSms() ? 1 : 0) + "', " + + "smsPort='" + mo.getSmsPort() + "', " + + "smsVerze='" + mo.getSmsVerze() + "' " + + "WHERE id=" + mo.getId()); + } + + public static Event addEvent(int mo_id, String description, int type) { + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + Event event = new Event(mo_id, + timestamp.getTime(), + description, + type); + int id = insert("INSERT INTO events (" + + "object, " + + "start, " + + "description, " + + "type" + + ") VALUES (" + + "'" + event.getObject() + "'," + + "'" + event.getStart() + "'," + + "'" + event.getDescription() + "'," + + "'" + event.getType() + "'" + + ")"); + event.setId(id); + return event; + + } + + public static Event endEvent(int objectId, int type) { + Event event = null; + try { + + String select_query = "SELECT * FROM events WHERE object = '" + objectId + "' && type = '" + type + "' ORDER BY id DESC LIMIT 1"; + System.err.println(select_query); + PreparedStatement stmt = getCurrentConnection().prepareStatement(select_query); + ResultSet rs = stmt.executeQuery(); + // Process the result + if (rs.next()) { + event = new Event( + objectId, + rs.getLong("start"), + rs.getString("description"), + type); + event.setId(rs.getInt("id")); + } + Timestamp timestamp = new Timestamp(System.currentTimeMillis()); + event.setEnd(timestamp.getTime()); + String update_query = "UPDATE events SET finish='" + event.getEnd() + "' WHERE id=" + event.getId(); + update(update_query); + + } catch (SQLException ex) { + LogFile.printErr("MySQL exception: " + ex.getMessage()); + } + return event; + } + + static int addUser(User user) { + return insert("INSERT INTO users (" + + "username, " + + "password, " + + "add_map, " + + "remove_map, " + + "edit_map, " + + "add_object, " + + "remove_object, " + + "edit_object, " + + "edit_server" + + ") VALUES (" + + "'"+user.getUsername()+"'," + + "'"+user.getPassword()+"'," + + "'"+(user.isAddMap()?1:0)+"'," + + "'"+(user.isRemoveMap()?1:0)+"'," + + "'"+(user.isEditMap()?1:0)+"'," + + "'"+(user.isAddObject()?1:0)+"'," + + "'"+(user.isRemoveObject()?1:0)+"'," + + "'"+(user.isEditObject()?1:0)+"'," + + "'"+(user.isEditServer()?1:0)+"'" + + ")"); + } + + static void editUser(User ur) { + String sql = "UPDATE users SET " + + "username='" + ur.getUsername() + "'," + + "add_map='" + (ur.isAddMap() ? 1:0) + "'," + + "remove_map='" + (ur.isRemoveMap() ? 1:0) + "'," + + "edit_map='" + (ur.isEditMap() ? 1:0) + "'," + + "add_object='" + (ur.isAddObject() ? 1:0) + "'," + + "remove_object='" + (ur.isEditObject() ? 1:0) + "'," + + "edit_object='" + (ur.isRemoveObject() ? 1:0) + "'," + + "edit_server='" + (ur.isEditServer() ? 1:0) + "'" + + "WHERE id='" + ur.getId() + "'"; + update(sql); + } + + static void deleteObjectLog(int objId) { + String sql = "DELETE FROM events WHERE object = " + objId; + try { + Statement statement = getCurrentConnection().createStatement(); + statement.executeUpdate(sql); + statement.close(); + } catch (SQLException ex) { + LogFile.printErr("MySQL exception: " + ex.getMessage() + " SQL: " + sql); + } + } + +} diff --git a/src/jnet/server/Server.java b/src/jnet/server/Server.java new file mode 100644 index 0000000..145be27 --- /dev/null +++ b/src/jnet/server/Server.java @@ -0,0 +1,149 @@ +package jnet.server; + +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import jnet.lib.BuilddDate; +import jnet.lib.LogFile; +import jnet.lib.LogWindow; +import jnet.lib.OSValidator; +import jnet.lib.PasswordHashing; +import jnet.lib.PropertiesManager; +import jnet.lib.object.Event; +import jnet.lib.object.Map; +import jnet.lib.object.MapObject; +import jnet.lib.object.ObjectType; +import jnet.lib.object.OnlineClients; +import jnet.lib.object.SnmpProbe; +import jnet.lib.object.SnmpProfile; +import jnet.lib.object.User; +import jnet.server.network.NettyServer; +import jnet.server.probe.Ping2; + +public class Server { + + // verze serveru + public static final int SERVER_VERSION = 1; + + // minimální verze klienta + public static final int MINIMAL_CLIENT_VERSION = 1; + + + public static PropertiesManager config; + public static List maps = new ArrayList<>(); + public static ArrayList mapObject= new ArrayList<>(); + public static ArrayList onlineClients = new ArrayList<>(); + public static ArrayList objectType = new ArrayList<>(); + public static ArrayList snmpProfile = new ArrayList<>(); + public static ArrayList snmpProbe = new ArrayList<>(); + public static ArrayList users = new ArrayList<>(); + public static ArrayList events = new ArrayList<>(); + + public static void main(String[] args) { + + // pokud je hostitelsky system windows otevre logovaci okno + if (OSValidator.isWindows()) { + new LogWindow(); + } + + + LogWindow.addRow("tset"); + + LogFile.clear(); + LogFile.setDebug(false); + LogFile.printInfo("---------------------------------------------"); + LogFile.printInfo(" jNet Server "); + LogFile.printInfo(" Version: " + SERVER_VERSION + " (" + BuilddDate.get() + ")"); + LogFile.printInfo("---------------------------------------------"); + LogFile.printInfo(""); + + + /// + /// nahrani konfigurace + /// + LogFile.printInfo("Loading config ..."); + try { + // Načtení existující konfigurace, pokud soubor existuje + config = new PropertiesManager("config.properties"); + config.load(); + LogFile.printInfo(" successfully"); + } catch (PropertiesManager.FileException | PropertiesManager.ConfigException ex) { + LogFile.printErr(" fail. " + ex.getMessage()); + System.exit(0); + } + + + + /// + /// debug rezim ? + /// + if (config.getBoolean("debug")) { + LogFile.setDebug(true); + LogFile.printDebug("Debug mode on"); + } + + /// + /// pripojeni k databazi + /// + new Database().connect(config.getString("mysql_server"), + config.getString("mysql_port"), + config.getString("mysql_database"), + config.getString("mysql_user"), + config.getString("mysql_password")); + + /// + /// konfigurace z databaze + /// + LogFile.printInfo("Loading user list ..."); + users = Database.getUsers(); + LogFile.printInfo(" load " + users.size() + " user(s)"); + + LogFile.printInfo("Loading map list ..."); + maps = Database.getMapList(); + LogFile.printInfo(" load " + maps.size() + " map(s)"); + + LogFile.printInfo("Loading object list ..."); + mapObject = Database.getAllMapObject(); + LogFile.printInfo(" load " + mapObject.size() + " object(s)"); + + LogFile.printInfo("Loading object type ..."); + objectType = Database.getObjectType(); + LogFile.printInfo(" load " + objectType.size() + " type(s)"); + + LogFile.printInfo("Loading SNMP profile ..."); + snmpProfile = Database.getSnmpProfile(); + LogFile.printInfo(" load " + snmpProfile.size() + " profile(s)"); + +// LogFile.printInfo("Loading SNMP template ..."); +// snmpProbe = Database.getSnmpProbe(); +// LogFile.printInfo(" load " + snmpProbe.size() + " template(s)"); + + LogFile.printInfo("Loading events ..."); + events = Database.getEvents(); + LogFile.printInfo(" load " + events.size() + " event(s)"); + + + + /// + /// spusteni serveru + /// + NettyServer nettyserver = new NettyServer(config.getInt("server_port")); + nettyserver.start(); + + /// + /// spusteni ping probe + /// + /// spousete pro kazdou mapu samostatne ? + /// +// Ping pp = new Ping(); +// pp.start(); + + Ping2 p2 = new Ping2(); + p2.start(); + + } + +} diff --git a/src/jnet/server/ServerMessageParser.java b/src/jnet/server/ServerMessageParser.java new file mode 100644 index 0000000..c2d3b1e --- /dev/null +++ b/src/jnet/server/ServerMessageParser.java @@ -0,0 +1,336 @@ +package jnet.server; + +import io.netty.channel.Channel; +import io.netty.channel.group.ChannelGroup; +import io.netty.channel.group.DefaultChannelGroup; +import io.netty.util.concurrent.GlobalEventExecutor; +import java.net.InetSocketAddress; +import java.util.ListIterator; +import jnet.lib.LogFile; +import jnet.lib.Message; +import jnet.lib.PasswordHashing; +import jnet.lib.object.Event; +import jnet.lib.object.Map; +import jnet.lib.object.MapObject; +import jnet.lib.object.ObjectType; +import jnet.lib.object.OnlineClients; +import jnet.lib.object.ServerConfig; +import jnet.lib.object.SnmpProfile; +import jnet.lib.object.User; + +public class ServerMessageParser { + + private final Channel currentClient; + private static final ChannelGroup channels = new DefaultChannelGroup( + "containers", GlobalEventExecutor.INSTANCE); + + public ServerMessageParser(Channel currentClient) { + this.currentClient = currentClient; + } + + public void parse(Message msg) { + + LogFile.printDebug("-> Message type: " + msg.getType()); + + ListIterator iteratorMap = Server.maps.listIterator(); + ListIterator iteratorMapObject = Server.mapObject.listIterator(); + + switch (msg.getType()) { + + case Message.CLIENT_VERSION: + int client_version = (int) msg.getMsg(); + if (client_version < Server.MINIMAL_CLIENT_VERSION) { + LogFile.printInfo("Outdated client. Sent update request (" + ((InetSocketAddress) currentClient.remoteAddress()).getHostName() + ")"); + send(new Message(Message.UPDATE, null)); + } else { + LogFile.printInfo("Authorization request send (" + ((InetSocketAddress) currentClient.remoteAddress()).getHostName() + ")"); + // oodeslat pozadavek na autorizacni udaje + send(new Message(Message.AUTH_REQUEST, null)); + } + break; + + case Message.AUTH: + String[] userData = (String[]) msg.getMsg(); + String username = userData[0]; + String password = userData[1]; + int platform = Integer.parseInt(userData[2]); + + User u = Database.getUserInfo(username); + + if (PasswordHashing.verify(password, u.getPassword())) { + LogFile.printInfo("User: " + username + " logged in (" + ((InetSocketAddress) currentClient.remoteAddress()).getAddress().getHostName() + ")"); + // odeslat informaci uzivateli o jeho uspesnem prihlaseni + send(new Message(Message.AUTH_SUCEFULL, null)); + // pridani uzivatele mezi pripojene kanaly + channels.add(currentClient); + // vložit uživatele na seznam online uživatelů + InetSocketAddress socketAddress = (InetSocketAddress) currentClient.remoteAddress(); + String clientIp = socketAddress.getAddress().getHostAddress(); + String clientPort = String.valueOf(socketAddress.getPort()); + Server.onlineClients.add(new OnlineClients( + String.valueOf(u.getId()), + u.getUsername(), + clientIp, + clientPort, + platform)); + // odeslat informace o prihlasenem uzivateli, opravneni atd + send(new Message(Message.USER_INFO, u)); + // odeslat vsem nový seznam pripojenych klientu + sendAll(new Message(Message.ONLINE_CLIENTS, Server.onlineClients)); + // odeslat nastaveni serveru + ServerConfig sc = new ServerConfig( + Server.config.getInt("ping_attempt"), + Server.config.getInt("ping_timeout"), + Server.config.getInt("instability_attempt"), + Server.config.getInt("instability_limit")); + send(new Message(Message.SERVER_CONFIG, sc)); + // odeslat typy objektu + for (ObjectType ot : Server.objectType) { + send(new Message(Message.OBJECT_TYPE, ot)); + } + // odesila seznam uzivatelu + for (User us : Server.users) { + send(new Message(Message.USER, us)); + } + // odeslat seznam map + for (Map i : Server.maps) { + send(new Message(Message.MAP, i)); + } + // odeslat seznam objektu + send(Message.OBJECT_LIST, Server.mapObject); + // odeslat seznam udalosti + send(new Message(Message.EVENT_LIST, Server.events)); + // odeslat seznam snmp profilů + for (SnmpProfile i : Server.snmpProfile) { + send(new Message(Message.SNMP_PROFILE, i)); + } + + } else { + LogFile.printInfo("Authorization failed (ser: " + username + " )"); + } + break; + + case Message.NEW_OBJECT_TYPE: + ObjectType not = (ObjectType) msg.getMsg(); + int id = Database.addObjectType(not); + not.setId(id); + Server.objectType.add(not); + sendAll(new Message(Message.OBJECT_TYPE, not)); + break; + + case Message.SET_MAP_LOCK: + int[] data_lock = (int[]) msg.getMsg(); + while (iteratorMap.hasNext()) { + Map map = iteratorMap.next(); + if (map.getId() == data_lock[0]) { + map.setLock((data_lock[1] == 1)); + break; + } + } + // upravit informaci v databazi + Database.mapLock(data_lock[1], data_lock[0]); + // odeslani informace ostatnim + sendAll(new Message(Message.SET_MAP_LOCK, data_lock)); + break; + + case Message.ADD_OBJECT: + MapObject mo = Database.addMapObject((MapObject) msg.getMsg()); + // pridat do seznamu + iteratorMapObject.add(mo); + // odesle všem novy objekt + sendAll(new Message(Message.ADD_OBJECT, mo)); + // prida event a odesle ho + Event event = Database.addEvent(mo.getId(), "Přidáno", Event.TYPE_INFO); + sendAll(new Message(Message.EVENT_NEW, event)); + // pokud je object vypnuty prida log + if (!mo.isActive()) { + Event event_disable = Database.addEvent(mo.getId(), "Ping vypnut", Event.TYPE_PING_OFF); + sendAll(new Message(Message.EVENT_NEW, event_disable)); + } + break; + + case Message.REMOVE_OBJECT: + while (iteratorMapObject.hasNext()) { + MapObject obj = iteratorMapObject.next(); + if (obj.getId() == (int) msg.getMsg()) { + // odebere z databaze + Database.removeObject(obj.getId()); + // odesle informaci o odebrani objektu klientum + sendAll(new Message(Message.REMOVE_OBJECT, obj.getId())); + // odebere ze seznamu + iteratorMapObject.remove(); + break; + } + } + break; + + case Message.MAP_REMOVE: + while (iteratorMap.hasNext()) { + Map map = iteratorMap.next(); + if (map.getId() == (int) msg.getMsg()) { + // odebere z databaze + Database.removeMap(map.getId()); + // odesle informaci o odebrani objektu klientum + sendAll(new Message(Message.MAP_REMOVE, map.getId())); + // odebere ze seznamu + iteratorMap.remove(); + break; + } + } + break; + + case Message.MAP_ADD: + Map map = new Map((String) msg.getMsg()); + // přidání mapy do databaze + map.setId(Database.addMap(map.getName())); + //odeslání mapy klientum + send(new Message(Message.MAP, map)); + // pridani mapy do seznamu + iteratorMap.add(map); + break; + + case Message.OBJECT_MOVE: + int[] data = (int[]) msg.getMsg(); + // 0 = obj id + // 2 = x + // 2 = y + // zmenit v databázi + Database.objectMove(data[0], data[1], data[2]); + // zmenit v seznamu + while (iteratorMapObject.hasNext()) { + MapObject obj = iteratorMapObject.next(); + if (obj.getId() == data[0]) { + // zmenit pozici + obj.setX(data[1]); + obj.setY(data[2]); + // zapsat zmenu do databaze + Database.objectMove(data[0], data[1], data[2]); + // preposlat zmenu klientum + sendAll(new Message(Message.UPDATE_OBJECT, obj)); + break; + } + } + break; + case Message.UPDATE_OBJECT: + MapObject mo_u = (MapObject) msg.getMsg(); + // zmenit v databazi + Database.updateObject(mo_u); + // zmenit v seznamu + while (iteratorMapObject.hasNext()) { + if (iteratorMapObject.next().getId() == mo_u.getId()) { + iteratorMapObject.set(mo_u); + break; + } + } + // preposlat zmenu klientum + sendAll(new Message(Message.UPDATE_OBJECT, mo_u)); + break; + + case Message.DELETE_LOG: + int objId = (int) msg.getMsg(); + // vymaže logy v databazi + Database.deleteObjectLog(objId); + // vymaze logy v listu + ListIterator iterator = Server.events.listIterator(); + while (iterator.hasNext()) { + if (iterator.next().getObject() == objId) { + iterator.remove(); + break; + } + } + sendAll(new Message(Message.DELETE_LOG, objId)); + break; + + case Message.USER: + User user = (User) msg.getMsg(); + user.setPassword(PasswordHashing.hash(user.getPassword())); + //pridáni do databáze a nastaveni id + user.setId(Database.addUser(user)); + // přidání do seznamu + Server.users.add(user); + // odeslat klientum nového uživatele + send(new Message(Message.USER, user)); + break; + + case Message.USER_EDIT: + User ue = (User) msg.getMsg(); + // upraveni v databázi + Database.editUser(ue); + // zmenit v seznamu + ListIterator iteratorUser = Server.users.listIterator(); + while (iteratorUser.hasNext()) { + User next = iteratorUser.next(); + if (next.getId() == ue.getId()) { + iteratorUser.set(ue); + break; + } + + } + // preposlat zmenu klientum + sendAll(new Message(Message.USER_EDIT, ue)); + break; + + case Message.SERVER_CONFIG: + ServerConfig sc = (ServerConfig) msg.getMsg(); + // ulozeni + Server.config.setInt("ping_attempt", sc.getPingAttempt()); + Server.config.setInt("ping_timeout", sc.getPingTimeout()); + Server.config.setInt("instability_attempt", sc.getInstabilityAttempt()); + Server.config.setInt("instability_limit", sc.getInstabilityLimit()); + Server.config.save(); + //odeslani vsem + sendAll(Message.SERVER_CONFIG, sc); + break; + + default: + LogFile.printErr("Neznamy typ zpravy"); + } + + } + + public void send(Message message) { + currentClient.writeAndFlush(message); + LogFile.printDebug("<- Message type: " + message.getType()); + } + + public void send(int type, Object obj) { + currentClient.writeAndFlush(new Message(type, obj)); + LogFile.printDebug("<- Message type: " + type); + } + + public static void sendAll(Message message) { + if (channels.isEmpty()) { + return; + } + channels.writeAndFlush(message); + LogFile.printDebug("<- For all. Message type: " + message.getType()); + } + + public static void sendAll(int type, Object obj) { + if (channels.isEmpty()) { + return; + } + channels.writeAndFlush(new Message(type, obj)); + LogFile.printDebug("<- For all. Message type: " + type); + } + + public static final void removeClient(Channel ch) { + // odebrani z připojenych kanalu + channels.remove(ch); + // odebrani ze seznamu klientu + InetSocketAddress socketAddress = (InetSocketAddress) ch.remoteAddress(); + String clientIp = socketAddress.getAddress().getHostAddress(); + String clientPort = String.valueOf(socketAddress.getPort()); + for (OnlineClients oc : Server.onlineClients) { + if (oc.getIp().equals(clientIp) && oc.getPort().equals(clientPort)) { + Server.onlineClients.remove(oc); + System.err.println("Client removed"); + break; + } + } + // odeslat vsem novy seznam klientu + sendAll(new Message(Message.ONLINE_CLIENTS, Server.onlineClients)); + + } + +} diff --git a/src/jnet/server/network/NettyServer.java b/src/jnet/server/network/NettyServer.java new file mode 100644 index 0000000..6f5407f --- /dev/null +++ b/src/jnet/server/network/NettyServer.java @@ -0,0 +1,61 @@ +package jnet.server.network; + +import jnet.lib.LogFile; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.codec.serialization.ClassResolvers; +import io.netty.handler.codec.serialization.ObjectDecoder; +import io.netty.handler.codec.serialization.ObjectEncoder; + +/** + * + * @author cucky + */ +public class NettyServer extends Thread { + + private int port; + + public NettyServer(int port) { + this.port = port; + } + + @Override + public void run() { + // Skupiny pro zpracování I/O operací + EventLoopGroup bossGroup = new NioEventLoopGroup(1); + EventLoopGroup workerGroup = new NioEventLoopGroup(); + + try { + // Vytvoření ServerBootstrap pro nastavení serveru + ServerBootstrap serverBootstrap = new ServerBootstrap() + .group(bossGroup, workerGroup) + .channel(NioServerSocketChannel.class) + //.handler(new LoggingHandler(LogLevel.INFO)) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) { + ch.pipeline().addLast("decoder", new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(getClass().getClassLoader()))); + ch.pipeline().addLast("encoder", new ObjectEncoder()); + ch.pipeline().addLast(new ServerHandler()); // Vlastní handler pro zpracování zpráv + } + }); + + // Bind serveru na specifikovaný port (např. 8080) + Channel channel = serverBootstrap.bind(port).sync().channel(); + + LogFile.printInfo("Server is ready and listening on port " + port); + + // Čekání na ukončení serveru + channel.closeFuture().sync(); + } catch (Exception ex) { + LogFile.printErr("Server exception: " + ex); + } finally { + // Uvolnění prostředků + bossGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + } +} diff --git a/src/jnet/server/network/ServerHandler.java b/src/jnet/server/network/ServerHandler.java new file mode 100644 index 0000000..1e21fda --- /dev/null +++ b/src/jnet/server/network/ServerHandler.java @@ -0,0 +1,40 @@ +package jnet.server.network; + +import jnet.server.ServerMessageParser; +import io.netty.channel.Channel; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import jnet.lib.LogFile; +import jnet.lib.Message; + +public class ServerHandler extends ChannelInboundHandlerAdapter { + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + if (msg instanceof Message) { + Message m = (Message) msg; + new ServerMessageParser(ctx.channel()).parse((Message) msg); + } + if (msg instanceof String) { + System.out.println("Client message: " + msg); + } + } + + @Override + public void channelRegistered(ChannelHandlerContext ctx) throws Exception { + System.out.println("Client connected"); + Channel currentClient = ctx.channel(); + currentClient.writeAndFlush(new Message(Message.CLIENT_VERSION, null)); + } + + @Override + public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { + LogFile.printInfo("Client disconnected"); + ServerMessageParser.removeClient(ctx.channel()); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + ctx.close(); + } +} \ No newline at end of file diff --git a/src/jnet/server/network/ServerSsl.java b/src/jnet/server/network/ServerSsl.java new file mode 100644 index 0000000..cfc82de --- /dev/null +++ b/src/jnet/server/network/ServerSsl.java @@ -0,0 +1,88 @@ +package jnet.server.network; + +import io.netty.bootstrap.ServerBootstrap; +import io.netty.channel.*; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.SocketChannel; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.handler.codec.string.StringDecoder; +import io.netty.handler.codec.string.StringEncoder; +import io.netty.handler.ssl.SslContext; +import io.netty.handler.ssl.SslContextBuilder; +import io.netty.handler.ssl.util.InsecureTrustManagerFactory; +import io.netty.handler.ssl.util.SelfSignedCertificate; +import java.security.cert.CertificateException; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.net.ssl.SSLException; + +/** + * + * @author cucky + */ +public class ServerSsl extends Thread { + + private int port; + + public ServerSsl(int port) { + this.port = port; + } + + @Override + public void run() { + + try { + + // Načtení self-signed certifikátu a privátního klíče + //File certChainFile = new File("cert.pem"); + //File privateKeyFile = new File("key.pem"); + // Vytvoření SSL kontextu + //SslContext sslContext = SslContextBuilder.forServer(certChainFile, privateKeyFile).build(); + + // Self-signed certifikát pro server + SelfSignedCertificate ssc = new SelfSignedCertificate(); + + // SSL kontext pro server + SslContext sslContext = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) + .trustManager(InsecureTrustManagerFactory.INSTANCE) // Nepožadujeme důvěryhodné klientské certifikáty + .build(); + // Skupiny pro zpracování I/O operací + EventLoopGroup bossGroup = new NioEventLoopGroup(1); + EventLoopGroup workerGroup = new NioEventLoopGroup(); + try { + // Vytvoření ServerBootstrap pro nastavení serveru + ServerBootstrap serverBootstrap = new ServerBootstrap() + .group(bossGroup, workerGroup) + .channel(NioServerSocketChannel.class) + //.handler(new LoggingHandler(LogLevel.INFO)) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(SocketChannel ch) { + ch.pipeline().addLast(sslContext.newHandler(ch.alloc())); // SSL handler + ch.pipeline().addLast(new StringDecoder()); // Dekóduje zprávy přijaté od klienta + ch.pipeline().addLast(new StringEncoder()); // Kóduje zprávy odeslané klientovi + ch.pipeline().addLast(new ServerHandler()); // Vlastní handler pro zpracování zpráv + } + }); + + // Bind serveru na specifikovaný port (např. 8080) + Channel channel = serverBootstrap.bind(port).sync().channel(); + + System.out.println("ssl Server is ready and listening on port " + port); + + // Čekání na ukončení serveru + channel.closeFuture().sync(); + } catch (Exception ex) { + Logger.getLogger(ServerSsl.class.getName()).log(Level.SEVERE, null, ex); + } finally { + // Uvolnění prostředků + bossGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(); + } + } catch (SSLException ex) { + Logger.getLogger(ServerSsl.class.getName()).log(Level.SEVERE, null, ex); + } catch (CertificateException ex) { + Logger.getLogger(ServerSsl.class.getName()).log(Level.SEVERE, null, ex); + } + } +} diff --git a/src/jnet/server/probe/Ping.java b/src/jnet/server/probe/Ping.java new file mode 100644 index 0000000..28aeac6 --- /dev/null +++ b/src/jnet/server/probe/Ping.java @@ -0,0 +1,136 @@ +package jnet.server.probe; + +import java.io.IOException; +import java.net.InetAddress; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; +import jnet.lib.LogFile; +import jnet.lib.Message; +import jnet.lib.Status; +import jnet.lib.object.Event; +import jnet.lib.object.MapObject; +import jnet.server.Database; +import jnet.server.Server; +import jnet.server.ServerMessageParser; + +public class Ping extends Thread { + + // Perioda opakování v sekundách + private static final int PERIOD = 3; + // Timeout pro ping (v milisekundách) + private static final int TIMEOUT = 2000; + // pocet pokus pro nastaveni offline statusu + private static final int ATTEMPT = 3; + + public Ping() { + } + + @Override + public void start() { + init(); + } + + private void init() { + // ExecutorService pro paralelní provádění pingů + ExecutorService executorService = Executors.newCachedThreadPool(); + + // ScheduledExecutorService pro periodické provádění + ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1); + + // Naplánování periodického provádění kontrol + scheduledExecutorService.scheduleAtFixedRate(() -> { + for (MapObject mo : Server.mapObject) { + if (mo.isActive()) { + // Vytvoření úkolu pro pingování každé IP adresy + executorService.submit(() -> { + try { + long responseTime = pingWithResponseTime(mo.getIp()); + if (responseTime >= 0) { + isOnline(mo, responseTime); + } else { + isOffline(mo); + } + } catch (Exception e) { + LogFile.printDebug("Chyba pri pingovani " + mo.getIp() + ": " + e.getMessage()); + } + }); + } + + } + }, 0, PERIOD, TimeUnit.SECONDS); + } + + // Funkce pro kontrolu dostupnosti IP adresy s timeoutem a zobrazení času odezvy + private static long pingWithResponseTime(String ipAddress) throws IOException, InterruptedException { + InetAddress inet = InetAddress.getByName(ipAddress); + long startTime = System.currentTimeMillis(); // Začátek měření času + boolean reachable = inet.isReachable(TIMEOUT); // Timeout pro ping 5 sekund + long endTime = System.currentTimeMillis(); // Konec měření času + + if (reachable) { + return endTime - startTime; // Vrátí dobu odezvy v milisekundách + } else { + return -1; // Pokud není dostupná, vrátí -1 + } + } + + private void isOnline(MapObject mo, long responseTime) { + // LogFile.printDebug(mo.getName() + "(" + mo.getIp() + ") online, latence: " + responseTime + " ms"); + // pokud neni predchozi stav ok odesle novy stav + if (mo.getStatus() != Status.OK) { + // pokud byl predchozi stav offline ukonci event + if (mo.getStatus() == Status.OFFLINE) { + // zapise do logu konec udalosti + Event event = Database.endEvent(mo.getId(), Event.TYPE_PING); + for (int i = 0; i < Server.events.size(); i++) { + if (Server.events.get(i).getId() == event.getId()) { + Server.events.set(i, event); + ServerMessageParser.sendAll(new Message(Message.EVENT_UPDATE, (Event) event)); + break; + } + } + // vynuluje počet pokusu o ping + mo.setPingAttemp(0); + // nastavi a odesle stav + setNewState(mo, Status.OK); + } + // pokud byl predchozi stav N/A + if (mo.getStatus() == Status.NA) { + // nastavi a odesle stav + setNewState(mo, Status.OK); + } + } + + } + + private void setNewState(MapObject mo, int state) { + mo.setStatus(state); + // odesle stav + int[] o = {mo.getId(), state}; + ServerMessageParser.sendAll(new Message(Message.STATUS_UPDATE, o)); + } + + private void isOffline(MapObject mo) { + // zvysi pocet jiz probehlích pokusu o ping + mo.pingAttemp++; + + // vyhodnoti + if (mo.getStatus() != Status.OFFLINE && mo.getPingAttemp() >= ATTEMPT) { + int[] o = {mo.getId(), Status.OFFLINE}; + // nastavi objektu status + mo.setStatus(Status.OFFLINE); + // zapise do logu + + // zapise do databaze + Event event = Database.addEvent(mo.getId(), "offline", Event.TYPE_PING); + Server.events.add(event); + + //odesle stav a event klientum + ServerMessageParser.sendAll(new Message(Message.STATUS_UPDATE, o)); + ServerMessageParser.sendAll(new Message(Message.EVENT_NEW, event)); + } + } + +} diff --git a/src/jnet/server/probe/Ping2.java b/src/jnet/server/probe/Ping2.java new file mode 100644 index 0000000..1d04400 --- /dev/null +++ b/src/jnet/server/probe/Ping2.java @@ -0,0 +1,78 @@ +package jnet.server.probe; + +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import jnet.lib.LogFile; +import jnet.lib.Status; +import jnet.lib.object.MapObject; +import jnet.server.Server; +import org.icmp4j.IcmpPingRequest; +import org.icmp4j.IcmpPingResponse; +import org.icmp4j.IcmpPingUtil; + +public class Ping2 extends Thread { + + // Maximální počet paralelně běžících pingů + private static final int MAX_COUNT = 1000; + // Čekání před dalším opakováním pingu (ms) + private static final int WAITING = 1000; + + private static final ExecutorService executor = Executors.newFixedThreadPool(MAX_COUNT); + private static final List hosts = new CopyOnWriteArrayList<>(); // Dynamický seznam hostů + + public Ping2() { + + } + + @Override + public void start() { + LogFile.printInfo("Ping start ..."); + startPingLoop(); + } + + // Metoda pro spuštění opakovaného pingování + private static void startPingLoop() { + while (true) { + + Iterator itMapObject = Server.mapObject.iterator(); + while (itMapObject.hasNext()) { + MapObject obj = itMapObject.next(); + if (obj.isActive()) { + executor.submit(() -> pingHost(obj)); + } + } + + try { + Thread.sleep(WAITING); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + } + + // Metoda pro provedení jednoho pingu na host + private static void pingHost(MapObject obj) { + try { + IcmpPingRequest request = IcmpPingUtil.createIcmpPingRequest(); + request.setHost(obj.getIp()); + // Nastavení timeoutu na 3000 ms (3 sekundy) + request.setTimeout(3000); + + // Odeslání pingu a zpracování odpovědi + IcmpPingResponse response = IcmpPingUtil.executePingRequest(request); + if (response.getSuccessFlag()) { + //System.out.println("Ping na " + obj.getIp() + " úspěšný. Latence: " + response.getDuration() + " ms"); + new PingTestResult(obj).test(Status.OK, response.getDuration()); + } else { + System.out.println("Ping na " + obj.getName() + " (obj id: " + obj.getId() + ") selhal. Status: " + response.getErrorMessage()); + new PingTestResult(obj).test(Status.OFFLINE, response.getDuration()); + } + } catch (Exception e) { + LogFile.printErr("Ping error: " + obj.getIp() + ": " + e.getMessage()); + } + } + +} diff --git a/src/jnet/server/probe/PingTestResult.java b/src/jnet/server/probe/PingTestResult.java new file mode 100644 index 0000000..cc2bef5 --- /dev/null +++ b/src/jnet/server/probe/PingTestResult.java @@ -0,0 +1,91 @@ +package jnet.server.probe; + +import java.util.ListIterator; +import jnet.lib.Message; +import jnet.lib.Status; +import jnet.lib.object.Event; +import jnet.lib.object.MapObject; +import jnet.server.Database; +import jnet.server.Server; +import jnet.server.ServerMessageParser; + +public class PingTestResult { + + private static MapObject obj; + private static ListIterator it_event = Server.events.listIterator(); + + public PingTestResult(MapObject obj) { + this.obj = obj; + } + + public static void test(int state, long latency) { + + // oveří jestli neni zarizeni vypnuto + if (obj.isActive()) { + + // oveří zda je stav rozdilny od predchozího + if (obj.getStatus() != state) { + + switch (state) { + case Status.OK: + obj.setPingAttemp(0); + + if (obj.getStatus() == Status.OFFLINE) { + // pokud je predchozi stav offline ukonci event +// Event event = Database.endEvent(obj.getId(), Event.TYPE_PING); +// if (event != null) { +// // odesle event klientum +// ServerMessageParser.sendAll(new Message(Message.EVENT_UPDATE, event)); +// // aktualizuje v seznamu +// while (it_event.hasNext()) { +// Event e = it_event.next(); +// if (e.getId() == event.getId()) { +// it_event.set(e); +// break; +// } +// } +// } + } + // zmena stavu v seznamu + System.out.println("online obj id: " + obj.getId()); + changeStateOnObject(state); + // odesle informaci o novem stavu klientum + int[] o = {obj.getId(), state}; + ServerMessageParser.sendAll(new Message(Message.STATUS_UPDATE, o)); + break; + case Status.OFFLINE: + if (obj.getPingAttemp() >= Server.config.getInt("ping_attempt")) { + // pridáni eventu + Event event = Database.addEvent(obj.getId(), "Offline", Event.TYPE_PING); + it_event.add(event); + // Odeslani eventu klientum + ServerMessageParser.sendAll(new Message(Message.EVENT_NEW, event)); + // zmena stavu v seznamu + System.err.println("offline obj id: " + obj.getId()); + changeStateOnObject(state); + // odesle informaci o novem stavu klientum + int[] oo = {obj.getId(), state}; + ServerMessageParser.sendAll(new Message(Message.STATUS_UPDATE, oo)); + } else { + obj.pingAttemp++; + System.out.println("offline obj id: " + obj.getId() + " pokus: " + obj.pingAttemp); + } + + break; + default: + System.err.println("default -> " + state); + throw new AssertionError(); + } + + } + } + + } + + private static synchronized void changeStateOnObject(int state) { + System.out.println("Change status " + obj.getId() + " -> " + state); + // upravi stav v listu + obj.setStatus(state); + } + +}