commit 3230b722fb2b58d2e7b13500716ed53f8f30363a Author: Sandro Leuchter Date: Tue Mar 18 07:08:10 2025 +0100 initial diff --git a/02-udp/justfile b/02-udp/justfile new file mode 100644 index 0000000..b7e9b7b --- /dev/null +++ b/02-udp/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +zed: + $VISUAL udp.echo udp.echo_solution udp.time udp.time_solution udp.messwerte udp.messwerte_solution udp.game_solution diff --git a/02-udp/pom.xml b/02-udp/pom.xml new file mode 100644 index 0000000..0862258 --- /dev/null +++ b/02-udp/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + udp + 1.0-SNAPSHOT + pom + + + vs + parent + 1.0-SNAPSHOT + + + diff --git a/02-udp/udp.code-workspace b/02-udp/udp.code-workspace new file mode 100644 index 0000000..3ef8fbc --- /dev/null +++ b/02-udp/udp.code-workspace @@ -0,0 +1,43 @@ +{ + "folders": [ + { + "name": "1. Echo Service", + "path": "udp.echo", + }, + { + "name": "1. Echo Service (ML)", + "path": "udp.echo_solution", + }, + { + "name": "2. Time Service", + "path": "udp.time", + }, + { + "name": "2. Time Service (ML)", + "path": "udp.time_solution", + }, + { + "name": "3. Messwert Service", + "path": "udp.messwerte", + }, + { + "name": "3. Messwert Service (ML)", + "path": "udp.messwerte_solution", + }, + { + "name": "4. ReactionGame (ML)", + "path": "udp.game_solution", + }, + ], + "extensions": { + "recommendations": [ + "vscjava.vscode-java-pack", + "ms-azuretools.vscode-docker", + "skellock.just", + ], + }, + "settings": { + "java.dependency.syncWithFolderExplorer": true, + "java.project.explorer.showNonJavaResources": false, + }, +} diff --git a/02-udp/udp.echo/justfile b/02-udp/udp.echo/justfile new file mode 100644 index 0000000..785b05d --- /dev/null +++ b/02-udp/udp.echo/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +server: + just exec vs.EchoServer "" +client message: + just exec vs.EchoClient "{{message}}" diff --git a/02-udp/udp.echo/pom.xml b/02-udp/udp.echo/pom.xml new file mode 100644 index 0000000..6a655d6 --- /dev/null +++ b/02-udp/udp.echo/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + udp.echo + 1.0-SNAPSHOT + jar + + + vs + udp + 1.0-SNAPSHOT + + diff --git a/02-udp/udp.echo/src/main/java/vs/EchoClient.java b/02-udp/udp.echo/src/main/java/vs/EchoClient.java new file mode 100644 index 0000000..df54a3b --- /dev/null +++ b/02-udp/udp.echo/src/main/java/vs/EchoClient.java @@ -0,0 +1,33 @@ +package vs; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.SocketTimeoutException; + +public class EchoClient { + private static final String HOST = "localhost"; + private static final int PORT = 4711; + private static final int BUFSIZE = 512; + private static final int TIMEOUT = 2000; + + public static void main(String[] args) { + byte[] data = args[0].getBytes(); + try (DatagramSocket socket = new DatagramSocket()) { + socket.setSoTimeout(TIMEOUT); // Zeit in ms, für wie lange ein read() auf socket blockiert. + // Bei timeout is java.net.SocketTimeoutException (TIMEOUT == 0 + // => blockiert für immer) + InetAddress iaddr = InetAddress.getByName(HOST); + DatagramPacket packetOut = new DatagramPacket(data, data.length, iaddr, PORT); + socket.send(packetOut); + DatagramPacket packetIn = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); + socket.receive(packetOut); + String received = new String(packetIn.getData(), 0, packetIn.getLength()); + System.out.println("Received: " + received); + } catch (SocketTimeoutException e) { + System.err.println("Timeout: " + e.getMessage()); + } catch (Exception e) { + System.err.println(e); + } + } +} diff --git a/02-udp/udp.echo/src/main/java/vs/EchoServer.java b/02-udp/udp.echo/src/main/java/vs/EchoServer.java new file mode 100644 index 0000000..c765d4f --- /dev/null +++ b/02-udp/udp.echo/src/main/java/vs/EchoServer.java @@ -0,0 +1,31 @@ +package vs; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; + +public class EchoServer { + private static final int PORT = 4711; + private static final int BUFSIZE = 512; + + public static void main(final String[] args) { + try (DatagramSocket socket = new DatagramSocket(PORT)) { + DatagramPacket packetIn = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); + DatagramPacket packetOut = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); + + System.out.println("Server gestartet ..."); + + while (true) { + socket.receive(packetIn); + System.out.println( + "Received: " + packetIn.getLength() + " bytes: " + new String(packetIn.getData())); + packetOut.setData(packetIn.getData()); + packetOut.setLength(packetIn.getLength()); + // mehr Eigenschaften von packetOut setzen... + socket.send(packetOut); + } + } catch (IOException e) { + System.err.println(e); + } + } +} diff --git a/02-udp/udp.echo_solution/justfile b/02-udp/udp.echo_solution/justfile new file mode 100644 index 0000000..785b05d --- /dev/null +++ b/02-udp/udp.echo_solution/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +server: + just exec vs.EchoServer "" +client message: + just exec vs.EchoClient "{{message}}" diff --git a/02-udp/udp.echo_solution/pom.xml b/02-udp/udp.echo_solution/pom.xml new file mode 100644 index 0000000..4193942 --- /dev/null +++ b/02-udp/udp.echo_solution/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + udp.echo_solution + 1.0-SNAPSHOT + jar + + + vs + udp + 1.0-SNAPSHOT + + diff --git a/02-udp/udp.echo_solution/src/main/java/vs/EchoClient.java b/02-udp/udp.echo_solution/src/main/java/vs/EchoClient.java new file mode 100644 index 0000000..2261b42 --- /dev/null +++ b/02-udp/udp.echo_solution/src/main/java/vs/EchoClient.java @@ -0,0 +1,58 @@ +package vs; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.SocketTimeoutException; + +/** + * Client for echo var.sockets.udp.echo.EchoServer service. Sendet Kommandozeilenargument an HOST, + * wartet bis TIMEOUT auf Antwort vom Server, liest sie und gibt den Inhalt aus. + * + * @author Sandro Leuchter + * + */ +public class EchoClient { + /** + * host on which server is running (IP-address or hostname) + */ + private static final String HOST = "localhost"; + /** + * port on which service is running on host + */ + private static final int PORT = 4711; + /** + * maximum size of payload in datagram + */ + private static final int BUFSIZE = 512; + /** + * timeout in ms for waiting for a response from server + */ + private static final int TIMEOUT = 2000; + + /** + * main method: entrypoint to run + * + * @param args + * must be String[1]: message to be send to server + */ + public static void main(String[] args) { + byte[] data = args[0].getBytes(); + try (DatagramSocket socket = new DatagramSocket()) { + socket.setSoTimeout(TIMEOUT); // Zeit in ms, für wie lange ein read() auf socket blockiert. + // Bei timeout is java.net.SocketTimeoutException (TIMEOUT == 0 + // => blockiert für immer) + InetAddress iaddr = InetAddress.getByName(HOST); + DatagramPacket packetOut = new DatagramPacket(data, data.length, iaddr, PORT); + socket.send(packetOut); + DatagramPacket packetIn = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); + socket.receive(packetIn); + String received = new String(packetIn.getData(), 0, packetIn.getLength()); + System.out.println("Received: " + received); + } catch (SocketTimeoutException e) { + System.err.println("Timeout: " + e.getMessage()); + } catch (Exception e) { + System.err.println(e); + } + } +} diff --git a/02-udp/udp.echo_solution/src/main/java/vs/EchoServer.java b/02-udp/udp.echo_solution/src/main/java/vs/EchoServer.java new file mode 100644 index 0000000..e9742f9 --- /dev/null +++ b/02-udp/udp.echo_solution/src/main/java/vs/EchoServer.java @@ -0,0 +1,50 @@ +package vs; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; + +/** + * Server for var.sockets.udp.echo.EchoServer service. Empfängt ANfrage von Clients und sendet den + * Inhalt jeweils an den Client zurück + * + * @author Sandro Leuchter + * + */ +public class EchoServer { + /** + * port on which service is running on host + */ + private static final int PORT = 4711; + /** + * maximum size of payload in datagram + */ + private static final int BUFSIZE = 512; + + /** + * main method: entrypoint to run + * + * @param args + * ignored + */ + public static void main(final String[] args) { + try (DatagramSocket socket = new DatagramSocket(PORT)) { + DatagramPacket packetIn = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); + DatagramPacket packetOut = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); + + System.out.println("Server gestartet ..."); + + while (true) { + socket.receive(packetIn); + System.out.println("Received: " + packetIn.getLength() + " bytes: " + + new String(packetIn.getData(), 0, packetIn.getLength())); + packetOut.setData(packetIn.getData()); + packetOut.setLength(packetIn.getLength()); + packetOut.setSocketAddress(packetIn.getSocketAddress()); + socket.send(packetOut); + } + } catch (IOException e) { + System.err.println(e); + } + } +} diff --git a/02-udp/udp.game_solution/justfile b/02-udp/udp.game_solution/justfile new file mode 100644 index 0000000..bbb9452 --- /dev/null +++ b/02-udp/udp.game_solution/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +server: + just exec vs.ReactionGameServer "" +client: + just exec vs.ReactionGameClient "" diff --git a/02-udp/udp.game_solution/pom.xml b/02-udp/udp.game_solution/pom.xml new file mode 100644 index 0000000..fb0df6b --- /dev/null +++ b/02-udp/udp.game_solution/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + udp.game_solution + 1.0-SNAPSHOT + jar + + + vs + udp + 1.0-SNAPSHOT + + diff --git a/02-udp/udp.game_solution/src/main/java/vs/ReactionGameClient.java b/02-udp/udp.game_solution/src/main/java/vs/ReactionGameClient.java new file mode 100644 index 0000000..82b3bec --- /dev/null +++ b/02-udp/udp.game_solution/src/main/java/vs/ReactionGameClient.java @@ -0,0 +1,42 @@ +package vs; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +/** + * Client for echo var.sockets.udp.game.ReactionGameServer service. Sendet leerees Paket an HOST. + * + * @author Sandro Leuchter + * + */ +public class ReactionGameClient { + /** + * host on which server is running (IP-address or hostname) + */ + private static final String HOST = "localhost"; + /** + * port on which service is running on host + */ + private static final int PORT = 4714; + /** + * maximum size of payload in datagram + */ + private static final int BUFSIZE = 0; + + /** + * main method: entrypoint to run + * + * @param args + * ignored + */ + public static void main(String[] args) { + try (DatagramSocket socket = new DatagramSocket()) { + InetAddress iaddr = InetAddress.getByName(HOST); + DatagramPacket packetOut = new DatagramPacket(new byte[BUFSIZE], BUFSIZE, iaddr, PORT); + socket.send(packetOut); + } catch (Exception e) { + System.err.println(e); + } + } +} diff --git a/02-udp/udp.game_solution/src/main/java/vs/ReactionGameServer.java b/02-udp/udp.game_solution/src/main/java/vs/ReactionGameServer.java new file mode 100644 index 0000000..d3c4109 --- /dev/null +++ b/02-udp/udp.game_solution/src/main/java/vs/ReactionGameServer.java @@ -0,0 +1,63 @@ +package vs; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.SocketTimeoutException; +import java.util.Random; + +/** + * Server for var.sockets.udp.game.ReactionGameServer service. Waits a random time less than + * MAX_WAITING_TIME_MS ms, then opens Gate for GATE_OPEN_DURATION_MS ms on port PORT, waiting for a + * UDP packet to receive. + * + * @author Sandro Leuchter + * + */ +public class ReactionGameServer { + /** + * port on which service is running on host + */ + private static final int PORT = 4714; + private static final int GATE_OPEN_DURATION_MS = 2000; + private static final int MAX_WAITING_TIME_MS = 4000; + private static final Random random = new Random(System.currentTimeMillis()); + /** + * maximum size of payload in datagram + */ + private static final int BUFSIZE = 512; + + /** + * main method: entrypoint to run + * + * @param args + * ignored + * @throws InterruptedException + * if interrupt during random sleeping period + */ + public static void main(final String[] args) throws InterruptedException { + try (DatagramSocket socket = new DatagramSocket(PORT)) { + socket.setSoTimeout(GATE_OPEN_DURATION_MS); + DatagramPacket packetIn = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); + + System.out.println("Server gestartet ..."); + + Thread.sleep(random.nextInt(MAX_WAITING_TIME_MS)); + boolean timeout = false; + System.out.println("offen für Empfang"); + try { + socket.receive(packetIn); + } catch (SocketTimeoutException e) { + timeout = true; + } + System.out.println("Empfang geschlossen"); + if (timeout) { + System.out.println("nicht schnell genug!"); + } else { + System.out.println("Paket hat es geschafft"); + } + } catch (IOException e) { + System.err.println(e); + } + } +} diff --git a/02-udp/udp.messwerte/justfile b/02-udp/udp.messwerte/justfile new file mode 100644 index 0000000..1e8ebeb --- /dev/null +++ b/02-udp/udp.messwerte/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +server: + just exec vs.MesswertServer "" +client: + just exec vs.MesswertClient "" diff --git a/02-udp/udp.messwerte/pom.xml b/02-udp/udp.messwerte/pom.xml new file mode 100644 index 0000000..39b2a87 --- /dev/null +++ b/02-udp/udp.messwerte/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + udp.messwerte + 1.0-SNAPSHOT + jar + + + vs + udp + 1.0-SNAPSHOT + + diff --git a/02-udp/udp.messwerte/src/main/java/vs/MesswertClient.java b/02-udp/udp.messwerte/src/main/java/vs/MesswertClient.java new file mode 100644 index 0000000..d4501b3 --- /dev/null +++ b/02-udp/udp.messwerte/src/main/java/vs/MesswertClient.java @@ -0,0 +1,22 @@ +package vs; + +import java.util.Date; +import java.util.Random; + +public class MesswertClient { + + public static void main(String[] args) { + Random rg = new Random(); + try { + // ... + while (true) { + String jetzt = (new Date()).toString(); + String messung = Double.toString(rg.nextDouble() * 100.0); + // ... + Thread.sleep(5000); + } + } catch (Exception e) { + System.err.println(e); + } + } +} diff --git a/02-udp/udp.messwerte/src/main/java/vs/MesswertServer.java b/02-udp/udp.messwerte/src/main/java/vs/MesswertServer.java new file mode 100644 index 0000000..5fc9e36 --- /dev/null +++ b/02-udp/udp.messwerte/src/main/java/vs/MesswertServer.java @@ -0,0 +1,8 @@ +package vs; + +public class MesswertServer { + + public static void main(String[] args) { + // TODO Auto-generated method stub + } +} diff --git a/02-udp/udp.messwerte_solution/justfile b/02-udp/udp.messwerte_solution/justfile new file mode 100644 index 0000000..1e8ebeb --- /dev/null +++ b/02-udp/udp.messwerte_solution/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +server: + just exec vs.MesswertServer "" +client: + just exec vs.MesswertClient "" diff --git a/02-udp/udp.messwerte_solution/pom.xml b/02-udp/udp.messwerte_solution/pom.xml new file mode 100644 index 0000000..b8d43ad --- /dev/null +++ b/02-udp/udp.messwerte_solution/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + udp.messwerte_solution + 1.0-SNAPSHOT + jar + + + vs + udp + 1.0-SNAPSHOT + + diff --git a/02-udp/udp.messwerte_solution/src/main/java/vs/MesswertClient.java b/02-udp/udp.messwerte_solution/src/main/java/vs/MesswertClient.java new file mode 100644 index 0000000..2c54927 --- /dev/null +++ b/02-udp/udp.messwerte_solution/src/main/java/vs/MesswertClient.java @@ -0,0 +1,56 @@ +package vs; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.SocketTimeoutException; +import java.util.Random; + +/** + * Client for var.sockets.udp.messwerte.MesswertServer service. Sendet fortwährend Messwerte + * + * @author Sandro Leuchter + * + */ +public class MesswertClient { + /** + * host on which server is running (IP-address or hostname) + */ + private static final String HOST = "localhost"; + /** + * port on which service is running on host + */ + private static final int PORT = 4713; + /** + * timeout in ms for waiting for a response from server + */ + private static final int TIMEOUT = 2000; + + /** + * main method: entrypoint to run + * + * @param args + * ignored + */ + public static void main(String[] args) { + Random randomGenerator = new Random(); + try (DatagramSocket socket = new DatagramSocket()) { + socket.setSoTimeout(TIMEOUT); // Zeit in ms, für wie lange ein read() auf socket blockiert. + // Bei timeout is java.net.SocketTimeoutException (TIMEOUT == 0 + // => blockiert für immer) + InetAddress iaddr = InetAddress.getByName(HOST); + while (true) { + String messung = Double.toString(randomGenerator.nextDouble() * 100.0); + DatagramPacket packetOut = new DatagramPacket(messung.getBytes(), messung.length(), iaddr, + PORT); + socket.send(packetOut); + Thread.sleep(5000); + } + } catch (SocketTimeoutException e) { + System.err.println("Timeout: " + e.getMessage()); + } catch (Exception e) { + System.err.println(e); + } + } + +} diff --git a/02-udp/udp.messwerte_solution/src/main/java/vs/MesswertServer.java b/02-udp/udp.messwerte_solution/src/main/java/vs/MesswertServer.java new file mode 100644 index 0000000..40e0b8b --- /dev/null +++ b/02-udp/udp.messwerte_solution/src/main/java/vs/MesswertServer.java @@ -0,0 +1,47 @@ +package vs; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.util.Date; + +/** + * Server for var.sockets.udp.messwerte.MesswertServer service. Empfängt Messwerte von Clients und + * gibt sie aus. + * + * @author Sandro Leuchter + * + */ +public class MesswertServer { + /** + * port on which service is running on host + */ + private static final int PORT = 4713; + /** + * maximum size of payload in datagram + */ + private static final int BUFSIZE = 512; + + /** + * main method: entrypoint to run + * + * @param args + * ignored + */ + public static void main(final String[] args) { + try (DatagramSocket socket = new DatagramSocket(PORT)) { + DatagramPacket packetIn = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); + + System.out.println("Server gestartet ..."); + + while (true) { + socket.receive(packetIn); + String jetzt = (new Date()).toString(); + System.out.println(packetIn.getAddress().getHostAddress() + ":" + packetIn.getPort() + " " + + jetzt + " " + new String(packetIn.getData())); + } + } catch (IOException e) { + System.err.println(e); + } + } +} diff --git a/02-udp/udp.time/justfile b/02-udp/udp.time/justfile new file mode 100644 index 0000000..7fedffd --- /dev/null +++ b/02-udp/udp.time/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +server: + just exec vs.TimeServer "" +client: + just exec vs.TimeClient "" diff --git a/02-udp/udp.time/pom.xml b/02-udp/udp.time/pom.xml new file mode 100644 index 0000000..086d35b --- /dev/null +++ b/02-udp/udp.time/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + udp.time + 1.0-SNAPSHOT + jar + + + vs + udp + 1.0-SNAPSHOT + + diff --git a/02-udp/udp.time/src/main/java/vs/TimeClient.java b/02-udp/udp.time/src/main/java/vs/TimeClient.java new file mode 100644 index 0000000..49a9aff --- /dev/null +++ b/02-udp/udp.time/src/main/java/vs/TimeClient.java @@ -0,0 +1,8 @@ +package vs; + +public class TimeClient { + + public static void main(String[] args) { + // TODO Auto-generated method stub + } +} diff --git a/02-udp/udp.time/src/main/java/vs/TimeServer.java b/02-udp/udp.time/src/main/java/vs/TimeServer.java new file mode 100644 index 0000000..0d419f8 --- /dev/null +++ b/02-udp/udp.time/src/main/java/vs/TimeServer.java @@ -0,0 +1,8 @@ +package vs; + +public class TimeServer { + + public static void main(String[] args) { + // TODO Auto-generated method stub + } +} diff --git a/02-udp/udp.time_solution/justfile b/02-udp/udp.time_solution/justfile new file mode 100644 index 0000000..7fedffd --- /dev/null +++ b/02-udp/udp.time_solution/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +server: + just exec vs.TimeServer "" +client: + just exec vs.TimeClient "" diff --git a/02-udp/udp.time_solution/pom.xml b/02-udp/udp.time_solution/pom.xml new file mode 100644 index 0000000..a6d2c80 --- /dev/null +++ b/02-udp/udp.time_solution/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + udp.time_solution + 1.0-SNAPSHOT + jar + + + vs + udp + 1.0-SNAPSHOT + + diff --git a/02-udp/udp.time_solution/src/main/java/vs/TimeClient.java b/02-udp/udp.time_solution/src/main/java/vs/TimeClient.java new file mode 100644 index 0000000..159a46a --- /dev/null +++ b/02-udp/udp.time_solution/src/main/java/vs/TimeClient.java @@ -0,0 +1,57 @@ +package vs; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.SocketTimeoutException; + +/** + * Client for echo var.sockets.udp.time.TimeServer service. Sendet leeres Paket an Server, wartet + * bis TIMEOUT aus Antwort vom Server, liest die Antwort und gibt sie aus + * + * @author Sandro Leuchter + * + */ +public class TimeClient { + /** + * host on which server is running (IP-address or hostname) + */ + private static final String HOST = "localhost"; + /** + * port on which service is running on host + */ + private static final int PORT = 4712; + /** + * maximum size of payload in datagram + */ + private static final int BUFSIZE = 512; + /** + * timeout in ms for waiting for a response from server + */ + private static final int TIMEOUT = 2000; + + /** + * main method: entrypoint to run + * + * @param args + * ignored + */ + public static void main(String[] args) { + try (DatagramSocket socket = new DatagramSocket()) { + socket.setSoTimeout(TIMEOUT); // Zeit in ms, für wie lange ein read() auf socket blockiert. + // Bei timeout is java.net.SocketTimeoutException (TIMEOUT == 0 + // => blockiert für immer) + InetAddress iaddr = InetAddress.getByName(HOST); + DatagramPacket packetOut = new DatagramPacket(new byte[0], 0, iaddr, PORT); + socket.send(packetOut); + DatagramPacket packetIn = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); + socket.receive(packetIn); + String received = new String(packetIn.getData(), 0, packetIn.getLength()); + System.out.println("Received: " + received); + } catch (SocketTimeoutException e) { + System.err.println("Timeout: " + e.getMessage()); + } catch (Exception e) { + System.err.println(e); + } + } +} diff --git a/02-udp/udp.time_solution/src/main/java/vs/TimeServer.java b/02-udp/udp.time_solution/src/main/java/vs/TimeServer.java new file mode 100644 index 0000000..1740631 --- /dev/null +++ b/02-udp/udp.time_solution/src/main/java/vs/TimeServer.java @@ -0,0 +1,53 @@ +package vs; + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.util.Date; + +/** + * Server for echo var.sockets.udp.time.TimeServer service. Empfängt Datagramm von Client, liest + * Absenderinformationen daraus und sendet Zeitinformation zurück. + * + * @author Sandro Leuchter + * + */ +public class TimeServer { + /** + * port on which service is running on host + */ + private static final int PORT = 4712; + /** + * maximum size of payload in datagram + */ + private static final int BUFSIZE = 512; + + /** + * main method: entrypoint to run + * + * @param args + * ignored + */ + public static void main(String[] args) { + try (DatagramSocket socket = new DatagramSocket(PORT)) { + DatagramPacket packetIn = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); + DatagramPacket packetOut = new DatagramPacket(new byte[BUFSIZE], BUFSIZE); + + System.out.println("Server gestartet ..."); + + while (true) { + socket.receive(packetIn); + System.out.println( + "Received from: " + packetIn.getAddress().getHostAddress() + ":" + packetIn.getPort()); + String jetzt = (new Date()).toString(); + packetOut.setData(jetzt.getBytes()); + packetOut.setLength(jetzt.length()); + packetOut.setSocketAddress(packetIn.getSocketAddress()); + socket.send(packetOut); + } + } catch (final IOException e) { + System.err.println(e); + } + } + +} diff --git a/03-tcp/justfile b/03-tcp/justfile new file mode 100644 index 0000000..ad5bd2f --- /dev/null +++ b/03-tcp/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +zed: + $VISUAL tcp.echo tcp.echo_solution tcp.filer tcp.filer_solution tcp.time tcp.time_solution diff --git a/03-tcp/pom.xml b/03-tcp/pom.xml new file mode 100644 index 0000000..bc444a2 --- /dev/null +++ b/03-tcp/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + tcp + 1.0-SNAPSHOT + pom + + + vs + parent + 1.0-SNAPSHOT + + + diff --git a/03-tcp/tcp.code-workspace b/03-tcp/tcp.code-workspace new file mode 100644 index 0000000..a4d330c --- /dev/null +++ b/03-tcp/tcp.code-workspace @@ -0,0 +1,39 @@ +{ + "folders": [ + { + "name": "1. Echo Service", + "path": "tcp.echo", + }, + { + "name": "1. Echo Service (ML)", + "path": "tcp.echo_solution", + }, + { + "name": "2. File Service", + "path": "tcp.filer", + }, + { + "name": "2. File Service (ML)", + "path": "tcp.filer_solution", + }, + { + "name": "3. Time Service", + "path": "tcp.time", + }, + { + "name": "3. Time Service (ML)", + "path": "tcp.time_solution", + }, + ], + "extensions": { + "recommendations": [ + "vscjava.vscode-java-pack", + "ms-azuretools.vscode-docker", + "skellock.just", + ], + }, + "settings": { + "java.dependency.syncWithFolderExplorer": true, + "java.project.explorer.showNonJavaResources": false, + }, +} diff --git a/03-tcp/tcp.echo/justfile b/03-tcp/tcp.echo/justfile new file mode 100644 index 0000000..6284451 --- /dev/null +++ b/03-tcp/tcp.echo/justfile @@ -0,0 +1,11 @@ +import '../justfile' + +port := "4747" + +server-iterativ backlog_size: + just exec vs.EchoServerIterativ "{{port}} {{backlog_size}}" +server-threaded: + just exec vs.EchoServerThreaded {{port}} +client host: + just exec vs.EchoClient "{{host}} {{port}}" + diff --git a/03-tcp/tcp.echo/pom.xml b/03-tcp/tcp.echo/pom.xml new file mode 100644 index 0000000..decc71a --- /dev/null +++ b/03-tcp/tcp.echo/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + tcp.echo + 1.0-SNAPSHOT + jar + + + vs + tcp + 1.0-SNAPSHOT + + diff --git a/03-tcp/tcp.echo/src/main/java/vs/EchoClient.java b/03-tcp/tcp.echo/src/main/java/vs/EchoClient.java new file mode 100644 index 0000000..690c196 --- /dev/null +++ b/03-tcp/tcp.echo/src/main/java/vs/EchoClient.java @@ -0,0 +1,37 @@ +package vs; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.Socket; + +public class EchoClient { + public static void main(String[] args) { + String host = args[0]; + int port = Integer.parseInt(args[1]); + + try (Socket socket = new Socket(host, port); + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + PrintWriter out = new PrintWriter(socket.getOutputStream(), true); + BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in))) { + + // Begrüßung vom Server empfangen und auf Konsole ausgeben + String msg = in.readLine(); + System.out.println(msg); + + // Zeile von Konsole einlesen, an Server senden und Antwort von + // Server auf Konsole ausgeben, bis eingegebene Zeile == "q" + while (true) { + System.out.print(">> "); + String line = stdin.readLine(); + if ("q".equals(line)) { + break; + } + out.println(line); + System.out.println(in.readLine()); + } + } catch (Exception e) { + System.err.println(e); + } + } +} diff --git a/03-tcp/tcp.echo/src/main/java/vs/EchoServerIterativ.java b/03-tcp/tcp.echo/src/main/java/vs/EchoServerIterativ.java new file mode 100644 index 0000000..7e60198 --- /dev/null +++ b/03-tcp/tcp.echo/src/main/java/vs/EchoServerIterativ.java @@ -0,0 +1,60 @@ +package vs; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; + +public class EchoServerIterativ { + private int port; + private int backlog; + + public EchoServerIterativ(int port, int backlog) { + this.port = port; + this.backlog = backlog; + } + + public void start() { + try (ServerSocket serverSocket = new ServerSocket(port, backlog)) { + System.out.println("EchoServer (iterativ) auf " + serverSocket.getLocalSocketAddress() + " gestartet ..."); + while (true) { + handleClient(serverSocket); + } + } catch (IOException e) { + System.err.println(e); + } + } + + private void handleClient(ServerSocket server) { + SocketAddress socketAddress = null; + try (Socket socket = server.accept(); + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { + socketAddress = socket.getRemoteSocketAddress(); + System.out.println("Verbindung zu " + socketAddress + " aufgebaut"); + out.println("Server ist bereit ..."); + String input; + while ((input = in.readLine()) != null) { + System.out.println(socketAddress + ">> [" + input + "]"); + out.println("echo: " + input); + } + } catch (IOException e) { + System.err.println(e); + } finally { + System.out.println("Verbindung zu " + socketAddress + " abgebaut"); + } + } + + public static void main(String[] args) { + int port = Integer.parseInt(args[0]); + int backlog = 50; + if (args.length == 2) { + backlog = Integer.parseInt(args[1]); + } + + new EchoServerIterativ(port, backlog).start(); + } +} diff --git a/03-tcp/tcp.echo/src/main/java/vs/EchoServerThreaded.java b/03-tcp/tcp.echo/src/main/java/vs/EchoServerThreaded.java new file mode 100644 index 0000000..cb585c6 --- /dev/null +++ b/03-tcp/tcp.echo/src/main/java/vs/EchoServerThreaded.java @@ -0,0 +1,41 @@ +package vs; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; + +public class EchoServerThreaded { + private int port; + + public EchoServerThreaded(int port) { + this.port = port; + } + + public void start() { + try (ServerSocket serverSocket = new ServerSocket(port)) { + System.out.println("EchoServer (threaded) auf " + serverSocket.getLocalSocketAddress() + " gestartet ..."); + // hier müssen Verbindungswünsche von Clients in einem neuen Thread + // angenommen werden + } catch (IOException e) { + System.err.println(e); + } + } + + private class EchoThread extends Thread { + private Socket socket; + + public EchoThread(Socket socket) { + this.socket = socket; + } + + public void run() { + // hier muss die Verbindung mit dem Client über this.socket + // abgearbeitet werden + } + } + + public static void main(String[] args) { + int port = Integer.parseInt(args[0]); + new EchoServerThreaded(port).start(); + } +} diff --git a/03-tcp/tcp.echo_solution/justfile b/03-tcp/tcp.echo_solution/justfile new file mode 100644 index 0000000..6255554 --- /dev/null +++ b/03-tcp/tcp.echo_solution/justfile @@ -0,0 +1,13 @@ +import '../justfile' + +port := "4747" + +server-iterativ backlog_size: + just exec vs.EchoServerIterativ "{{port}} {{backlog_size}}" +server-threaded: + just exec vs.EchoServerThreaded {{port}} +server-pool: + just exec vs.EchoServerThreadPool {{port}} +client host: + just exec vs.EchoClient "{{host}} {{port}}" + diff --git a/03-tcp/tcp.echo_solution/pom.xml b/03-tcp/tcp.echo_solution/pom.xml new file mode 100644 index 0000000..133a856 --- /dev/null +++ b/03-tcp/tcp.echo_solution/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + tcp.echo_solution + 1.0-SNAPSHOT + jar + + + vs + tcp + 1.0-SNAPSHOT + + diff --git a/03-tcp/tcp.echo_solution/src/main/java/vs/EchoClient.java b/03-tcp/tcp.echo_solution/src/main/java/vs/EchoClient.java new file mode 100644 index 0000000..b7f69b2 --- /dev/null +++ b/03-tcp/tcp.echo_solution/src/main/java/vs/EchoClient.java @@ -0,0 +1,53 @@ +package vs; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.Socket; + +/** + * Client for echo var.sockets.tcp.echo.EchoServer* service. Liest zeilenweise + * von der Console und sendet zum Server. Der Server sendet eine Zeichenkette + * zurück, die auf der Konsole ausgegeben wird. + * + * @author Sandro Leuchter + * + */ +public class EchoClient { + + /** + * main method: entrypoint to run + * + * @param args address of service to connect to (must be String[0]: host + * (IP-address or DNS hostname), String[1]: port) + * + */ + public static void main(String[] args) { + String host = args[0]; + int port = Integer.parseInt(args[1]); + + try (Socket socket = new Socket(host, port); + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + PrintWriter out = new PrintWriter(socket.getOutputStream(), true); + BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in))) { + + // Begrüßung vom Server empfangen und auf Konsole ausgeben + String msg = in.readLine(); + System.out.println(msg); + + // Zeile von Konsole einlesen, an Server senden und Antwort von + // Server auf Konsole ausgeben, bis eingegebene Zeile == "q" + while (true) { + System.out.print(">> "); + String line = stdin.readLine(); + if ("q".equals(line)) { + break; + } + out.println(line); + System.out.println(in.readLine()); + } + } catch (Exception e) { + System.err.println(e); + } + } +} diff --git a/03-tcp/tcp.echo_solution/src/main/java/vs/EchoServerIterativ.java b/03-tcp/tcp.echo_solution/src/main/java/vs/EchoServerIterativ.java new file mode 100644 index 0000000..a422816 --- /dev/null +++ b/03-tcp/tcp.echo_solution/src/main/java/vs/EchoServerIterativ.java @@ -0,0 +1,98 @@ +package vs; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; + +/** + * iterative server for var.sockets.tcp.echo Echo service. waits for the next + * client to connect, sends greeting message to client, reads line by line from + * client and sends it back adding "echo: " in front of each line until + * connection is closed by client. + * + * @author Sandro Leuchter + * + */ +public class EchoServerIterativ { + /** + * port on which this service is currently listening on localhost + */ + private final int port; + /** + * current maximum length of the queue of incoming connections. + */ + private final int backlog; + + /** + * the only constructor for this class + * + * @param port port on which this service will be listening on localhost + * @param backlog requested maximum length of the queue of incoming connections. + */ + public EchoServerIterativ(int port, int backlog) { + this.port = port; + this.backlog = backlog; + } + + /** + * creates server socket on localhost:port, infinitely handles connections to + * clients one after another + */ + public void start() { + try (ServerSocket serverSocket = new ServerSocket(this.port, this.backlog)) { + System.out.println("EchoServer (iterativ) auf " + serverSocket.getLocalSocketAddress() + " gestartet ..."); + while (true) { + handleClient(serverSocket); + } + } catch (IOException e) { + System.err.println(e); + } + } + + /** + * waits for the next client to connect to server, sends greeting message to + * client, reads line by line from client and sends it back adding "echo: " in + * front of each line until connection is closed by client. + * + * @param server "welcome socket" on which server is listening for clients + */ + private void handleClient(ServerSocket server) { + SocketAddress socketAddress = null; + try (Socket socket = server.accept(); + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { + socketAddress = socket.getRemoteSocketAddress(); + System.out.println("Verbindung zu " + socketAddress + " aufgebaut"); + out.println("Server ist bereit ..."); + String input; + while ((input = in.readLine()) != null) { + System.out.println(socketAddress + ">> [" + input + "]"); + out.println("echo: " + input); + } + } catch (IOException e) { + System.err.println(e); + } finally { + System.out.println("Verbindung zu " + socketAddress + " abgebaut"); + } + } + + /** + * main method: entrypoint to run service + * + * @param args args[0] must be the port number of the server (int); rest of args + * is ignored + */ + public static void main(String[] args) { + int port = Integer.parseInt(args[0]); + int backlog = 50; + if (args.length == 2) { + backlog = Integer.parseInt(args[1]); + } + + new EchoServerIterativ(port, backlog).start(); + } +} diff --git a/03-tcp/tcp.echo_solution/src/main/java/vs/EchoServerThreadPool.java b/03-tcp/tcp.echo_solution/src/main/java/vs/EchoServerThreadPool.java new file mode 100644 index 0000000..062f9d2 --- /dev/null +++ b/03-tcp/tcp.echo_solution/src/main/java/vs/EchoServerThreadPool.java @@ -0,0 +1,115 @@ +package vs; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +/** + * threaded server for var.sockets.tcp.echo Echo service. waits for the next + * client to connect, creates thread and handles connection in concurrently: + * sends greeting message to client, reads line by line from client and sends it + * back adding "echo: " in front of each line until connection is closed by + * client. + * + * @author Sandro Leuchter + * + */ +public class EchoServerThreadPool { + /** + * port on which this service is currently listening on localhost + */ + private final int port; + /** + * thread pool of this server + */ + private final Executor threadPool; + + /** + * the only constructor for this class + * + * @param port port on which this service will be listening on localhost + */ + public EchoServerThreadPool(int port) { + this.port = port; + // threadPool = Executors.newSingleThreadExecutor(); + // threadPool = Executors.newCachedThreadPool(); + this.threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); + } + + /** + * creates server socket on localhost:port, infinitely handles connections to + * clients concurrently + */ + public void start() { + try (ServerSocket serverSocket = new ServerSocket(this.port)) { + System.out.println("EchoServer (threaded) auf " + serverSocket.getLocalSocketAddress() + " gestartet ..."); + while (true) { + Socket socket = serverSocket.accept(); + this.threadPool.execute(new EchoThread(socket)); + } + } catch (IOException e) { + System.err.println(e); + } + } + + /** + * Each connection is handled with an instance of this class. + */ + private class EchoThread implements Runnable { + /** + * TCP connection to client + */ + private final Socket socket; + + /** + * the only constructor for this class + * + * @param socket the individual socket that the server created on accepting a + * client that this EchoThread instance will be communicating with + */ + public EchoThread(Socket socket) { + this.socket = socket; + } + + /** + * defines the behavior of this Thread instance, will be executed concurrently + * if start() is called on instance + * + */ + @Override + public void run() { + SocketAddress socketAddress = this.socket.getRemoteSocketAddress(); + System.out.println("Verbindung zu " + socketAddress + " aufgebaut"); + try (BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); + PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true)) { + out.println("Server ist bereit ..."); + String input; + while ((input = in.readLine()) != null) { + System.out.println(socketAddress + ">> [" + input + "]"); + out.println("echo: " + input); + } + } catch (Exception e) { + System.err.println(e); + } finally { + System.out.println("Verbindung zu " + socketAddress + " abgebaut"); + } + } + } + + /** + * main method: entrypoint to run service + * + * @param args args[0] must be the port number of the server (int); rest of args + * is ignored + */ + public static void main(String[] args) { + int port = Integer.parseInt(args[0]); + new EchoServerThreadPool(port).start(); + } +} diff --git a/03-tcp/tcp.echo_solution/src/main/java/vs/EchoServerThreaded.java b/03-tcp/tcp.echo_solution/src/main/java/vs/EchoServerThreaded.java new file mode 100644 index 0000000..990e234 --- /dev/null +++ b/03-tcp/tcp.echo_solution/src/main/java/vs/EchoServerThreaded.java @@ -0,0 +1,106 @@ +package vs; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; + +/** + * threaded server for var.sockets.tcp.echo Echo service. waits for the next + * client to connect, creates thread and handles connection in concurrently: + * sends greeting message to client, reads line by line from client and sends it + * back adding "echo: " in front of each line until connection is closed by + * client. + * + * @author Sandro Leuchter + * + */ +public class EchoServerThreaded { + /** + * port on which this service is currently listening on localhost + */ + private final int port; + + /** + * the only constructor for this class + * + * @param port port on which this service will be listening on localhost + */ + public EchoServerThreaded(int port) { + this.port = port; + } + + /** + * creates server socket on localhost:port, infinitely handles connections to + * clients concurrently + */ + public void start() { + try (ServerSocket serverSocket = new ServerSocket(this.port)) { + System.out.println("EchoServer (threaded) auf " + serverSocket.getLocalSocketAddress() + " gestartet ..."); + while (true) { + Socket socket = serverSocket.accept(); + new EchoThread(socket).start(); + } + } catch (IOException e) { + System.err.println(e); + } + } + + /** + * Each connection is handled with an instance of this class. + */ + private class EchoThread extends Thread { + /** + * TCP connection to client + */ + private final Socket socket; + + /** + * the only constructor for this class + * + * @param socket the individual socket that the server created on accepting a + * client that this EchoThread instance will be communicating with + */ + public EchoThread(Socket socket) { + this.socket = socket; + } + + /** + * defines the behavior of this Thread instance, will be executed concurrently + * if start() is called on instance + * + */ + @Override + public void run() { + SocketAddress socketAddress = this.socket.getRemoteSocketAddress(); + System.out.println("Verbindung zu " + socketAddress + " aufgebaut"); + try (BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); + PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true)) { + out.println("Server ist bereit ..."); + String input; + while ((input = in.readLine()) != null) { + System.out.println(socketAddress + ">> [" + input + "]"); + out.println("echo: " + input); + } + } catch (Exception e) { + System.err.println(e); + } finally { + System.out.println("Verbindung zu " + socketAddress + " abgebaut"); + } + } + } + + /** + * main method: entrypoint to run service + * + * @param args args[0] must be the port number of the server (int); rest of args + * is ignored + */ + public static void main(String[] args) { + int port = Integer.parseInt(args[0]); + new EchoServerThreaded(port).start(); + } +} diff --git a/03-tcp/tcp.filer/justfile b/03-tcp/tcp.filer/justfile new file mode 100644 index 0000000..d9c06d8 --- /dev/null +++ b/03-tcp/tcp.filer/justfile @@ -0,0 +1,10 @@ +import '../justfile' + +port := "4747" + +server-iterativ backlog_size: + just exec vs.FileServerIterativ "{{port}} {{backlog_size}}" +server-threaded: + just exec vs.FileServerThreaded {{port}} +client host: + just exec vs.FileClient "{{host}} {{port}}" diff --git a/03-tcp/tcp.filer/pom.xml b/03-tcp/tcp.filer/pom.xml new file mode 100644 index 0000000..ce9311f --- /dev/null +++ b/03-tcp/tcp.filer/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + tcp.filer + 1.0-SNAPSHOT + jar + + + vs + tcp + 1.0-SNAPSHOT + + diff --git a/03-tcp/tcp.filer/src/main/java/vs/FileClient.java b/03-tcp/tcp.filer/src/main/java/vs/FileClient.java new file mode 100644 index 0000000..18697e5 --- /dev/null +++ b/03-tcp/tcp.filer/src/main/java/vs/FileClient.java @@ -0,0 +1,22 @@ +package vs; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.Socket; + +public class FileClient { + public static void main(String[] args) { + String host = args[0]; + int port = Integer.parseInt(args[1]); + + try (Socket socket = new Socket(host, port); + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { + String line; + while ((line = in.readLine()) != null) { + System.out.println(line); + } + } catch (Exception e) { + System.err.println(e); + } + } +} diff --git a/03-tcp/tcp.filer/src/main/java/vs/FileServerIterativ.java b/03-tcp/tcp.filer/src/main/java/vs/FileServerIterativ.java new file mode 100644 index 0000000..00f816c --- /dev/null +++ b/03-tcp/tcp.filer/src/main/java/vs/FileServerIterativ.java @@ -0,0 +1,61 @@ +package vs; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; + +public class FileServerIterativ { + private static final String FILE = "target/classes/message.txt"; + private int port; + private int backlog; + + public FileServerIterativ(int port, int backlog) { + this.port = port; + this.backlog = backlog; + } + + public void start() { + try (ServerSocket serverSocket = new ServerSocket(port, backlog)) { + System.out.println("FileServer (iterativ) auf " + serverSocket.getLocalSocketAddress() + " gestartet ..."); + File file = new File(FILE); + if (file.exists()) { + System.out.println("\"" + file.getAbsolutePath() + "\" soll gesendet werden."); + while (true) { + handleClient(serverSocket); + } + } + } catch (IOException e) { + System.err.println(e); + } + } + + private void handleClient(ServerSocket server) { + SocketAddress socketAddress = null; + try (Socket socket = server.accept(); + BufferedReader in = new BufferedReader(new FileReader(FILE)); + PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { + socketAddress = socket.getRemoteSocketAddress(); + System.out.println("Verbindung zu " + socketAddress + " aufgebaut"); + // Inhalt von in zeilenweise an out senden + } catch (IOException e) { + System.err.println(e); + } finally { + System.out.println("Verbindung zu " + socketAddress + " abgebaut"); + } + } + + public static void main(String[] args) { + int port = Integer.parseInt(args[0]); + int backlog = 50; + if (args.length == 2) { + backlog = Integer.parseInt(args[1]); + } + + new FileServerIterativ(port, backlog).start(); + } +} diff --git a/03-tcp/tcp.filer/src/main/java/vs/FileServerThreaded.java b/03-tcp/tcp.filer/src/main/java/vs/FileServerThreaded.java new file mode 100644 index 0000000..e2883e0 --- /dev/null +++ b/03-tcp/tcp.filer/src/main/java/vs/FileServerThreaded.java @@ -0,0 +1,49 @@ +package vs; + +import java.io.File; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; + +public class FileServerThreaded { + private static final String FILE = "target/classes/message.txt"; + private int port; + + public FileServerThreaded(int port) { + this.port = port; + } + + public void start() { + try (ServerSocket serverSocket = new ServerSocket(port)) { + System.out.println("FileServer (threaded) auf " + serverSocket.getLocalSocketAddress() + " gestartet ..."); + File file = new File(FILE); + if (file.exists()) { + System.out.println("\"" + file.getAbsolutePath() + "\" soll gesendet werden."); + while (true) { + // hier müssen Verbindungswünsche von Clients in einem neuen + // Thread angenommen werden + } + } + } catch (IOException e) { + System.err.println(e); + } + } + + private class FileThread extends Thread { + private Socket socket; + + public FileThread(Socket socket) { + this.socket = socket; + } + + public void run() { + // hier muss die Verbindung mit dem Client über this.socket + // abgearbeitet werden + } + } + + public static void main(String[] args) { + int port = Integer.parseInt(args[0]); + new FileServerThreaded(port).start(); + } +} diff --git a/03-tcp/tcp.filer/src/main/resources/message.txt b/03-tcp/tcp.filer/src/main/resources/message.txt new file mode 100644 index 0000000..8f8b45d --- /dev/null +++ b/03-tcp/tcp.filer/src/main/resources/message.txt @@ -0,0 +1,25 @@ +Mannheimer Mittelstandsmesse 2017 +================================= + +Zum zehnten Mal lädt die Hochschule Mannheim zur Mittelstandsmesse (MaMi) ein. 14 Unternehmen, +die sich beim Mannheimer Modell Mittelstands-Stipendien engagieren, präsentierten sich in +der Aula der Hochschule + +Studierende der Hochschule haben am 04.04.2017 von 12.00 – 16.00 Uhr wieder die Gelegenheit, +Kontakte zu mittelständischen Unternehmen der Metropolregion zu knüpfen, Möglichkeiten für +Praktika auszuloten oder mit Personalverantwortlichen über Stellenangebote zu sprechen. Auch +für Lehrende und Forschende ist die Messe eine gute Gelegenheit, mit interessierten Unternehmen +Kooperationen anzubahnen oder zu vertiefen. + +Ziel der Messe ist, die Sichtbarkeit von mittelständischen Unternehmen in der Metropolregion +Rhein-Neckar zu erhöhen und Hochschulabsolventen die Attraktivität einer beruflichen Karriere +insbesondere im Mittelstand deutlich zu machen. Mittelständische Unternehmen prägen die +Wirtschaftsstruktur in Deutschland. 99 Prozent aller Unternehmen werden den mittelständischen +Unternehmen zugerechnet, sie beschäftigen rund 2/3 aller Erwerbstätigen. + +Parallel zur Eröffnung der MaMi wird auch die Förderrunde 2017/18 für die Mannheimer +Mittelstands-Stipendien ausgeschrieben. Durch das seit 2007 etablierte Stipendienmodell, das +in tatkräftiger Kooperation der Hochschule mit mittelständischen Unternehmen und unterstützt +von der Metropolregion Rhein-Neckar ins Leben gerufen wurde, können im Studienjahr 30-40 +Stipendien in Höhe von je 1.000 € vergeben werden. So ist die MaMi auch eine gute Gelegenheit +für Studierende, sich an den Ständen der Unternehmen als potenzielle Stipendiaten zu präsentieren. diff --git a/03-tcp/tcp.filer_solution/justfile b/03-tcp/tcp.filer_solution/justfile new file mode 100644 index 0000000..6ea8821 --- /dev/null +++ b/03-tcp/tcp.filer_solution/justfile @@ -0,0 +1,12 @@ +import '../justfile' + +port := "4747" + +server-iterativ backlog_size: + just exec vs.FileServerIterativ "{{port}} {{backlog_size}}" +server-threaded: + just exec vs.FileServerThreaded {{port}} +server-pool: + just exec vs.FileServerThreadPool {{port}} +client host: + just exec vs.FileClient "{{host}} {{port}}" diff --git a/03-tcp/tcp.filer_solution/pom.xml b/03-tcp/tcp.filer_solution/pom.xml new file mode 100644 index 0000000..a67ee1a --- /dev/null +++ b/03-tcp/tcp.filer_solution/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + tcp.filer_solution + 1.0-SNAPSHOT + jar + + + vs + tcp + 1.0-SNAPSHOT + + diff --git a/03-tcp/tcp.filer_solution/src/main/java/vs/FileClient.java b/03-tcp/tcp.filer_solution/src/main/java/vs/FileClient.java new file mode 100644 index 0000000..c6b18b6 --- /dev/null +++ b/03-tcp/tcp.filer_solution/src/main/java/vs/FileClient.java @@ -0,0 +1,39 @@ +package vs; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.Socket; + +/** + * Client for echo var.sockets.tcp.filer.FileServer* service. Verbindet sich mit + * Server, empfängt dann zeilenweise vom Server und gibt auf der Konsole aus, + * was empfangen wurde. Empfängt und gibt so lange aus, bis der Server die + * Kommunikation beendet und den Socket schließt. + * + * @author Sandro Leuchter + * + */ +public class FileClient { + + /** + * main method: entrypoint to run + * + * @param args address of service to connect to (must be String[0]: host + * (IP-address or DNS hostname), String[1]: port) + * + */ + public static void main(String[] args) { + String host = args[0]; + int port = Integer.parseInt(args[1]); + + try (Socket socket = new Socket(host, port); + BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) { + String line; + while ((line = in.readLine()) != null) { + System.out.println(line); + } + } catch (Exception e) { + System.err.println(e); + } + } +} diff --git a/03-tcp/tcp.filer_solution/src/main/java/vs/FileServerIterativ.java b/03-tcp/tcp.filer_solution/src/main/java/vs/FileServerIterativ.java new file mode 100644 index 0000000..c867759 --- /dev/null +++ b/03-tcp/tcp.filer_solution/src/main/java/vs/FileServerIterativ.java @@ -0,0 +1,109 @@ +package vs; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; + +/** + * iterative server for var.sockets.tcp.filer File service. waits for the next + * client to connect. Upon connection sends a manually defined file back to + * client. closes the connection directly afterwards and handles then next + * client + * + * @author Sandro Leuchter + * + */ +public class FileServerIterativ { + /** + * path to file which will be sent to clients; relative to current working + * directory (e.g. project root) + */ + private static final String FILE = "target/classes/message.txt"; + /** + * port on which this service is currently listening on localhost + */ + private final int port; + /** + * requested maximum length of the queue of incoming connections. + */ + private final int backlog; + + /** + * the only constructor for this class + * + * @param port port on which this service will be listening on localhost + * @param backlog requested maximum length of the queue of incoming connections. + */ + public FileServerIterativ(int port, int backlog) { + this.port = port; + this.backlog = backlog; + } + + /** + * creates server socket on localhost:port, infinitely handles connections to + * clients one after another + */ + public void start() { + try (ServerSocket serverSocket = new ServerSocket(this.port, this.backlog)) { + System.out.println("FileServer (iterativ) auf " + serverSocket.getLocalSocketAddress() + " gestartet ..."); + File file = new File(FILE); + if (file.exists()) { + System.out.println("\"" + file.getAbsolutePath() + "\" soll gesendet werden."); + while (true) { + handleClient(serverSocket); + } + } + } catch (IOException e) { + System.err.println(e); + } + } + + /** + * waits for the next client to connect. Upon connection sends a manually + * defined file back to client. closes the connection directly afterwards and + * handles then next client + * + * @param server "welcome socket" on which server is listening for clients + */ + private void handleClient(ServerSocket server) { + SocketAddress socketAddress = null; + try (Socket socket = server.accept(); + BufferedReader in = new BufferedReader(new FileReader(FILE)); + PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { + socketAddress = socket.getRemoteSocketAddress(); + System.out.println("Verbindung zu " + socketAddress + " aufgebaut"); + // Inhalt von in zeilenweise an out senden: + System.out.println("Übertragung zu " + socketAddress + " begonnen"); + String input; + while ((input = in.readLine()) != null) { + out.println(input); + } + System.out.println("Übertragung zu " + socketAddress + " beendet"); + } catch (IOException e) { + System.err.println(e); + } finally { + System.out.println("Verbindung zu " + socketAddress + " abgebaut"); + } + } + + /** + * main method: entrypoint to run service + * + * @param args args[0] must be the port number of the server (int); rest of args + * is ignored + */ + public static void main(String[] args) { + int port = Integer.parseInt(args[0]); + int backlog = 50; + if (args.length == 2) { + backlog = Integer.parseInt(args[1]); + } + + new FileServerIterativ(port, backlog).start(); + } +} diff --git a/03-tcp/tcp.filer_solution/src/main/java/vs/FileServerThreadPool.java b/03-tcp/tcp.filer_solution/src/main/java/vs/FileServerThreadPool.java new file mode 100644 index 0000000..d87474c --- /dev/null +++ b/03-tcp/tcp.filer_solution/src/main/java/vs/FileServerThreadPool.java @@ -0,0 +1,128 @@ +package vs; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +/** + * threaded server for var.sockets.tcp.filer File service. waits for clients to + * connect. Upon connection sends concurrently to other client connections a + * manually defined file back to client. closes the connection directly + * afterwards. + * + * @author Sandro Leuchter + * + */ +public class FileServerThreadPool { + /** + * path to file which will be sent to clients; relative to current working + * directory (e.g. project root) + */ + private static final String FILE = "target/classes/message.txt"; + /** + * port on which this service is currently listening on localhost + */ + private final int port; + /** + * thread pool of this server + */ + private final Executor threadPool; + + /** + * the only constructor for this class + * + * @param port port on which this service will be listening on localhost + */ + public FileServerThreadPool(int port) { + this.port = port; + this.threadPool = Executors.newSingleThreadExecutor(); + // threadPool = Executors.newCachedThreadPool(); + // threadPool = + // Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*2); + } + + /** + * creates server socket on localhost:port, infinitely handles connections to + * clients concurrently + */ + public void start() { + try (ServerSocket serverSocket = new ServerSocket(this.port)) { + System.out.println("FileServer (threaded) auf " + serverSocket.getLocalSocketAddress() + " gestartet ..."); + File file = new File(FILE); + if (file.exists()) { + System.out.println("\"" + file.getAbsolutePath() + "\" soll gesendet werden."); + while (true) { + Socket socket = serverSocket.accept(); + this.threadPool.execute(new FileThread(socket)); + } + } + } catch (IOException e) { + System.err.println(e); + } + } + + /** + * Each connection is handled with an instance of this class. + */ + private class FileThread implements Runnable { + /** + * TCP connection to client + */ + private final Socket socket; + + /** + * the only constructor for this class + * + * @param socket the individual socket that the server created on accepting a + * client that this EchoThread instance will be communicating with + */ + public FileThread(Socket socket) { + this.socket = socket; + } + + /** + * defines the behavior of this Thread instance, will be executed concurrently + * if start() is called on instance + * + */ + @Override + public void run() { + SocketAddress socketAddress = null; + try (BufferedReader in = new BufferedReader(new FileReader(FILE)); + PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true)) { + socketAddress = this.socket.getRemoteSocketAddress(); + System.out.println("Verbindung zu " + socketAddress + " aufgebaut"); + // Inhalt von in zeilenweise an out senden: + System.out.println("Übertragung zu " + socketAddress + " begonnen"); + String input; + while ((input = in.readLine()) != null) { + out.println(input); + // Thread.sleep(1000); + } + System.out.println("Übertragung zu " + socketAddress + " beendet"); + } catch (Exception e) { + System.err.println(e); + } finally { + System.out.println("Verbindung zu " + socketAddress + " abgebaut"); + } + } + } + + /** + * main method: entrypoint to run service + * + * @param args args[0] must be the port number of the server (int); rest of args + * is ignored + */ + public static void main(String[] args) { + int port = Integer.parseInt(args[0]); + new FileServerThreadPool(port).start(); + } +} diff --git a/03-tcp/tcp.filer_solution/src/main/java/vs/FileServerThreaded.java b/03-tcp/tcp.filer_solution/src/main/java/vs/FileServerThreaded.java new file mode 100644 index 0000000..9bd946a --- /dev/null +++ b/03-tcp/tcp.filer_solution/src/main/java/vs/FileServerThreaded.java @@ -0,0 +1,118 @@ +package vs; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; + +/** + * threaded server for var.sockets.tcp.filer File service. waits for clients to + * connect. Upon connection sends concurrently to other client connections a + * manually defined file back to client. closes the connection directly + * afterwards. + * + * @author Sandro Leuchter + * + */ +public class FileServerThreaded { + /** + * path to file which will be sent to clients; relative to current working + * directory (e.g. project root) + */ + private static final String FILE = "target/classes/message.txt"; + /** + * port on which this service is currently listening on localhost + */ + private final int port; + + /** + * the only constructor for this class + * + * @param port port on which this service will be listening on localhost + */ + public FileServerThreaded(int port) { + this.port = port; + } + + /** + * creates server socket on localhost:port, infinitely handles connections to + * clients concurrently + */ + public void start() { + try (ServerSocket serverSocket = new ServerSocket(this.port)) { + System.out.println("FileServer (threaded) auf " + serverSocket.getLocalSocketAddress() + " gestartet ..."); + File file = new File(FILE); + if (file.exists()) { + System.out.println("\"" + file.getAbsolutePath() + "\" soll gesendet werden."); + while (true) { + Socket socket = serverSocket.accept(); + new FileThread(socket).start(); + } + } + } catch (IOException e) { + System.err.println(e); + } + } + + /** + * Each connection is handled with an instance of this class. + */ + private class FileThread extends Thread { + /** + * TCP connection to client + */ + private final Socket socket; + + /** + * the only constructor for this class + * + * @param socket the individual socket that the server created on accepting a + * client that this EchoThread instance will be communicating with + */ + public FileThread(Socket socket) { + this.socket = socket; + } + + /** + * defines the behavior of this Thread instance, will be executed concurrently + * if start() is called on instance + * + */ + @Override + public void run() { + SocketAddress socketAddress = null; + try (BufferedReader in = new BufferedReader(new FileReader(FILE)); + PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true)) { + socketAddress = this.socket.getRemoteSocketAddress(); + System.out.println("Verbindung zu " + socketAddress + " aufgebaut"); + // Inhalt von in zeilenweise an out senden: + System.out.println("Übertragung zu " + socketAddress + " begonnen"); + String input; + while ((input = in.readLine()) != null) { + out.println(input); + // Thread.sleep(1000); + } + System.out.println("Übertragung zu " + socketAddress + " beendet"); + } catch (Exception e) { + System.err.println(e); + } finally { + System.out.println("Verbindung zu " + socketAddress + " abgebaut"); + } + } + } + + /** + * main method: entrypoint to run service + * + * @param args args[0] must be the port number of the server (int); rest of args + * is ignored + */ + public static void main(String[] args) { + int port = Integer.parseInt(args[0]); + new FileServerThreaded(port).start(); + } +} diff --git a/03-tcp/tcp.filer_solution/src/main/resources/message.txt b/03-tcp/tcp.filer_solution/src/main/resources/message.txt new file mode 100644 index 0000000..8f8b45d --- /dev/null +++ b/03-tcp/tcp.filer_solution/src/main/resources/message.txt @@ -0,0 +1,25 @@ +Mannheimer Mittelstandsmesse 2017 +================================= + +Zum zehnten Mal lädt die Hochschule Mannheim zur Mittelstandsmesse (MaMi) ein. 14 Unternehmen, +die sich beim Mannheimer Modell Mittelstands-Stipendien engagieren, präsentierten sich in +der Aula der Hochschule + +Studierende der Hochschule haben am 04.04.2017 von 12.00 – 16.00 Uhr wieder die Gelegenheit, +Kontakte zu mittelständischen Unternehmen der Metropolregion zu knüpfen, Möglichkeiten für +Praktika auszuloten oder mit Personalverantwortlichen über Stellenangebote zu sprechen. Auch +für Lehrende und Forschende ist die Messe eine gute Gelegenheit, mit interessierten Unternehmen +Kooperationen anzubahnen oder zu vertiefen. + +Ziel der Messe ist, die Sichtbarkeit von mittelständischen Unternehmen in der Metropolregion +Rhein-Neckar zu erhöhen und Hochschulabsolventen die Attraktivität einer beruflichen Karriere +insbesondere im Mittelstand deutlich zu machen. Mittelständische Unternehmen prägen die +Wirtschaftsstruktur in Deutschland. 99 Prozent aller Unternehmen werden den mittelständischen +Unternehmen zugerechnet, sie beschäftigen rund 2/3 aller Erwerbstätigen. + +Parallel zur Eröffnung der MaMi wird auch die Förderrunde 2017/18 für die Mannheimer +Mittelstands-Stipendien ausgeschrieben. Durch das seit 2007 etablierte Stipendienmodell, das +in tatkräftiger Kooperation der Hochschule mit mittelständischen Unternehmen und unterstützt +von der Metropolregion Rhein-Neckar ins Leben gerufen wurde, können im Studienjahr 30-40 +Stipendien in Höhe von je 1.000 € vergeben werden. So ist die MaMi auch eine gute Gelegenheit +für Studierende, sich an den Ständen der Unternehmen als potenzielle Stipendiaten zu präsentieren. diff --git a/03-tcp/tcp.time/justfile b/03-tcp/tcp.time/justfile new file mode 100644 index 0000000..98f9ffc --- /dev/null +++ b/03-tcp/tcp.time/justfile @@ -0,0 +1,10 @@ +import '../justfile' + +port := "4747" + +server-long: + just exec vs.TimeLongServer {{port}} +server-text: + just exec vs.TimeTextServer {{port}} +client host: + just exec vs.TimeClient "{{host}} {{port}}" diff --git a/03-tcp/tcp.time/pom.xml b/03-tcp/tcp.time/pom.xml new file mode 100644 index 0000000..11d0d2c --- /dev/null +++ b/03-tcp/tcp.time/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + tcp.time + 1.0-SNAPSHOT + jar + + + vs + tcp + 1.0-SNAPSHOT + + diff --git a/03-tcp/tcp.time/src/main/java/vs/TimeClient.java b/03-tcp/tcp.time/src/main/java/vs/TimeClient.java new file mode 100644 index 0000000..11bfda0 --- /dev/null +++ b/03-tcp/tcp.time/src/main/java/vs/TimeClient.java @@ -0,0 +1,23 @@ +package vs; + +import java.io.InputStream; +import java.net.Socket; + +public class TimeClient { + public static void main(String[] args) { + try (Socket socket = new Socket(args[0], Integer.parseInt(args[1])); + InputStream in = socket.getInputStream()) { + StringBuilder stringBuilder = new StringBuilder(); + + int c; + while ((c = in.read()) != -1) { + stringBuilder.append((char) c); + } + + // stringBuilder-Inhalt in ein Date-Objekt konvertieren und ausgeben + + } catch (Exception e) { + System.err.println(e); + } + } +} diff --git a/03-tcp/tcp.time/src/main/java/vs/TimeLongServer.java b/03-tcp/tcp.time/src/main/java/vs/TimeLongServer.java new file mode 100644 index 0000000..99bde96 --- /dev/null +++ b/03-tcp/tcp.time/src/main/java/vs/TimeLongServer.java @@ -0,0 +1,38 @@ +package vs; + +import java.io.IOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.text.DateFormat; +import java.util.Date; + +public class TimeLongServer { + private int port; + + public TimeLongServer(int port) { + this.port = port; + } + + public void startServer() { + try (ServerSocket serverSocket = new ServerSocket(port)) { + while (true) { + try (Socket socket = serverSocket.accept(); + PrintWriter out = new PrintWriter(socket.getOutputStream())) { + Date now = new Date(); + long currentTime = // Zeit von now in ms seit 01.01.1970 00:00:00 GMT abrufen + out.print(currentTime); + out.flush(); + } catch (IOException e) { + System.err.println(e); + } + } + } catch (IOException e) { + System.err.println(e); + } + } + + public static void main(String[] args) { + new TimeLongServer(Integer.parseInt(args[0])).startServer(); + } +} diff --git a/03-tcp/tcp.time/src/main/java/vs/TimeTextServer.java b/03-tcp/tcp.time/src/main/java/vs/TimeTextServer.java new file mode 100644 index 0000000..5df1508 --- /dev/null +++ b/03-tcp/tcp.time/src/main/java/vs/TimeTextServer.java @@ -0,0 +1,38 @@ +package vs; + +import java.io.IOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.text.DateFormat; +import java.util.Date; + +public class TimeTextServer { + private int port; + + public TimeTextServer(int port) { + this.port = port; + } + + public void startServer() { + try (ServerSocket serverSocket = new ServerSocket(port)) { + while (true) { + try (Socket socket = serverSocket.accept(); + PrintWriter out = new PrintWriter(socket.getOutputStream())) { + Date now = new Date(); + String currentTime = // DateFormat Instanz holen und mit dessen format Methode now zum String machen + out.print(currentTime); + out.flush(); + } catch (IOException e) { + System.err.println(e); + } + } + } catch (IOException e) { + System.err.println(e); + } + } + + public static void main(String[] args) { + new TimeTextServer(Integer.parseInt(args[0])).startServer(); + } +} diff --git a/03-tcp/tcp.time_solution/justfile b/03-tcp/tcp.time_solution/justfile new file mode 100644 index 0000000..98f9ffc --- /dev/null +++ b/03-tcp/tcp.time_solution/justfile @@ -0,0 +1,10 @@ +import '../justfile' + +port := "4747" + +server-long: + just exec vs.TimeLongServer {{port}} +server-text: + just exec vs.TimeTextServer {{port}} +client host: + just exec vs.TimeClient "{{host}} {{port}}" diff --git a/03-tcp/tcp.time_solution/pom.xml b/03-tcp/tcp.time_solution/pom.xml new file mode 100644 index 0000000..b5a8e94 --- /dev/null +++ b/03-tcp/tcp.time_solution/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + tcp.time_solution + 1.0-SNAPSHOT + jar + + + vs + tcp + 1.0-SNAPSHOT + + diff --git a/03-tcp/tcp.time_solution/src/main/java/vs/TimeClient.java b/03-tcp/tcp.time_solution/src/main/java/vs/TimeClient.java new file mode 100644 index 0000000..54e440a --- /dev/null +++ b/03-tcp/tcp.time_solution/src/main/java/vs/TimeClient.java @@ -0,0 +1,63 @@ +package vs; + +import java.io.InputStream; +import java.net.Socket; +import java.text.DateFormat; +import java.text.ParseException; +import java.util.Date; + +/** + * Client for echo var.sockets.tcp.time.Time*Server service. Verbindet sich mit + * dem Server und empfängt eine Repräsentation eines Zeitstempels. Das Format + * des Zeitstempels kann entweder die Zeit in ms seit dem 01.01.1970 00:00:00 + * GMT als ASCII-Zeichen sein oder ein String, der die Zeit kompatibel zu ISO + * 8601 enthält. + * + * @author Sandro Leuchter + * + */ +public class TimeClient { + + /** + * main method: entrypoint to run + * + * @param args address of service to connect to (must be String[0]: host + * (IP-address or DNS hostname), String[1]: port) + * + */ + public static void main(String[] args) { + try (Socket socket = new Socket(args[0], Integer.parseInt(args[1])); InputStream in = socket.getInputStream()) { + StringBuilder stringBuilder = new StringBuilder(); + + int c; + while ((c = in.read()) != -1) { + stringBuilder.append((char) c); + } + + // stringBuilder-Inhalt in ein Date-Objekt konvertieren und ausgeben + DateFormat dateFormatter = DateFormat.getInstance(); + Date date = null; + try { + date = dateFormatter.parse(stringBuilder.toString()); + } catch (ParseException parseException) { + try { + date = new Date(Long.parseLong(stringBuilder.toString())); + } catch (NumberFormatException numberException) { + // weder verständliches Textformat, noch long-Zahl (ms. seit + // 01.01.1970 00:00) + // System.err.println(numberException); + } + } + System.out.println("empfangen: \"" + stringBuilder.toString() + "\""); + if (date != null) { + System.out.println("gewandelt: " + date); + } else { + // weder verständliches Textformat, noch long-Zahl (ms. seit + // 01.01.1970 00:00) + System.err.println("es war nicht mögich ein Date-Objekt daraus zu erzeugen."); + } + } catch (Exception e) { + System.err.println(e); + } + } +} diff --git a/03-tcp/tcp.time_solution/src/main/java/vs/TimeLongServer.java b/03-tcp/tcp.time_solution/src/main/java/vs/TimeLongServer.java new file mode 100644 index 0000000..29587c6 --- /dev/null +++ b/03-tcp/tcp.time_solution/src/main/java/vs/TimeLongServer.java @@ -0,0 +1,65 @@ +package vs; + +import java.io.IOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.Date; + +/** + * iterative server for var.sockets.tcp.time Time service. waits for the next + * client to connect, then sends time back. format for time is ASCII + * representation of ms since begin of epoch: Jan 1, 1970 00:00:00 GMT. + * + * @author Sandro Leuchter + * + */ +public class TimeLongServer { + /** + * port on which this service is currently listening on localhost + */ + private final int port; + + /** + * the only constructor for this class + * + * @param port port on which this service will be listening on localhost + */ + public TimeLongServer(int port) { + this.port = port; + } + + /** + * creates server socket on localhost:port, infinitely handles connections to + * clients one after another: waits for the next client to connect, send time + * back. format for time is ASCII representation of ms since begin of epoch: Jan + * 1, 1970 00:00:00 GMT. + */ + public void startServer() { + try (ServerSocket serverSocket = new ServerSocket(this.port)) { + while (true) { + try (Socket socket = serverSocket.accept(); + PrintWriter out = new PrintWriter(socket.getOutputStream())) { + Date now = new Date(); + long currentTime = now.getTime(); + out.print(currentTime); + out.flush(); + } catch (IOException e) { + System.err.println(e); + } + } + } catch (IOException e) { + System.err.println(e); + } + } + + /** + * main method: entrypoint to run service + * + * @param args args[0] must be the port number of the server (int); rest of args + * is ignored + */ + public static void main(String[] args) { + new TimeLongServer(Integer.parseInt(args[0])).startServer(); + } +} diff --git a/03-tcp/tcp.time_solution/src/main/java/vs/TimeTextServer.java b/03-tcp/tcp.time_solution/src/main/java/vs/TimeTextServer.java new file mode 100644 index 0000000..eb4f528 --- /dev/null +++ b/03-tcp/tcp.time_solution/src/main/java/vs/TimeTextServer.java @@ -0,0 +1,65 @@ +package vs; + +import java.io.IOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.text.DateFormat; +import java.util.Date; + +/** + * iterative server for var.sockets.tcp.time Time service. waits for the next + * client to connect, then sends time back. format for time is short date and + * time according to current locale. + * + * @author Sandro Leuchter + * + */ +public class TimeTextServer { + /** + * port on which this service is currently listening on localhost + */ + private final int port; + + /** + * the only constructor for this class + * + * @param port port on which this service will be listening on localhost + */ + public TimeTextServer(int port) { + this.port = port; + } + + /** + * creates server socket on localhost:port, infinitely handles connections to + * clients one after another: waits for the next client to connect, send time + * back. format for time is short date and time according to current locale. + */ + public void startServer() { + try (ServerSocket serverSocket = new ServerSocket(this.port)) { + while (true) { + try (Socket socket = serverSocket.accept(); + PrintWriter out = new PrintWriter(socket.getOutputStream())) { + Date now = new Date(); + String currentTime = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(now); + out.print(currentTime); + out.flush(); + } catch (IOException e) { + System.err.println(e); + } + } + } catch (IOException e) { + System.err.println(e); + } + } + + /** + * main method: entrypoint to run + * + * @param args args[0] must be the port number of the server (int); rest of args + * is ignored + */ + public static void main(String[] args) { + new TimeTextServer(Integer.parseInt(args[0])).startServer(); + } +} diff --git a/05-jms/jms.chat/justfile b/05-jms/jms.chat/justfile new file mode 100644 index 0000000..e619b7f --- /dev/null +++ b/05-jms/jms.chat/justfile @@ -0,0 +1,8 @@ +import '../justfile' + +chatter1: + just chatter Dave +chatter2: + just chatter HAL9000 +chatter name: + just exec vs.ChatClient "{{name}}" diff --git a/05-jms/jms.chat/pom.xml b/05-jms/jms.chat/pom.xml new file mode 100644 index 0000000..92ec090 --- /dev/null +++ b/05-jms/jms.chat/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + jms.chat + 1.0-SNAPSHOT + jar + + + vs + jms + 1.0-SNAPSHOT + + + diff --git a/05-jms/jms.chat/src/main/java/vs/ChatClient.java b/05-jms/jms.chat/src/main/java/vs/ChatClient.java new file mode 100644 index 0000000..8a39f1a --- /dev/null +++ b/05-jms/jms.chat/src/main/java/vs/ChatClient.java @@ -0,0 +1,69 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +// Code aus JMS-Client mit Umbenennung des Typs von JMSClient zu ChatClient und Anpassung des packages +public class ChatClient implements MessageListener { + private Connection connection; + private Session session; + private MessageConsumer consumer; + + public ChatClient() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Destination queue = (Destination) ctx.lookup(Conf.QUEUE); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createConsumer(queue); + consumer.setMessageListener(this); + connection.start(); + } + + @Override + public void onMessage(Message message) { + try { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + String messageText = textMessage.getText(); + String priority = textMessage.getStringProperty("Priority"); + System.out.println(messageText + " [Priority=" + priority + "]"); + } + } catch (JMSException e) { + System.err.println(e); + } + + } + + public static void main(String[] args) { + long wait = Long.parseLong(args[0]); + ChatClient node = null; + try { + node = new ChatClient(); + Thread.sleep(wait); + } catch (InterruptedException | NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if (node != null && node.consumer != null) + node.consumer.close(); + if (node != null && node.session != null) + node.session.close(); + if (node != null && node.connection != null) + node.connection.close(); + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.chat/src/main/resources/jndi.properties b/05-jms/jms.chat/src/main/resources/jndi.properties new file mode 100644 index 0000000..f76bbf7 --- /dev/null +++ b/05-jms/jms.chat/src/main/resources/jndi.properties @@ -0,0 +1,5 @@ +java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory +java.naming.provider.url = tcp://localhost:61616 + +topic.vs.channel = topic4735 + diff --git a/05-jms/jms.chat_solution/justfile b/05-jms/jms.chat_solution/justfile new file mode 100644 index 0000000..d400190 --- /dev/null +++ b/05-jms/jms.chat_solution/justfile @@ -0,0 +1,15 @@ +import '../justfile' + +chatter1: + just chatter Dave +chatter2: + just chatter HAL9000 +chatter name: + just exec vs.ChatClient "{{name}}" + +chatterA: + just chatter-prop Dave +chatterB: + just chatter-prop HAL9000 +chatter-prop name: + just exec vs.ChatClientUserProperty "{{name}}" diff --git a/05-jms/jms.chat_solution/pom.xml b/05-jms/jms.chat_solution/pom.xml new file mode 100644 index 0000000..0f95fee --- /dev/null +++ b/05-jms/jms.chat_solution/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + jms.chat_solution + 1.0-SNAPSHOT + jar + + + vs + jms + 1.0-SNAPSHOT + + + diff --git a/05-jms/jms.chat_solution/src/main/java/vs/ChatClient.java b/05-jms/jms.chat_solution/src/main/java/vs/ChatClient.java new file mode 100644 index 0000000..6d9c8ab --- /dev/null +++ b/05-jms/jms.chat_solution/src/main/java/vs/ChatClient.java @@ -0,0 +1,111 @@ +package vs; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.MessageProducer; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * Chat Client using publish/subscribe on JMS provider Topic; represents user + * name as part of message payload + * + * @author Sandro Leuchter + * + */ +public class ChatClient implements MessageListener { + private Connection connection; + private Session session; + private MessageProducer producer; + private MessageConsumer consumer; + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards producer and consumer are ready + * + * @param sendDest Destination for producer + * @param receiveDest Destination for consumer + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + * @see jakarta.jms.Destination + */ + public ChatClient(String sendDest, String receiveDest) throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destOut = (Destination) ctx.lookup(sendDest); + Destination destIn = (Destination) ctx.lookup(receiveDest); + this.producer = this.session.createProducer(destOut); + this.consumer = this.session.createConsumer(destIn); + this.consumer.setMessageListener(this); + this.connection.start(); + } + + /** + * asynchronous message consumption + * + * @see jakarta.jms.MessageListener + */ + @Override + public void onMessage(Message message) { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + try { + System.out.println(textMessage.getText()); + } catch (JMSException e) { + System.err.println(e); + } + } + } + + /** + * main routine and starting point of program + * + * @param args[0] user name + */ + public static void main(String[] args) { + ChatClient node = null; + try { + node = new ChatClient(Conf.TOPIC, Conf.TOPIC); + BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); + String line; + while (true) { + line = input.readLine(); + node.producer.send(node.session.createTextMessage(args[0] + "> " + line)); + } + } catch (NamingException | JMSException | IOException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.producer != null)) { + node.producer.close(); + } + if ((node != null) && (node.consumer != null)) { + node.consumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.chat_solution/src/main/java/vs/ChatClientUserProperty.java b/05-jms/jms.chat_solution/src/main/java/vs/ChatClientUserProperty.java new file mode 100644 index 0000000..d850031 --- /dev/null +++ b/05-jms/jms.chat_solution/src/main/java/vs/ChatClientUserProperty.java @@ -0,0 +1,113 @@ +package vs; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.MessageProducer; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * Chat Client using publish/subscribe on JMS provider Topic; represents user + * name as String property of message + * + * @author Sandro Leuchter + * + */ +public class ChatClientUserProperty implements MessageListener { + private Connection connection; + private Session session; + private MessageProducer producer; + private MessageConsumer consumer; + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards producer and consumer are ready + * + * @param sendDest Destination for producer + * @param receiveDest Destination for consumer + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + * @see jakarta.jms.Destination + */ + public ChatClientUserProperty(String sendDest, String receiveDest) throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destOut = (Destination) ctx.lookup(sendDest); + Destination destIn = (Destination) ctx.lookup(receiveDest); + this.producer = this.session.createProducer(destOut); + this.consumer = this.session.createConsumer(destIn); + this.consumer.setMessageListener(this); + this.connection.start(); + } + + /** + * asynchronous message consumption + * + * @see jakarta.jms.MessageListener + */ + @Override + public void onMessage(Message message) { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + try { + System.out.println(textMessage.getStringProperty("user") + "> " + textMessage.getText()); + } catch (JMSException e) { + System.err.println(e); + } + } + } + + /** + * main routine and starting point of program + * + * @param args[0] user name + */ + public static void main(String[] args) { + ChatClientUserProperty node = null; + try { + node = new ChatClientUserProperty(Conf.TOPIC, Conf.TOPIC); + BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); + String line; + while (true) { + line = input.readLine(); + TextMessage msg = node.session.createTextMessage(line); + msg.setStringProperty("user", args[0]); + node.producer.send(msg); + } + } catch (NamingException | JMSException | IOException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.producer != null)) { + node.producer.close(); + } + if ((node != null) && (node.consumer != null)) { + node.consumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.chat_solution/src/main/java/vs/Conf.java b/05-jms/jms.chat_solution/src/main/java/vs/Conf.java new file mode 100644 index 0000000..a953eb1 --- /dev/null +++ b/05-jms/jms.chat_solution/src/main/java/vs/Conf.java @@ -0,0 +1,5 @@ +package vs; + +public class Conf { + public static final String TOPIC = "vs.chat"; +} diff --git a/05-jms/jms.chat_solution/src/main/resources/jndi.properties b/05-jms/jms.chat_solution/src/main/resources/jndi.properties new file mode 100644 index 0000000..ec1c480 --- /dev/null +++ b/05-jms/jms.chat_solution/src/main/resources/jndi.properties @@ -0,0 +1,5 @@ +java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory +java.naming.provider.url = tcp://localhost:61616 + +topic.vs.chat = topic4735 + diff --git a/05-jms/jms.client/justfile b/05-jms/jms.client/justfile new file mode 100644 index 0000000..3d81654 --- /dev/null +++ b/05-jms/jms.client/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + just exec vs.JMSClient "" diff --git a/05-jms/jms.client/pom.xml b/05-jms/jms.client/pom.xml new file mode 100644 index 0000000..dbb96ee --- /dev/null +++ b/05-jms/jms.client/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + jms.client + 1.0-SNAPSHOT + jar + + + vs + jms + 1.0-SNAPSHOT + + + diff --git a/05-jms/jms.client/src/main/java/vs/JMSClient.java b/05-jms/jms.client/src/main/java/vs/JMSClient.java new file mode 100644 index 0000000..b7cb575 --- /dev/null +++ b/05-jms/jms.client/src/main/java/vs/JMSClient.java @@ -0,0 +1,84 @@ +package vs; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import jakarta.jms.BytesMessage; +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.MessageProducer; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +public class JMSClient implements MessageListener { + private Connection connection; + private Session session; + private MessageProducer producer; + private MessageConsumer consumer; + + public JMSClient(String sendDest, String receiveDest) throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destOut = (Destination) ctx.lookup(sendDest); + Destination destIn = (Destination) ctx.lookup(receiveDest); + producer = session.createProducer(destOut); + consumer = session.createConsumer(destIn); + consumer.setMessageListener(this); + connection.start(); + } + + @Override + public void onMessage(Message message) { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + try { + System.out.println(textMessage.getText()); + } catch (JMSException e) { + System.err.println(e); + } + } + } + + public static void main(String[] args) { + JMSClient node = null; + try { + node = new JMSClient("vs.queue1", "vs.queue2"); + BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); + String line; + while (true) { + line = input.readLine(); + node.producer.send(node.session.createTextMessage(line)); + } + } catch (NamingException | JMSException | IOException e) { + System.err.println(e); + } finally { + try { + if (node != null && node.producer != null) { + node.producer.close(); + } + if (node != null && node.consumer != null) { + node.consumer.close(); + } + if (node != null && node.session != null) { + node.session.close(); + } + if (node != null && node.connection != null) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.client/src/main/resources/jndi.properties b/05-jms/jms.client/src/main/resources/jndi.properties new file mode 100644 index 0000000..af6e097 --- /dev/null +++ b/05-jms/jms.client/src/main/resources/jndi.properties @@ -0,0 +1,6 @@ +java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory +java.naming.provider.url = tcp://localhost:61616 + +queue.vs.queue1 = queue4731 +queue.vs.queue2 = queue4732 + diff --git a/05-jms/jms.client_solution/justfile b/05-jms/jms.client_solution/justfile new file mode 100644 index 0000000..3d81654 --- /dev/null +++ b/05-jms/jms.client_solution/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + just exec vs.JMSClient "" diff --git a/05-jms/jms.client_solution/pom.xml b/05-jms/jms.client_solution/pom.xml new file mode 100644 index 0000000..9c1d99a --- /dev/null +++ b/05-jms/jms.client_solution/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + jms.client_solution + 1.0-SNAPSHOT + jar + + + vs + jms + 1.0-SNAPSHOT + + + diff --git a/05-jms/jms.client_solution/src/main/java/vs/JMSClient.java b/05-jms/jms.client_solution/src/main/java/vs/JMSClient.java new file mode 100644 index 0000000..ff890bf --- /dev/null +++ b/05-jms/jms.client_solution/src/main/java/vs/JMSClient.java @@ -0,0 +1,110 @@ +package vs; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.MessageProducer; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * general JMS client with one producer and one consumer + * + * @author Sandro Leuchter + * + */ +public class JMSClient implements MessageListener { + private Connection connection; + private Session session; + private MessageProducer producer; + private MessageConsumer consumer; + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards producer and consumer are ready + * + * @param sendDest Destination for producer + * @param receiveDest Destination for consumer + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + * @see jakarta.jms.Destination + */ + public JMSClient(String sendDest, String receiveDest) throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination destOut = (Destination) ctx.lookup(sendDest); + Destination destIn = (Destination) ctx.lookup(receiveDest); + this.producer = this.session.createProducer(destOut); + this.consumer = this.session.createConsumer(destIn); + this.consumer.setMessageListener(this); + this.connection.start(); + } + + /** + * asynchronous message consumption + * + * @see jakarta.jms.MessageListener + */ + @Override + public void onMessage(Message message) { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + try { + System.out.println(textMessage.getText()); + } catch (JMSException e) { + System.err.println(e); + } + } + } + + /** + * main routine and starting point of program + * + * @param args not used + */ + public static void main(String[] args) { + JMSClient node = null; + try { + node = new JMSClient("vs.queue1", "vs.queue2"); + BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); + String line; + while (true) { + line = input.readLine(); + node.producer.send(node.session.createTextMessage(line)); + } + } catch (NamingException | JMSException | IOException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.producer != null)) { + node.producer.close(); + } + if ((node != null) && (node.consumer != null)) { + node.consumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.client_solution/src/main/resources/jndi.properties b/05-jms/jms.client_solution/src/main/resources/jndi.properties new file mode 100644 index 0000000..af6e097 --- /dev/null +++ b/05-jms/jms.client_solution/src/main/resources/jndi.properties @@ -0,0 +1,6 @@ +java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory +java.naming.provider.url = tcp://localhost:61616 + +queue.vs.queue1 = queue4731 +queue.vs.queue2 = queue4732 + diff --git a/05-jms/jms.code-workspace b/05-jms/jms.code-workspace new file mode 100644 index 0000000..3da1dcb --- /dev/null +++ b/05-jms/jms.code-workspace @@ -0,0 +1,55 @@ +{ + "folders": [ + { + "name": "0. Client Service", + "path": "jms.client", + }, + { + "name": "0. Client Service (ML)", + "path": "jms.client_solution", + }, + { + "name": "1. Echo Service", + "path": "jms.echo", + }, + { + "name": "1. Echo Service (ML)", + "path": "jms.echo_solution", + }, + { + "name": "2. Logger Service", + "path": "jms.logger", + }, + { + "name": "2. Logger Service (ML)", + "path": "jms.logger_solution", + }, + { + "name": "3. Textumdreher Service (ML)", + "path": "jms.revers_solution", + }, + { + "name": "4. Chat Service", + "path": "jms.chat", + }, + { + "name": "4. Chat Service (ML)", + "path": "jms.chat_solution", + }, + { + "name": "5. Worker/Tasker für SHA-256 Hashes (ML)", + "path": "jms.tasks_solution", + }, + ], + "extensions": { + "recommendations": [ + "vscjava.vscode-java-pack", + "ms-azuretools.vscode-docker", + "skellock.just", + ], + }, + "settings": { + "java.dependency.syncWithFolderExplorer": true, + "java.project.explorer.showNonJavaResources": false, + }, +} diff --git a/05-jms/jms.echo/justfile b/05-jms/jms.echo/justfile new file mode 100644 index 0000000..fce18a7 --- /dev/null +++ b/05-jms/jms.echo/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +requester text: + just exec vs.EchoRequesterNode "{{text}}" +replier: + just exec vs.EchoReplierNode "" diff --git a/05-jms/jms.echo/pom.xml b/05-jms/jms.echo/pom.xml new file mode 100644 index 0000000..c0d4a87 --- /dev/null +++ b/05-jms/jms.echo/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + jms.echo + 1.0-SNAPSHOT + jar + + + vs + jms + 1.0-SNAPSHOT + + + diff --git a/05-jms/jms.echo/src/main/java/vs/Conf.java b/05-jms/jms.echo/src/main/java/vs/Conf.java new file mode 100644 index 0000000..6f992ef --- /dev/null +++ b/05-jms/jms.echo/src/main/java/vs/Conf.java @@ -0,0 +1,5 @@ +package vs; + +public class Conf { + public static final String QUEUE = "vs.echo"; +} diff --git a/05-jms/jms.echo/src/main/java/vs/EchoReplierNode.java b/05-jms/jms.echo/src/main/java/vs/EchoReplierNode.java new file mode 100644 index 0000000..b9b830e --- /dev/null +++ b/05-jms/jms.echo/src/main/java/vs/EchoReplierNode.java @@ -0,0 +1,74 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.MessageProducer; +import jakarta.jms.Queue; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +public class EchoReplierNode implements MessageListener { + private Connection connection; + private Session session; + private MessageConsumer consumer; + + public EchoReplierNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Queue queue = (Queue) ctx.lookup(Conf.QUEUE); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createConsumer(queue); + consumer.setMessageListener(this); + connection.start(); + } + + @Override + public void onMessage(Message request) { + try { + if (request instanceof TextMessage) { + TextMessage requestText = (TextMessage) request; + System.out.println("empfangen: " + requestText.getText()); + MessageProducer replyProducer = session.createProducer(request.getJMSReplyTo()); + TextMessage reply = session.createTextMessage(); + reply.setText("echo: " + requestText.getText()); + Thread.sleep(5000); + replyProducer.send(reply); + replyProducer.close(); + } + } catch (JMSException | InterruptedException e) { + System.err.println(e); + } + + } + + public static void main(String[] args) { + EchoReplierNode node = null; + try { + node = new EchoReplierNode(); + while (true) { + Thread.sleep(1000); + } + } catch (InterruptedException | NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if (node != null && node.consumer != null) + node.consumer.close(); + if (node != null && node.session != null) + node.session.close(); + if (node != null && node.connection != null) + node.connection.close(); + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.echo/src/main/java/vs/EchoRequesterNode.java b/05-jms/jms.echo/src/main/java/vs/EchoRequesterNode.java new file mode 100644 index 0000000..d7219e3 --- /dev/null +++ b/05-jms/jms.echo/src/main/java/vs/EchoRequesterNode.java @@ -0,0 +1,85 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageProducer; +import jakarta.jms.Queue; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +public class EchoRequesterNode { + private Connection connection; + private Session session; + private MessageProducer producer; + private MessageConsumer consumer; + private Queue replyQueue; + + public EchoRequesterNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = (Queue) ctx.lookup(Conf.QUEUE); + producer = session.createProducer(queue); + replyQueue = session.createTemporaryQueue(); + consumer = session.createConsumer(replyQueue); + connection.start(); + } + + public void receiveAndPrintMessages() throws JMSException { + Message request; + while ((request = consumer.receive()) != null) { + try { + if (request instanceof TextMessage) { + TextMessage requestText = (TextMessage) request; + String messageText = requestText.getText(); + System.out.println("empfangen: " + messageText); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } + + public void sendMessage(String text) throws JMSException { + TextMessage message = session.createTextMessage(); + message.setText(text); + message.setJMSReplyTo(replyQueue); + producer.send(message); + } + + public static void main(String[] args) { + String text = args[0]; + EchoRequesterNode node = null; + try { + node = new EchoRequesterNode(); + node.sendMessage(text); + node.receiveAndPrintMessages(); + } catch (NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if (node != null && node.producer != null) { + node.producer.close(); + } + if (node != null && node.consumer != null) { + node.consumer.close(); + } + if (node != null && node.session != null) { + node.session.close(); + } + if (node != null && node.connection != null) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.echo/src/main/resources/jndi.properties b/05-jms/jms.echo/src/main/resources/jndi.properties new file mode 100644 index 0000000..a659ecb --- /dev/null +++ b/05-jms/jms.echo/src/main/resources/jndi.properties @@ -0,0 +1,6 @@ +java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory +java.naming.provider.url = tcp://localhost:61616 + +queue.vs.echo = queue4734 + + diff --git a/05-jms/jms.echo/target/classes/jndi.properties b/05-jms/jms.echo/target/classes/jndi.properties new file mode 100644 index 0000000..a659ecb --- /dev/null +++ b/05-jms/jms.echo/target/classes/jndi.properties @@ -0,0 +1,6 @@ +java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory +java.naming.provider.url = tcp://localhost:61616 + +queue.vs.echo = queue4734 + + diff --git a/05-jms/jms.echo/target/classes/vs/Conf.class b/05-jms/jms.echo/target/classes/vs/Conf.class new file mode 100644 index 0000000..fb65882 Binary files /dev/null and b/05-jms/jms.echo/target/classes/vs/Conf.class differ diff --git a/05-jms/jms.echo/target/classes/vs/EchoReplierNode.class b/05-jms/jms.echo/target/classes/vs/EchoReplierNode.class new file mode 100644 index 0000000..23914a9 Binary files /dev/null and b/05-jms/jms.echo/target/classes/vs/EchoReplierNode.class differ diff --git a/05-jms/jms.echo/target/classes/vs/EchoRequesterNode.class b/05-jms/jms.echo/target/classes/vs/EchoRequesterNode.class new file mode 100644 index 0000000..7a93e9f Binary files /dev/null and b/05-jms/jms.echo/target/classes/vs/EchoRequesterNode.class differ diff --git a/05-jms/jms.echo_solution/justfile b/05-jms/jms.echo_solution/justfile new file mode 100644 index 0000000..fce18a7 --- /dev/null +++ b/05-jms/jms.echo_solution/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +requester text: + just exec vs.EchoRequesterNode "{{text}}" +replier: + just exec vs.EchoReplierNode "" diff --git a/05-jms/jms.echo_solution/pom.xml b/05-jms/jms.echo_solution/pom.xml new file mode 100644 index 0000000..49ff8f9 --- /dev/null +++ b/05-jms/jms.echo_solution/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + jms.echo_solution + 1.0-SNAPSHOT + jar + + + vs + jms + 1.0-SNAPSHOT + + + diff --git a/05-jms/jms.echo_solution/src/main/java/vs/Conf.java b/05-jms/jms.echo_solution/src/main/java/vs/Conf.java new file mode 100644 index 0000000..da885d7 --- /dev/null +++ b/05-jms/jms.echo_solution/src/main/java/vs/Conf.java @@ -0,0 +1,16 @@ +package vs; + +/** + * global configuration for echo service + * + * @author Sandro Leuchter + * + */ +public class Conf { + /** + * String constant for requests to the destination of echo service + * + * @see javax.jms.Destination + */ + public static final String QUEUE = "vs.echo"; +} diff --git a/05-jms/jms.echo_solution/src/main/java/vs/EchoReplierNode.java b/05-jms/jms.echo_solution/src/main/java/vs/EchoReplierNode.java new file mode 100644 index 0000000..53f820f --- /dev/null +++ b/05-jms/jms.echo_solution/src/main/java/vs/EchoReplierNode.java @@ -0,0 +1,100 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.MessageProducer; +import jakarta.jms.Queue; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * replier node for the echo service + * + * @author Sandro Leuchter + * + */ +public class EchoReplierNode implements MessageListener { + private Connection connection; + private Session session; + private MessageConsumer consumer; + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards consumer is ready + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + */ + public EchoReplierNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Queue queue = (Queue) ctx.lookup(Conf.QUEUE); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + this.consumer = this.session.createConsumer(queue); + this.consumer.setMessageListener(this); + this.connection.start(); + } + + /** + * asynchronous message consumption + * + * @see jakarta.jms.MessageListener + */ + @Override + public void onMessage(Message request) { + try { + if (request instanceof TextMessage) { + TextMessage requestText = (TextMessage) request; + System.out.println("empfangen: " + requestText.getText()); + MessageProducer replyProducer = this.session.createProducer(request.getJMSReplyTo()); + TextMessage reply = this.session.createTextMessage(); + reply.setText("echo: " + requestText.getText()); + Thread.sleep(5000); + replyProducer.send(reply); + replyProducer.close(); + } + } catch (JMSException | InterruptedException e) { + System.err.println(e); + } + + } + + /** + * main routine and starting point of program + * + * @param args not used + */ + public static void main(String[] args) { + EchoReplierNode node = null; + try { + node = new EchoReplierNode(); + while (true) { + Thread.sleep(1000); + } + } catch (InterruptedException | NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.consumer != null)) { + node.consumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.echo_solution/src/main/java/vs/EchoRequesterNode.java b/05-jms/jms.echo_solution/src/main/java/vs/EchoRequesterNode.java new file mode 100644 index 0000000..c5f5a30 --- /dev/null +++ b/05-jms/jms.echo_solution/src/main/java/vs/EchoRequesterNode.java @@ -0,0 +1,117 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageProducer; +import jakarta.jms.Queue; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * requester node for the echo service + * + * @author Sandro Leuchter + * + */ +public class EchoRequesterNode { + private Connection connection; + private Session session; + private MessageProducer producer; + private MessageConsumer consumer; + private Queue replyQueue; + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards producer and consumer are ready + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + */ + public EchoRequesterNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = (Queue) ctx.lookup(Conf.QUEUE); + this.producer = this.session.createProducer(queue); + this.replyQueue = this.session.createTemporaryQueue(); + this.consumer = this.session.createConsumer(this.replyQueue); + this.connection.start(); + } + + /** + * synchronously receives the TextMessages in an infinite loop and prints + * payload text to StdOut + * + * @see jakarta.jms.TextMessage + * @throws JMSException JMS exceptions + */ + public void receiveAndPrintMessages() throws JMSException { + Message request; + while ((request = this.consumer.receive()) != null) { + try { + if (request instanceof TextMessage) { + TextMessage requestText = (TextMessage) request; + String messageText = requestText.getText(); + System.out.println("empfangen: " + messageText); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } + + /** + * creates TextMessage for JMS provider with temporary reply queue set and sends + * it to Destination of producer, which is configured in Conf.QUEUE + * + * @param text text to be send + * @throws JMSException JMS exceptions + */ + public void sendMessage(String text) throws JMSException { + TextMessage message = this.session.createTextMessage(); + message.setText(text); + message.setJMSReplyTo(this.replyQueue); + this.producer.send(message); + } + + /** + * main routine and starting point of program + * + * @param args[0] text to be send to echo service replier + */ + public static void main(String[] args) { + String text = args[0]; + EchoRequesterNode node = null; + try { + node = new EchoRequesterNode(); + node.sendMessage(text); + node.receiveAndPrintMessages(); + } catch (NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.producer != null)) { + node.producer.close(); + } + if ((node != null) && (node.consumer != null)) { + node.consumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.echo_solution/src/main/resources/jndi.properties b/05-jms/jms.echo_solution/src/main/resources/jndi.properties new file mode 100644 index 0000000..a659ecb --- /dev/null +++ b/05-jms/jms.echo_solution/src/main/resources/jndi.properties @@ -0,0 +1,6 @@ +java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory +java.naming.provider.url = tcp://localhost:61616 + +queue.vs.echo = queue4734 + + diff --git a/05-jms/jms.logger/justfile b/05-jms/jms.logger/justfile new file mode 100644 index 0000000..692c5ed --- /dev/null +++ b/05-jms/jms.logger/justfile @@ -0,0 +1,12 @@ +include '../justfile' + +wait_time_ms := "10000" + +consumer-sync: + just exec vs.ConsumerPullNode "{{wait_time_ms}}" +consumer-async-all: + just exec vs.ConsumerCallbackNode "{{wait_time_ms}}" +consumer-async-high: + just exec vs.ConsumerFilteredNode "{{wait_time_ms}}" +producer text prio: + just exec vs.ProducerNode "{{text}} {{prio}}" diff --git a/05-jms/jms.logger/pom.xml b/05-jms/jms.logger/pom.xml new file mode 100644 index 0000000..e4f372a --- /dev/null +++ b/05-jms/jms.logger/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + jms.logger + 1.0-SNAPSHOT + jar + + + vs + jms + 1.0-SNAPSHOT + + + diff --git a/05-jms/jms.logger/src/main/java/vs/Conf.java b/05-jms/jms.logger/src/main/java/vs/Conf.java new file mode 100644 index 0000000..00385dd --- /dev/null +++ b/05-jms/jms.logger/src/main/java/vs/Conf.java @@ -0,0 +1,5 @@ +package vs; + +public class Conf { + public static final String QUEUE = "vs.queue"; +} diff --git a/05-jms/jms.logger/src/main/java/vs/ConsumerCallbackNode.java b/05-jms/jms.logger/src/main/java/vs/ConsumerCallbackNode.java new file mode 100644 index 0000000..c9f9cc3 --- /dev/null +++ b/05-jms/jms.logger/src/main/java/vs/ConsumerCallbackNode.java @@ -0,0 +1,68 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +public class ConsumerCallbackNode implements MessageListener { + private Connection connection; + private Session session; + private MessageConsumer consumer; + + public ConsumerCallbackNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Destination queue = (Destination) ctx.lookup(Conf.QUEUE); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createConsumer(queue); + consumer.setMessageListener(this); + connection.start(); + } + + @Override + public void onMessage(Message message) { + try { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + String messageText = textMessage.getText(); + String priority = textMessage.getStringProperty("Priority"); + System.out.println(messageText + " [Priority=" + priority + "]"); + } + } catch (JMSException e) { + System.err.println(e); + } + + } + + public static void main(String[] args) { + long wait = Long.parseLong(args[0]); + ConsumerCallbackNode node = null; + try { + node = new ConsumerCallbackNode(); + Thread.sleep(wait); + } catch (InterruptedException | NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if (node != null && node.consumer != null) + node.consumer.close(); + if (node != null && node.session != null) + node.session.close(); + if (node != null && node.connection != null) + node.connection.close(); + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.logger/src/main/java/vs/ConsumerFilteredNode.java b/05-jms/jms.logger/src/main/java/vs/ConsumerFilteredNode.java new file mode 100644 index 0000000..fb1bf63 --- /dev/null +++ b/05-jms/jms.logger/src/main/java/vs/ConsumerFilteredNode.java @@ -0,0 +1,68 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +public class ConsumerFilteredNode implements MessageListener { + private Connection connection; + private Session session; + private MessageConsumer consumer; + + public ConsumerFilteredNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Destination queue = (Destination) ctx.lookup(Conf.QUEUE); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createConsumer(queue, "Priority='high'"); + consumer.setMessageListener(this); + connection.start(); + } + + @Override + public void onMessage(Message message) { + try { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + String messageText = textMessage.getText(); + String priority = textMessage.getStringProperty("Priority"); + System.out.println(messageText + " [Priority=" + priority + "]"); + } + } catch (JMSException e) { + System.err.println(e); + } + } + + public static void main(String[] args) { + long wait = Long.parseLong(args[0]); + ConsumerFilteredNode node = null; + try { + node = new ConsumerFilteredNode(); + Thread.sleep(wait); + } catch (InterruptedException | NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if (node != null && node.consumer != null) + node.consumer.close(); + if (node != null && node.session != null) + node.session.close(); + if (node != null && node.connection != null) + node.connection.close(); + } catch (JMSException e) { + System.err.println(e); + } + } + } + +} diff --git a/05-jms/jms.logger/src/main/java/vs/ConsumerPullNode.java b/05-jms/jms.logger/src/main/java/vs/ConsumerPullNode.java new file mode 100644 index 0000000..5ca0d0d --- /dev/null +++ b/05-jms/jms.logger/src/main/java/vs/ConsumerPullNode.java @@ -0,0 +1,62 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +public class ConsumerPullNode { + private Connection connection; + private Session session; + private MessageConsumer consumer; + + public ConsumerPullNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Destination queue = (Destination) ctx.lookup(Conf.QUEUE); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + consumer = session.createConsumer(queue); + connection.start(); + } + + public void receiveAndPrintMessages(long timeout) throws JMSException { + Message message; + while ((message = consumer.receive(timeout)) != null) { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + String messageText = textMessage.getText(); + System.out.println(messageText); + } + } + } + + public static void main(String[] args) { + long timeout = Long.parseLong(args[0]); + ConsumerPullNode node = null; + try { + node = new ConsumerPullNode(); + node.receiveAndPrintMessages(timeout); + } catch (NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if (node != null && node.consumer != null) + node.consumer.close(); + if (node != null && node.session != null) + node.session.close(); + if (node != null && node.connection != null) + node.connection.close(); + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.logger/src/main/java/vs/ProducerNode.java b/05-jms/jms.logger/src/main/java/vs/ProducerNode.java new file mode 100644 index 0000000..1e04b0c --- /dev/null +++ b/05-jms/jms.logger/src/main/java/vs/ProducerNode.java @@ -0,0 +1,60 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.MessageProducer; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +public class ProducerNode { + private Connection connection; + private Session session; + private MessageProducer producer; + + public ProducerNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + connection = factory.createConnection(); + session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination queue = (Destination) ctx.lookup(Conf.QUEUE); + producer = session.createProducer(queue); + } + + public void sendMessage(String text, String priority) throws JMSException { + TextMessage message = session.createTextMessage(); + message.setText(text); + message.setStringProperty("Priority", priority); + producer.send(message); + } + + public static void main(String[] args) { + String text = args[0]; + String priority = args[1]; + ProducerNode node = null; + try { + node = new ProducerNode(); + node.sendMessage(text, priority); + } catch (NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if (node != null && node.producer != null) { + node.producer.close(); + } + if (node != null && node.session != null) { + node.session.close(); + } + if (node != null && node.connection != null) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.logger/src/main/resources/jndi.properties b/05-jms/jms.logger/src/main/resources/jndi.properties new file mode 100644 index 0000000..14e1072 --- /dev/null +++ b/05-jms/jms.logger/src/main/resources/jndi.properties @@ -0,0 +1,4 @@ +java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory +java.naming.provider.url = tcp://localhost:61616 + +queue.vs.queue = queue4733 diff --git a/05-jms/jms.logger_solution/justfile b/05-jms/jms.logger_solution/justfile new file mode 100644 index 0000000..6009784 --- /dev/null +++ b/05-jms/jms.logger_solution/justfile @@ -0,0 +1,12 @@ +import '../justfile' + +wait_time_ms := "10000" + +consumer-sync: + just exec vs.ConsumerPullNode "{{wait_time_ms}}" +consumer-async-all: + just exec vs.ConsumerCallbackNode "{{wait_time_ms}}" +consumer-async-high: + just exec vs.ConsumerFilteredNode "{{wait_time_ms}}" +producer text prio: + just exec vs.ProducerNode "{{text}} {{prio}}" diff --git a/05-jms/jms.logger_solution/pom.xml b/05-jms/jms.logger_solution/pom.xml new file mode 100644 index 0000000..ffc4116 --- /dev/null +++ b/05-jms/jms.logger_solution/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + jms.logger_solution + 1.0-SNAPSHOT + jar + + + vs + jms + 1.0-SNAPSHOT + + + diff --git a/05-jms/jms.logger_solution/src/main/java/vs/Conf.java b/05-jms/jms.logger_solution/src/main/java/vs/Conf.java new file mode 100644 index 0000000..d57b94a --- /dev/null +++ b/05-jms/jms.logger_solution/src/main/java/vs/Conf.java @@ -0,0 +1,16 @@ +package vs; + +/** + * global configuration for logger service + * + * @author Sandro Leuchter + * + */ +public class Conf { + /** + * String constant for the destination of logger service + * + * @see javax.jms.Destination + */ + public static final String QUEUE = "vs.queue"; +} diff --git a/05-jms/jms.logger_solution/src/main/java/vs/ConsumerCallbackNode.java b/05-jms/jms.logger_solution/src/main/java/vs/ConsumerCallbackNode.java new file mode 100644 index 0000000..427e0f7 --- /dev/null +++ b/05-jms/jms.logger_solution/src/main/java/vs/ConsumerCallbackNode.java @@ -0,0 +1,94 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * asynchronous provider for the log service + * + * @author Sandro Leuchter + * + */ +public class ConsumerCallbackNode implements MessageListener { + private Connection connection; + private Session session; + private MessageConsumer consumer; + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards consumer is ready + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + */ + public ConsumerCallbackNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Destination queue = (Destination) ctx.lookup(Conf.QUEUE); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + this.consumer = this.session.createConsumer(queue); + this.consumer.setMessageListener(this); + this.connection.start(); + } + + /** + * asynchronous message consumption + * + * @see jakarta.jms.MessageListener + */ + @Override + public void onMessage(Message message) { + try { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + String messageText = textMessage.getText(); + String priority = textMessage.getStringProperty("Priority"); + System.out.println(messageText + " [Priority=" + priority + "]"); + } + } catch (JMSException e) { + System.err.println(e); + } + + } + + /** + * main routine and starting point of program + * + * @param args[0] time to wait in ms + */ + public static void main(String[] args) { + long wait = Long.parseLong(args[0]); + ConsumerCallbackNode node = null; + try { + node = new ConsumerCallbackNode(); + Thread.sleep(wait); + } catch (InterruptedException | NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.consumer != null)) { + node.consumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.logger_solution/src/main/java/vs/ConsumerFilteredNode.java b/05-jms/jms.logger_solution/src/main/java/vs/ConsumerFilteredNode.java new file mode 100644 index 0000000..98b45fb --- /dev/null +++ b/05-jms/jms.logger_solution/src/main/java/vs/ConsumerFilteredNode.java @@ -0,0 +1,97 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * asynchronous provider for the log service, flitering only messages with + * String property "Priority"=="high" + * + * @author Sandro Leuchter + * + */ + +public class ConsumerFilteredNode implements MessageListener { + private Connection connection; + private Session session; + private MessageConsumer consumer; + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards consumer is ready filtering only + * messages with String property "Priority" set to "high" + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + */ + public ConsumerFilteredNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Destination queue = (Destination) ctx.lookup(Conf.QUEUE); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + this.consumer = this.session.createConsumer(queue, "Priority='high'"); + this.consumer.setMessageListener(this); + this.connection.start(); + } + + /** + * asynchronous message consumption + * + * @see jakarta.jms.MessageListener + */ + @Override + public void onMessage(Message message) { + try { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + String messageText = textMessage.getText(); + String priority = textMessage.getStringProperty("Priority"); + System.out.println(messageText + " [Priority=" + priority + "]"); + } + } catch (JMSException e) { + System.err.println(e); + } + } + + /** + * main routine and starting point of program + * + * @param args[0] time to wait in ms + */ + public static void main(String[] args) { + long wait = Long.parseLong(args[0]); + ConsumerFilteredNode node = null; + try { + node = new ConsumerFilteredNode(); + Thread.sleep(wait); + } catch (InterruptedException | NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.consumer != null)) { + node.consumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } + +} diff --git a/05-jms/jms.logger_solution/src/main/java/vs/ConsumerPullNode.java b/05-jms/jms.logger_solution/src/main/java/vs/ConsumerPullNode.java new file mode 100644 index 0000000..ec8ffd7 --- /dev/null +++ b/05-jms/jms.logger_solution/src/main/java/vs/ConsumerPullNode.java @@ -0,0 +1,92 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * synchronous provider for the log service + * + * @author Sandro Leuchter + * + */ + +public class ConsumerPullNode { + private Connection connection; + private Session session; + private MessageConsumer consumer; + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards consumer is ready + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + */ + public ConsumerPullNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Destination queue = (Destination) ctx.lookup(Conf.QUEUE); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + this.consumer = this.session.createConsumer(queue); + this.connection.start(); + } + + /** + * synchronously receives the TextMessages in an infinite loop and prints + * payload text to StdOut + * + * @param timeout timeout in ms + * @see jakarta.jms.TextMessage + * @throws JMSException JMS exceptions + */ + public void receiveAndPrintMessages(long timeout) throws JMSException { + Message message; + while ((message = this.consumer.receive(timeout)) != null) { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + String messageText = textMessage.getText(); + System.out.println(messageText); + } + } + } + + /** + * main routine and starting point of program + * + * @param args[0] time to wait in ms + */ + public static void main(String[] args) { + long timeout = Long.parseLong(args[0]); + ConsumerPullNode node = null; + try { + node = new ConsumerPullNode(); + node.receiveAndPrintMessages(timeout); + } catch (NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.consumer != null)) { + node.consumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.logger_solution/src/main/java/vs/ProducerNode.java b/05-jms/jms.logger_solution/src/main/java/vs/ProducerNode.java new file mode 100644 index 0000000..27e4cd1 --- /dev/null +++ b/05-jms/jms.logger_solution/src/main/java/vs/ProducerNode.java @@ -0,0 +1,88 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.MessageProducer; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * client for the log service + * + * @author Sandro Leuchter + * + */ +public class ProducerNode { + private Connection connection; + private Session session; + private MessageProducer producer; + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards producer is ready + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + */ + public ProducerNode() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Destination queue = (Destination) ctx.lookup(Conf.QUEUE); + this.producer = this.session.createProducer(queue); + } + + /** + * creates TextMessage for JMS provider sets String property "Priority" to value + * of parameter priority and sends message to Destination of producer, which is + * configured in Conf.QUEUE + * + * @param text payload of message + * @param priority value of String property "Priority" + * @throws JMSException JMS exceptions + */ + public void sendMessage(String text, String priority) throws JMSException { + TextMessage message = this.session.createTextMessage(); + message.setText(text); + message.setStringProperty("Priority", priority); + this.producer.send(message); + } + + /** + * main routine and starting point of program + * + * @param args[0] time to wait in ms + * @param args[1] of message ("high" or anything else) + */ + public static void main(String[] args) { + String text = args[0]; + String priority = args[1]; + ProducerNode node = null; + try { + node = new ProducerNode(); + node.sendMessage(text, priority); + } catch (NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.producer != null)) { + node.producer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.logger_solution/src/main/resources/jndi.properties b/05-jms/jms.logger_solution/src/main/resources/jndi.properties new file mode 100644 index 0000000..14e1072 --- /dev/null +++ b/05-jms/jms.logger_solution/src/main/resources/jndi.properties @@ -0,0 +1,4 @@ +java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory +java.naming.provider.url = tcp://localhost:61616 + +queue.vs.queue = queue4733 diff --git a/05-jms/jms.revers_solution/justfile b/05-jms/jms.revers_solution/justfile new file mode 100644 index 0000000..8288a5b --- /dev/null +++ b/05-jms/jms.revers_solution/justfile @@ -0,0 +1,8 @@ +import '../justfile' + +requester: + just exec vs.Anfrager "" +replier: + just exec vs.Umdreher "" +replier-reuse: + just exec vs.UmdreherReuseProducers "" diff --git a/05-jms/jms.revers_solution/pom.xml b/05-jms/jms.revers_solution/pom.xml new file mode 100644 index 0000000..edb86b0 --- /dev/null +++ b/05-jms/jms.revers_solution/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + jms.revers_solution + 1.0-SNAPSHOT + jar + + + vs + jms + 1.0-SNAPSHOT + + + diff --git a/05-jms/jms.revers_solution/src/main/java/vs/Anfrager.java b/05-jms/jms.revers_solution/src/main/java/vs/Anfrager.java new file mode 100644 index 0000000..4b87cd5 --- /dev/null +++ b/05-jms/jms.revers_solution/src/main/java/vs/Anfrager.java @@ -0,0 +1,124 @@ +package vs; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.MessageProducer; +import jakarta.jms.Queue; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * requester for String reverter service + * + * @author Sandro Leuchter + * + */ +public class Anfrager implements MessageListener { + private Connection connection; + private Session session; + private MessageProducer producer; + private MessageConsumer consumer; + private Queue replyQueue; + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards producer and a consumer to a temporary + * replyQueue are ready + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + */ + public Anfrager() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue queue = (Queue) ctx.lookup(Conf.QUEUE); + this.producer = this.session.createProducer(queue); + this.replyQueue = this.session.createTemporaryQueue(); + this.consumer = this.session.createConsumer(this.replyQueue); + this.consumer.setMessageListener(this); + this.connection.start(); + } + + /** + * asynchronous message consumption + * + * @see jakarta.jms.MessageListener + */ + @Override + public void onMessage(Message message) { + try { + if (message instanceof TextMessage) { + TextMessage textMessage = (TextMessage) message; + String messageText = textMessage.getText(); + System.out.println(messageText); + } + } catch (JMSException e) { + System.err.println(e); + } + + } + + /** + * creates TextMessage for JMS provider with temporary reply queue set and sends + * it to Destination of producer, which is configured in Conf.QUEUE + * + * @param text text to be sent + * @throws JMSException JMS exceptions + */ + public void sendMessage(String text) throws JMSException { + TextMessage message = this.session.createTextMessage(); + message.setText(text); + message.setJMSReplyTo(this.replyQueue); + this.producer.send(message); + } + + /** + * main routine and starting point of program + * + * @param args not used + */ + public static void main(String[] args) { + Anfrager node = null; + try { + node = new Anfrager(); + BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); + String line; + while (true) { + line = input.readLine(); + node.sendMessage(line); + } + } catch (NamingException | JMSException | IOException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.producer != null)) { + node.producer.close(); + } + if ((node != null) && (node.consumer != null)) { + node.consumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.revers_solution/src/main/java/vs/Conf.java b/05-jms/jms.revers_solution/src/main/java/vs/Conf.java new file mode 100644 index 0000000..78724b4 --- /dev/null +++ b/05-jms/jms.revers_solution/src/main/java/vs/Conf.java @@ -0,0 +1,16 @@ +package vs; + +/** + * global configuration for String reverter service + * + * @author Sandro Leuchter + * + */ +public class Conf { + /** + * String constant for the request destination of String reverter service + * + * @see jakarta.jms.Destination + */ + public static final String QUEUE = "vs.revers"; +} diff --git a/05-jms/jms.revers_solution/src/main/java/vs/Umdreher.java b/05-jms/jms.revers_solution/src/main/java/vs/Umdreher.java new file mode 100644 index 0000000..0669ce0 --- /dev/null +++ b/05-jms/jms.revers_solution/src/main/java/vs/Umdreher.java @@ -0,0 +1,114 @@ +package vs; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.MessageProducer; +import jakarta.jms.Queue; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * replier for String reverter service + * + * @author Sandro Leuchter + * + */ +public class Umdreher implements MessageListener { + private Connection connection; + private Session session; + private MessageConsumer consumer; + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards a consumer is ready + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + */ + public Umdreher() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Queue queue = (Queue) ctx.lookup(Conf.QUEUE); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + this.consumer = this.session.createConsumer(queue); + this.consumer.setMessageListener(this); + this.connection.start(); + } + + /** + * actual implementation of reverse service + * + * @param in String to reverse + * @return reverse of in + */ + public String revers(String in) { + String out = ""; + for (char c : in.toCharArray()) { + out = c + out; + } + return out; + } + + /** + * asynchronous message consumption + * + * @see jakarta.jms.MessageListener + */ + @Override + public void onMessage(Message request) { + try { + if (request instanceof TextMessage) { + TextMessage requestText = (TextMessage) request; + System.out.println("empfangen: " + requestText.getText()); + MessageProducer replyProducer = this.session.createProducer(request.getJMSReplyTo()); + TextMessage reply = this.session.createTextMessage(); + reply.setText(revers(requestText.getText())); + replyProducer.send(reply); + replyProducer.close(); + Thread.sleep(3000); + } + } catch (JMSException | InterruptedException e) { + System.err.println(e); + } + + } + + /** + * main routine and starting point of program + * + * @param args not used + */ + public static void main(String[] args) { + Umdreher node = null; + try { + node = new Umdreher(); + while (true) { + Thread.sleep(1000); + } + } catch (InterruptedException | NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.consumer != null)) { + node.consumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.revers_solution/src/main/java/vs/UmdreherReuseProducers.java b/05-jms/jms.revers_solution/src/main/java/vs/UmdreherReuseProducers.java new file mode 100644 index 0000000..5b5a25a --- /dev/null +++ b/05-jms/jms.revers_solution/src/main/java/vs/UmdreherReuseProducers.java @@ -0,0 +1,127 @@ +package vs; + +import java.util.HashMap; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.Destination; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.MessageProducer; +import jakarta.jms.Queue; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +/** + * replier for String reverter service, reuses MessageProducer objects for + * temporary reply queues to requesters via replyProducers + * + * @author Sandro Leuchter + * + */ +public class UmdreherReuseProducers implements MessageListener { + private Connection connection; + private Session session; + private MessageConsumer consumer; + private HashMap replyProducers = new HashMap<>(); + + /** + * constructor, establishes and starts connection to JMS provider specified in + * JNDI (via jndi.properties), afterwards a consumer is ready + * + * @throws NamingException JNDI exceptions + * @throws JMSException JMS exceptions + */ + public UmdreherReuseProducers() throws NamingException, JMSException { + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Queue queue = (Queue) ctx.lookup(Conf.QUEUE); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + this.consumer = this.session.createConsumer(queue); + this.consumer.setMessageListener(this); + this.connection.start(); + } + + /** + * actual implementation of reverse service + * + * @param in String to reverse + * @return reverse of in + */ + public String revers(String in) { + String out = ""; + for (char c : in.toCharArray()) { + out = c + out; + } + return out; + } + + /** + * asynchronous message consumption + * + * @see jakarta.jms.MessageListener + */ + @Override + public void onMessage(Message request) { + try { + if (request instanceof TextMessage) { + TextMessage requestText = (TextMessage) request; + System.out.println("empfangen: " + requestText.getText()); + Destination replyQueue = request.getJMSReplyTo(); + MessageProducer replyProducer = null; + if (this.replyProducers.containsKey(replyQueue)) { + replyProducer = this.replyProducers.get(replyQueue); + System.out.println("Producer wird wiederverwendet: " + replyQueue.toString()); + } else { + replyProducer = this.session.createProducer(replyQueue); + this.replyProducers.put(replyQueue, replyProducer); + System.out.println("Producer wird neu erzeugt: " + replyQueue.toString()); + } + TextMessage reply = this.session.createTextMessage(); + reply.setText(revers(requestText.getText())); + replyProducer.send(reply); + Thread.sleep(1000); + } + } catch (JMSException | InterruptedException e) { + System.err.println(e); + } + + } + + /** + * main routine and starting point of program + * + * @param args not used + */ + public static void main(String[] args) { + UmdreherReuseProducers node = null; + try { + node = new UmdreherReuseProducers(); + while (true) { + Thread.sleep(1000); + } + } catch (InterruptedException | NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.consumer != null)) { + node.consumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.revers_solution/src/main/resources/jndi.properties b/05-jms/jms.revers_solution/src/main/resources/jndi.properties new file mode 100644 index 0000000..16d2e40 --- /dev/null +++ b/05-jms/jms.revers_solution/src/main/resources/jndi.properties @@ -0,0 +1,6 @@ +java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory +java.naming.provider.url = tcp://localhost:61616 + +queue.vs.revers = queue4736 + + diff --git a/05-jms/jms.tasks_solution/justfile b/05-jms/jms.tasks_solution/justfile new file mode 100644 index 0000000..6596ce6 --- /dev/null +++ b/05-jms/jms.tasks_solution/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +generator: + just exec vs.PasswordCandidateGenerator "" +validator: + just exec vs.PasswordCandidateValidator "" diff --git a/05-jms/jms.tasks_solution/pom.xml b/05-jms/jms.tasks_solution/pom.xml new file mode 100644 index 0000000..0d802a7 --- /dev/null +++ b/05-jms/jms.tasks_solution/pom.xml @@ -0,0 +1,22 @@ + + 4.0.0 + vs + jms.tasks_solution + 1.0-SNAPSHOT + jar + + + vs + jms + 1.0-SNAPSHOT + + + + + jakarta.xml.bind + jakarta.xml.bind-api + 4.0.2 + + + + diff --git a/05-jms/jms.tasks_solution/src/main/java/vs/Conf.java b/05-jms/jms.tasks_solution/src/main/java/vs/Conf.java new file mode 100644 index 0000000..edcfb26 --- /dev/null +++ b/05-jms/jms.tasks_solution/src/main/java/vs/Conf.java @@ -0,0 +1,6 @@ +package vs; + +public class Conf { + public static final String TASK_QUEUE = "vs.tasks"; + public static final String SUCCESS_TOPIC = "vs.tasksSuccess"; +} diff --git a/05-jms/jms.tasks_solution/src/main/java/vs/PasswordCandidateGenerator.java b/05-jms/jms.tasks_solution/src/main/java/vs/PasswordCandidateGenerator.java new file mode 100644 index 0000000..083f3f6 --- /dev/null +++ b/05-jms/jms.tasks_solution/src/main/java/vs/PasswordCandidateGenerator.java @@ -0,0 +1,90 @@ +package vs; + +import java.util.Random; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.MessageProducer; +import jakarta.jms.Queue; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import jakarta.jms.Topic; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +public class PasswordCandidateGenerator implements MessageListener { + private Connection connection; + private Session session; + private MessageProducer producer; + private MessageConsumer consumer; + private Random random; + private boolean stopped = false; + + public PasswordCandidateGenerator() throws NamingException, JMSException { + this.random = new Random(); + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + Queue taskQueue = (Queue) ctx.lookup(Conf.TASK_QUEUE); + this.producer = this.session.createProducer(taskQueue); + Topic successTopic = (Topic) ctx.lookup(Conf.SUCCESS_TOPIC); + this.consumer = this.session.createConsumer(successTopic); + this.consumer.setMessageListener(this); + this.connection.start(); + } + + @Override + public void onMessage(Message message) { + this.stopped = true; + System.out.println("Password gefunden. PasswordCandidateGenerator wird gestoppt."); + } + + public void sendMessage(String text) throws JMSException { + TextMessage message = this.session.createTextMessage(); + message.setText(text); + this.producer.send(message); + } + + public String generatePasswordCandidate(int length) { + StringBuilder buffer = new StringBuilder(length); + final int letterA = 97; + final int letterZ = 122; + for (int i = 0; i < length; i++) { + buffer.append((char) (letterA + (int) (this.random.nextFloat() * ((letterZ - letterA) + 1)))); + } + return buffer.toString(); + } + + public static void main(String[] args) { + PasswordCandidateGenerator node = null; + try { + node = new PasswordCandidateGenerator(); + while (!node.stopped) { + node.sendMessage(node.generatePasswordCandidate(8)); + } + } catch (NamingException | JMSException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.producer != null)) { + node.producer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } + +} diff --git a/05-jms/jms.tasks_solution/src/main/java/vs/PasswordCandidateValidator.java b/05-jms/jms.tasks_solution/src/main/java/vs/PasswordCandidateValidator.java new file mode 100644 index 0000000..23c1451 --- /dev/null +++ b/05-jms/jms.tasks_solution/src/main/java/vs/PasswordCandidateValidator.java @@ -0,0 +1,101 @@ +package vs; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; + +import jakarta.jms.Connection; +import jakarta.jms.ConnectionFactory; +import jakarta.jms.JMSException; +import jakarta.jms.Message; +import jakarta.jms.MessageConsumer; +import jakarta.jms.MessageListener; +import jakarta.jms.Queue; +import jakarta.jms.Session; +import jakarta.jms.TextMessage; +import jakarta.jms.Topic; +import jakarta.xml.bind.DatatypeConverter; +import javax.naming.Context; +import javax.naming.InitialContext; +import javax.naming.NamingException; + +public class PasswordCandidateValidator implements MessageListener { + private static int messageCounter = 0; + private final byte[] target; + private final MessageDigest dig; + private Connection connection; + private Session session; + private MessageConsumer taskConsumer; + private MessageConsumer successConsumer; + private boolean stopped = false; + + public PasswordCandidateValidator(String target) throws NamingException, JMSException, NoSuchAlgorithmException { + this.dig = MessageDigest.getInstance("SHA-256"); + this.target = DatatypeConverter.parseHexBinary(target); + Context ctx = new InitialContext(); + ConnectionFactory factory = (ConnectionFactory) ctx.lookup("ConnectionFactory"); + Queue queue = (Queue) ctx.lookup(Conf.TASK_QUEUE); + this.connection = factory.createConnection(); + this.session = this.connection.createSession(false, Session.AUTO_ACKNOWLEDGE); + this.taskConsumer = this.session.createConsumer(queue); + this.taskConsumer.setMessageListener(this); + Topic successTopic = (Topic) ctx.lookup(Conf.SUCCESS_TOPIC); + this.successConsumer = this.session.createConsumer(successTopic); + this.successConsumer.setMessageListener(new MessageListener() { + @Override + public void onMessage(Message message) { + PasswordCandidateValidator.this.stopped = true; + System.out.println("Password gefunden. PasswordCandidateValidator wird gestoppt."); + + } + }); + this.connection.start(); + } + + @Override + public void onMessage(Message message) { + synchronized (PasswordCandidateValidator.class) { + if (PasswordCandidateValidator.messageCounter++ >= 99) { + System.out.println(System.currentTimeMillis()); + PasswordCandidateValidator.messageCounter = 0; + } + } + if (message instanceof TextMessage) { + TextMessage task = (TextMessage) message; + try { + byte[] hash = this.dig.digest(task.getText().getBytes()); + if (Arrays.equals(hash, this.target)) { + System.out.println("Lösung gefunden: " + task.getText()); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } + + public static void main(String[] args) { + PasswordCandidateValidator node = null; + try { + node = new PasswordCandidateValidator("865ae56c298c677e9d4987fe13268fa915bd041646526c595d293d5448481443"); + while (!node.stopped) { + Thread.sleep(1000); + } + } catch (InterruptedException | NamingException | JMSException | NoSuchAlgorithmException e) { + System.err.println(e); + } finally { + try { + if ((node != null) && (node.taskConsumer != null)) { + node.taskConsumer.close(); + } + if ((node != null) && (node.session != null)) { + node.session.close(); + } + if ((node != null) && (node.connection != null)) { + node.connection.close(); + } + } catch (JMSException e) { + System.err.println(e); + } + } + } +} diff --git a/05-jms/jms.tasks_solution/src/main/resources/jndi.properties b/05-jms/jms.tasks_solution/src/main/resources/jndi.properties new file mode 100644 index 0000000..808fc1d --- /dev/null +++ b/05-jms/jms.tasks_solution/src/main/resources/jndi.properties @@ -0,0 +1,6 @@ +java.naming.factory.initial = org.apache.activemq.jndi.ActiveMQInitialContextFactory +java.naming.provider.url = tcp://localhost:61616 + +queue.vs.tasks = passwordCandidates +topic.vs.tasksSuccess = passwordFound + diff --git a/05-jms/justfile b/05-jms/justfile new file mode 100644 index 0000000..8958e43 --- /dev/null +++ b/05-jms/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +zed: + $VISUAL jms.client jms.client_solution jms.echo jms.echo_solution jms.logger jms.logger_solution jms.revers_solution jms.chat jms.chat_solution jms.tasks_solution diff --git a/05-jms/pom.xml b/05-jms/pom.xml new file mode 100644 index 0000000..199cd59 --- /dev/null +++ b/05-jms/pom.xml @@ -0,0 +1,22 @@ + + 4.0.0 + vs + jms + 1.0-SNAPSHOT + pom + + + vs + parent + 1.0-SNAPSHOT + + + + + org.apache.activemq + activemq-client + 6.1.3 + + + + diff --git a/06-mqtt/.gitignore b/06-mqtt/.gitignore new file mode 100644 index 0000000..6c6cee2 --- /dev/null +++ b/06-mqtt/.gitignore @@ -0,0 +1 @@ +*/paho* diff --git a/06-mqtt/justfile b/06-mqtt/justfile new file mode 100644 index 0000000..815694f --- /dev/null +++ b/06-mqtt/justfile @@ -0,0 +1,8 @@ +import '../justfile' + + +clean-paho: clean + rm -r paho* || true + +zed: + $VISUAL mqtt.logger mqtt.logger_solution mqtt.smarthome_solution diff --git a/06-mqtt/mqtt.code-workspace b/06-mqtt/mqtt.code-workspace new file mode 100644 index 0000000..69e60ae --- /dev/null +++ b/06-mqtt/mqtt.code-workspace @@ -0,0 +1,27 @@ +{ + "folders": [ + { + "name": "1. Logger", + "path": "mqtt.logger", + }, + { + "name": "1. Logger (ML)", + "path": "mqtt.logger_solution", + }, + { + "name": "2. Smarthome (ML)", + "path": "mqtt.smarthome_solution", + }, + ], + "extensions": { + "recommendations": [ + "vscjava.vscode-java-pack", + "ms-azuretools.vscode-docker", + "skellock.just", + ], + }, + "settings": { + "java.dependency.syncWithFolderExplorer": true, + "java.project.explorer.showNonJavaResources": false, + }, +} diff --git a/06-mqtt/mqtt.logger/justfile b/06-mqtt/mqtt.logger/justfile new file mode 100644 index 0000000..a3cacee --- /dev/null +++ b/06-mqtt/mqtt.logger/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +publisher: + just exec vs.Publisher "" +subscriber: + just exec vs.Subscriber "" diff --git a/06-mqtt/mqtt.logger/pom.xml b/06-mqtt/mqtt.logger/pom.xml new file mode 100644 index 0000000..5971e09 --- /dev/null +++ b/06-mqtt/mqtt.logger/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + mqtt.logger + 1.0-SNAPSHOT + jar + + + vs + mqtt + 1.0-SNAPSHOT + + + diff --git a/06-mqtt/mqtt.logger/src/main/java/vs/Conf.java b/06-mqtt/mqtt.logger/src/main/java/vs/Conf.java new file mode 100644 index 0000000..ba8093b --- /dev/null +++ b/06-mqtt/mqtt.logger/src/main/java/vs/Conf.java @@ -0,0 +1,7 @@ +package vs; + +public class Conf { + public static final String TOPIC = "var/mom/mqtt/4711/messages"; + // public static final String BROKER = "tcp://broker.mqttdashboard.com"; + public static final String BROKER = "tcp://localhost:1883"; +} diff --git a/06-mqtt/mqtt.logger/src/main/java/vs/Publisher.java b/06-mqtt/mqtt.logger/src/main/java/vs/Publisher.java new file mode 100644 index 0000000..85d758c --- /dev/null +++ b/06-mqtt/mqtt.logger/src/main/java/vs/Publisher.java @@ -0,0 +1,24 @@ +package vs; + +import java.util.Date; + +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; + +public class Publisher { + public static void main(String... args) { + var clientId = MqttClient.generateClientId(); + try (var client = new MqttClient(Conf.BROKER, clientId)) { + client.connect(); + var message = new MqttMessage(); + for (var i = 0; i < 30; i++) { + var m = "[" + clientId + "] message " + i + ": " + (new Date()).toString(); + message.setPayload(m.getBytes()); + client.publish(Conf.TOPIC, message); + } + } catch (MqttException e) { + System.err.println(e.getMessage()); + } + } +} diff --git a/06-mqtt/mqtt.logger/src/main/java/vs/Subscriber.java b/06-mqtt/mqtt.logger/src/main/java/vs/Subscriber.java new file mode 100644 index 0000000..89cf68f --- /dev/null +++ b/06-mqtt/mqtt.logger/src/main/java/vs/Subscriber.java @@ -0,0 +1,38 @@ +package vs; + +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.MqttCallback; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; + +public class Subscriber { + public static void main(String... args) { + try (var client = new MqttClient(Conf.BROKER, MqttClient.generateClientId())) { + client.setCallback(new MqttCallback() { + + @Override + public void connectionLost(Throwable arg0) { + } + + @Override + public void deliveryComplete(IMqttDeliveryToken arg0) { + } + + @Override + public void messageArrived(String topic, MqttMessage m) throws Exception { + System.out.println("Topic: " + topic + ", Message: " + m.toString()); + } + }); + client.connect(); + client.subscribe(Conf.TOPIC); + while (true) { + Thread.sleep(1000); + } + } catch (MqttException e) { + System.err.println(e.getMessage()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/06-mqtt/mqtt.logger_solution/justfile b/06-mqtt/mqtt.logger_solution/justfile new file mode 100644 index 0000000..a3cacee --- /dev/null +++ b/06-mqtt/mqtt.logger_solution/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +publisher: + just exec vs.Publisher "" +subscriber: + just exec vs.Subscriber "" diff --git a/06-mqtt/mqtt.logger_solution/pom.xml b/06-mqtt/mqtt.logger_solution/pom.xml new file mode 100644 index 0000000..9d6bfab --- /dev/null +++ b/06-mqtt/mqtt.logger_solution/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + mqtt.logger_solution + 1.0-SNAPSHOT + jar + + + vs + mqtt + 1.0-SNAPSHOT + + + diff --git a/06-mqtt/mqtt.logger_solution/src/main/java/vs/Conf.java b/06-mqtt/mqtt.logger_solution/src/main/java/vs/Conf.java new file mode 100644 index 0000000..d5f1466 --- /dev/null +++ b/06-mqtt/mqtt.logger_solution/src/main/java/vs/Conf.java @@ -0,0 +1,16 @@ +package vs; + +public class Conf { + /** + * topic for the MQTT log service + */ + public static final String TOPIC = "vs/mqtt/topic/4715"; + + /** + * broker for the MQTT log service + */ + //public static final String BROKER = "tcp://localhost:1883"; // alternatively to + // HiveMQ + public static final String BROKER = "tcp://broker.mqttdashboard.com"; + // alternatively to ApacheMQ +} diff --git a/06-mqtt/mqtt.logger_solution/src/main/java/vs/Publisher.java b/06-mqtt/mqtt.logger_solution/src/main/java/vs/Publisher.java new file mode 100644 index 0000000..d00b941 --- /dev/null +++ b/06-mqtt/mqtt.logger_solution/src/main/java/vs/Publisher.java @@ -0,0 +1,41 @@ +package vs; + +import java.util.Date; + +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; + +/** + * client for the log service + * + * @author Sandro Leuchter + * + */ +public class Publisher { + + /** + * main routine and starting point of program + * + * @param args not used + */ + public static void main(String... args) { + var clientId = MqttClient.generateClientId(); + try (var client = new MqttClient(Conf.BROKER, clientId)) { + var options = new MqttConnectOptions(); + options.setWill(Conf.TOPIC, "LWT: Das war das Ende. Hilfe!".getBytes(), 2, false); + client.connect(options); + var message = new MqttMessage(); + for (var i = 29; i >= 0; i--) { + var m = "[" + clientId + "] message " + i + " (" + 29 / i + "): " + (new Date()).toString(); + message.setPayload(m.getBytes()); + message.setRetained(true); + client.publish(Conf.TOPIC, message); + } + client.disconnect(); + } catch (MqttException e) { + System.err.println(e.getMessage()); + } + } +} diff --git a/06-mqtt/mqtt.logger_solution/src/main/java/vs/Subscriber.java b/06-mqtt/mqtt.logger_solution/src/main/java/vs/Subscriber.java new file mode 100644 index 0000000..440f00f --- /dev/null +++ b/06-mqtt/mqtt.logger_solution/src/main/java/vs/Subscriber.java @@ -0,0 +1,52 @@ +package vs; + +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.MqttCallback; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; +import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; + +/** + * asynchronous subscriber for the log service + * + * @author Sandro Leuchter + * + */ +public class Subscriber { + + /** + * main routine and starting point of program + * + * @param args not used + */ + public static void main(String... args) { + try (var client = new MqttClient(Conf.BROKER, MqttClient.generateClientId())) { + client.setCallback(new MqttCallback() { + + @Override + public void connectionLost(Throwable arg0) { + } + + @Override + public void deliveryComplete(IMqttDeliveryToken arg0) { + } + + @Override + public void messageArrived(String topic, MqttMessage m) throws Exception { + System.out.println("Topic: " + topic + ", Message: " + m.toString()); + } + }); + client.connect(); + client.subscribe(Conf.TOPIC); + while (true) { + Thread.sleep(1000); + } + } catch (MqttException e) { + System.err.println(e.getMessage()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } +} diff --git a/06-mqtt/mqtt.smarthome_solution/justfile b/06-mqtt/mqtt.smarthome_solution/justfile new file mode 100644 index 0000000..5b3b4c3 --- /dev/null +++ b/06-mqtt/mqtt.smarthome_solution/justfile @@ -0,0 +1,20 @@ +import '../justfile' + +scenario: + just sensor-self-descr groundfloor livingroom temperature 20.0 & + just sensor-self-descr groundfloor library temperature 16.0 & + just sensor-self-descr groundfloor kitchen temperature 24.0 & + just sensor-self-descr upstairs masterbedroom temperature 17.0 & + just plotter groundfloor temperature & + just logger + +sensor floor room type initial_double: + just exec vs.Sensor "{{floor}} {{room}} {{type}} {{initial_double}}" +sensor-self-descr floor room type initial_double: + just exec vs.Sensor "{{floor}} {{room}} {{type}} {{initial_double}}" +alarmer floor room type threshold_double: + just exec vs.AlarmSubscriber "{{floor}} {{room}} {{type}} {{threshold_double}}" +plotter floor type: + just exec vs.FloorPlotter "{{floor}} {{type}}" +logger: + just exec vs.LoggingSubscriber "" diff --git a/06-mqtt/mqtt.smarthome_solution/pom.xml b/06-mqtt/mqtt.smarthome_solution/pom.xml new file mode 100644 index 0000000..535d7d3 --- /dev/null +++ b/06-mqtt/mqtt.smarthome_solution/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + mqtt.smarthome_solution + 1.0-SNAPSHOT + jar + + + vs + mqtt + 1.0-SNAPSHOT + + + diff --git a/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/AlarmSubscriber.java b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/AlarmSubscriber.java new file mode 100644 index 0000000..b234c77 --- /dev/null +++ b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/AlarmSubscriber.java @@ -0,0 +1,76 @@ +package vs; + +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.MqttCallback; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; + +/** + * client for the Smart Home application: prints out alarm messages to the + * console if trigger condition in topic is detected + * + * @author Sandro Leuchter + * + */ +public class AlarmSubscriber { + /** + * trigger alarm if observation > threshold + */ + static double threshold; + + /** + * main routine and starting point of program: subscribes to topic + * Conf.TOPICSTART/args[0]/args[1]/args[2] i.e. a specific sensor and + * prints messages to console if observation > threshold + * + * @param args[0] floor where sensor is located + * @param args[1] room where sensor is located + * @param args[2] type of sensor + * @param args[3] threshold + * @throws MqttException Paho library exceptions that have something to do with MQTT + */ + public static void main(String[] args) throws MqttException { + String topic = Conf.TOPICSTART + "/" + args[0] + "/" + args[1] + "/" + args[2]; + threshold = Double.valueOf(args[3]); + MqttClient client = new MqttClient(Conf.BROKER, MqttClient.generateClientId()); + client.setCallback(new MqttCallback() { + @Override + public void messageArrived(String topic, MqttMessage m) throws Exception { + try { + double observation = Double.valueOf(m.toString()); + if (observation > threshold) { + System.out.println("ALARM: " + topic + ": " + m); + } + } catch (NumberFormatException e) { + System.out.println(m); // message is not a sensor + // observation: will be printed + // instead + } + } + + @Override + public void deliveryComplete(IMqttDeliveryToken arg0) { + } + + @Override + public void connectionLost(Throwable arg0) { + } + }); + client.connect(); + client.subscribe(topic); + try { + while (true) { + Thread.sleep(1000); + } + } catch (InterruptedException e) { + System.err.println(e.getMessage()); + } finally { + try { + client.disconnect(); + } catch (MqttException e) { + // unrecoverable + } + } + } +} diff --git a/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/Conf.java b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/Conf.java new file mode 100644 index 0000000..a18741f --- /dev/null +++ b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/Conf.java @@ -0,0 +1,22 @@ +package vs; + +public class Conf { + /** + * beginning topic level topic for the Smart Home Application + */ + public static final String TOPICSTART = "SmartHome4751"; // should be made + // unique + + /** + * broker for the Smart Home Application + */ + public static final String BROKER = "tcp://localhost:1883"; // alternatively + // to HiveMQ + // public static final String BROKER = "tcp://broker.mqttdashboard.com"; + // alternatively to ApacheMQ + + /** + * MQTT quality of service level for the Smart Home Application sensor messages + */ + public static final int QOS = 2; +} diff --git a/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/FloorPlotter.java b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/FloorPlotter.java new file mode 100644 index 0000000..25e996d --- /dev/null +++ b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/FloorPlotter.java @@ -0,0 +1,141 @@ +package vs; + +import java.awt.Color; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.MqttCallback; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; + +/** + * client for the Smart Home application: plots graphically sensor observations + * + * @author Sandro Leuchter + * + */ +public class FloorPlotter extends Frame { + /** + * + */ + private static final long serialVersionUID = 8554414803806269611L; + private static FloorPlotter plot; + private static final int MAXX = 1000; + private static final int MAXY = 600; + private static Map topicColors = new HashMap<>(); + private static Color[] colors = { Color.red, Color.blue, Color.black, Color.cyan }; + private static int lastColor = 0; + private static Color[][] plotdata = new Color[MAXX][MAXY]; + private static long start = System.currentTimeMillis(); + private static String sensorType; + private static String floor; + + /** + * main routine and starting point of program. subscribes to all messages + * (sensor observations) on topic Conf.TOPICSTART/args[0]/+/args[1] + * i.e. all observations from a certain sensor type in all rooms on a certain + * floor. + * + * @param args[0] floor where sensor is located + * @param args[1] type of sensor + * @throws MqttException Paho library exceptions that have something to do with + * MQTT + * + */ + public static void main(String[] args) throws MqttException { + floor = args[0]; + sensorType = args[1]; + String topic = Conf.TOPICSTART + "/" + floor + "/+/" + sensorType; + + plot = new FloorPlotter(); + plot.setTitle("Floor Plot: " + floor); + plot.setSize(MAXX, MAXY); + plot.setVisible(true); + + MqttClient client = new MqttClient(Conf.BROKER, MqttClient.generateClientId()); + client.setCallback(new MqttCallback() { + + @Override + public void connectionLost(Throwable arg0) { + } + + @Override + public void deliveryComplete(IMqttDeliveryToken arg0) { + } + + @Override + public void messageArrived(String topic, MqttMessage m) throws Exception { + int x = (int) ((System.currentTimeMillis() - start) / 1000.0); + try { + double messwert = Double.valueOf(m.toString()); + int y = (int) Math.round(100.0 + (messwert * 10.0)); + String[] topicLevels = topic.split("/"); + String etage = topicLevels[1]; + String raum = topicLevels[2]; + if (!topicColors.containsKey(raum)) { + topicColors.put(raum, colors[lastColor++]); + System.out + .println("Dem Plot der Etage " + etage + " wurde der " + sensorType + "-Sensor im Raum " + + raum + " in der Farbe " + topicColors.get(raum).toString() + " hinzugefügt."); + } + // System.out.format("(%3d, %3d) <- %2.2f, %s\n", x, y, + // Double.valueOf(m.toString()), raum); + plotdata[x][y] = topicColors.get(raum); + plot.repaint(); + } catch (NumberFormatException e) { + System.out.println(m); // message is not an observation: + // will be printed out instead + } + } + }); + client.connect(); + client.subscribe(topic); + try { + while (true) { + Thread.sleep(1000); + } + } catch (InterruptedException e) { + System.err.println(e.getMessage()); + } finally { + try { + client.disconnect(); + } catch (MqttException e) { + // unrecoverable + } + } + } + + /** + * constructor. initializes window and adds WindowListener for close event + */ + public FloorPlotter() { + addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent ev) { + dispose(); + System.exit(0); + } + }); + } + + /** + * @see java.awt.Frame#paint(Graphics) + */ + @Override + public void paint(Graphics g) { + for (int x = 0; x < MAXX; x++) { + for (int y = 0; y < MAXY; y++) { + if (plotdata[x][y] != null) { + g.setColor(plotdata[x][y]); + g.fillOval(x, y, 3, 3); + } + } + } + } +} diff --git a/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/LoggingSubscriber.java b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/LoggingSubscriber.java new file mode 100644 index 0000000..e9487da --- /dev/null +++ b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/LoggingSubscriber.java @@ -0,0 +1,60 @@ +package vs; + +import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; +import org.eclipse.paho.client.mqttv3.MqttCallback; +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; + +/** + * client for the Smart Home application: logs sensor observations + * + * @author Sandro Leuchter + * + */ +public class LoggingSubscriber { + + /** + * main routine and starting point of program. subscribe to topic + * Conf.TOPICSTART/# i.e. all messages in the Smart Home Application + * + * @param args not used + * @throws MqttException Paho library exceptions that have something to do with + * MQTT + * + */ + public static void main(String[] args) throws MqttException { + MqttClient client; + client = new MqttClient(Conf.BROKER, MqttClient.generateClientId()); + client.setCallback(new MqttCallback() { + + @Override + public void connectionLost(Throwable arg0) { + } + + @Override + public void deliveryComplete(IMqttDeliveryToken arg0) { + } + + @Override + public void messageArrived(String topic, MqttMessage m) throws Exception { + System.out.println(topic + ": " + m.toString()); + } + }); + client.connect(); + client.subscribe(Conf.TOPICSTART + "/#"); + try { + while (true) { + Thread.sleep(1000); + } + } catch (InterruptedException e) { + System.err.println(e.getMessage()); + } finally { + try { + client.disconnect(); + } catch (MqttException e) { + // unrecoverable + } + } + } +} diff --git a/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/Sensor.java b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/Sensor.java new file mode 100644 index 0000000..9e8825b --- /dev/null +++ b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/Sensor.java @@ -0,0 +1,77 @@ +package vs; + +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; + +/** + * client for the Smart Home application: sensor simulator + * + * @author Sandro Leuchter + * + */ +public class Sensor { + /** + * topic to which this sensor publishes its observations + */ + static String topic; + /** + * floor where sensor is located + */ + static String floor; + /** + * room where sensor is located + */ + static String room; + /** + * type of sensor + */ + static String sensorType; + /** + * unique name of client + */ + static String clientId = MqttClient.generateClientId(); + + /** + * main routine and starting point of program + * + * @param args[0] floor where sensor is located + * @param args[1] room where sensor is located + * @param args[2] type of sensor + * @param args[3] initial observation of sensor + * @throws MqttException Paho library exceptions that have something to do with + * MQTT + * + */ + public static void main(String[] args) throws MqttException { + floor = args[0]; + room = args[1]; + sensorType = args[2]; + topic = Conf.TOPICSTART + "/" + floor + "/" + room + "/" + sensorType; + double lastObservation = Double.valueOf(args[3]); + MqttClient client; + client = new MqttClient(Conf.BROKER, clientId); + client.connect(); + MqttMessage message = new MqttMessage(); + try { + while (true) { + if (Math.random() > 0.5) { // randomly +/- 0.1 + lastObservation += 0.1; + } else { + lastObservation -= 0.1; + } + message.setPayload(String.valueOf(lastObservation).getBytes()); + client.publish(topic, message); + Thread.sleep((int) (Math.random() * 1000)); // < 1 s waiting + } + } catch (InterruptedException e) { + System.err.println(e.getMessage()); + } finally { + try { + client.disconnect(); + } catch (MqttException e) { + // unrecoverable + } + } + } +} diff --git a/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/SensorSelfDescribung.java b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/SensorSelfDescribung.java new file mode 100644 index 0000000..7b4b942 --- /dev/null +++ b/06-mqtt/mqtt.smarthome_solution/src/main/java/vs/SensorSelfDescribung.java @@ -0,0 +1,93 @@ +package vs; + +import org.eclipse.paho.client.mqttv3.MqttClient; +import org.eclipse.paho.client.mqttv3.MqttConnectOptions; +import org.eclipse.paho.client.mqttv3.MqttException; +import org.eclipse.paho.client.mqttv3.MqttMessage; + +/** + * client for the Smart Home application: sensor simulator + * + * @author Sandro Leuchter + * + */ +public class SensorSelfDescribung { + /** + * topic to which this sensor publishes its observations + */ + static String topic; + /** + * floor where sensor is located + */ + static String floor; + /** + * room where sensor is located + */ + static String room; + /** + * type of sensor + */ + static String sensorType; + /** + * unique name of client + */ + static String clientId = MqttClient.generateClientId(); + + /** + * get the description of sensor (class) + * + * @return description of sensor + */ + public static String getDescription() { + return clientId + "\n Topic: " + topic + "\n Type: " + sensorType + "\n Location: " + floor + "." + room; + } + + /** + * main routine and starting point of program + * + * @param args[0] floor where sensor is located + * @param args[1] room where sensor is located + * @param args[2] type of sensor + * @param args[3] initial observation of sensor + * @throws MqttException Paho library exceptions that have something to do with + * MQTT + * + */ + public static void main(String[] args) throws MqttException { + floor = args[0]; + room = args[1]; + sensorType = args[2]; + topic = Conf.TOPICSTART + "/" + floor + "/" + room + "/" + sensorType; + double lastObservation = Double.valueOf(args[3]); + MqttClient client; + client = new MqttClient(Conf.BROKER, clientId); + MqttConnectOptions options = new MqttConnectOptions(); + options.setWill(topic, ("deregistering sensor: " + getDescription()).getBytes(), Conf.QOS, true); + client.connect(options); + MqttMessage selfIntroduction = new MqttMessage(); + selfIntroduction.setRetained(true); + selfIntroduction.setPayload(("registering sensor: " + getDescription()).getBytes()); + client.publish(topic, selfIntroduction); + MqttMessage message = new MqttMessage(); + try { + while (true) { + if (Math.random() > 0.5) { // randomly +/- 0.1 + lastObservation += 0.1; + } else { + lastObservation -= 0.1; + } + message.setPayload(String.valueOf(lastObservation).getBytes()); + client.publish(topic, message); + Thread.sleep((int) (Math.random() * 1000)); // < 1 s waiting + } + } catch (InterruptedException e) { + System.err.println(e.getMessage()); + } finally { + try { + client.disconnect(); + } catch (MqttException e) { + // unrecoverable + } + } + } +} diff --git a/06-mqtt/pom.xml b/06-mqtt/pom.xml new file mode 100644 index 0000000..6f38cd5 --- /dev/null +++ b/06-mqtt/pom.xml @@ -0,0 +1,21 @@ + + 4.0.0 + vs + mqtt + 1.0-SNAPSHOT + pom + + + vs + parent + 1.0-SNAPSHOT + + + + + org.eclipse.paho + org.eclipse.paho.client.mqttv3 + 1.2.5 + + + diff --git a/07-http/http.webserver/justfile b/07-http/http.webserver/justfile new file mode 100644 index 0000000..3d38c15 --- /dev/null +++ b/07-http/http.webserver/justfile @@ -0,0 +1,6 @@ +import '../../justfile' + +server: + just exec vs.WebServer "" +client: + firefox http://localhost:8000/form.html diff --git a/07-http/http.webserver/pom.xml b/07-http/http.webserver/pom.xml new file mode 100644 index 0000000..876a94a --- /dev/null +++ b/07-http/http.webserver/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + http.webserver + 1.0-SNAPSHOT + jar + + + vs + http + 1.0-SNAPSHOT + + diff --git a/07-http/http.webserver/src/main/java/vs/WebServer.java b/07-http/http.webserver/src/main/java/vs/WebServer.java new file mode 100644 index 0000000..0301600 --- /dev/null +++ b/07-http/http.webserver/src/main/java/vs/WebServer.java @@ -0,0 +1,59 @@ +package vs; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; + +public class WebServer { + public void start() { + try (ServerSocket serverSocket = new ServerSocket(8000)) { + System.out.println("WebServer gestartet ..."); + while (true) { + Socket socket = serverSocket.accept(); + new WebThread(socket).start(); + } + } catch (IOException e) { + System.err.println(e); + } + } + + private class WebThread extends Thread { + private Socket socket; + + public WebThread(Socket socket) { + this.socket = socket; + } + + @Override + public void run() { + SocketAddress socketAddress = socket.getRemoteSocketAddress(); + System.err.println("Verbindung zu " + socketAddress + " aufgebaut"); + try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); + PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { + String input; + while (null != (input = in.readLine())) { + System.out.println(input); + } + } catch (Exception e) { + System.err.println(e); + } finally { + try { + socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.err.println("Verbindung zu " + socketAddress + " abgebaut"); + } + } + + } + + public static void main(String[] args) { + new WebServer().start(); + } +} diff --git a/07-http/http.webserver/src/main/resources/docs/form.html b/07-http/http.webserver/src/main/resources/docs/form.html new file mode 100644 index 0000000..5956718 --- /dev/null +++ b/07-http/http.webserver/src/main/resources/docs/form.html @@ -0,0 +1,14 @@ + + +
+Latein
+Hochschule Mannheim
+unknown
+ +
+
+/http/WebServer.java
+../src/var/web/http/WebServer.java
+verteilteArchitekturen.html
+ + \ No newline at end of file diff --git a/07-http/http.webserver/src/main/resources/docs/img/by-nc-sa1.png b/07-http/http.webserver/src/main/resources/docs/img/by-nc-sa1.png new file mode 100644 index 0000000..b9a5553 Binary files /dev/null and b/07-http/http.webserver/src/main/resources/docs/img/by-nc-sa1.png differ diff --git a/07-http/http.webserver_solution/justfile b/07-http/http.webserver_solution/justfile new file mode 100644 index 0000000..3d38c15 --- /dev/null +++ b/07-http/http.webserver_solution/justfile @@ -0,0 +1,6 @@ +import '../../justfile' + +server: + just exec vs.WebServer "" +client: + firefox http://localhost:8000/form.html diff --git a/07-http/http.webserver_solution/pom.xml b/07-http/http.webserver_solution/pom.xml new file mode 100644 index 0000000..8db8ef0 --- /dev/null +++ b/07-http/http.webserver_solution/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + http.webserver_solution + 1.0-SNAPSHOT + jar + + + vs + http + 1.0-SNAPSHOT + + diff --git a/07-http/http.webserver_solution/src/main/java/vs/WebServer.java b/07-http/http.webserver_solution/src/main/java/vs/WebServer.java new file mode 100644 index 0000000..8797f3c --- /dev/null +++ b/07-http/http.webserver_solution/src/main/java/vs/WebServer.java @@ -0,0 +1,123 @@ +package vs; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; + +enum Type { + REQ1, REQ2, FILE, UNKNOWN; +} + +public class WebServer { + public void start() { + try (ServerSocket serverSocket = new ServerSocket(8000)) { + System.out.println("WebServer gestartet ..."); + while (true) { + Socket socket = serverSocket.accept(); + new WebThread(socket).start(); + } + } catch (IOException e) { + System.err.println(e); + } + } + + private class WebThread extends Thread { + private Socket socket; + + public WebThread(Socket socket) { + this.socket = socket; + } + + @Override + public void run() { + SocketAddress socketAddress = this.socket.getRemoteSocketAddress(); + System.err.println("Verbindung zu " + socketAddress + " aufgebaut"); + try (BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); + PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true)) { + String input; + Type type = Type.UNKNOWN; + String fileName = ""; + input = in.readLine(); + if (input.matches("^GET /cgi/choice\\?selection=Latein HTTP/\\d\\.\\d$")) { + type = Type.REQ1; + } else if (input.matches("^GET /cgi/choice\\?selection=HS-Mannheim HTTP/\\d\\.\\d$")) { + type = Type.REQ2; + } else if (input.matches("^GET (.+) HTTP/\\d\\.\\d$")) { + type = Type.FILE; + fileName = input.substring(4); // "GET " abschneiden + fileName = fileName.substring(0, fileName.length() - 9); // " HTTPx.x" abschneiden + } else { + type = Type.UNKNOWN; + } + while (!"".equals(input = in.readLine())) { + System.out.println(input); + } + File file = null; + if (type == Type.FILE) { + file = new File("target/classes/docs" + fileName); + if (!file.canRead()) { + type = Type.UNKNOWN; + } + } + switch (type) { + case REQ1: + out.printf("HTTP/1.1 200 OK\r\n"); + out.printf("Content-Type: text/html; charset=utf-8\r\n"); + out.printf("\r\n"); + out.printf("Non scholae sed vitae discimus.\r\n"); + break; + case REQ2: + out.printf("HTTP/1.1 200 OK\r\n"); + out.printf("Content-Type: text/html; charset=utf-8\r\n"); + out.printf("\r\n"); + out.printf( + "Die Hochschule Mannheim ist bekannt für eine praxisnahe und theoretisch fundierte Ausbildung\r\n"); + break; + case FILE: + out.printf("HTTP/1.1 200 OK\r\n"); + if ("html".equalsIgnoreCase(fileName.substring(fileName.length() - 4))) { + out.printf("Content-Type: text/html; charset=utf-8\r\n"); + } else { + out.printf("Content-Type: application/octet-stream\r\n"); + } + out.printf("\r\n"); + FileInputStream fileIn = new FileInputStream(file); + OutputStream outBin = this.socket.getOutputStream(); + int c; + while ((c = fileIn.read()) != -1) { + outBin.write(c); + } + outBin.close(); + break; + case UNKNOWN: + out.printf("HTTP/1.1 404 Not Found\r\n"); + out.printf("Content-Type: text/plain; charset=utf-8\r\n"); + out.printf("\r\n"); + out.printf("nicht gefunden\r\n"); + break; + } + } catch (Exception e) { + System.err.println(e); + } finally { + try { + this.socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.err.println("Verbindung zu " + socketAddress + " abgebaut"); + } + } + + } + + public static void main(String[] args) { + new WebServer().start(); + } +} diff --git a/07-http/http.webserver_solution/src/main/resources/docs/form.html b/07-http/http.webserver_solution/src/main/resources/docs/form.html new file mode 100644 index 0000000..e7d8e85 --- /dev/null +++ b/07-http/http.webserver_solution/src/main/resources/docs/form.html @@ -0,0 +1,13 @@ + + +
+Latein
+Hochschule Mannheim
+unknown
+ +
+
+/http/WebServer.java
+verteilteArchitekturen.html
+ + diff --git a/07-http/http.webserver_solution/src/main/resources/docs/http/WebServer.java b/07-http/http.webserver_solution/src/main/resources/docs/http/WebServer.java new file mode 100644 index 0000000..8797f3c --- /dev/null +++ b/07-http/http.webserver_solution/src/main/resources/docs/http/WebServer.java @@ -0,0 +1,123 @@ +package vs; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketAddress; + +enum Type { + REQ1, REQ2, FILE, UNKNOWN; +} + +public class WebServer { + public void start() { + try (ServerSocket serverSocket = new ServerSocket(8000)) { + System.out.println("WebServer gestartet ..."); + while (true) { + Socket socket = serverSocket.accept(); + new WebThread(socket).start(); + } + } catch (IOException e) { + System.err.println(e); + } + } + + private class WebThread extends Thread { + private Socket socket; + + public WebThread(Socket socket) { + this.socket = socket; + } + + @Override + public void run() { + SocketAddress socketAddress = this.socket.getRemoteSocketAddress(); + System.err.println("Verbindung zu " + socketAddress + " aufgebaut"); + try (BufferedReader in = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); + PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true)) { + String input; + Type type = Type.UNKNOWN; + String fileName = ""; + input = in.readLine(); + if (input.matches("^GET /cgi/choice\\?selection=Latein HTTP/\\d\\.\\d$")) { + type = Type.REQ1; + } else if (input.matches("^GET /cgi/choice\\?selection=HS-Mannheim HTTP/\\d\\.\\d$")) { + type = Type.REQ2; + } else if (input.matches("^GET (.+) HTTP/\\d\\.\\d$")) { + type = Type.FILE; + fileName = input.substring(4); // "GET " abschneiden + fileName = fileName.substring(0, fileName.length() - 9); // " HTTPx.x" abschneiden + } else { + type = Type.UNKNOWN; + } + while (!"".equals(input = in.readLine())) { + System.out.println(input); + } + File file = null; + if (type == Type.FILE) { + file = new File("target/classes/docs" + fileName); + if (!file.canRead()) { + type = Type.UNKNOWN; + } + } + switch (type) { + case REQ1: + out.printf("HTTP/1.1 200 OK\r\n"); + out.printf("Content-Type: text/html; charset=utf-8\r\n"); + out.printf("\r\n"); + out.printf("Non scholae sed vitae discimus.\r\n"); + break; + case REQ2: + out.printf("HTTP/1.1 200 OK\r\n"); + out.printf("Content-Type: text/html; charset=utf-8\r\n"); + out.printf("\r\n"); + out.printf( + "Die Hochschule Mannheim ist bekannt für eine praxisnahe und theoretisch fundierte Ausbildung\r\n"); + break; + case FILE: + out.printf("HTTP/1.1 200 OK\r\n"); + if ("html".equalsIgnoreCase(fileName.substring(fileName.length() - 4))) { + out.printf("Content-Type: text/html; charset=utf-8\r\n"); + } else { + out.printf("Content-Type: application/octet-stream\r\n"); + } + out.printf("\r\n"); + FileInputStream fileIn = new FileInputStream(file); + OutputStream outBin = this.socket.getOutputStream(); + int c; + while ((c = fileIn.read()) != -1) { + outBin.write(c); + } + outBin.close(); + break; + case UNKNOWN: + out.printf("HTTP/1.1 404 Not Found\r\n"); + out.printf("Content-Type: text/plain; charset=utf-8\r\n"); + out.printf("\r\n"); + out.printf("nicht gefunden\r\n"); + break; + } + } catch (Exception e) { + System.err.println(e); + } finally { + try { + this.socket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + System.err.println("Verbindung zu " + socketAddress + " abgebaut"); + } + } + + } + + public static void main(String[] args) { + new WebServer().start(); + } +} diff --git a/07-http/http.webserver_solution/src/main/resources/docs/img/by-nc-sa1.png b/07-http/http.webserver_solution/src/main/resources/docs/img/by-nc-sa1.png new file mode 100644 index 0000000..b9a5553 Binary files /dev/null and b/07-http/http.webserver_solution/src/main/resources/docs/img/by-nc-sa1.png differ diff --git a/07-http/pom.xml b/07-http/pom.xml new file mode 100644 index 0000000..702ec96 --- /dev/null +++ b/07-http/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + http + 1.0-SNAPSHOT + pom + + + vs + parent + 1.0-SNAPSHOT + + + diff --git a/08-servlet/justfile b/08-servlet/justfile new file mode 100644 index 0000000..dbba21b --- /dev/null +++ b/08-servlet/justfile @@ -0,0 +1,7 @@ +import '../justfile' + +serve: war + mvn jetty:run +war: + mvn war:war + touch src/main/webapp/index.html diff --git a/08-servlet/pom.xml b/08-servlet/pom.xml new file mode 100644 index 0000000..29ea3d3 --- /dev/null +++ b/08-servlet/pom.xml @@ -0,0 +1,37 @@ + + 4.0.0 + vs + servlet + 1.0-SNAPSHOT + pom + + + vs + parent + 1.0-SNAPSHOT + + + + + jakarta.servlet + jakarta.servlet-api + 6.0.0 + provided + + + + + + + org.eclipse.jetty.ee10 + jetty-ee10-maven-plugin + 12.0.14 + + + org.apache.maven.plugins + maven-war-plugin + 3.4.0 + + + + diff --git a/08-servlet/servlet.hello/justfile b/08-servlet/servlet.hello/justfile new file mode 100644 index 0000000..f8066da --- /dev/null +++ b/08-servlet/servlet.hello/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + firefox http://localhost:8080/ diff --git a/08-servlet/servlet.hello/pom.xml b/08-servlet/servlet.hello/pom.xml new file mode 100644 index 0000000..4bd885b --- /dev/null +++ b/08-servlet/servlet.hello/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + servlet.hello + 1.0-SNAPSHOT + war + + + vs + servlet + 1.0-SNAPSHOT + + + diff --git a/08-servlet/servlet.hello/src/main/java/vs/HelloWorld.java b/08-servlet/servlet.hello/src/main/java/vs/HelloWorld.java new file mode 100644 index 0000000..e1970fa --- /dev/null +++ b/08-servlet/servlet.hello/src/main/java/vs/HelloWorld.java @@ -0,0 +1,84 @@ +package vs; + +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Enumeration; + +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +/** + * Servlet implementation class HelloWorld + */ +@WebServlet(urlPatterns = { "/HelloWorld", "/vs", "/hello" }) +public class HelloWorld extends HttpServlet { + /** + * + */ + private static final long serialVersionUID = -3570303195316235943L; + private Integer counter = 0; + + /** + * @see HttpServlet#HttpServlet() + */ + public HelloWorld() { + super(); + } + + /** + * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse + * response) + */ + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println("HTTPRequest Inhalte ausgeben"); + // Header + out.println("

Header

    "); + Enumeration headerNames = request.getHeaderNames(); + while (headerNames.hasMoreElements()) { + String headerName = headerNames.nextElement(); + out.println("
  • " + headerName + ": " + request.getHeader(headerName)); + } + out.println("
"); + + // Parameter + out.println("

Parameter

    "); + Enumeration parameterNames = request.getParameterNames(); + while (parameterNames.hasMoreElements()) { + String parameterName = parameterNames.nextElement(); + out.println("
  • " + parameterName + ": " + request.getParameter(parameterName)); + } + out.println("
"); + + // Zugriffszähler + out.println("

Zugriffszähler

    "); + synchronized (this.counter) { + if (this.counter != null) { + this.counter += 1; + } else { + this.counter = 1; + } + out.println("

    dies war Aufruf Nr. " + this.counter); + } + + out.println(""); + out.flush(); + } + + /** + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse + * response) + */ + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + doGet(request, response); + } + +} diff --git a/08-servlet/servlet.hello/src/main/webapp/META-INF/MANIFEST.MF b/08-servlet/servlet.hello/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/08-servlet/servlet.hello/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/08-servlet/servlet.hello/src/main/webapp/WEB-INF/web.xml b/08-servlet/servlet.hello/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..cf3d638 --- /dev/null +++ b/08-servlet/servlet.hello/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,12 @@ + + + VAR-Servlets + + index.html + index.htm + index.jsp + default.html + default.htm + default.jsp + + \ No newline at end of file diff --git a/08-servlet/servlet.hello/src/main/webapp/dir/form1.html b/08-servlet/servlet.hello/src/main/webapp/dir/form1.html new file mode 100644 index 0000000..0714185 --- /dev/null +++ b/08-servlet/servlet.hello/src/main/webapp/dir/form1.html @@ -0,0 +1,16 @@ + + + + +Formular 1 + + +

    + + + Eingabe:
    +
    + +
    + + diff --git a/08-servlet/servlet.hello/src/main/webapp/form1.html b/08-servlet/servlet.hello/src/main/webapp/form1.html new file mode 100644 index 0000000..0937ad6 --- /dev/null +++ b/08-servlet/servlet.hello/src/main/webapp/form1.html @@ -0,0 +1,16 @@ + + + + +Formular 1 + + +
    + + + Eingabe:
    +
    + +
    + + diff --git a/08-servlet/servlet.hello/src/main/webapp/form2.html b/08-servlet/servlet.hello/src/main/webapp/form2.html new file mode 100644 index 0000000..6802314 --- /dev/null +++ b/08-servlet/servlet.hello/src/main/webapp/form2.html @@ -0,0 +1,16 @@ + + + + +Formular 1 + + +
    + + + Eingabe:
    +
    + +
    + + diff --git a/08-servlet/servlet.hello/src/main/webapp/index.html b/08-servlet/servlet.hello/src/main/webapp/index.html new file mode 100644 index 0000000..d254020 --- /dev/null +++ b/08-servlet/servlet.hello/src/main/webapp/index.html @@ -0,0 +1,19 @@ + + + + +VS + + +

    Verteilte Systeme

    + + + + + diff --git a/08-servlet/servlet.hello/target/classes/vs/HelloWorld.class b/08-servlet/servlet.hello/target/classes/vs/HelloWorld.class new file mode 100644 index 0000000..5a6df3e Binary files /dev/null and b/08-servlet/servlet.hello/target/classes/vs/HelloWorld.class differ diff --git a/08-servlet/servlet.hello/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst b/08-servlet/servlet.hello/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst new file mode 100644 index 0000000..1975445 --- /dev/null +++ b/08-servlet/servlet.hello/target/maven-status/maven-compiler-plugin/compile/default-compile/createdFiles.lst @@ -0,0 +1 @@ +vs/HelloWorld.class diff --git a/08-servlet/servlet.hello/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst b/08-servlet/servlet.hello/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst new file mode 100644 index 0000000..6cf98a4 --- /dev/null +++ b/08-servlet/servlet.hello/target/maven-status/maven-compiler-plugin/compile/default-compile/inputFiles.lst @@ -0,0 +1 @@ +/var/home/sandro/git/vs/labs/08-servlet/servlet.hello/src/main/java/vs/HelloWorld.java diff --git a/08-servlet/servlet.media_solution/justfile b/08-servlet/servlet.media_solution/justfile new file mode 100644 index 0000000..f8066da --- /dev/null +++ b/08-servlet/servlet.media_solution/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + firefox http://localhost:8080/ diff --git a/08-servlet/servlet.media_solution/pom.xml b/08-servlet/servlet.media_solution/pom.xml new file mode 100644 index 0000000..a39f87b --- /dev/null +++ b/08-servlet/servlet.media_solution/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + servlet.media_solution + 1.0-SNAPSHOT + war + + + vs + servlet + 1.0-SNAPSHOT + + + diff --git a/08-servlet/servlet.media_solution/src/main/java/vs/DocDeliveryServlet.java b/08-servlet/servlet.media_solution/src/main/java/vs/DocDeliveryServlet.java new file mode 100644 index 0000000..0df0655 --- /dev/null +++ b/08-servlet/servlet.media_solution/src/main/java/vs/DocDeliveryServlet.java @@ -0,0 +1,79 @@ +package vs; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Calendar; + +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@WebServlet(urlPatterns = "/doc/*") +public class DocDeliveryServlet extends HttpServlet { + /** + * + */ + private static final long serialVersionUID = 203911783064136439L; + + // alternatively use jakarta.servlet.Filter + @Override + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + doPost(req, resp); + } + + @Override + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + String pdfName = req.getPathInfo(); + if ((pdfName == null) || "".equals(pdfName)) { + resp.sendError(HttpServletResponse.SC_BAD_REQUEST); + } else { + try { + Calendar now = Calendar.getInstance(); + if ((now.get(Calendar.HOUR_OF_DAY) > 6) && (now.get(Calendar.HOUR_OF_DAY) < 21)) { + // Access only allowed between 06:00-21:00 (local time of server); + // works here as a filter + resp.sendError(HttpServletResponse.SC_FORBIDDEN, + "access to " + pdfName + " is currently forbidden"); + } else { + // => [ServletContext]/WebContent/doc/....pdf + String pdfFilePath = getServletContext().getRealPath("/doc/" + pdfName); + File pdfFile = new File(pdfFilePath); + if (!pdfFile.exists()) { + throw new Exception("file does not exist in doc/"); + } + if (!pdfFile.isFile()) { + throw new Exception("file ist not regular"); + } + if (!pdfFile.canRead()) { + throw new Exception("file not readable"); + } + if (!pdfFile.getParentFile().getCanonicalPath() + .equals((new File(getServletContext().getRealPath("/doc/"))).getCanonicalPath())) { + throw new Exception("file not in doc/"); + } + OutputStream out = resp.getOutputStream(); + resp.setHeader("Content-Disposition", "inline;filename=" + pdfName + "\""); + resp.setContentType("application/pdf"); + try (InputStream in = new BufferedInputStream(new FileInputStream(pdfFile))) { + int character; + while ((character = in.read()) != -1) { + out.write((byte) character); + } + } catch (Exception ex) { + // an IOException could occur but can't be handled, at least in will be closed + } + } + } catch (Exception e) { + resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getLocalizedMessage()); + } + + } + } + +} diff --git a/08-servlet/servlet.media_solution/src/main/webapp/META-INF/MANIFEST.MF b/08-servlet/servlet.media_solution/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/08-servlet/servlet.media_solution/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR1-Cover.pdf b/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR1-Cover.pdf new file mode 100644 index 0000000..d206530 Binary files /dev/null and b/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR1-Cover.pdf differ diff --git a/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR2-Cover.pdf b/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR2-Cover.pdf new file mode 100644 index 0000000..42429d2 Binary files /dev/null and b/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR2-Cover.pdf differ diff --git a/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR3-Cover.pdf b/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR3-Cover.pdf new file mode 100644 index 0000000..e09b185 Binary files /dev/null and b/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR3-Cover.pdf differ diff --git a/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR4-Cover.pdf b/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR4-Cover.pdf new file mode 100644 index 0000000..1655987 Binary files /dev/null and b/08-servlet/servlet.media_solution/src/main/webapp/doc/VAR4-Cover.pdf differ diff --git a/08-servlet/servlet.media_solution/src/main/webapp/index.html b/08-servlet/servlet.media_solution/src/main/webapp/index.html new file mode 100644 index 0000000..de78a64 --- /dev/null +++ b/08-servlet/servlet.media_solution/src/main/webapp/index.html @@ -0,0 +1,20 @@ + + + + +Test DocDeliveryServlet + + + + + + \ No newline at end of file diff --git a/08-servlet/servlet.poll/justfile b/08-servlet/servlet.poll/justfile new file mode 100644 index 0000000..f8066da --- /dev/null +++ b/08-servlet/servlet.poll/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + firefox http://localhost:8080/ diff --git a/08-servlet/servlet.poll/pom.xml b/08-servlet/servlet.poll/pom.xml new file mode 100644 index 0000000..4236595 --- /dev/null +++ b/08-servlet/servlet.poll/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + servlet.poll + 1.0-SNAPSHOT + war + + + vs + servlet + 1.0-SNAPSHOT + + + diff --git a/08-servlet/servlet.poll/src/main/java/vs/BallotBox.java b/08-servlet/servlet.poll/src/main/java/vs/BallotBox.java new file mode 100644 index 0000000..4550052 --- /dev/null +++ b/08-servlet/servlet.poll/src/main/java/vs/BallotBox.java @@ -0,0 +1,37 @@ +package vs; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class BallotBox { + private Map votes = new HashMap<>(); + + public synchronized void vote(String choice) { + Integer votes = this.votes.get(choice); + if (votes == null) { + votes = 0; + } + this.votes.put(choice, votes + 1); + } + + public synchronized int countVotes() { + int sum = 0; + for (Map.Entry choice : this.votes.entrySet()) { + sum += choice.getValue(); + } + return sum; + } + + public synchronized int getNumberOfVotes(String choice) { + Integer votes = this.votes.get(choice); + if (votes == null) { + votes = 0; + } + return votes; + } + + public synchronized Set getChoices() { + return this.votes.keySet(); + } +} diff --git a/08-servlet/servlet.poll/src/main/java/vs/BallotBoxServlet.java b/08-servlet/servlet.poll/src/main/java/vs/BallotBoxServlet.java new file mode 100644 index 0000000..b5e3038 --- /dev/null +++ b/08-servlet/servlet.poll/src/main/java/vs/BallotBoxServlet.java @@ -0,0 +1,63 @@ +package vs; + +import java.io.IOException; +import java.io.PrintWriter; + +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@WebServlet("/vote") +public class BallotBoxServlet extends HttpServlet { + /** + * + */ + private static final long serialVersionUID = 659659337839534283L; + private BallotBox ballotBox = new BallotBox(); + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println(""); + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("vote")) { + String alternative = request.getParameter("alternative"); + if ((alternative == null) || alternative.equals("")) { + alternative = "ungültige Stimmenabgabe"; + } + this.ballotBox.vote(alternative); + out.println("

    Ihre Stimme wurde gezählt.

    "); + } else if (action.equals("print")) { + out.println("

    abgegebene Stimmen

    "); + out.println(""); + out.println(""); + for (String alternative : this.ballotBox.getChoices()) { + out.println(""); + out.println(""); + } + out.println(""); + out.println(""); + out.println("
    AlternativeStimmen
    " + alternative + "" + this.ballotBox.getNumberOfVotes(alternative) + "
    Summe:" + this.ballotBox.countVotes() + "
    "); + } else { + response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, + "action-Parameter hatte den Wert '" + action + "'. Erlaubte Werte sind 'vote' und 'print'"); + } + } else { + response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, + "action-Parameter hatte keinen Wert gesetzt. Erlaubte Werte sind 'vote' und 'print'"); + } + out.println(""); + out.flush(); + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + doGet(request, response); + } +} diff --git a/08-servlet/servlet.poll/src/main/webapp/META-INF/MANIFEST.MF b/08-servlet/servlet.poll/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/08-servlet/servlet.poll/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/08-servlet/servlet.poll/src/main/webapp/index.html b/08-servlet/servlet.poll/src/main/webapp/index.html new file mode 100644 index 0000000..45e404c --- /dev/null +++ b/08-servlet/servlet.poll/src/main/webapp/index.html @@ -0,0 +1,34 @@ + + + + + Klassensprecherwahlen + + +

    Online Wahl für das Amt der Klassensprecherin oder des + Klassensprechers

    +

    Sie haben eine Stimme. Wählen Sie Ihre Kandidatin oder Ihren + Kandidaten für das Amt des Klassensprechers:

    +

    Kandidaten:

    +
    + +
    + +
    +

    + Alternativ können Sie das Ergebnis der + Wahl abrufen. +

    + + \ No newline at end of file diff --git a/08-servlet/servlet.wahlen/justfile b/08-servlet/servlet.wahlen/justfile new file mode 100644 index 0000000..f8066da --- /dev/null +++ b/08-servlet/servlet.wahlen/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + firefox http://localhost:8080/ diff --git a/08-servlet/servlet.wahlen/pom.xml b/08-servlet/servlet.wahlen/pom.xml new file mode 100644 index 0000000..459d05b --- /dev/null +++ b/08-servlet/servlet.wahlen/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + servlet.wahlen + 1.0-SNAPSHOT + war + + + vs + servlet + 1.0-SNAPSHOT + + + diff --git a/08-servlet/servlet.wahlen/src/main/java/vs/WahlenController.java b/08-servlet/servlet.wahlen/src/main/java/vs/WahlenController.java new file mode 100644 index 0000000..a51a8ca --- /dev/null +++ b/08-servlet/servlet.wahlen/src/main/java/vs/WahlenController.java @@ -0,0 +1,59 @@ +package vs; + +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +/** + * Servlet implementation class WahlenController + */ +@WebServlet(name = "ControllerWahlen", description = "Controller für die Wahlen Web-Anwendung", urlPatterns = { "/do", + "/wahlservlet" }) +public class WahlenController extends HttpServlet { + private static final long serialVersionUID = 1L; + private Map poll = new HashMap<>(); + + /** + * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse + * response) + */ + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + String choice = request.getParameter("choice"); + if (choice != null) { + if (!this.poll.containsKey(choice)) { + this.poll.put(choice, 0); + } + this.poll.put(choice, this.poll.get(choice) + 1); + response.getOutputStream() + .println("

    Wahlergebnisse

    Stimme ist gezählt"); + } else { + String action = request.getParameter("action"); + if (action != null && action.equals("ergebnis")) { + response.getOutputStream().println("

    Wahlergebnisse

      "); + for (var c : poll.keySet()) { + response.getOutputStream().println("
    • " + c + ": " + poll.get(c) + "
    • "); + } + response.getOutputStream().println("
    "); + } else { + response.sendError(jakarta.servlet.http.HttpServletResponse.SC_BAD_REQUEST); + } + } + } + + /** + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse + * response) + */ + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + doGet(request, response); + } + +} diff --git a/08-servlet/servlet.wahlen/src/main/webapp/index.html b/08-servlet/servlet.wahlen/src/main/webapp/index.html new file mode 100644 index 0000000..8b131d1 --- /dev/null +++ b/08-servlet/servlet.wahlen/src/main/webapp/index.html @@ -0,0 +1,20 @@ + + + + +Wahl-Anwendung + + +

    Wahl-Anwendung

    +
    + + +
    +

    Ergebnis ausgeben + + \ No newline at end of file diff --git a/09-cloud/justfile b/09-cloud/justfile new file mode 100644 index 0000000..c3bfdc9 --- /dev/null +++ b/09-cloud/justfile @@ -0,0 +1,22 @@ +import '../justfile' + +project_id := "vs-gae" + +serve-local: war + mvn jetty:run +war: + mvn war:war + touch src/main/webapp/index.html +deploy: + mvn package appengine:deploy -Dapp.deploy.projectId={{project_id}} -Dapp.deploy.version=GCLOUD_CONFIG + +client-local: + firefox http://localhost:8080/ +client-cloud: + gcloud app browse + +setup: + gcloud init + distrobox enter gcloud -e sudo gcloud components install app-engine-java + gcloud auth login + gcloud app create --project {{project_id}} diff --git a/09-cloud/pom.xml b/09-cloud/pom.xml new file mode 100644 index 0000000..77198b9 --- /dev/null +++ b/09-cloud/pom.xml @@ -0,0 +1,42 @@ + + 4.0.0 + vs + cloud + 1.0-SNAPSHOT + war + + + vs + parent + 1.0-SNAPSHOT + + + + + javax.servlet + javax.servlet-api + 4.0.1 + provided + + + + + + + com.google.cloud.tools + appengine-maven-plugin + 2.7.0 + + + org.eclipse.jetty + jetty-maven-plugin + 10.0.24 + + + org.apache.maven.plugins + maven-war-plugin + 3.4.0 + + + + diff --git a/09-cloud/src/main/java/vs/BallotBox.java b/09-cloud/src/main/java/vs/BallotBox.java new file mode 100644 index 0000000..4550052 --- /dev/null +++ b/09-cloud/src/main/java/vs/BallotBox.java @@ -0,0 +1,37 @@ +package vs; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class BallotBox { + private Map votes = new HashMap<>(); + + public synchronized void vote(String choice) { + Integer votes = this.votes.get(choice); + if (votes == null) { + votes = 0; + } + this.votes.put(choice, votes + 1); + } + + public synchronized int countVotes() { + int sum = 0; + for (Map.Entry choice : this.votes.entrySet()) { + sum += choice.getValue(); + } + return sum; + } + + public synchronized int getNumberOfVotes(String choice) { + Integer votes = this.votes.get(choice); + if (votes == null) { + votes = 0; + } + return votes; + } + + public synchronized Set getChoices() { + return this.votes.keySet(); + } +} diff --git a/09-cloud/src/main/java/vs/BallotBoxServlet.java b/09-cloud/src/main/java/vs/BallotBoxServlet.java new file mode 100644 index 0000000..273bbee --- /dev/null +++ b/09-cloud/src/main/java/vs/BallotBoxServlet.java @@ -0,0 +1,62 @@ +package vs; + +import java.io.IOException; +import java.io.PrintWriter; + +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +public class BallotBoxServlet extends HttpServlet { + /** + * + */ + private static final long serialVersionUID = -2604266232876957201L; + private BallotBox ballotBox = new BallotBox(); + + @Override + protected void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + out.println(""); + String action = request.getParameter("action"); + if (action != null) { + if (action.equals("vote")) { + String alternative = request.getParameter("alternative"); + if ((alternative == null) || alternative.equals("")) { + alternative = "ungültige Stimmenabgabe"; + } + this.ballotBox.vote(alternative); + out.println("

    Ihre Stimme wurde gezählt.

    "); + } else if (action.equals("print")) { + out.println("

    abgegebene Stimmen

    "); + out.println(""); + out.println(""); + for (String alternative : this.ballotBox.getChoices()) { + out.println(""); + out.println(""); + } + out.println(""); + out.println(""); + out.println("
    AlternativeStimmen
    " + alternative + "" + this.ballotBox.getNumberOfVotes(alternative) + "
    Summe:" + this.ballotBox.countVotes() + "
    "); + } else { + response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, + "action-Parameter hatte den Wert '" + action + "'. Erlaubte Werte sind 'vote' und 'print'"); + } + } else { + response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, + "action-Parameter hatte keinen Wert gesetzt. Erlaubte Werte sind 'vote' und 'print'"); + } + out.println(""); + out.flush(); + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + doGet(request, response); + } +} diff --git a/09-cloud/src/main/webapp/META-INF/MANIFEST.MF b/09-cloud/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/09-cloud/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/09-cloud/src/main/webapp/WEB-INF/appengine-web.xml b/09-cloud/src/main/webapp/WEB-INF/appengine-web.xml new file mode 100644 index 0000000..4775509 --- /dev/null +++ b/09-cloud/src/main/webapp/WEB-INF/appengine-web.xml @@ -0,0 +1,7 @@ + + + + false + java17 + + diff --git a/09-cloud/src/main/webapp/WEB-INF/lib/jstl-1.2.jar b/09-cloud/src/main/webapp/WEB-INF/lib/jstl-1.2.jar new file mode 100644 index 0000000..0fd275e Binary files /dev/null and b/09-cloud/src/main/webapp/WEB-INF/lib/jstl-1.2.jar differ diff --git a/09-cloud/src/main/webapp/WEB-INF/web.xml b/09-cloud/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..d86739c --- /dev/null +++ b/09-cloud/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,15 @@ + + + + wahl.html + + + vote + vs.BallotBoxServlet + + + + vote + /vote + + diff --git a/09-cloud/src/main/webapp/favicon.ico b/09-cloud/src/main/webapp/favicon.ico new file mode 100644 index 0000000..a5fefb1 Binary files /dev/null and b/09-cloud/src/main/webapp/favicon.ico differ diff --git a/09-cloud/src/main/webapp/index.html b/09-cloud/src/main/webapp/index.html new file mode 100644 index 0000000..e69de29 diff --git a/09-cloud/src/main/webapp/wahl.html b/09-cloud/src/main/webapp/wahl.html new file mode 100644 index 0000000..45e404c --- /dev/null +++ b/09-cloud/src/main/webapp/wahl.html @@ -0,0 +1,34 @@ + + + + + Klassensprecherwahlen + + +

    Online Wahl für das Amt der Klassensprecherin oder des + Klassensprechers

    +

    Sie haben eine Stimme. Wählen Sie Ihre Kandidatin oder Ihren + Kandidaten für das Amt des Klassensprechers:

    +

    Kandidaten:

    +
    + +
    + +
    +

    + Alternativ können Sie das Ergebnis der + Wahl abrufen. +

    + + \ No newline at end of file diff --git a/15-protobuf/justfile b/15-protobuf/justfile new file mode 100644 index 0000000..97c8a6d --- /dev/null +++ b/15-protobuf/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +build: + mvn clean protobuf:compile compile package diff --git a/15-protobuf/pom.xml b/15-protobuf/pom.xml new file mode 100644 index 0000000..6c98142 --- /dev/null +++ b/15-protobuf/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + vs + protobuf + 1.0-SNAPSHOT + pom + + + vs + parent + 1.0-SNAPSHOT + + + + + com.google.protobuf + protobuf-java + 4.28.3 + + + com.google.protobuf + protobuf-java-util + 4.28.3 + + + + + + + kr.motd.maven + os-maven-plugin + 1.6.2 + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + 0.6.1 + + com.google.protobuf:protoc:4.28.3:exe:${os.detected.classifier} + + + + + compile + test-compile + + + + + + + + diff --git a/15-protobuf/protobuf.syslog/.gitignore b/15-protobuf/protobuf.syslog/.gitignore new file mode 100644 index 0000000..1fcb152 --- /dev/null +++ b/15-protobuf/protobuf.syslog/.gitignore @@ -0,0 +1 @@ +out diff --git a/15-protobuf/protobuf.syslog/justfile b/15-protobuf/protobuf.syslog/justfile new file mode 100644 index 0000000..7fbdd7b --- /dev/null +++ b/15-protobuf/protobuf.syslog/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +write: build + just exec vs.WriteLogMessage "" +read: + just exec vs.ReadLogMessage "" diff --git a/15-protobuf/protobuf.syslog/pom.xml b/15-protobuf/protobuf.syslog/pom.xml new file mode 100644 index 0000000..7690f30 --- /dev/null +++ b/15-protobuf/protobuf.syslog/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + protobuf.syslog + 1.0-SNAPSHOT + jar + + + vs + protobuf + 1.0-SNAPSHOT + + diff --git a/15-protobuf/protobuf.syslog/src/main/java/vs/ReadLogMessage.java b/15-protobuf/protobuf.syslog/src/main/java/vs/ReadLogMessage.java new file mode 100644 index 0000000..1297d0c --- /dev/null +++ b/15-protobuf/protobuf.syslog/src/main/java/vs/ReadLogMessage.java @@ -0,0 +1,13 @@ +package vs; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; + +public class ReadLogMessage { + public static void main(String... args) + throws FileNotFoundException, IOException { + Syslog.Message m = Syslog.Message.parseFrom(new FileInputStream("out")); + System.out.println(m); + } +} diff --git a/15-protobuf/protobuf.syslog/src/main/java/vs/WriteLogMessage.java b/15-protobuf/protobuf.syslog/src/main/java/vs/WriteLogMessage.java new file mode 100644 index 0000000..757fe71 --- /dev/null +++ b/15-protobuf/protobuf.syslog/src/main/java/vs/WriteLogMessage.java @@ -0,0 +1,34 @@ +package vs; + +import java.io.FileOutputStream; +import java.io.IOException; + +import com.google.protobuf.Any; + +public class WriteLogMessage { + + public static void main(String... args) throws IOException { + Syslog.Message m = Syslog.Message // + .newBuilder() // + .setAppname("Test App") // + .addData(Syslog.ComplexData // + .newBuilder() // + .setKey("key 1") // + .setText("data 1") // + .build()) // + .addData(Syslog.ComplexData // + .newBuilder() // + .setKey("key 2") // + .setText("data 2") // + .build()) // + .addData(Syslog.ComplexData // + .newBuilder() // + .setKey("key 3") // + .setData(Any.pack(Syslog.StructuredData.newBuilder() + .setValue("abc").build())) + .build()) // + .setPriority(Syslog.Severity.Alert) // + .build(); + m.writeTo(new FileOutputStream("out")); + } +} diff --git a/15-protobuf/protobuf.syslog/src/main/proto/syslog.proto b/15-protobuf/protobuf.syslog/src/main/proto/syslog.proto new file mode 100644 index 0000000..b15bb4d --- /dev/null +++ b/15-protobuf/protobuf.syslog/src/main/proto/syslog.proto @@ -0,0 +1,41 @@ +syntax = "proto3"; +package vs; + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/any.proto"; + +enum Severity { + Emergency = 0; + Alert = 1; + Critical = 2; + Error = 3; + Warning = 4; + Notice = 5; + Informational = 6; + Debug = 7; +} + +message StructuredData { + string key = 1; + string value = 2; +} + +message ComplexData { + string key = 1; + oneof value { + string text = 2; + google.protobuf.Any data = 3; + } +} + + +message Message { + Severity priority = 1; + uint32 version = 2; + google.protobuf.Timestamp timestamp = 3; + string hostname = 4; + string appname = 5; + uint32 procid = 6; + uint32 msgid = 7; + repeated ComplexData data = 8; +} diff --git a/15-protobuf/protobuf.syslog/src/main/proto/test.proto b/15-protobuf/protobuf.syslog/src/main/proto/test.proto new file mode 100644 index 0000000..d98b3b6 --- /dev/null +++ b/15-protobuf/protobuf.syslog/src/main/proto/test.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; +package vs; + +message SearchResponse { + message Result { + string url = 1; + string title = 2; + repeated string snippets = 3; + } + repeated Result results = 1; +} diff --git a/18-rest/justfile b/18-rest/justfile new file mode 100644 index 0000000..dbba21b --- /dev/null +++ b/18-rest/justfile @@ -0,0 +1,7 @@ +import '../justfile' + +serve: war + mvn jetty:run +war: + mvn war:war + touch src/main/webapp/index.html diff --git a/18-rest/pom.xml b/18-rest/pom.xml new file mode 100644 index 0000000..09daa8b --- /dev/null +++ b/18-rest/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + vs + rest + 1.0-SNAPSHOT + pom + + + vs + parent + 1.0-SNAPSHOT + + + + + jakarta.servlet + jakarta.servlet-api + 6.0.0 + provided + + + org.glassfish.jersey.containers + jersey-container-servlet-core + 3.1.9 + + + org.glassfish.jersey.inject + jersey-hk2 + 3.1.9 + + + + + + + org.eclipse.jetty.ee10 + jetty-ee10-maven-plugin + 12.0.14 + + + org.apache.maven.plugins + maven-war-plugin + 3.4.0 + + + + diff --git a/18-rest/rest.hello/justfile b/18-rest/rest.hello/justfile new file mode 100644 index 0000000..32bde3c --- /dev/null +++ b/18-rest/rest.hello/justfile @@ -0,0 +1,6 @@ +import '../justfile' + +client1: + firefox http://localhost:8080/test.html +client2: + just exec vs.TestClient "" diff --git a/18-rest/rest.hello/pom.xml b/18-rest/rest.hello/pom.xml new file mode 100644 index 0000000..2a74380 --- /dev/null +++ b/18-rest/rest.hello/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + rest.hello + 1.0-SNAPSHOT + war + + + vs + rest + 1.0-SNAPSHOT + + + diff --git a/18-rest/rest.hello/src/main/java/vs/HelloMoon.java b/18-rest/rest.hello/src/main/java/vs/HelloMoon.java new file mode 100644 index 0000000..dccb0e5 --- /dev/null +++ b/18-rest/rest.hello/src/main/java/vs/HelloMoon.java @@ -0,0 +1,15 @@ +package vs; + +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; + +@Path("/hello") +public class HelloMoon { + @POST + @Produces("text/plain") + public String helloWorldPOST() { + return "Hello Moon neu erzeugen"; + } + +} diff --git a/18-rest/rest.hello/src/main/java/vs/HelloWorld.java b/18-rest/rest.hello/src/main/java/vs/HelloWorld.java new file mode 100644 index 0000000..22a157c --- /dev/null +++ b/18-rest/rest.hello/src/main/java/vs/HelloWorld.java @@ -0,0 +1,60 @@ +package vs; + +import jakarta.ws.rs.Consumes; +import jakarta.ws.rs.DELETE; +import jakarta.ws.rs.FormParam; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.HEAD; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.Request; +import jakarta.ws.rs.core.UriInfo; + +@Path("/hello") +public class HelloWorld { + @Context UriInfo uriInfo; + @Context Request request; + + + @GET + public String helloWorld( + @QueryParam("year") String jahr, + @QueryParam("month") String monat, + @QueryParam("day") String tag + ) { + return "hello: " + tag + "." + monat + "." + jahr; + } + + @POST + @Consumes("application/x-www-form-urlencoded") + public String helloWorldNew( + @FormParam("year") String jahr, + @FormParam("month") String monat, + @FormParam("day") String tag + ) { + return "hello: " + tag + "." + monat + "." + jahr; + } + + @PUT + @Produces("text/plain") + public String helloWorldPUT() { + return "Hello World ändern"; + } + + @DELETE + @Produces("text/plain") + public String helloWorldDELETE() { + return "Hello World löschen"; + } + + @HEAD + @Produces("text/plain") + public String helloWorldHEAD() { + return "Hello World Metadaten"; + } + +} diff --git a/18-rest/rest.hello/src/main/java/vs/HelloWorld2.java b/18-rest/rest.hello/src/main/java/vs/HelloWorld2.java new file mode 100644 index 0000000..1577a29 --- /dev/null +++ b/18-rest/rest.hello/src/main/java/vs/HelloWorld2.java @@ -0,0 +1,36 @@ +package vs; + +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.PathParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.Context; +import jakarta.ws.rs.core.HttpHeaders; +import jakarta.ws.rs.core.Request; +import jakarta.ws.rs.core.UriInfo; + +@Path("/hello") +public class HelloWorld2 { + @Context UriInfo uriInfo; + @Context Request request; + + @GET + @Path("/1/{param}") + @Produces("text/plain") + + public String helloWorld(@PathParam("param") String parameter, @Context HttpHeaders headers) { + if (headers.getRequestHeaders().containsKey("HelloHeader")) { + return "Hello World"; + } else { + return "dlroW olleH"; + } + } + + + @GET + @Path("/2/{param}") + @Produces("text/plain") + public String helloWorldRechtsrum(@PathParam("param") String parameter) { + return "Hello World 2/" + parameter; + } +} diff --git a/18-rest/rest.hello/src/main/java/vs/TestClient.java b/18-rest/rest.hello/src/main/java/vs/TestClient.java new file mode 100644 index 0000000..63a98a5 --- /dev/null +++ b/18-rest/rest.hello/src/main/java/vs/TestClient.java @@ -0,0 +1,36 @@ +package vs; + +import jakarta.ws.rs.client.Client; +import jakarta.ws.rs.client.ClientBuilder; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.client.WebTarget; +import jakarta.ws.rs.core.Form; +import jakarta.ws.rs.core.MediaType; + +public class TestClient { + + public static void main(String[] args) { + Client client = ClientBuilder.newClient(); + WebTarget target = client + .target("http://localhost:8080") + .path("/rest") + .path("hello"); + + System.out.println("GET HelloWorld: " + + target + .queryParam("year", "2016") + .queryParam("month", "06") + .queryParam("day", "21") + .request() + .get(String.class)); + + Form form = new Form(); + form.param("year", "2016"); + form.param("month", "06"); + form.param("day", "21"); + + System.out.println(target + .request(MediaType.APPLICATION_JSON_TYPE) + .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class)); + } +} diff --git a/18-rest/rest.hello/src/main/webapp/WEB-INF/web.xml b/18-rest/rest.hello/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..6bf17c3 --- /dev/null +++ b/18-rest/rest.hello/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,18 @@ + + + Jersey + + JAX-RS Tools Generated - Do not modify + JAX-RS Servlet + org.glassfish.jersey.servlet.ServletContainer + + jersey.config.server.provider.classnames + vs.HelloWorld, vs.HelloMoon, vs.HelloWorld2 + + 1 + + + JAX-RS Servlet + /rest/* + + diff --git a/18-rest/rest.hello/src/main/webapp/index.html b/18-rest/rest.hello/src/main/webapp/index.html new file mode 100644 index 0000000..e69de29 diff --git a/18-rest/rest.hello/src/main/webapp/test.html b/18-rest/rest.hello/src/main/webapp/test.html new file mode 100644 index 0000000..b5968ef --- /dev/null +++ b/18-rest/rest.hello/src/main/webapp/test.html @@ -0,0 +1,21 @@ + + + + +hello-Test + + +
    + + + + +
    +
    + + + + +
    + + diff --git a/20-websocket/.gitignore b/20-websocket/.gitignore new file mode 100644 index 0000000..eb5a316 --- /dev/null +++ b/20-websocket/.gitignore @@ -0,0 +1 @@ +target diff --git a/20-websocket/justfile b/20-websocket/justfile new file mode 100644 index 0000000..dbba21b --- /dev/null +++ b/20-websocket/justfile @@ -0,0 +1,7 @@ +import '../justfile' + +serve: war + mvn jetty:run +war: + mvn war:war + touch src/main/webapp/index.html diff --git a/20-websocket/pom.xml b/20-websocket/pom.xml new file mode 100644 index 0000000..2859b56 --- /dev/null +++ b/20-websocket/pom.xml @@ -0,0 +1,48 @@ + + 4.0.0 + vs + websocket + 1.0-SNAPSHOT + pom + + + vs + parent + 1.0-SNAPSHOT + + + + + jakarta.servlet + jakarta.servlet-api + 6.0.0 + provided + + + jakarta.websocket + jakarta.websocket-api + 2.1.0 + provided + + + org.eclipse.jetty.ee10.websocket + jetty-ee10-websocket-jakarta-server + 12.0.14 + + + + + + + org.eclipse.jetty.ee10 + jetty-ee10-maven-plugin + 12.0.14 + + + org.apache.maven.plugins + maven-war-plugin + 3.4.0 + + + + diff --git a/20-websocket/websocket.chat/justfile b/20-websocket/websocket.chat/justfile new file mode 100644 index 0000000..f8066da --- /dev/null +++ b/20-websocket/websocket.chat/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + firefox http://localhost:8080/ diff --git a/20-websocket/websocket.chat/pom.xml b/20-websocket/websocket.chat/pom.xml new file mode 100644 index 0000000..47e88f3 --- /dev/null +++ b/20-websocket/websocket.chat/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + websocket.chat + 1.0-SNAPSHOT + war + + + vs + websocket + 1.0-SNAPSHOT + + + diff --git a/20-websocket/websocket.chat/src/main/java/vs/ChatServer.java b/20-websocket/websocket.chat/src/main/java/vs/ChatServer.java new file mode 100644 index 0000000..94849cd --- /dev/null +++ b/20-websocket/websocket.chat/src/main/java/vs/ChatServer.java @@ -0,0 +1,56 @@ +package vs; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import jakarta.websocket.OnClose; +import jakarta.websocket.OnError; +import jakarta.websocket.OnMessage; +import jakarta.websocket.OnOpen; +import jakarta.websocket.Session; +import jakarta.websocket.server.ServerEndpoint; + +@ServerEndpoint("/chat") +public class ChatServer { + private static List clients = new ArrayList<>(); + + @OnOpen + public void open(Session session) { + synchronized (clients) { + clients.add(session); + } + try { + session.getBasicRemote().sendText("Verbindung wurde hergestellt."); + } catch (IOException e) { + e.printStackTrace(System.err); + } + } + + @OnClose + public void close(Session session) { + synchronized (clients) { + clients.remove(session); + } + } + + @OnMessage + public void message(Session session, String message) throws IOException { + synchronized (clients) { + for (Session client : clients) { + if (client.isOpen() && !client.getId().equals(session.getId())) + client.getBasicRemote().sendText("client#" + session.getId() + ": " + message); + } + } + } + + @OnError + public synchronized void error(Session session, Throwable ex) throws IOException { + synchronized (clients) { + for (Session client : clients) { + if (client.isOpen()) + client.getBasicRemote().sendText("client#" + session.getId() + ": " + ex.getMessage()); + } + } + } +} diff --git a/20-websocket/websocket.chat/src/main/webapp/META-INF/MANIFEST.MF b/20-websocket/websocket.chat/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/20-websocket/websocket.chat/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/20-websocket/websocket.chat/src/main/webapp/chat.html b/20-websocket/websocket.chat/src/main/webapp/chat.html new file mode 100644 index 0000000..6c749be --- /dev/null +++ b/20-websocket/websocket.chat/src/main/webapp/chat.html @@ -0,0 +1,39 @@ + + + + +Chat Client + + + + + +
    +

    +

     
    +

    +
    + + diff --git a/20-websocket/websocket.chat/src/main/webapp/index.html b/20-websocket/websocket.chat/src/main/webapp/index.html new file mode 100644 index 0000000..7de6277 --- /dev/null +++ b/20-websocket/websocket.chat/src/main/webapp/index.html @@ -0,0 +1,12 @@ + + + + +WebSocket-Projekt + + + + + diff --git a/20-websocket/websocket.chat_solution/justfile b/20-websocket/websocket.chat_solution/justfile new file mode 100644 index 0000000..f8066da --- /dev/null +++ b/20-websocket/websocket.chat_solution/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + firefox http://localhost:8080/ diff --git a/20-websocket/websocket.chat_solution/pom.xml b/20-websocket/websocket.chat_solution/pom.xml new file mode 100644 index 0000000..2ab8104 --- /dev/null +++ b/20-websocket/websocket.chat_solution/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + websocket.chat_solution + 1.0-SNAPSHOT + war + + + vs + websocket + 1.0-SNAPSHOT + + + diff --git a/20-websocket/websocket.chat_solution/src/main/java/vs/ChatServer.java b/20-websocket/websocket.chat_solution/src/main/java/vs/ChatServer.java new file mode 100644 index 0000000..94849cd --- /dev/null +++ b/20-websocket/websocket.chat_solution/src/main/java/vs/ChatServer.java @@ -0,0 +1,56 @@ +package vs; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import jakarta.websocket.OnClose; +import jakarta.websocket.OnError; +import jakarta.websocket.OnMessage; +import jakarta.websocket.OnOpen; +import jakarta.websocket.Session; +import jakarta.websocket.server.ServerEndpoint; + +@ServerEndpoint("/chat") +public class ChatServer { + private static List clients = new ArrayList<>(); + + @OnOpen + public void open(Session session) { + synchronized (clients) { + clients.add(session); + } + try { + session.getBasicRemote().sendText("Verbindung wurde hergestellt."); + } catch (IOException e) { + e.printStackTrace(System.err); + } + } + + @OnClose + public void close(Session session) { + synchronized (clients) { + clients.remove(session); + } + } + + @OnMessage + public void message(Session session, String message) throws IOException { + synchronized (clients) { + for (Session client : clients) { + if (client.isOpen() && !client.getId().equals(session.getId())) + client.getBasicRemote().sendText("client#" + session.getId() + ": " + message); + } + } + } + + @OnError + public synchronized void error(Session session, Throwable ex) throws IOException { + synchronized (clients) { + for (Session client : clients) { + if (client.isOpen()) + client.getBasicRemote().sendText("client#" + session.getId() + ": " + ex.getMessage()); + } + } + } +} diff --git a/20-websocket/websocket.chat_solution/src/main/webapp/META-INF/MANIFEST.MF b/20-websocket/websocket.chat_solution/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/20-websocket/websocket.chat_solution/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/20-websocket/websocket.chat_solution/src/main/webapp/chat.html b/20-websocket/websocket.chat_solution/src/main/webapp/chat.html new file mode 100644 index 0000000..6c749be --- /dev/null +++ b/20-websocket/websocket.chat_solution/src/main/webapp/chat.html @@ -0,0 +1,39 @@ + + + + +Chat Client + + + + + +
    +

    +

     
    +

    +
    + + diff --git a/20-websocket/websocket.chat_solution/src/main/webapp/index.html b/20-websocket/websocket.chat_solution/src/main/webapp/index.html new file mode 100644 index 0000000..7de6277 --- /dev/null +++ b/20-websocket/websocket.chat_solution/src/main/webapp/index.html @@ -0,0 +1,12 @@ + + + + +WebSocket-Projekt + + + + + diff --git a/20-websocket/websocket.datasensor_solution/justfile b/20-websocket/websocket.datasensor_solution/justfile new file mode 100644 index 0000000..f8066da --- /dev/null +++ b/20-websocket/websocket.datasensor_solution/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + firefox http://localhost:8080/ diff --git a/20-websocket/websocket.datasensor_solution/pom.xml b/20-websocket/websocket.datasensor_solution/pom.xml new file mode 100644 index 0000000..aff276c --- /dev/null +++ b/20-websocket/websocket.datasensor_solution/pom.xml @@ -0,0 +1,28 @@ + + 4.0.0 + vs + websocket.datasensor_solution + 1.0-SNAPSHOT + war + + + vs + websocket + 1.0-SNAPSHOT + + + + + jakarta.json + jakarta.json-api + 2.1.3 + provided + + + org.glassfish + jakarta.json + 2.0.1 + + + + diff --git a/20-websocket/websocket.datasensor_solution/src/main/java/vs/DataDecoder.java b/20-websocket/websocket.datasensor_solution/src/main/java/vs/DataDecoder.java new file mode 100644 index 0000000..4238948 --- /dev/null +++ b/20-websocket/websocket.datasensor_solution/src/main/java/vs/DataDecoder.java @@ -0,0 +1,45 @@ +package vs; + +import java.io.StringReader; +import java.util.Date; + +import jakarta.json.Json; +import jakarta.json.JsonObject; +import jakarta.json.JsonReader; +import jakarta.websocket.DecodeException; +import jakarta.websocket.Decoder; +import jakarta.websocket.EndpointConfig; + +public class DataDecoder implements Decoder.Text { + + @Override + public void destroy() { + } + + @Override + public void init(EndpointConfig arg0) { + } + + @Override + public Messung decode(String messungData) throws DecodeException { + JsonReader reader = Json.createReader(new StringReader(messungData)); + JsonObject messungJson = reader.readObject(); + Messung messung = new Messung(); + messung.setUnit(Messung.Unit.valueOf(messungJson.getString("unit"))); + messung.setObservation(Double.parseDouble(messungJson.getString("observation"))); + Messung.Place where = new Messung.Place(); + where.setLat(messungJson.getJsonObject("where").getInt("lat")); + where.setLon(messungJson.getJsonObject("where").getInt("lon")); + messung.setWhere(where); + messung.setSensor(messungJson.getString("sensor")); + messung.setWhen(new Date(messungJson.getJsonNumber("when").longValueExact())); + reader.close(); + return messung; + } + + @Override + public boolean willDecode(String arg0) { + return true; + } + +} diff --git a/20-websocket/websocket.datasensor_solution/src/main/java/vs/DataEncoder.java b/20-websocket/websocket.datasensor_solution/src/main/java/vs/DataEncoder.java new file mode 100644 index 0000000..7f66a87 --- /dev/null +++ b/20-websocket/websocket.datasensor_solution/src/main/java/vs/DataEncoder.java @@ -0,0 +1,32 @@ +package vs; + +import jakarta.json.Json; +import jakarta.websocket.EncodeException; +import jakarta.websocket.Encoder; +import jakarta.websocket.EndpointConfig; + +public class DataEncoder implements Encoder.Text { + @Override + public void destroy() { + } + + @Override + public void init(EndpointConfig arg0) { + } + + @Override + public String encode(Messung messung) throws EncodeException { + return Json.createObjectBuilder() + .add("unit", messung.getUnit().toString()) + .add("observation", String.format("%.2f", messung.getObservation())) + .add("where", + Json.createObjectBuilder() + .add("lat", messung.getWhere().getLat()) + .add("lon", messung.getWhere().getLon()) + .build()) + .add("sensor", messung.getSensor().toString()) + .add("when", messung.getWhen().getTime()) + .build() + .toString(); + } +} diff --git a/20-websocket/websocket.datasensor_solution/src/main/java/vs/Messung.java b/20-websocket/websocket.datasensor_solution/src/main/java/vs/Messung.java new file mode 100644 index 0000000..1c20524 --- /dev/null +++ b/20-websocket/websocket.datasensor_solution/src/main/java/vs/Messung.java @@ -0,0 +1,87 @@ +package vs; + +import java.util.Date; + +public class Messung { + public enum Unit { + degreeCentigrade, degreeFahrenheit, candela; + } + + static public class Place { + private double lat; // latitude + private double lon; // longitude + + public Place() { + super(); + } + + public Place(double lat, double lon) { + this(); + this.lat = lat; + this.lon = lon; + } + + public double getLat() { + return lat; + } + public void setLat(double lat) { + this.lat = lat; + } + public double getLon() { + return lon; + } + public void setLon(double lon) { + this.lon = lon; + } + } + + private Unit unit; + private double observation; + private Place where; // where observed + private String sensor; // description + private Date when; // when observed + + public Messung() { + super(); + } + + public Unit getUnit() { + return unit; + } + + public void setUnit(Unit unit) { + this.unit = unit; + } + + public double getObservation() { + return observation; + } + + public void setObservation(double observation) { + this.observation = observation; + } + + public Place getWhere() { + return where; + } + + public void setWhere(Place where) { + this.where = where; + } + + public String getSensor() { + return sensor; + } + + public void setSensor(String sensor) { + this.sensor = sensor; + } + + public Date getWhen() { + return when; + } + + public void setWhen(Date when) { + this.when = when; + } +} diff --git a/20-websocket/websocket.datasensor_solution/src/main/java/vs/MessungsService.java b/20-websocket/websocket.datasensor_solution/src/main/java/vs/MessungsService.java new file mode 100644 index 0000000..19112b3 --- /dev/null +++ b/20-websocket/websocket.datasensor_solution/src/main/java/vs/MessungsService.java @@ -0,0 +1,25 @@ +package vs; + +import jakarta.websocket.OnClose; +import jakarta.websocket.OnOpen; +import jakarta.websocket.Session; +import jakarta.websocket.server.ServerEndpoint; + +@ServerEndpoint(value = "/dataService", encoders = DataEncoder.class) +public class MessungsService { + + @OnOpen + public void open(Session session) { + SensorSimulator sensor = new SensorSimulator(session); + session.getUserProperties().put("sensor", sensor); + sensor.start(); + } + + @SuppressWarnings("deprecation") + @OnClose + public void close(Session session) { + SensorSimulator sensor = (SensorSimulator) session.getUserProperties().get("sensor"); + sensor.stop(); + session.getUserProperties().remove("sensor"); + } +} diff --git a/20-websocket/websocket.datasensor_solution/src/main/java/vs/SensorSimulator.java b/20-websocket/websocket.datasensor_solution/src/main/java/vs/SensorSimulator.java new file mode 100644 index 0000000..b4fb97f --- /dev/null +++ b/20-websocket/websocket.datasensor_solution/src/main/java/vs/SensorSimulator.java @@ -0,0 +1,54 @@ +package vs; + +import java.io.IOException; +import java.util.Date; +import java.util.Random; + +import jakarta.websocket.EncodeException; +import jakarta.websocket.RemoteEndpoint; +import jakarta.websocket.Session; + +public class SensorSimulator extends Thread { + private Session session; + private Random random; + private double messwert; + + public SensorSimulator(Session session) { + super(); + this.session = session; + random = new Random(); + messwert = 100.0; + } + + public void notifyClient() throws IOException { + RemoteEndpoint.Basic client = session.getBasicRemote(); + Messung messung = new Messung(); + messung.setObservation(messwert); + messung.setSensor("Sensor XYZ"); + messung.setUnit(Messung.Unit.degreeCentigrade); + messung.setWhen(new Date()); + messung.setWhere(new Messung.Place(49.5121, 8.5316)); + try { + client.sendObject(messung); + } catch (EncodeException e) { + e.printStackTrace(System.err); + } + } + + @Override + public void run() { + try { + while (session != null && session.isOpen()) { + sleep(random.nextInt(1000)); + if (random.nextBoolean()) { + messwert += 0.1; + } else { + messwert -= 0.1; + } + notifyClient(); + } + } catch (InterruptedException | IOException e) { + e.printStackTrace(); + } + } +} diff --git a/20-websocket/websocket.datasensor_solution/src/main/webapp/META-INF/MANIFEST.MF b/20-websocket/websocket.datasensor_solution/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/20-websocket/websocket.datasensor_solution/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/20-websocket/websocket.datasensor_solution/src/main/webapp/datasensor.html b/20-websocket/websocket.datasensor_solution/src/main/webapp/datasensor.html new file mode 100644 index 0000000..3f36130 --- /dev/null +++ b/20-websocket/websocket.datasensor_solution/src/main/webapp/datasensor.html @@ -0,0 +1,35 @@ + + + + +Client für Sensormessungen (Datenobjekt) + + + + + +
     
    + + diff --git a/20-websocket/websocket.datasensor_solution/src/main/webapp/index.html b/20-websocket/websocket.datasensor_solution/src/main/webapp/index.html new file mode 100644 index 0000000..42b8791 --- /dev/null +++ b/20-websocket/websocket.datasensor_solution/src/main/webapp/index.html @@ -0,0 +1,12 @@ + + + + +WebSocket-Projekt + + + + + diff --git a/20-websocket/websocket.echo/justfile b/20-websocket/websocket.echo/justfile new file mode 100644 index 0000000..f8066da --- /dev/null +++ b/20-websocket/websocket.echo/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + firefox http://localhost:8080/ diff --git a/20-websocket/websocket.echo/pom.xml b/20-websocket/websocket.echo/pom.xml new file mode 100644 index 0000000..3f3a6e7 --- /dev/null +++ b/20-websocket/websocket.echo/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + websocket.echo + 1.0-SNAPSHOT + war + + + vs + websocket + 1.0-SNAPSHOT + + + diff --git a/20-websocket/websocket.echo/src/main/java/vs/EchoServer.java b/20-websocket/websocket.echo/src/main/java/vs/EchoServer.java new file mode 100644 index 0000000..f3f2ceb --- /dev/null +++ b/20-websocket/websocket.echo/src/main/java/vs/EchoServer.java @@ -0,0 +1,20 @@ +package vs; + +import java.io.IOException; + +import jakarta.websocket.OnMessage; +import jakarta.websocket.Session; +import jakarta.websocket.server.ServerEndpoint; + +@ServerEndpoint("/echo") +public class EchoServer { + + @OnMessage + public void onMessage(Session s, String text) { + try { + s.getBasicRemote().sendText(text); + } catch (IOException e) { + e.printStackTrace(System.err); + } + } +} diff --git a/20-websocket/websocket.echo/src/main/java/vs/Service.java b/20-websocket/websocket.echo/src/main/java/vs/Service.java new file mode 100644 index 0000000..c84c4b5 --- /dev/null +++ b/20-websocket/websocket.echo/src/main/java/vs/Service.java @@ -0,0 +1,25 @@ +package vs; + +import java.io.IOException; + +import jakarta.websocket.OnMessage; +import jakarta.websocket.OnOpen; +import jakarta.websocket.Session; +import jakarta.websocket.server.PathParam; +import jakarta.websocket.server.ServerEndpoint; + +@ServerEndpoint("/service/{user}") +public class Service { + + @OnOpen + public void init(Session s, @PathParam("user") String nickName) throws IOException { + s.getUserProperties().put("nickName", nickName); + } + + @OnMessage + public void onMessage(String m, Session s) throws IOException { + String nickName = (String) s.getUserProperties().get("nickName"); + s.getBasicRemote().sendText(nickName + ", empfangen: " + m); + } + +} diff --git a/20-websocket/websocket.echo/src/main/webapp/META-INF/MANIFEST.MF b/20-websocket/websocket.echo/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/20-websocket/websocket.echo/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/20-websocket/websocket.echo/src/main/webapp/echo.html b/20-websocket/websocket.echo/src/main/webapp/echo.html new file mode 100644 index 0000000..672ebf9 --- /dev/null +++ b/20-websocket/websocket.echo/src/main/webapp/echo.html @@ -0,0 +1,37 @@ + + + + +EchoClient + + + + + +
    +
    +
    + + diff --git a/20-websocket/websocket.echo/src/main/webapp/echoNickname.html b/20-websocket/websocket.echo/src/main/webapp/echoNickname.html new file mode 100644 index 0000000..5003546 --- /dev/null +++ b/20-websocket/websocket.echo/src/main/webapp/echoNickname.html @@ -0,0 +1,37 @@ + + + + +clientID enabled EchoClient + + + + + +
    +
     
    +
    + + diff --git a/20-websocket/websocket.echo/src/main/webapp/index.html b/20-websocket/websocket.echo/src/main/webapp/index.html new file mode 100644 index 0000000..185acad --- /dev/null +++ b/20-websocket/websocket.echo/src/main/webapp/index.html @@ -0,0 +1,13 @@ + + + + +WebSocket-Projekt + + + + + diff --git a/20-websocket/websocket.echo_solution/justfile b/20-websocket/websocket.echo_solution/justfile new file mode 100644 index 0000000..f8066da --- /dev/null +++ b/20-websocket/websocket.echo_solution/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + firefox http://localhost:8080/ diff --git a/20-websocket/websocket.echo_solution/pom.xml b/20-websocket/websocket.echo_solution/pom.xml new file mode 100644 index 0000000..99903ac --- /dev/null +++ b/20-websocket/websocket.echo_solution/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + websocket.echo_solution + 1.0-SNAPSHOT + war + + + vs + websocket + 1.0-SNAPSHOT + + + diff --git a/20-websocket/websocket.echo_solution/src/main/java/vs/EchoServer.java b/20-websocket/websocket.echo_solution/src/main/java/vs/EchoServer.java new file mode 100644 index 0000000..f3f2ceb --- /dev/null +++ b/20-websocket/websocket.echo_solution/src/main/java/vs/EchoServer.java @@ -0,0 +1,20 @@ +package vs; + +import java.io.IOException; + +import jakarta.websocket.OnMessage; +import jakarta.websocket.Session; +import jakarta.websocket.server.ServerEndpoint; + +@ServerEndpoint("/echo") +public class EchoServer { + + @OnMessage + public void onMessage(Session s, String text) { + try { + s.getBasicRemote().sendText(text); + } catch (IOException e) { + e.printStackTrace(System.err); + } + } +} diff --git a/20-websocket/websocket.echo_solution/src/main/java/vs/Service.java b/20-websocket/websocket.echo_solution/src/main/java/vs/Service.java new file mode 100644 index 0000000..c84c4b5 --- /dev/null +++ b/20-websocket/websocket.echo_solution/src/main/java/vs/Service.java @@ -0,0 +1,25 @@ +package vs; + +import java.io.IOException; + +import jakarta.websocket.OnMessage; +import jakarta.websocket.OnOpen; +import jakarta.websocket.Session; +import jakarta.websocket.server.PathParam; +import jakarta.websocket.server.ServerEndpoint; + +@ServerEndpoint("/service/{user}") +public class Service { + + @OnOpen + public void init(Session s, @PathParam("user") String nickName) throws IOException { + s.getUserProperties().put("nickName", nickName); + } + + @OnMessage + public void onMessage(String m, Session s) throws IOException { + String nickName = (String) s.getUserProperties().get("nickName"); + s.getBasicRemote().sendText(nickName + ", empfangen: " + m); + } + +} diff --git a/20-websocket/websocket.echo_solution/src/main/webapp/META-INF/MANIFEST.MF b/20-websocket/websocket.echo_solution/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/20-websocket/websocket.echo_solution/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/20-websocket/websocket.echo_solution/src/main/webapp/echo.html b/20-websocket/websocket.echo_solution/src/main/webapp/echo.html new file mode 100644 index 0000000..672ebf9 --- /dev/null +++ b/20-websocket/websocket.echo_solution/src/main/webapp/echo.html @@ -0,0 +1,37 @@ + + + + +EchoClient + + + + + +
    +
    +
    + + diff --git a/20-websocket/websocket.echo_solution/src/main/webapp/echoNickname.html b/20-websocket/websocket.echo_solution/src/main/webapp/echoNickname.html new file mode 100644 index 0000000..5003546 --- /dev/null +++ b/20-websocket/websocket.echo_solution/src/main/webapp/echoNickname.html @@ -0,0 +1,37 @@ + + + + +clientID enabled EchoClient + + + + + +
    +
     
    +
    + + diff --git a/20-websocket/websocket.echo_solution/src/main/webapp/index.html b/20-websocket/websocket.echo_solution/src/main/webapp/index.html new file mode 100644 index 0000000..185acad --- /dev/null +++ b/20-websocket/websocket.echo_solution/src/main/webapp/index.html @@ -0,0 +1,13 @@ + + + + +WebSocket-Projekt + + + + + diff --git a/20-websocket/websocket.sensor_solution/justfile b/20-websocket/websocket.sensor_solution/justfile new file mode 100644 index 0000000..f8066da --- /dev/null +++ b/20-websocket/websocket.sensor_solution/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +client: + firefox http://localhost:8080/ diff --git a/20-websocket/websocket.sensor_solution/pom.xml b/20-websocket/websocket.sensor_solution/pom.xml new file mode 100644 index 0000000..be33bbf --- /dev/null +++ b/20-websocket/websocket.sensor_solution/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + websocket.sensor_solution + 1.0-SNAPSHOT + war + + + vs + websocket + 1.0-SNAPSHOT + + diff --git a/20-websocket/websocket.sensor_solution/src/main/java/vs/MessungsService.java b/20-websocket/websocket.sensor_solution/src/main/java/vs/MessungsService.java new file mode 100644 index 0000000..1857834 --- /dev/null +++ b/20-websocket/websocket.sensor_solution/src/main/java/vs/MessungsService.java @@ -0,0 +1,25 @@ +package vs; + +import jakarta.websocket.OnClose; +import jakarta.websocket.OnOpen; +import jakarta.websocket.Session; +import jakarta.websocket.server.ServerEndpoint; + +@ServerEndpoint(value = "/messungen") +public class MessungsService { + + @OnOpen + public void open(Session session) { + SensorSimulator sensor = new SensorSimulator(session); + session.getUserProperties().put("sensor", sensor); + sensor.start(); + } + + @SuppressWarnings("deprecation") + @OnClose + public void close(Session session) { + SensorSimulator sensor = (SensorSimulator) session.getUserProperties().get("sensor"); + sensor.stop(); + session.getUserProperties().remove("sensor"); + } +} diff --git a/20-websocket/websocket.sensor_solution/src/main/java/vs/SensorSimulator.java b/20-websocket/websocket.sensor_solution/src/main/java/vs/SensorSimulator.java new file mode 100644 index 0000000..397c656 --- /dev/null +++ b/20-websocket/websocket.sensor_solution/src/main/java/vs/SensorSimulator.java @@ -0,0 +1,43 @@ +package vs; + +import java.io.IOException; +import java.util.Random; + +import jakarta.websocket.RemoteEndpoint; +import jakarta.websocket.Session; + +public class SensorSimulator extends Thread { + private Session session; + private Random random; + private double messwert; + + public SensorSimulator(Session session) { + super(); + this.session = session; + random = new Random(); + messwert = 100.0; + } + + public void notifyClient() throws IOException { + RemoteEndpoint.Basic client = session.getBasicRemote(); + String message = String.format("%.2f", messwert); + client.sendText(message); + } + + @Override + public void run() { + try { + while (session != null && session.isOpen()) { + sleep(random.nextInt(1000)); + if (random.nextBoolean()) { + messwert += 0.1; + } else { + messwert -= 0.1; + } + notifyClient(); + } + } catch (InterruptedException | IOException e) { + e.printStackTrace(); + } + } +} diff --git a/20-websocket/websocket.sensor_solution/src/main/webapp/META-INF/MANIFEST.MF b/20-websocket/websocket.sensor_solution/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/20-websocket/websocket.sensor_solution/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/20-websocket/websocket.sensor_solution/src/main/webapp/index.html b/20-websocket/websocket.sensor_solution/src/main/webapp/index.html new file mode 100644 index 0000000..10c58ac --- /dev/null +++ b/20-websocket/websocket.sensor_solution/src/main/webapp/index.html @@ -0,0 +1,13 @@ + + + + +WebSocket-Projekt + + + + + diff --git a/20-websocket/websocket.sensor_solution/src/main/webapp/sensor.html b/20-websocket/websocket.sensor_solution/src/main/webapp/sensor.html new file mode 100644 index 0000000..1750e93 --- /dev/null +++ b/20-websocket/websocket.sensor_solution/src/main/webapp/sensor.html @@ -0,0 +1,31 @@ + + + + +Client für Sensormessungen + + + + + +
     
    + + diff --git a/20-websocket/websocket.sensor_solution/src/main/webapp/sensoren.html b/20-websocket/websocket.sensor_solution/src/main/webapp/sensoren.html new file mode 100644 index 0000000..fc4403b --- /dev/null +++ b/20-websocket/websocket.sensor_solution/src/main/webapp/sensoren.html @@ -0,0 +1,43 @@ + + + + +Client für Sensormessungen + + + + + +
     
    +
     
    +
     
    + + diff --git a/21-graphql/graphql.election/README.md b/21-graphql/graphql.election/README.md new file mode 100644 index 0000000..f4c2801 --- /dev/null +++ b/21-graphql/graphql.election/README.md @@ -0,0 +1,19 @@ +# GraphQL Queries + +``just serve`` + + - zuerst einige Stimmen über das Servlet abgeben: ["Howard Joel Wolowitz" wählen](http://localhost:8080/vote?action=vote&alternative=Howard+Joel+Wolowitz) + - dann einige Stimmen weitere über das Servlet abgeben: ["Dr. Amy Farrah Fowler" wählen](http://localhost:8080/vote?action=vote&alternative=Dr.+Amy+Farrah+Fowler) + - über das Servlet abfragen, wie gewählt wurde: [Ergebnis abrufen](http://localhost:8080/vote?action=print) + +## GraphiQL-UI + +[http://localhost:8080/graphiql/](http://localhost:8080/graphiql/) + +## GraphQL-Queries +- Anzahl aller abgegebenen Stimmen: [``{votesNumber}``](http://localhost:8080/graphiql/?query=%23%20Anzahl%20aller%20abgegebenen%20Stimmen%0A%7B%0A%20%20votesNumber%0A%7D%0A) +- alle Stimmen: [``{allVotes {choice votes}}``](http://localhost:8080/graphiql/?query=%23%20alle%20Stimmen%3A%20%0Aquery%20%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A) +- alle Stimmen, nur die Namen: [``{allVotes {choice}}``](http://localhost:8080/graphiql/?query=%23%20alle%20Stimmen%2C%20nur%20die%20Namen%3A%20%0Aquery%20%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%7D%0A%7D%0A) +- Anzahl der Stimmen für "Dr. Amy Farrah Fowler": [``{votes(choice: "Dr. Amy Farrah Fowler")}``](http://localhost:8080/graphiql/?query=%23%20Anzahl%20der%20Stimmen%20f%C3%BCr%20%22Dr.%20Amy%20Farrah%20Fowler%22%3A%20%0A%7B%0A%20%20votes(choice%3A%20%22Dr.%20Amy%20Farrah%20Fowler%22)%0A%7D%0A) +- mit nicht gewähltem Namen geht es auch (Ergebnis = 0): [``{votes(choice: "Lex Luthor")}``](http://localhost:8080/graphiql/?query=%23%20mit%20nicht%20gew%C3%A4hltem%20Namen%20geht%20es%20auch%20(Ergebnis%20%3D%200)%3A%20%0A%7B%0A%20%20votes(choice%3A%20%22Lex%20Luthor%22)%0A%7D%0A) +- ohne Namen geht es nicht (Pflichtfeld): [``{votes()}``](http://localhost:8080/graphiql/?query=%23%20ohne%20Namen%20geht%20es%20nicht%20(Pflichtfeld)%3A%20%0Aquery%20%7Bvotes()%7D) diff --git a/21-graphql/graphql.election/justfile b/21-graphql/graphql.election/justfile new file mode 100644 index 0000000..733b437 --- /dev/null +++ b/21-graphql/graphql.election/justfile @@ -0,0 +1,23 @@ +import '../justfile' + +base := 'http://localhost:8080/' + +client-test: + firefox {{base}}test +client-web: + firefox {{base}} +client-tui: + just exec vs.Main "" +client-graphiql: + firefox {{base}}graphiql/ + +skript: + just _step '%23%20Anzahl%20aller%20abgegebenen%20Stimmen%0A%7B%0A%20%20votesNumber%0A%7D%0A' + just _step '%23%20alle%20Stimmen%3A%20%0Aquery%20%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A' + just _step '%23%20alle%20Stimmen%2C%20nur%20die%20Namen%3A%20%0Aquery%20%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%7D%0A%7D%0A' + just _step '%23%20Anzahl%20der%20Stimmen%20f%C3%BCr%20%22Dr.%20Amy%20Farrah%20Fowler%22%3A%20%0A%7B%0A%20%20votes(choice%3A%20%22Dr.%20Amy%20Farrah%20Fowler%22)%0A%7D%0A' + just _step '%23%20mit%20nicht%20gew%C3%A4hltem%20Namen%20geht%20es%20auch%20(Ergebnis%20%3D%200)%3A%20%0A%7B%0A%20%20votes(choice%3A%20%22Lex%20Luthor%22)%0A%7D%0A' + just _step '%23%20ohne%20Namen%20geht%20es%20nicht%20(Pflichtfeld)%3A%20%0Aquery%20%7Bvotes()%7D' + +_step query: + firefox '{{base}}graphiql/?query={{query}}' diff --git a/21-graphql/graphql.election/pom.xml b/21-graphql/graphql.election/pom.xml new file mode 100644 index 0000000..77bf589 --- /dev/null +++ b/21-graphql/graphql.election/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + graphql.election + 1.0-SNAPSHOT + war + + + vs + graphql + 1.0-SNAPSHOT + + + diff --git a/21-graphql/graphql.election/src/main/java/vs/BallotBox.java b/21-graphql/graphql.election/src/main/java/vs/BallotBox.java new file mode 100644 index 0000000..db02889 --- /dev/null +++ b/21-graphql/graphql.election/src/main/java/vs/BallotBox.java @@ -0,0 +1,61 @@ +package vs; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class BallotBox { + private static Map votesUnsafe = new HashMap<>(); + private static Map votesSafe = Collections + .synchronizedMap(votesUnsafe); + + public static void vote(String choice) { + synchronized (votesSafe) { + var v = votesUnsafe.get(choice); + if (v == null) { + v = 0; + } + votesUnsafe.put(choice, v + 1); + } + } + + public static int votesNumber() { + var sum = 0; + synchronized (votesSafe) { + for (var choice : votesUnsafe.entrySet()) { + sum += choice.getValue(); + } + } + return sum; + } + + public static int votes(String choice) { + if (votesSafe.get(choice) == null) { + return 0; + } else { + return votesUnsafe.get(choice); + } + } + + public static List votes() { + var listOfVotes = new ArrayList(); + synchronized (votesSafe) { + for (var choice : votesUnsafe.entrySet()) { + listOfVotes.add(new Vote(choice.getKey(), choice.getValue())); + } + } + return listOfVotes; + } + + public static Vote cheat(String choice, int votes) { + BallotBox.votesSafe.put(choice, votes); + return new Vote(choice, votes); + } + + public static Set choices() { + return votesSafe.keySet(); + } +} diff --git a/21-graphql/graphql.election/src/main/java/vs/BallotBoxServlet.java b/21-graphql/graphql.election/src/main/java/vs/BallotBoxServlet.java new file mode 100644 index 0000000..df3475b --- /dev/null +++ b/21-graphql/graphql.election/src/main/java/vs/BallotBoxServlet.java @@ -0,0 +1,63 @@ +package vs; + +import java.io.IOException; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@SuppressWarnings("serial") +@WebServlet(urlPatterns = "/vote") +public class BallotBoxServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + var out = response.getWriter(); + response.setContentType("text/html"); + out.println(""); + var action = request.getParameter("action"); + if (action != null) { + if (action.equals("vote")) { + var alternative = request.getParameter("alternative"); + if ((alternative == null) || alternative.equals("")) { + alternative = "ungültige Stimmenabgabe"; + } + BallotBox.vote(alternative); + out.println("

    Ihre Stimme wurde gezählt.

    "); + } else if (action.equals("print")) { + out.println("

    abgegebene Stimmen

    "); + out.println(""); + out.println( + ""); + var sum = 0; + for (var vote : BallotBox.votes()) { + out.println( + ""); + out.println( + ""); + sum += vote.votes(); + } + out.println(""); + out.println(""); + out.println("
    AlternativeStimmen
    " + vote.choice() + "" + vote.votes() + "
    Summe:" + sum + "
    "); + } else { + response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, + "action-Parameter hatte den Wert '" + action + + "'. Erlaubte Werte sind 'vote' und 'print'"); + } + } else { + response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, + "action-Parameter hatte keinen Wert gesetzt. Erlaubte Werte sind 'vote' und 'print'"); + } + out.println(""); + out.flush(); + } + + @Override + protected void doPost(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + doGet(request, response); + } +} diff --git a/21-graphql/graphql.election/src/main/java/vs/GraphQLEndpoint.java b/21-graphql/graphql.election/src/main/java/vs/GraphQLEndpoint.java new file mode 100644 index 0000000..8d634f1 --- /dev/null +++ b/21-graphql/graphql.election/src/main/java/vs/GraphQLEndpoint.java @@ -0,0 +1,27 @@ +package vs; + +import jakarta.servlet.annotation.WebServlet; +import graphql.kickstart.servlet.GraphQLConfiguration; +import graphql.kickstart.servlet.GraphQLHttpServlet; +import graphql.kickstart.tools.SchemaParser; +import graphql.schema.GraphQLSchema; + +@SuppressWarnings("serial") +@WebServlet(urlPatterns = "/graphql") +public class GraphQLEndpoint extends GraphQLHttpServlet { + + @Override + protected GraphQLConfiguration getConfiguration() { + return GraphQLConfiguration.with(createSchema()).build(); + } + + static GraphQLSchema createSchema() { + return SchemaParser // + .newParser() // + .file("schema.graphqls")// + .resolvers(new Query()) // + .build()// + .makeExecutableSchema(); + } + +} diff --git a/21-graphql/graphql.election/src/main/java/vs/Main.java b/21-graphql/graphql.election/src/main/java/vs/Main.java new file mode 100644 index 0000000..e3d7856 --- /dev/null +++ b/21-graphql/graphql.election/src/main/java/vs/Main.java @@ -0,0 +1,13 @@ +package vs; + +import graphql.GraphQL; + +public class Main { + public static void main(String... args) { + var graph = GraphQL.newGraphQL(GraphQLEndpoint.createSchema()).build(); + BallotBox.vote("Dr. Amy Farrah Fowler"); + BallotBox.vote("Dr. Amy Farrah Fowler"); + var exec = graph.execute("{allVotes{choice votes}}"); + System.out.println(exec.toSpecification()); + } +} diff --git a/21-graphql/graphql.election/src/main/java/vs/Query.java b/21-graphql/graphql.election/src/main/java/vs/Query.java new file mode 100644 index 0000000..05ba94a --- /dev/null +++ b/21-graphql/graphql.election/src/main/java/vs/Query.java @@ -0,0 +1,15 @@ +package vs; + +import java.util.List; +import graphql.kickstart.tools.GraphQLQueryResolver; + +public class Query implements GraphQLQueryResolver { + + public List allVotes() { + return BallotBox.votes(); + } + + public int votesNumber() { + return BallotBox.votesNumber(); + } +} diff --git a/21-graphql/graphql.election/src/main/java/vs/Vote.java b/21-graphql/graphql.election/src/main/java/vs/Vote.java new file mode 100644 index 0000000..7229f32 --- /dev/null +++ b/21-graphql/graphql.election/src/main/java/vs/Vote.java @@ -0,0 +1,54 @@ +package vs; + +public class Vote { + private final String choice; + private final int votes; + + public String choice() { + return choice; + } + + public int votes() { + return votes; + } + + public Vote(String choice, int votes) { + super(); + this.choice = choice; + this.votes = votes; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((choice == null) ? 0 : choice.hashCode()); + result = prime * result + votes; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Vote other = (Vote) obj; + if (choice == null) { + if (other.choice != null) + return false; + } else if (!choice.equals(other.choice)) + return false; + if (votes != other.votes) + return false; + return true; + } + + @Override + public String toString() { + return "Vote [choice=" + choice + ", votes=" + votes + "]"; + } + +} diff --git a/21-graphql/graphql.election/src/main/resources/schema.graphqls b/21-graphql/graphql.election/src/main/resources/schema.graphqls new file mode 100644 index 0000000..50f2e2f --- /dev/null +++ b/21-graphql/graphql.election/src/main/resources/schema.graphqls @@ -0,0 +1,13 @@ +type Vote { + choice: String! + votes: Int! +} + +type Query { + allVotes: [Vote] + votesNumber: Int +} + +schema { + query: Query +} diff --git a/21-graphql/graphql.election/src/main/webapp/graphiql/index.html b/21-graphql/graphql.election/src/main/webapp/graphiql/index.html new file mode 100644 index 0000000..440fda4 --- /dev/null +++ b/21-graphql/graphql.election/src/main/webapp/graphiql/index.html @@ -0,0 +1,156 @@ + + + + +GraphiQL-UI für Klassensprecherwahlen + + + + + + + + + + + + + + + + + + + +
    Loading...
    + + + diff --git a/21-graphql/graphql.election/src/main/webapp/index.html b/21-graphql/graphql.election/src/main/webapp/index.html new file mode 100644 index 0000000..dd92e4e --- /dev/null +++ b/21-graphql/graphql.election/src/main/webapp/index.html @@ -0,0 +1,37 @@ + + + + + Klassensprecherwahlen + + +

    Online Wahl für das Amt der Klassensprecherin oder des + Klassensprechers

    +

    Sie haben eine Stimme. Wählen Sie Ihre Kandidatin oder Ihren + Kandidaten für das Amt des Klassensprechers:

    +

    Kandidaten:

    +
    + +
    + +
    +

    + Alternativ können Sie das Ergebnis der + Wahl abrufen. +

    + + + \ No newline at end of file diff --git a/21-graphql/graphql.election_solution/README.md b/21-graphql/graphql.election_solution/README.md new file mode 100644 index 0000000..0a78928 --- /dev/null +++ b/21-graphql/graphql.election_solution/README.md @@ -0,0 +1,30 @@ +# GraphQL Queries + +``just serve`` + + - zuerst einige Stimmen über das Servlet abgeben: ["Howard Joel Wolowitz" wählen](http://localhost:8080/vote?action=vote&alternative=Howard+Joel+Wolowitz) + - dann einige Stimmen weitere über das Servlet abgeben: ["Dr. Amy Farrah Fowler" wählen](http://localhost:8080/vote?action=vote&alternative=Dr.+Amy+Farrah+Fowler) + - über das Servlet abfragen, wie gewählt wurde: [Ergebnis abrufen](http://localhost:8080/vote?action=print) + +## GraphiQL-UI + +[http://localhost:8080/graphiql/](http://localhost:8080/graphiql/) + +## GraphQL-Queries +- Anzahl aller abgegebenen Stimmen: [``{votesNumber}``](http://localhost:8080/graphiql/?query=%23%20Anzahl%20aller%20abgegebenen%20Stimmen%0A%7B%0A%20%20votesNumber%0A%7D%0A) +- alle Stimmen: [``{allVotes {choice votes}}``](http://localhost:8080/graphiql/?query=%23%20alle%20Stimmen%3A%20%0Aquery%20%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A) +- alle Stimmen, nur die Namen: [``{allVotes {choice}}``](http://localhost:8080/graphiql/?query=%23%20alle%20Stimmen%2C%20nur%20die%20Namen%3A%20%0Aquery%20%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%7D%0A%7D%0A) +- Anzahl der Stimmen für "Dr. Amy Farrah Fowler": [``{votes(choice: "Dr. Amy Farrah Fowler")}``](http://localhost:8080/graphiql/?query=%23%20Anzahl%20der%20Stimmen%20f%C3%BCr%20%22Dr.%20Amy%20Farrah%20Fowler%22%3A%20%0A%7B%0A%20%20votes(choice%3A%20%22Dr.%20Amy%20Farrah%20Fowler%22)%0A%7D%0A) +- mit nicht gewähltem Namen geht es auch (Ergebnis = 0): [``{votes(choice: "Lex Luthor")}``](http://localhost:8080/graphiql/?query=%23%20mit%20nicht%20gew%C3%A4hltem%20Namen%20geht%20es%20auch%20(Ergebnis%20%3D%200)%3A%20%0A%7B%0A%20%20votes(choice%3A%20%22Lex%20Luthor%22)%0A%7D%0A) +- ohne Namen geht es nicht (Pflichtfeld): [``{votes()}``](http://localhost:8080/graphiql/?query=%23%20ohne%20Namen%20geht%20es%20nicht%20(Pflichtfeld)%3A%20%0Aquery%20%7Bvotes()%7D) + +## ändernde GraphQL-Queries *("Mutation")* + +- Mutation: Stimme für Superman abgeben: [``mutation {vote(choice: "Clark Kent")}``](http://localhost:8080/graphiql/?query=%23%20Mutation%3A%20Stimme%20f%C3%BCr%20Superman%20abgeben%3A%0Amutation%20%7B%0A%20%20vote(choice%3A%20%22Clark%20Kent%22)%0A%7D%0A) +- alle Stimmen, jetzt mit Clark Kent: [``{allVotes {choice votes}}``](http://localhost:8080/graphiql/?query=%23%20alle%20Stimmen%2C%20jetzt%20mit%20Clark%20Kent%3A%0Aquery%20%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A) +- Fehler: Anzahl Parameter falsch: [``mutation {vote(choice: "Clark Kent", votes: 42)}``](http://localhost:8080/graphiql/?query=%23%20Fehler%3A%20Anzahl%20Parameter%20falsch%3A%20%0Amutation%20%7B%0A%20%20vote(choice%3A%20%22Clark%20Kent%22%2C%20votes%3A%2042)%0A%7D%0A) +- Mutation: Datensatz ändern: [``mutation {cheat(choice: "Clark Kent" votes:43){choice}}``](http://localhost:8080/graphiql/?query=%23%20Mutation%3A%20Datensatz%20%C3%A4ndern%3A%0Amutation%20%7B%0A%20%20cheat(choice%3A%20%22Clark%20Kent%22%2C%20votes%3A%2043)%20%7B%0A%20%20%20%20choice%0A%20%20%7D%0A%7D%0A) +- Mutation: Datensatz ändern und Ergebnis-Datensatz sehen: [``mutation {cheat(choice: "Clark Kent", votes: 42){choice votes}}``](http://localhost:8080/graphiql/?query=%23%20Mutation%3A%20Datensatz%20%C3%A4ndern%20und%20Ergebnis-Datensatz%20sehen%3A%0Amutation%20%7B%0A%20%20cheat(choice%3A%20%22Clark%20Kent%22%2C%20votes%3A%2042)%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A) +- alle Stimmen, Anzahl Stimmen von Clark Kent geändert: [``{allVotes {choice votes}}``](http://localhost:8080/graphiql/?query=%23%20alle%20Stimmen%2C%20Anzahl%20Stimmen%20von%20Clark%20Kent%20ge%C3%A4ndert%3A%0A%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A) +- Mutation: Datensatz neu eintragen: [``mutation {cheat(choice: "Bruce Wayne", votes: 42){choice}}``](http://localhost:8080/graphiql/?query=%23%20Mutation%3A%20Datensatz%20neu%20eintragen%3A%0Amutation%20%7B%0A%20%20cheat(choice%3A%20%22Bruce%20Wayne%22%2C%20votes%3A%2042)%20%7B%0A%20%20%20%20choice%0A%20%20%7D%0A%7D%0A) +- alle Stimmen: [``{allVotes {choice votes}}``](http://localhost:8080/graphiql/?query=%23%20alle%20Stimmen%3A%0A%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A) diff --git a/21-graphql/graphql.election_solution/justfile b/21-graphql/graphql.election_solution/justfile new file mode 100644 index 0000000..0f4de74 --- /dev/null +++ b/21-graphql/graphql.election_solution/justfile @@ -0,0 +1,32 @@ +import '../justfile' + +base := 'http://localhost:8080/' + +client-test: + firefox {{base}}test +client-web: + firefox {{base}} +client-tui: + just exec vs.Main "" +client-graphiql: + firefox {{base}}graphiql/ + +skript-query: + just _step '%23%20Anzahl%20aller%20abgegebenen%20Stimmen%0A%7B%0A%20%20votesNumber%0A%7D%0A' + just _step '%23%20alle%20Stimmen%3A%20%0Aquery%20%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A' + just _step '%23%20alle%20Stimmen%2C%20nur%20die%20Namen%3A%20%0Aquery%20%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%7D%0A%7D%0A' + just _step '%23%20Anzahl%20der%20Stimmen%20f%C3%BCr%20%22Dr.%20Amy%20Farrah%20Fowler%22%3A%20%0A%7B%0A%20%20votes(choice%3A%20%22Dr.%20Amy%20Farrah%20Fowler%22)%0A%7D%0A' + just _step '%23%20mit%20nicht%20gew%C3%A4hltem%20Namen%20geht%20es%20auch%20(Ergebnis%20%3D%200)%3A%20%0A%7B%0A%20%20votes(choice%3A%20%22Lex%20Luthor%22)%0A%7D%0A' + just _step '%23%20ohne%20Namen%20geht%20es%20nicht%20(Pflichtfeld)%3A%20%0Aquery%20%7Bvotes()%7D' +skript-mutation: + just _step '%23%20Mutation%3A%20Stimme%20f%C3%BCr%20Superman%20abgeben%3A%0Amutation%20%7B%0A%20%20vote(choice%3A%20%22Clark%20Kent%22)%0A%7D%0A' + just _step '%23%20alle%20Stimmen%2C%20jetzt%20mit%20Clark%20Kent%3A%0Aquery%20%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A' + just _step '%23%20Fehler%3A%20Anzahl%20Parameter%20falsch%3A%20%0Amutation%20%7B%0A%20%20vote(choice%3A%20%22Clark%20Kent%22%2C%20votes%3A%2042)%0A%7D%0A' + just _step '%23%20Mutation%3A%20Datensatz%20%C3%A4ndern%3A%0Amutation%20%7B%0A%20%20cheat(choice%3A%20%22Clark%20Kent%22%2C%20votes%3A%2043)%20%7B%0A%20%20%20%20choice%0A%20%20%7D%0A%7D%0A' + just _step '%23%20Mutation%3A%20Datensatz%20%C3%A4ndern%20und%20Ergebnis-Datensatz%20sehen%3A%0Amutation%20%7B%0A%20%20cheat(choice%3A%20%22Clark%20Kent%22%2C%20votes%3A%2042)%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A' + just _step '%23%20alle%20Stimmen%2C%20Anzahl%20Stimmen%20von%20Clark%20Kent%20ge%C3%A4ndert%3A%0A%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A' + just _step '%23%20Mutation%3A%20Datensatz%20neu%20eintragen%3A%0Amutation%20%7B%0A%20%20cheat(choice%3A%20%22Bruce%20Wayne%22%2C%20votes%3A%2042)%20%7B%0A%20%20%20%20choice%0A%20%20%7D%0A%7D%0A' + just _step '%23%20alle%20Stimmen%3A%0A%7B%0A%20%20allVotes%20%7B%0A%20%20%20%20choice%0A%20%20%20%20votes%0A%20%20%7D%0A%7D%0A' + +_step query: + firefox '{{base}}graphiql/?query={{query}}' diff --git a/21-graphql/graphql.election_solution/pom.xml b/21-graphql/graphql.election_solution/pom.xml new file mode 100644 index 0000000..66a6c66 --- /dev/null +++ b/21-graphql/graphql.election_solution/pom.xml @@ -0,0 +1,14 @@ + + 4.0.0 + vs + graphql.election_solution + 1.0-SNAPSHOT + war + + + vs + graphql + 1.0-SNAPSHOT + + + diff --git a/21-graphql/graphql.election_solution/src/main/java/vs/BallotBox.java b/21-graphql/graphql.election_solution/src/main/java/vs/BallotBox.java new file mode 100644 index 0000000..db02889 --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/java/vs/BallotBox.java @@ -0,0 +1,61 @@ +package vs; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class BallotBox { + private static Map votesUnsafe = new HashMap<>(); + private static Map votesSafe = Collections + .synchronizedMap(votesUnsafe); + + public static void vote(String choice) { + synchronized (votesSafe) { + var v = votesUnsafe.get(choice); + if (v == null) { + v = 0; + } + votesUnsafe.put(choice, v + 1); + } + } + + public static int votesNumber() { + var sum = 0; + synchronized (votesSafe) { + for (var choice : votesUnsafe.entrySet()) { + sum += choice.getValue(); + } + } + return sum; + } + + public static int votes(String choice) { + if (votesSafe.get(choice) == null) { + return 0; + } else { + return votesUnsafe.get(choice); + } + } + + public static List votes() { + var listOfVotes = new ArrayList(); + synchronized (votesSafe) { + for (var choice : votesUnsafe.entrySet()) { + listOfVotes.add(new Vote(choice.getKey(), choice.getValue())); + } + } + return listOfVotes; + } + + public static Vote cheat(String choice, int votes) { + BallotBox.votesSafe.put(choice, votes); + return new Vote(choice, votes); + } + + public static Set choices() { + return votesSafe.keySet(); + } +} diff --git a/21-graphql/graphql.election_solution/src/main/java/vs/BallotBoxServlet.java b/21-graphql/graphql.election_solution/src/main/java/vs/BallotBoxServlet.java new file mode 100644 index 0000000..df3475b --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/java/vs/BallotBoxServlet.java @@ -0,0 +1,63 @@ +package vs; + +import java.io.IOException; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +@SuppressWarnings("serial") +@WebServlet(urlPatterns = "/vote") +public class BallotBoxServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + var out = response.getWriter(); + response.setContentType("text/html"); + out.println(""); + var action = request.getParameter("action"); + if (action != null) { + if (action.equals("vote")) { + var alternative = request.getParameter("alternative"); + if ((alternative == null) || alternative.equals("")) { + alternative = "ungültige Stimmenabgabe"; + } + BallotBox.vote(alternative); + out.println("

    Ihre Stimme wurde gezählt.

    "); + } else if (action.equals("print")) { + out.println("

    abgegebene Stimmen

    "); + out.println(""); + out.println( + ""); + var sum = 0; + for (var vote : BallotBox.votes()) { + out.println( + ""); + out.println( + ""); + sum += vote.votes(); + } + out.println(""); + out.println(""); + out.println("
    AlternativeStimmen
    " + vote.choice() + "" + vote.votes() + "
    Summe:" + sum + "
    "); + } else { + response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, + "action-Parameter hatte den Wert '" + action + + "'. Erlaubte Werte sind 'vote' und 'print'"); + } + } else { + response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, + "action-Parameter hatte keinen Wert gesetzt. Erlaubte Werte sind 'vote' und 'print'"); + } + out.println(""); + out.flush(); + } + + @Override + protected void doPost(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + doGet(request, response); + } +} diff --git a/21-graphql/graphql.election_solution/src/main/java/vs/GraphQLEndpoint.java b/21-graphql/graphql.election_solution/src/main/java/vs/GraphQLEndpoint.java new file mode 100644 index 0000000..e2ff520 --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/java/vs/GraphQLEndpoint.java @@ -0,0 +1,27 @@ +package vs; + +import jakarta.servlet.annotation.WebServlet; +import graphql.kickstart.servlet.GraphQLConfiguration; +import graphql.kickstart.servlet.GraphQLHttpServlet; +import graphql.kickstart.tools.SchemaParser; +import graphql.schema.GraphQLSchema; + +@SuppressWarnings("serial") +@WebServlet(urlPatterns = "/graphql") +public class GraphQLEndpoint extends GraphQLHttpServlet { + + @Override + protected GraphQLConfiguration getConfiguration() { + return GraphQLConfiguration.with(createSchema()).build(); + } + + static GraphQLSchema createSchema() { + return SchemaParser // + .newParser() // + .file("schema.graphqls")// + .resolvers(new Query(), new Mutation()) // + .build()// + .makeExecutableSchema(); + } + +} diff --git a/21-graphql/graphql.election_solution/src/main/java/vs/Main.java b/21-graphql/graphql.election_solution/src/main/java/vs/Main.java new file mode 100644 index 0000000..e9fb14c --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/java/vs/Main.java @@ -0,0 +1,14 @@ +package vs; + +import graphql.GraphQL; + +public class Main { + public static void main(String... args) { + var graph = GraphQL.newGraphQL(GraphQLEndpoint.createSchema()).build(); + BallotBox.vote("Dr. Amy Farrah Fowler"); + BallotBox.vote("Dr. Amy Farrah Fowler"); + var exec = graph.execute("mutation {vote(choice: \"Emily Sweeney\")}"); + exec = graph.execute("{allVotes{choice votes}}"); + System.out.println(exec.toSpecification()); + } +} diff --git a/21-graphql/graphql.election_solution/src/main/java/vs/Mutation.java b/21-graphql/graphql.election_solution/src/main/java/vs/Mutation.java new file mode 100644 index 0000000..e10b840 --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/java/vs/Mutation.java @@ -0,0 +1,15 @@ +package vs; + +import graphql.kickstart.tools.GraphQLMutationResolver; + +public class Mutation implements GraphQLMutationResolver { + + public boolean vote(String choice) { + BallotBox.vote(choice); + return true; + } + + public Vote cheat(String choice, int votes) { + return BallotBox.cheat(choice, votes); + } +} diff --git a/21-graphql/graphql.election_solution/src/main/java/vs/Query.java b/21-graphql/graphql.election_solution/src/main/java/vs/Query.java new file mode 100644 index 0000000..cc3e278 --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/java/vs/Query.java @@ -0,0 +1,19 @@ +package vs; + +import java.util.List; +import graphql.kickstart.tools.GraphQLQueryResolver; + +public class Query implements GraphQLQueryResolver { + + public List allVotes() { + return BallotBox.votes(); + } + + public int votesNumber() { + return BallotBox.votesNumber(); + } + + public int votes(String choice) { + return BallotBox.votes(choice); + } +} diff --git a/21-graphql/graphql.election_solution/src/main/java/vs/Test.java b/21-graphql/graphql.election_solution/src/main/java/vs/Test.java new file mode 100644 index 0000000..08cd49b --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/java/vs/Test.java @@ -0,0 +1,41 @@ +package vs; + +import jakarta.servlet.http.HttpServlet; +import java.io.IOException; +import jakarta.servlet.ServletException; +import jakarta.servlet.annotation.WebServlet; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; + +/** + * Servlet implementation class Test + */ +@WebServlet("/test") +public class Test extends HttpServlet { + private static final long serialVersionUID = 1L; + + /** + * @see HttpServlet#HttpServlet() + */ + public Test() { + super(); + // TODO Auto-generated constructor stub + } + + /** + * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) + */ + protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + // TODO Auto-generated method stub + response.getWriter().append("Served at: ").append(request.getContextPath()); + } + + /** + * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) + */ + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + // TODO Auto-generated method stub + doGet(request, response); + } + +} diff --git a/21-graphql/graphql.election_solution/src/main/java/vs/Vote.java b/21-graphql/graphql.election_solution/src/main/java/vs/Vote.java new file mode 100644 index 0000000..f7442c5 --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/java/vs/Vote.java @@ -0,0 +1,56 @@ +package vs; +public record Vote (String choice, int votes) {} +/* +public class Vote { + private final String choice; + private final int votes; + + public String choice() { + return choice; + } + + public int votes() { + return votes; + } + + public Vote(String choice, int votes) { + super(); + this.choice = choice; + this.votes = votes; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((choice == null) ? 0 : choice.hashCode()); + result = prime * result + votes; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Vote other = (Vote) obj; + if (choice == null) { + if (other.choice != null) + return false; + } else if (!choice.equals(other.choice)) + return false; + if (votes != other.votes) + return false; + return true; + } + + @Override + public String toString() { + return "Vote [choice=" + choice + ", votes=" + votes + "]"; + } + +} +*/ diff --git a/21-graphql/graphql.election_solution/src/main/resources/schema.graphqls b/21-graphql/graphql.election_solution/src/main/resources/schema.graphqls new file mode 100644 index 0000000..7d45194 --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/resources/schema.graphqls @@ -0,0 +1,20 @@ +type Vote { + choice: String! + votes: Int! +} + +type Query { + allVotes: [Vote] + votesNumber: Int + votes(choice: String!): Int +} + +type Mutation { + vote(choice: String): Boolean + cheat(choice: String, votes: Int): Vote +} + +schema { + query: Query + mutation: Mutation +} diff --git a/21-graphql/graphql.election_solution/src/main/webapp/META-INF/MANIFEST.MF b/21-graphql/graphql.election_solution/src/main/webapp/META-INF/MANIFEST.MF new file mode 100644 index 0000000..5e94951 --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/webapp/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/21-graphql/graphql.election_solution/src/main/webapp/WEB-INF/web.xml b/21-graphql/graphql.election_solution/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 0000000..74b69e0 --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,12 @@ + + + graphql.election_solution + + index.html + index.htm + index.jsp + default.html + default.htm + default.jsp + + diff --git a/21-graphql/graphql.election_solution/src/main/webapp/graphiql/index.html b/21-graphql/graphql.election_solution/src/main/webapp/graphiql/index.html new file mode 100644 index 0000000..440fda4 --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/webapp/graphiql/index.html @@ -0,0 +1,156 @@ + + + + +GraphiQL-UI für Klassensprecherwahlen + + + + + + + + + + + + + + + + + + + +
    Loading...
    + + + diff --git a/21-graphql/graphql.election_solution/src/main/webapp/index.html b/21-graphql/graphql.election_solution/src/main/webapp/index.html new file mode 100644 index 0000000..dd92e4e --- /dev/null +++ b/21-graphql/graphql.election_solution/src/main/webapp/index.html @@ -0,0 +1,37 @@ + + + + + Klassensprecherwahlen + + +

    Online Wahl für das Amt der Klassensprecherin oder des + Klassensprechers

    +

    Sie haben eine Stimme. Wählen Sie Ihre Kandidatin oder Ihren + Kandidaten für das Amt des Klassensprechers:

    +

    Kandidaten:

    +
    + +
    + +
    +

    + Alternativ können Sie das Ergebnis der + Wahl abrufen. +

    + + + \ No newline at end of file diff --git a/21-graphql/justfile b/21-graphql/justfile new file mode 100644 index 0000000..9f5ff22 --- /dev/null +++ b/21-graphql/justfile @@ -0,0 +1,7 @@ +import '../justfile' + +serve: default war + mvn jetty:run +war: + mvn war:war + touch src/main/webapp/index.html diff --git a/21-graphql/pom.xml b/21-graphql/pom.xml new file mode 100644 index 0000000..de4c176 --- /dev/null +++ b/21-graphql/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + vs + graphql + 1.0-SNAPSHOT + pom + + + vs + parent + 1.0-SNAPSHOT + + + + + jakarta.servlet + jakarta.servlet-api + 6.0.0 + provided + + + com.graphql-java-kickstart + graphql-java-servlet + 16.0.0 + + + com.graphql-java-kickstart + graphql-java-tools + 14.0.0 + + + + + + + org.eclipse.jetty.ee10 + jetty-ee10-maven-plugin + 12.0.14 + + + org.apache.maven.plugins + maven-war-plugin + 3.4.0 + + + + diff --git a/22-grpc/grpc.quarkus_solution/.dockerignore b/22-grpc/grpc.quarkus_solution/.dockerignore new file mode 100644 index 0000000..94810d0 --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/.dockerignore @@ -0,0 +1,5 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* +!target/quarkus-app/* \ No newline at end of file diff --git a/22-grpc/grpc.quarkus_solution/.gitignore b/22-grpc/grpc.quarkus_solution/.gitignore new file mode 100644 index 0000000..bdf57ce --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/.gitignore @@ -0,0 +1,39 @@ +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +release.properties + +# Eclipse +.project +.classpath +.settings/ +bin/ + +# IntelliJ +.idea +*.ipr +*.iml +*.iws + +# NetBeans +nb-configuration.xml + +# Visual Studio Code +.vscode +.factorypath + +# OSX +.DS_Store + +# Vim +*.swp +*.swo + +# patch +*.orig +*.rej + +# Local environment +.env diff --git a/22-grpc/grpc.quarkus_solution/.mvn/wrapper/MavenWrapperDownloader.java b/22-grpc/grpc.quarkus_solution/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..e76d1f3 --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed 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 + * + * https://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 License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/22-grpc/grpc.quarkus_solution/.mvn/wrapper/maven-wrapper.jar b/22-grpc/grpc.quarkus_solution/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..2cc7d4a Binary files /dev/null and b/22-grpc/grpc.quarkus_solution/.mvn/wrapper/maven-wrapper.jar differ diff --git a/22-grpc/grpc.quarkus_solution/.mvn/wrapper/maven-wrapper.properties b/22-grpc/grpc.quarkus_solution/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..598fb34 --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/22-grpc/grpc.quarkus_solution/README.md b/22-grpc/grpc.quarkus_solution/README.md new file mode 100644 index 0000000..8c090d0 --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/README.md @@ -0,0 +1,51 @@ +# grpc_quarkus_solution Project + +This project uses Quarkus, the Supersonic Subatomic Java Framework. + +If you want to learn more about Quarkus, please visit its website: https://quarkus.io/ . + +## Running the application in dev mode + +You can run your application in dev mode that enables live coding using: +```shell script +./mvnw compile quarkus:dev +``` + +> **_NOTE:_** Quarkus now ships with a Dev UI, which is available in dev mode only at http://localhost:8080/q/dev/. + +## Packaging and running the application + +The application can be packaged using: +```shell script +./mvnw package +``` +It produces the `quarkus-run.jar` file in the `target/quarkus-app/` directory. +Be aware that it’s not an _über-jar_ as the dependencies are copied into the `target/quarkus-app/lib/` directory. + +The application is now runnable using `java -jar target/quarkus-app/quarkus-run.jar`. + +If you want to build an _über-jar_, execute the following command: +```shell script +./mvnw package -Dquarkus.package.type=uber-jar +``` + +The application, packaged as an _über-jar_, is now runnable using `java -jar target/*-runner.jar`. + +## Creating a native executable + +You can create a native executable using: +```shell script +./mvnw package -Pnative +``` + +Or, if you don't have GraalVM installed, you can run the native executable build in a container using: +```shell script +./mvnw package -Pnative -Dquarkus.native.container-build=true +``` + +You can then execute your native executable with: `./target/grpc_quarkus_solution-1.0.0-SNAPSHOT-runner` + +If you want to learn more about building native executables, please consult https://quarkus.io/guides/maven-tooling. + +## Related Guides + diff --git a/22-grpc/grpc.quarkus_solution/justfile b/22-grpc/grpc.quarkus_solution/justfile new file mode 100644 index 0000000..b99e618 --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/justfile @@ -0,0 +1,17 @@ +server: clean compile + mvn quarkus:dev +client: + just -f ../grpc.syslog/justfile client localhost +clean: + mvn clean +uber: clean compile + mvn package -Dquarkus.package.type=uber-jar +runner: uber + java -jar target/grpc.quarkus_solution-1.0.0-SNAPSHOT-runner.jar +compile: + mvn compile +native: clean + mvn package -Pnative +dockerize: native + docker build -f src/main/docker/Dockerfile.native -t vs.grpc.quarkus_solution . + diff --git a/22-grpc/grpc.quarkus_solution/mvnw b/22-grpc/grpc.quarkus_solution/mvnw new file mode 100755 index 0000000..a16b543 --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF 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 +# +# https://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 License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/22-grpc/grpc.quarkus_solution/mvnw.cmd b/22-grpc/grpc.quarkus_solution/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/22-grpc/grpc.quarkus_solution/pom.xml b/22-grpc/grpc.quarkus_solution/pom.xml new file mode 100644 index 0000000..221d61e --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/pom.xml @@ -0,0 +1,118 @@ + + + 4.0.0 + vs + grpc.quarkus_solution + 1.0.0-SNAPSHOT + + 3.8.1 + 11 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 2.6.3.Final + 3.0.0-M5 + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + io.quarkus + quarkus-grpc + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-junit5 + test + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + + -parameters + + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + native + + + native + + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + native + + + + diff --git a/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.jvm b/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.jvm new file mode 100644 index 0000000..2f21983 --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.jvm @@ -0,0 +1,41 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/grpc_quarkus_solution-jvm . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/grpc_quarkus_solution-jvm +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 quarkus/grpc_quarkus_solution-jvm +# +### +FROM registry.access.redhat.com/ubi8/openjdk-11-runtime:1.10 + +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' + +# Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size. +ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" + +# We make four distinct layers so if there are application changes the library layers can be re-used +COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/ +COPY --chown=185 target/quarkus-app/*.jar /deployments/ +COPY --chown=185 target/quarkus-app/app/ /deployments/app/ +COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/ + +EXPOSE 9000 +USER 185 + +ENTRYPOINT [ "java", "-jar", "/deployments/quarkus-run.jar" ] + diff --git a/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.legacy-jar b/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.legacy-jar new file mode 100644 index 0000000..090314a --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.legacy-jar @@ -0,0 +1,37 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package -Dquarkus.package.type=legacy-jar +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/grpc_quarkus_solution-legacy-jar . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/grpc_quarkus_solution-legacy-jar +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 quarkus/grpc_quarkus_solution-legacy-jar +# +### +FROM registry.access.redhat.com/ubi8/openjdk-11-runtime:1.10 + +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' + +# Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size. +ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" + +COPY target/lib/* /deployments/lib/ +COPY target/*-runner.jar /deployments/quarkus-run.jar + +EXPOSE 9000 +USER 185 + +ENTRYPOINT [ "java", "-jar", "/deployments/quarkus-run.jar" ] diff --git a/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.native b/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.native new file mode 100644 index 0000000..f117346 --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.native @@ -0,0 +1,27 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native -t quarkus/grpc_quarkus_solution . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/grpc_quarkus_solution +# +### +FROM quay.io/quarkus/quarkus-micro-image:1.0 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 9000 +USER 1001 + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.native-distroless b/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.native-distroless new file mode 100644 index 0000000..83d63fa --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/src/main/docker/Dockerfile.native-distroless @@ -0,0 +1,23 @@ +#### +# This Dockerfile is used in order to build a distroless container that runs the Quarkus application in native (no JVM) mode +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native-distroless -t quarkus/grpc_quarkus_solution . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/grpc_quarkus_solution +# +### +FROM quay.io/quarkus/quarkus-distroless-image:1.0 +COPY target/*-runner /application + +EXPOSE 9000 +USER nonroot + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/22-grpc/grpc.quarkus_solution/src/main/java/vs/SyslogService.java b/22-grpc/grpc.quarkus_solution/src/main/java/vs/SyslogService.java new file mode 100644 index 0000000..492fdfd --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/src/main/java/vs/SyslogService.java @@ -0,0 +1,38 @@ +package vs; + +import io.quarkus.grpc.GrpcService; +import io.smallrye.mutiny.Uni; + +import vs.Syslog; +import vs.SyslogOuterClass.Message; +import vs.SyslogOuterClass.Result; +import vs.SyslogOuterClass.Severity; + +@GrpcService +public class SyslogService implements Syslog { + + @Override + public Uni checkUrgency(Message message) { + boolean urgency = false; + if (message.getPriority() == Severity.Alert + || message.getPriority() == Severity.Critical) { + urgency = true; + } + + Result result = Result // + .newBuilder() // + .setVal(urgency) // + .build(); + return Uni.createFrom().item(result); + } + + @Override + public Uni log(Message message) { + System.out.println(message); + return Uni.createFrom().item(Result// + .newBuilder() // + .setVal(true) // + .build()); + } + +} diff --git a/22-grpc/grpc.quarkus_solution/src/main/proto/syslog.proto b/22-grpc/grpc.quarkus_solution/src/main/proto/syslog.proto new file mode 100644 index 0000000..5b1ccae --- /dev/null +++ b/22-grpc/grpc.quarkus_solution/src/main/proto/syslog.proto @@ -0,0 +1,52 @@ +syntax = "proto3"; + +package vs; + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/any.proto"; + +service Syslog { + rpc CheckUrgency(Message) returns (Result) {}; + rpc Log(Message) returns (Result) {}; +} + +enum Severity { + Emergency = 0; + Alert = 1; + Critical = 2; + Error = 3; + Warning = 4; + Notice = 5; + Informational = 6; + Debug = 7; +} + +message StructuredData { + string key = 1; + string value = 2; +} + +message ComplexData { + string key = 1; + oneof value { + string text = 2; + google.protobuf.Any data = 3; + } +} + + +message Message { + Severity priority = 1; + uint32 version = 2; + google.protobuf.Timestamp timestamp = 3; + string hostname = 4; + string appname = 5; + uint32 procid = 6; + uint32 msgid = 7; + repeated StructuredData structureddata = 9; + repeated ComplexData data = 8; +} + +message Result { + bool val = 1; +} diff --git a/22-grpc/grpc.quarkus_solution/src/main/resources/application.properties b/22-grpc/grpc.quarkus_solution/src/main/resources/application.properties new file mode 100644 index 0000000..e69de29 diff --git a/22-grpc/grpc.syslog/justfile b/22-grpc/grpc.syslog/justfile new file mode 100644 index 0000000..012577d --- /dev/null +++ b/22-grpc/grpc.syslog/justfile @@ -0,0 +1,7 @@ +import '../justfile' + +server: + just exec vs.SyslogServer "" + +client host: + just exec vs.SyslogClient "{{host}}" diff --git a/22-grpc/grpc.syslog/pom.xml b/22-grpc/grpc.syslog/pom.xml new file mode 100644 index 0000000..a8b8e20 --- /dev/null +++ b/22-grpc/grpc.syslog/pom.xml @@ -0,0 +1,13 @@ + + 4.0.0 + vs + grpc.syslog + 1.0-SNAPSHOT + jar + + + vs + grpc + 1.0-SNAPSHOT + + diff --git a/22-grpc/grpc.syslog/src/main/java/vs/SyslogClient.java b/22-grpc/grpc.syslog/src/main/java/vs/SyslogClient.java new file mode 100644 index 0000000..d01214c --- /dev/null +++ b/22-grpc/grpc.syslog/src/main/java/vs/SyslogClient.java @@ -0,0 +1,42 @@ +package vs; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; + +import vs.SyslogGrpc; +import vs.SyslogOuterClass.ComplexData; +import vs.SyslogOuterClass.Message; +import vs.SyslogOuterClass.Severity; + +public class SyslogClient { + public static void main(String[] args) throws Exception { + ManagedChannel managedChannel = ManagedChannelBuilder + .forAddress(args[0], 9000)// + .usePlaintext()// + .build(); + SyslogGrpc.SyslogBlockingStub server = SyslogGrpc + .newBlockingStub(managedChannel); + + Message m = Message // + .newBuilder() // + .setAppname("Test App") // + .addData(ComplexData // + .newBuilder() // + .setKey("key 1") // + .setText("data 1") // + .build()) // + .addData(ComplexData // + .newBuilder() // + .setKey("key 2") // + .setText("data 2") // + .build()) // + .setPriority(Severity.Alert) // + .build(); + + if (server.checkUrgency(m).getVal()) { + System.out.println("client received: " + server.log(m).getVal()); + } + managedChannel.shutdown(); + } + +} diff --git a/22-grpc/grpc.syslog/src/main/java/vs/SyslogServer.java b/22-grpc/grpc.syslog/src/main/java/vs/SyslogServer.java new file mode 100644 index 0000000..4cbcef7 --- /dev/null +++ b/22-grpc/grpc.syslog/src/main/java/vs/SyslogServer.java @@ -0,0 +1,53 @@ +package vs; + +import java.io.IOException; +import io.grpc.Server; +import io.grpc.ServerBuilder; +import io.grpc.stub.StreamObserver; + + +import vs.SyslogGrpc; +import vs.SyslogOuterClass.Message; +import vs.SyslogOuterClass.Result; +import vs.SyslogOuterClass.Severity; + +public class SyslogServer extends SyslogGrpc.SyslogImplBase { + + @Override + public void checkUrgency(Message message, + StreamObserver resultObserver) { + boolean urgency = false; + if (message.getPriority() == Severity.Alert + || message.getPriority() == Severity.Critical) { + urgency = true; + } + + Result result = Result // + .newBuilder() // + .setVal(urgency) // + .build(); + resultObserver.onNext(result); + resultObserver.onCompleted(); + } + + @Override + public void log(Message message, StreamObserver resultObserver) { + System.out.println(message); + Result result = Result // + .newBuilder() // + .setVal(true) // + .build(); + resultObserver.onNext(result); + resultObserver.onCompleted(); + } + + public static void main(String[] args) + throws IOException, InterruptedException { + Server server = ServerBuilder // + .forPort(9000) // + .addService(new SyslogServer()) // + .build(); + server.start(); + server.awaitTermination(); + } +} diff --git a/22-grpc/grpc.syslog/src/main/proto/syslog.proto b/22-grpc/grpc.syslog/src/main/proto/syslog.proto new file mode 100644 index 0000000..3e9cb58 --- /dev/null +++ b/22-grpc/grpc.syslog/src/main/proto/syslog.proto @@ -0,0 +1,52 @@ +syntax = "proto3"; + +package vs; + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/any.proto"; + +service Syslog { + rpc CheckUrgency(Message) returns (Result) {}; + rpc Log(Message) returns (Result) {}; +} + +enum Severity { + Emergency = 0; + Alert = 1; + Critical = 2; + Error = 3; + Warning = 4; + Notice = 5; + Informational = 6; + Debug = 7; +} + +message StructuredData { + string key = 1; + string value = 2; +} + +message ComplexData { + string key = 1; + oneof value { + string text = 2; + google.protobuf.Any data = 3; + } +} + + +message Message { + Severity priority = 1; + uint32 version = 2; + google.protobuf.Timestamp timestamp = 3; + string hostname = 4; + string appname = 5; + uint32 procid = 6; + uint32 msgid = 7; + repeated StructuredData structureddata = 9; + repeated ComplexData data = 8; +} + +message Result { + bool val = 1; +} diff --git a/22-grpc/justfile b/22-grpc/justfile new file mode 100644 index 0000000..97c8a6d --- /dev/null +++ b/22-grpc/justfile @@ -0,0 +1,4 @@ +import '../justfile' + +build: + mvn clean protobuf:compile compile package diff --git a/22-grpc/pom.xml b/22-grpc/pom.xml new file mode 100644 index 0000000..ac4981e --- /dev/null +++ b/22-grpc/pom.xml @@ -0,0 +1,72 @@ + + 4.0.0 + vs + grpc + 1.0-SNAPSHOT + pom + + + vs + parent + 1.0-SNAPSHOT + + + + + io.grpc + grpc-netty + 1.62.2 + + + io.grpc + grpc-protobuf + 1.62.2 + + + io.grpc + grpc-stub + 1.62.2 + + + com.google.protobuf + protobuf-java + 4.28.3 + + + org.apache.tomcat + annotations-api + 6.0.53 + provided + + + + + + + kr.motd.maven + os-maven-plugin + 1.6.2 + + + + + org.xolstice.maven.plugins + protobuf-maven-plugin + 0.6.1 + + com.google.protobuf:protoc:4.28.3:exe:${os.detected.classifier} + grpc-java + io.grpc:protoc-gen-grpc-java:1.39.0:exe:${os.detected.classifier} + + + + + compile + compile-custom + + + + + + + diff --git a/99-microservices/quarkus-rest/.dockerignore b/99-microservices/quarkus-rest/.dockerignore new file mode 100644 index 0000000..94810d0 --- /dev/null +++ b/99-microservices/quarkus-rest/.dockerignore @@ -0,0 +1,5 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* +!target/quarkus-app/* \ No newline at end of file diff --git a/99-microservices/quarkus-rest/.gitignore b/99-microservices/quarkus-rest/.gitignore new file mode 100644 index 0000000..91a800a --- /dev/null +++ b/99-microservices/quarkus-rest/.gitignore @@ -0,0 +1,45 @@ +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +release.properties +.flattened-pom.xml + +# Eclipse +.project +.classpath +.settings/ +bin/ + +# IntelliJ +.idea +*.ipr +*.iml +*.iws + +# NetBeans +nb-configuration.xml + +# Visual Studio Code +.vscode +.factorypath + +# OSX +.DS_Store + +# Vim +*.swp +*.swo + +# patch +*.orig +*.rej + +# Local environment +.env + +# Plugin directory +/.quarkus/cli/plugins/ +# TLS Certificates +.certs/ diff --git a/99-microservices/quarkus-rest/.justfile b/99-microservices/quarkus-rest/.justfile new file mode 100644 index 0000000..55f21f6 --- /dev/null +++ b/99-microservices/quarkus-rest/.justfile @@ -0,0 +1,13 @@ +default: + #!/usr/bin/env bash + just dev & + just ui + +dev: + mvn clean compile quarkus:dev +test: + mvn clean compile test +ui: + chromium-browser http://localhost:8080/q/dev-ui/welcome +dev-ui: + chromium-browser http://localhost:8080/q/dev-ui/extensions diff --git a/99-microservices/quarkus-rest/README.md b/99-microservices/quarkus-rest/README.md new file mode 100644 index 0000000..35e4ccd --- /dev/null +++ b/99-microservices/quarkus-rest/README.md @@ -0,0 +1,66 @@ +# quarkus-rest + +This project uses Quarkus, the Supersonic Subatomic Java Framework. + +If you want to learn more about Quarkus, please visit its website: . + +## Running the application in dev mode + +You can run your application in dev mode that enables live coding using: + +```shell script +./mvnw quarkus:dev +``` + +> **_NOTE:_** Quarkus now ships with a Dev UI, which is available in dev mode only at . + +## Packaging and running the application + +The application can be packaged using: + +```shell script +./mvnw package +``` + +It produces the `quarkus-run.jar` file in the `target/quarkus-app/` directory. +Be aware that it’s not an _über-jar_ as the dependencies are copied into the `target/quarkus-app/lib/` directory. + +The application is now runnable using `java -jar target/quarkus-app/quarkus-run.jar`. + +If you want to build an _über-jar_, execute the following command: + +```shell script +./mvnw package -Dquarkus.package.jar.type=uber-jar +``` + +The application, packaged as an _über-jar_, is now runnable using `java -jar target/*-runner.jar`. + +## Creating a native executable + +You can create a native executable using: + +```shell script +./mvnw package -Dnative +``` + +Or, if you don't have GraalVM installed, you can run the native executable build in a container using: + +```shell script +./mvnw package -Dnative -Dquarkus.native.container-build=true +``` + +You can then execute your native executable with: `./target/quarkus-rest-1.0.0-SNAPSHOT-runner` + +If you want to learn more about building native executables, please consult . + +## Related Guides + +- REST ([guide](https://quarkus.io/guides/rest)): A Jakarta REST implementation utilizing build time processing and Vert.x. This extension is not compatible with the quarkus-resteasy extension, or any of the extensions that depend on it. + +## Provided Code + +### REST + +Easily start your REST Web Services + +[Related guide section...](https://quarkus.io/guides/getting-started-reactive#reactive-jax-rs-resources) diff --git a/99-microservices/quarkus-rest/pom.xml b/99-microservices/quarkus-rest/pom.xml new file mode 100644 index 0000000..44e2692 --- /dev/null +++ b/99-microservices/quarkus-rest/pom.xml @@ -0,0 +1,124 @@ + + + 4.0.0 + vs + quarkus-rest + 1.0.0-SNAPSHOT + + + 3.13.0 + 21 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 3.17.8 + true + 3.5.0 + + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + + io.quarkus + quarkus-rest + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + native-image-agent + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + true + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + native + + + native + + + + false + true + + + + diff --git a/99-microservices/quarkus-rest/src/main/docker/Dockerfile.jvm b/99-microservices/quarkus-rest/src/main/docker/Dockerfile.jvm new file mode 100644 index 0000000..55682ac --- /dev/null +++ b/99-microservices/quarkus-rest/src/main/docker/Dockerfile.jvm @@ -0,0 +1,97 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/quarkus-rest-jvm . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-rest-jvm +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005. +# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005 +# when running the container +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-rest-jvm +# +# This image uses the `run-java.sh` script to run the application. +# This scripts computes the command line to execute your Java application, and +# includes memory/GC tuning. +# You can configure the behavior using the following environment properties: +# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") +# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options +# in JAVA_OPTS (example: "-Dsome.property=foo") +# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is +# used to calculate a default maximal heap memory based on a containers restriction. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio +# of the container available memory as set here. The default is `50` which means 50% +# of the available memory is used as an upper boundary. You can skip this mechanism by +# setting this value to `0` in which case no `-Xmx` option is added. +# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This +# is used to calculate a default initial heap memory based on the maximum heap memory. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio +# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx` +# is used as the initial heap size. You can skip this mechanism by setting this value +# to `0` in which case no `-Xms` option is added (example: "25") +# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS. +# This is used to calculate the maximum value of the initial heap memory. If used in +# a container without any memory constraints for the container then this option has +# no effect. If there is a memory constraint then `-Xms` is limited to the value set +# here. The default is 4096MB which means the calculated value of `-Xms` never will +# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096") +# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output +# when things are happening. This option, if set to true, will set +# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true"). +# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example: +# true"). +# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787"). +# - CONTAINER_CORE_LIMIT: A calculated core limit as described in +# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2") +# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024"). +# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion. +# (example: "20") +# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking. +# (example: "40") +# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection. +# (example: "4") +# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus +# previous GC times. (example: "90") +# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20") +# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100") +# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should +# contain the necessary JRE command-line options to specify the required GC, which +# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC). +# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080") +# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080") +# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be +# accessed directly. (example: "foo.example.com,bar.example.com") +# +### +FROM registry.access.redhat.com/ubi8/openjdk-21:1.20 + +ENV LANGUAGE='en_US:en' + + +# We make four distinct layers so if there are application changes the library layers can be re-used +COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/ +COPY --chown=185 target/quarkus-app/*.jar /deployments/ +COPY --chown=185 target/quarkus-app/app/ /deployments/app/ +COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/ + +EXPOSE 8080 +USER 185 +ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" + +ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ] + diff --git a/99-microservices/quarkus-rest/src/main/docker/Dockerfile.legacy-jar b/99-microservices/quarkus-rest/src/main/docker/Dockerfile.legacy-jar new file mode 100644 index 0000000..6c77257 --- /dev/null +++ b/99-microservices/quarkus-rest/src/main/docker/Dockerfile.legacy-jar @@ -0,0 +1,93 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package -Dquarkus.package.jar.type=legacy-jar +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/quarkus-rest-legacy-jar . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-rest-legacy-jar +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005 being the default) like this : EXPOSE 8080 5005. +# Additionally you will have to set -e JAVA_DEBUG=true and -e JAVA_DEBUG_PORT=*:5005 +# when running the container +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-rest-legacy-jar +# +# This image uses the `run-java.sh` script to run the application. +# This scripts computes the command line to execute your Java application, and +# includes memory/GC tuning. +# You can configure the behavior using the following environment properties: +# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") +# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options +# in JAVA_OPTS (example: "-Dsome.property=foo") +# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is +# used to calculate a default maximal heap memory based on a containers restriction. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio +# of the container available memory as set here. The default is `50` which means 50% +# of the available memory is used as an upper boundary. You can skip this mechanism by +# setting this value to `0` in which case no `-Xmx` option is added. +# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This +# is used to calculate a default initial heap memory based on the maximum heap memory. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio +# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx` +# is used as the initial heap size. You can skip this mechanism by setting this value +# to `0` in which case no `-Xms` option is added (example: "25") +# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS. +# This is used to calculate the maximum value of the initial heap memory. If used in +# a container without any memory constraints for the container then this option has +# no effect. If there is a memory constraint then `-Xms` is limited to the value set +# here. The default is 4096MB which means the calculated value of `-Xms` never will +# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096") +# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output +# when things are happening. This option, if set to true, will set +# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true"). +# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example: +# true"). +# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787"). +# - CONTAINER_CORE_LIMIT: A calculated core limit as described in +# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2") +# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024"). +# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion. +# (example: "20") +# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking. +# (example: "40") +# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection. +# (example: "4") +# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus +# previous GC times. (example: "90") +# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20") +# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100") +# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should +# contain the necessary JRE command-line options to specify the required GC, which +# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC). +# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080") +# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080") +# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be +# accessed directly. (example: "foo.example.com,bar.example.com") +# +### +FROM registry.access.redhat.com/ubi8/openjdk-21:1.20 + +ENV LANGUAGE='en_US:en' + + +COPY target/lib/* /deployments/lib/ +COPY target/*-runner.jar /deployments/quarkus-run.jar + +EXPOSE 8080 +USER 185 +ENV JAVA_OPTS_APPEND="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" + +ENTRYPOINT [ "/opt/jboss/container/java/run/run-java.sh" ] diff --git a/99-microservices/quarkus-rest/src/main/docker/Dockerfile.native b/99-microservices/quarkus-rest/src/main/docker/Dockerfile.native new file mode 100644 index 0000000..0f48fbe --- /dev/null +++ b/99-microservices/quarkus-rest/src/main/docker/Dockerfile.native @@ -0,0 +1,27 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode. +# +# Before building the container image run: +# +# ./mvnw package -Dnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native -t quarkus/quarkus-rest . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-rest +# +### +FROM registry.access.redhat.com/ubi8/ubi-minimal:8.10 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 8080 +USER 1001 + +ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/99-microservices/quarkus-rest/src/main/docker/Dockerfile.native-micro b/99-microservices/quarkus-rest/src/main/docker/Dockerfile.native-micro new file mode 100644 index 0000000..8958ec2 --- /dev/null +++ b/99-microservices/quarkus-rest/src/main/docker/Dockerfile.native-micro @@ -0,0 +1,30 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode. +# It uses a micro base image, tuned for Quarkus native executables. +# It reduces the size of the resulting container image. +# Check https://quarkus.io/guides/quarkus-runtime-base-image for further information about this image. +# +# Before building the container image run: +# +# ./mvnw package -Dnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native-micro -t quarkus/quarkus-rest . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus-rest +# +### +FROM quay.io/quarkus/quarkus-micro-image:2.0 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 8080 +USER 1001 + +ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/99-microservices/quarkus-rest/src/main/java/vs/GreetingResource.java b/99-microservices/quarkus-rest/src/main/java/vs/GreetingResource.java new file mode 100644 index 0000000..fed713e --- /dev/null +++ b/99-microservices/quarkus-rest/src/main/java/vs/GreetingResource.java @@ -0,0 +1,16 @@ +package vs; + +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; + +@Path("/hello") +public class GreetingResource { + + @GET + @Produces(MediaType.TEXT_PLAIN) + public String hello() { + return "Hello from Quarkus REST"; + } +} diff --git a/99-microservices/quarkus-rest/src/main/resources/application.properties b/99-microservices/quarkus-rest/src/main/resources/application.properties new file mode 100644 index 0000000..e69de29 diff --git a/99-microservices/quarkus-rest/src/test/java/vs/GreetingResourceIT.java b/99-microservices/quarkus-rest/src/test/java/vs/GreetingResourceIT.java new file mode 100644 index 0000000..39183df --- /dev/null +++ b/99-microservices/quarkus-rest/src/test/java/vs/GreetingResourceIT.java @@ -0,0 +1,8 @@ +package vs; + +import io.quarkus.test.junit.QuarkusIntegrationTest; + +@QuarkusIntegrationTest +class GreetingResourceIT extends GreetingResourceTest { + // Execute the same tests but in packaged mode. +} diff --git a/99-microservices/quarkus-rest/src/test/java/vs/GreetingResourceTest.java b/99-microservices/quarkus-rest/src/test/java/vs/GreetingResourceTest.java new file mode 100644 index 0000000..92a7686 --- /dev/null +++ b/99-microservices/quarkus-rest/src/test/java/vs/GreetingResourceTest.java @@ -0,0 +1,20 @@ +package vs; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.CoreMatchers.is; + +@QuarkusTest +class GreetingResourceTest { + @Test + void testHelloEndpoint() { + given() + .when().get("/hello") + .then() + .statusCode(200) + .body(is("Hello from Quarkus REST")); + } + +} \ No newline at end of file diff --git a/99-microservices/quarkus_solution/.dockerignore b/99-microservices/quarkus_solution/.dockerignore new file mode 100755 index 0000000..94810d0 --- /dev/null +++ b/99-microservices/quarkus_solution/.dockerignore @@ -0,0 +1,5 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* +!target/quarkus-app/* \ No newline at end of file diff --git a/99-microservices/quarkus_solution/.gitignore b/99-microservices/quarkus_solution/.gitignore new file mode 100755 index 0000000..bdf57ce --- /dev/null +++ b/99-microservices/quarkus_solution/.gitignore @@ -0,0 +1,39 @@ +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +release.properties + +# Eclipse +.project +.classpath +.settings/ +bin/ + +# IntelliJ +.idea +*.ipr +*.iml +*.iws + +# NetBeans +nb-configuration.xml + +# Visual Studio Code +.vscode +.factorypath + +# OSX +.DS_Store + +# Vim +*.swp +*.swo + +# patch +*.orig +*.rej + +# Local environment +.env diff --git a/99-microservices/quarkus_solution/.mvn/wrapper/MavenWrapperDownloader.java b/99-microservices/quarkus_solution/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100755 index 0000000..e76d1f3 --- /dev/null +++ b/99-microservices/quarkus_solution/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * Copyright 2007-present the original author or authors. + * + * Licensed 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 + * + * https://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 License for the specific language governing permissions and + * limitations under the License. + */ +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader { + + private static final String WRAPPER_VERSION = "0.5.6"; + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" + + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = + ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = + ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if(mavenWrapperPropertyFile.exists()) { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } catch (IOException e) { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } finally { + try { + if(mavenWrapperPropertyFileInputStream != null) { + mavenWrapperPropertyFileInputStream.close(); + } + } catch (IOException e) { + // Ignore ... + } + } + } + System.out.println("- Downloading from: " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if(!outputFile.getParentFile().exists()) { + if(!outputFile.getParentFile().mkdirs()) { + System.out.println( + "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } catch (Throwable e) { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception { + if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { + String username = System.getenv("MVNW_USERNAME"); + char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); + Authenticator.setDefault(new Authenticator() { + @Override + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password); + } + }); + } + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/99-microservices/quarkus_solution/.mvn/wrapper/maven-wrapper.properties b/99-microservices/quarkus_solution/.mvn/wrapper/maven-wrapper.properties new file mode 100755 index 0000000..598fb34 --- /dev/null +++ b/99-microservices/quarkus_solution/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.4/apache-maven-3.8.4-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/99-microservices/quarkus_solution/README.md b/99-microservices/quarkus_solution/README.md new file mode 100755 index 0000000..aa9a08c --- /dev/null +++ b/99-microservices/quarkus_solution/README.md @@ -0,0 +1,73 @@ +# quarkus_solution Project + +This project uses Quarkus, the Supersonic Subatomic Java Framework. + +If you want to learn more about Quarkus, please visit its website: https://quarkus.io/ . + +## Running the application in dev mode + +You can run your application in dev mode that enables live coding using: +```shell script +./mvnw compile quarkus:dev +``` + +> **_NOTE:_** Quarkus now ships with a Dev UI, which is available in dev mode only at http://localhost:8080/q/dev/. + +## Packaging and running the application + +The application can be packaged using: +```shell script +./mvnw package +``` +It produces the `quarkus-run.jar` file in the `target/quarkus-app/` directory. +Be aware that it’s not an _über-jar_ as the dependencies are copied into the `target/quarkus-app/lib/` directory. + +The application is now runnable using `java -jar target/quarkus-app/quarkus-run.jar`. + +If you want to build an _über-jar_, execute the following command: +```shell script +./mvnw package -Dquarkus.package.type=uber-jar +``` + +The application, packaged as an _über-jar_, is now runnable using `java -jar target/*-runner.jar`. + +## Creating a native executable + +You can create a native executable using: +```shell script +./mvnw package -Pnative +``` + +Or, if you don't have GraalVM installed, you can run the native executable build in a container using: +```shell script +./mvnw package -Pnative -Dquarkus.native.container-build=true +``` + +You can then execute your native executable with: `./target/quarkus_solution-1.0.0-SNAPSHOT-runner` + +If you want to learn more about building native executables, please consult https://quarkus.io/guides/maven-tooling. + +## Related Guides + +- WebSockets ([guide](https://quarkus.io/guides/websockets)): WebSocket communication channel support +- RESTEasy JAX-RS ([guide](https://quarkus.io/guides/rest-json)): REST endpoint framework implementing JAX-RS and more + +## Provided Code + +### gRPC + +Create your first gRPC service + +[Related guide section...](https://quarkus.io/guides/grpc-getting-started) + +### RESTEasy JAX-RS + +Easily start your RESTful Web Services + +[Related guide section...](https://quarkus.io/guides/getting-started#the-jax-rs-resources) + +### WebSockets + +WebSocket communication channel starter code + +[Related guide section...](https://quarkus.io/guides/websockets) diff --git a/99-microservices/quarkus_solution/mvnw b/99-microservices/quarkus_solution/mvnw new file mode 100755 index 0000000..a16b543 --- /dev/null +++ b/99-microservices/quarkus_solution/mvnw @@ -0,0 +1,310 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF 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 +# +# https://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 License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/99-microservices/quarkus_solution/mvnw.cmd b/99-microservices/quarkus_solution/mvnw.cmd new file mode 100755 index 0000000..c8d4337 --- /dev/null +++ b/99-microservices/quarkus_solution/mvnw.cmd @@ -0,0 +1,182 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + +FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/99-microservices/quarkus_solution/pom.xml b/99-microservices/quarkus_solution/pom.xml new file mode 100755 index 0000000..5323640 --- /dev/null +++ b/99-microservices/quarkus_solution/pom.xml @@ -0,0 +1,143 @@ + + + 4.0.0 + de.verteiltearchitekturen + quarkus_solution + 1.0.0-SNAPSHOT + + 3.8.1 + 16 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 2.6.3.Final + 3.0.0-M5 + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + io.quarkus + quarkus-grpc + + + io.quarkus + quarkus-undertow + + + io.quarkus + quarkus-resteasy-jsonb + + + io.quarkus + quarkus-websockets + + + io.quarkus + quarkus-resteasy + + + io.quarkus + quarkus-smallrye-graphql + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + + -parameters + + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + native + + + native + + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + native + + + + diff --git a/99-microservices/quarkus_solution/src/main/docker/Dockerfile.jvm b/99-microservices/quarkus_solution/src/main/docker/Dockerfile.jvm new file mode 100755 index 0000000..abb513b --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/docker/Dockerfile.jvm @@ -0,0 +1,41 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/quarkus_solution-jvm . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus_solution-jvm +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus_solution-jvm +# +### +FROM registry.access.redhat.com/ubi8/openjdk-11-runtime:1.10 + +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' + +# Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size. +ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" + +# We make four distinct layers so if there are application changes the library layers can be re-used +COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/ +COPY --chown=185 target/quarkus-app/*.jar /deployments/ +COPY --chown=185 target/quarkus-app/app/ /deployments/app/ +COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/ + +EXPOSE 8080 +USER 185 + +ENTRYPOINT [ "java", "-jar", "/deployments/quarkus-run.jar" ] + diff --git a/99-microservices/quarkus_solution/src/main/docker/Dockerfile.legacy-jar b/99-microservices/quarkus_solution/src/main/docker/Dockerfile.legacy-jar new file mode 100755 index 0000000..eca097b --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/docker/Dockerfile.legacy-jar @@ -0,0 +1,37 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package -Dquarkus.package.type=legacy-jar +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/quarkus_solution-legacy-jar . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus_solution-legacy-jar +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus_solution-legacy-jar +# +### +FROM registry.access.redhat.com/ubi8/openjdk-11-runtime:1.10 + +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' + +# Configure the JAVA_OPTIONS, you can add -XshowSettings:vm to also display the heap size. +ENV JAVA_OPTIONS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" + +COPY target/lib/* /deployments/lib/ +COPY target/*-runner.jar /deployments/quarkus-run.jar + +EXPOSE 8080 +USER 185 + +ENTRYPOINT [ "java", "-jar", "/deployments/quarkus-run.jar" ] diff --git a/99-microservices/quarkus_solution/src/main/docker/Dockerfile.native b/99-microservices/quarkus_solution/src/main/docker/Dockerfile.native new file mode 100755 index 0000000..85a2f31 --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/docker/Dockerfile.native @@ -0,0 +1,27 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native -t quarkus/quarkus_solution . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus_solution +# +### +FROM quay.io/quarkus/quarkus-micro-image:1.0 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 8080 +USER 1001 + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/99-microservices/quarkus_solution/src/main/docker/Dockerfile.native-distroless b/99-microservices/quarkus_solution/src/main/docker/Dockerfile.native-distroless new file mode 100755 index 0000000..cbc1079 --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/docker/Dockerfile.native-distroless @@ -0,0 +1,23 @@ +#### +# This Dockerfile is used in order to build a distroless container that runs the Quarkus application in native (no JVM) mode +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native-distroless -t quarkus/quarkus_solution . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/quarkus_solution +# +### +FROM quay.io/quarkus/quarkus-distroless-image:1.0 +COPY target/*-runner /application + +EXPOSE 8080 +USER nonroot + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/election/BallotBox.java b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/election/BallotBox.java new file mode 100755 index 0000000..ba2e77a --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/election/BallotBox.java @@ -0,0 +1,63 @@ +package de.verteiltearchitekturen.election; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class BallotBox { + private static Map votes = Collections + .synchronizedMap(new HashMap<>()); + + public static void vote(String choice) { + synchronized (votes) { + var v = votes.get(choice); + if (v == null) { + v = 0; + } + votes.put(choice, v + 1); + } + } + + public static int votesNumber() { + var sum = 0; + synchronized (votes) { + for (var choice : votes.entrySet()) { + sum += choice.getValue(); + } + } + return sum; + } + + public static int votes(String choice) { + synchronized (votes) { + if (votes.get(choice) == null) + return 0; + else + return votes.get(choice); + } + } + + public static List votes() { + var listOfVotes = new ArrayList(); + synchronized (votes) { + for (var choice : votes.entrySet()) { + listOfVotes.add(new Vote(choice.getKey(), choice.getValue())); + } + } + return listOfVotes; + } + + public static Vote cheat(String choice, int votes) { + synchronized (BallotBox.votes) { + BallotBox.votes.put(choice, votes); + return new Vote(choice, BallotBox.votes.get(choice)); + } + } + + public static Set choices() { + return votes.keySet(); + } +} \ No newline at end of file diff --git a/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/election/BallotBoxServlet.java b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/election/BallotBoxServlet.java new file mode 100755 index 0000000..aa08c49 --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/election/BallotBoxServlet.java @@ -0,0 +1,63 @@ +package de.verteiltearchitekturen.election; + +import java.io.IOException; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +@SuppressWarnings("serial") +@WebServlet(urlPatterns = "/vote") +public class BallotBoxServlet extends HttpServlet { + + @Override + protected void doGet(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + var out = response.getWriter(); + response.setContentType("text/html"); + out.println(""); + var action = request.getParameter("action"); + if (action != null) { + if (action.equals("vote")) { + var alternative = request.getParameter("alternative"); + if ((alternative == null) || alternative.equals("")) { + alternative = "ungültige Stimmenabgabe"; + } + BallotBox.vote(alternative); + out.println("

    Ihre Stimme wurde gezählt.

    "); + } else if (action.equals("print")) { + out.println("

    abgegebene Stimmen

    "); + out.println(""); + out.println( + ""); + var sum = 0; + for (var vote : BallotBox.votes()) { + out.println( + ""); + out.println( + ""); + sum += vote.votes(); + } + out.println(""); + out.println(""); + out.println("
    AlternativeStimmen
    " + vote.choice() + "" + vote.votes() + "
    Summe:" + sum + "
    "); + } else { + response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, + "action-Parameter hatte den Wert '" + action + + "'. Erlaubte Werte sind 'vote' und 'print'"); + } + } else { + response.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, + "action-Parameter hatte keinen Wert gesetzt. Erlaubte Werte sind 'vote' und 'print'"); + } + out.println(""); + out.flush(); + } + + @Override + protected void doPost(HttpServletRequest request, + HttpServletResponse response) throws ServletException, IOException { + doGet(request, response); + } +} diff --git a/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/election/Vote.java b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/election/Vote.java new file mode 100755 index 0000000..0f226aa --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/election/Vote.java @@ -0,0 +1,56 @@ +package de.verteiltearchitekturen.election; +public record Vote (String choice, int votes) {} +/* +public class Vote { + private final String choice; + private final int votes; + + public String choice() { + return choice; + } + + public int votes() { + return votes; + } + + public Vote(String choice, int votes) { + super(); + this.choice = choice; + this.votes = votes; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((choice == null) ? 0 : choice.hashCode()); + result = prime * result + votes; + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Vote other = (Vote) obj; + if (choice == null) { + if (other.choice != null) + return false; + } else if (!choice.equals(other.choice)) + return false; + if (votes != other.votes) + return false; + return true; + } + + @Override + public String toString() { + return "Vote [choice=" + choice + ", votes=" + votes + "]"; + } + +} +*/ \ No newline at end of file diff --git a/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/GraphQLEndpoint.java b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/GraphQLEndpoint.java new file mode 100755 index 0000000..ea66ed2 --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/GraphQLEndpoint.java @@ -0,0 +1,27 @@ +package de.verteiltearchitekturen.graphql; + +import javax.servlet.annotation.WebServlet; +import graphql.kickstart.servlet.GraphQLConfiguration; +import graphql.kickstart.servlet.GraphQLHttpServlet; +import graphql.kickstart.tools.SchemaParser; +import graphql.schema.GraphQLSchema; + +@SuppressWarnings("serial") +@WebServlet(urlPatterns = "/graphql") +public class GraphQLEndpoint extends GraphQLHttpServlet { + + @Override + protected GraphQLConfiguration getConfiguration() { + return GraphQLConfiguration.with(createSchema()).build(); + } + + static GraphQLSchema createSchema() { + return SchemaParser // + .newParser() // + .file("schema.graphqls")// + .resolvers(new Query(), new Mutation()) // + .build()// + .makeExecutableSchema(); + } + +} \ No newline at end of file diff --git a/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/Main.java b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/Main.java new file mode 100755 index 0000000..a2bdfca --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/Main.java @@ -0,0 +1,15 @@ +package de.verteiltearchitekturen.graphql; + +import de.verteiltearchitekturen.election.BallotBox; +import graphql.GraphQL; + +public class Main { + public static void main(String... args) { + var graph = GraphQL.newGraphQL(GraphQLEndpoint.createSchema()).build(); + BallotBox.vote("Dr. Amy Farrah Fowler"); + BallotBox.vote("Dr. Amy Farrah Fowler"); + var exec = graph.execute("mutation {vote(choice: \"Emily Sweeney\")}"); + exec = graph.execute("{allVotes{choice votes}}"); + System.out.println(exec.toSpecification()); + } +} \ No newline at end of file diff --git a/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/Mutation.java b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/Mutation.java new file mode 100755 index 0000000..b078d7e --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/Mutation.java @@ -0,0 +1,16 @@ +package de.verteiltearchitekturen.graphql; + +import de.verteiltearchitekturen.election.*; +import graphql.kickstart.tools.GraphQLMutationResolver; + +public class Mutation implements GraphQLMutationResolver { + + public boolean vote(String choice) { + BallotBox.vote(choice); + return true; + } + + public Vote cheat(String choice, int votes) { + return BallotBox.cheat(choice, votes); + } +} \ No newline at end of file diff --git a/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/Query.java b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/Query.java new file mode 100755 index 0000000..d2f98ba --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/graphql/Query.java @@ -0,0 +1,20 @@ +package de.verteiltearchitekturen.graphql; + +import java.util.List; +import de.verteiltearchitekturen.election.*; +import graphql.kickstart.tools.GraphQLQueryResolver; + +public class Query implements GraphQLQueryResolver { + + public List allVotes() { + return BallotBox.votes(); + } + + public int votesNumber() { + return BallotBox.votesNumber(); + } + + public int votes(String choice) { + return BallotBox.votes(choice); + } +} \ No newline at end of file diff --git a/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/syslog/GreetingResource.java b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/syslog/GreetingResource.java new file mode 100755 index 0000000..b068a94 --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/syslog/GreetingResource.java @@ -0,0 +1,16 @@ +package de.verteiltearchitekturen.syslog; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("/hello") +public class GreetingResource { + + @GET + @Produces(MediaType.TEXT_PLAIN) + public String hello() { + return "Hello RESTEasy"; + } +} \ No newline at end of file diff --git a/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/syslog/StartWebSocket.java b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/syslog/StartWebSocket.java new file mode 100755 index 0000000..d7ae1fd --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/syslog/StartWebSocket.java @@ -0,0 +1,40 @@ +package de.verteiltearchitekturen.syslog; + +import javax.enterprise.context.ApplicationScoped; +import javax.websocket.EncodeException; +import javax.websocket.OnClose; +import javax.websocket.OnError; +import javax.websocket.OnMessage; +import javax.websocket.OnOpen; +import javax.websocket.Session; +import javax.websocket.server.PathParam; +import javax.websocket.server.ServerEndpoint; +import java.io.IOException; + +import static java.util.Objects.requireNonNull; + +@ServerEndpoint("/start-websocket/{name}") +@ApplicationScoped +public class StartWebSocket { + + @OnOpen + public void onOpen(Session session, @PathParam("name") String name) { + System.out.println("onOpen> " + name); + } + + @OnClose + public void onClose(Session session, @PathParam("name") String name) { + System.out.println("onClose> " + name); + } + + @OnError + public void onError(Session session, @PathParam("name") String name, + Throwable throwable) { + System.out.println("onError> " + name + ": " + throwable); + } + + @OnMessage + public void onMessage(String message, @PathParam("name") String name) { + System.out.println("onMessage> " + name + ": " + message); + } +} diff --git a/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/syslog/SyslogService.java b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/syslog/SyslogService.java new file mode 100755 index 0000000..689e585 --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/java/de/verteiltearchitekturen/syslog/SyslogService.java @@ -0,0 +1,37 @@ +package de.verteiltearchitekturen.syslog; + +import de.verteiltearchitekturen.syslog.model.Syslog; +import de.verteiltearchitekturen.syslog.model.SyslogOuterClass.Message; +import de.verteiltearchitekturen.syslog.model.SyslogOuterClass.Result; +import de.verteiltearchitekturen.syslog.model.SyslogOuterClass.Severity; +import io.quarkus.grpc.GrpcService; +import io.smallrye.mutiny.Uni; + +@GrpcService +public class SyslogService implements Syslog { + + @Override + public Uni checkUrgency(Message message) { + boolean urgency = false; + if (message.getPriority() == Severity.Alert + || message.getPriority() == Severity.Critical) { + urgency = true; + } + + Result result = Result // + .newBuilder() // + .setVal(urgency) // + .build(); + return Uni.createFrom().item(result); + } + + @Override + public Uni log(Message message) { + System.out.println(message); + return Uni.createFrom().item(Result// + .newBuilder() // + .setVal(true) // + .build()); + } + +} diff --git a/99-microservices/quarkus_solution/src/main/proto/syslog.proto b/99-microservices/quarkus_solution/src/main/proto/syslog.proto new file mode 100755 index 0000000..3ebb0ca --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/proto/syslog.proto @@ -0,0 +1,52 @@ +syntax = "proto3"; + +import "google/protobuf/timestamp.proto"; +import "google/protobuf/any.proto"; + +package de.verteiltearchitekturen.syslog.model; + +service Syslog { + rpc CheckUrgency(Message) returns (Result) {}; + rpc Log(Message) returns (Result) {}; +} + +enum Severity { + Emergency = 0; + Alert = 1; + Critical = 2; + Error = 3; + Warning = 4; + Notice = 5; + Informational = 6; + Debug = 7; +} + +message StructuredData { + string key = 1; + string value = 2; +} + +message ComplexData { + string key = 1; + oneof value { + string text = 2; + google.protobuf.Any data = 3; + } +} + + +message Message { + Severity priority = 1; + uint32 version = 2; + google.protobuf.Timestamp timestamp = 3; + string hostname = 4; + string appname = 5; + uint32 procid = 6; + uint32 msgid = 7; + repeated StructuredData structureddata = 9; + repeated ComplexData data = 8; +} + +message Result { + bool val = 1; +} diff --git a/99-microservices/quarkus_solution/src/main/resources/META-INF/resources/index.html b/99-microservices/quarkus_solution/src/main/resources/META-INF/resources/index.html new file mode 100755 index 0000000..25c6b22 --- /dev/null +++ b/99-microservices/quarkus_solution/src/main/resources/META-INF/resources/index.html @@ -0,0 +1,190 @@ + + + + + quarkus_solution - 1.0.0-SNAPSHOT + + + + + + +
    +
    +

    Congratulations, you have created a new Quarkus cloud application.

    + +

    What is this page?

    + +

    This page is served by Quarkus. The source is in + src/main/resources/META-INF/resources/index.html.

    + +

    What are your next steps?

    + +

    If not already done, run the application in dev mode using: ./mvnw compile quarkus:dev. +

    +
      +
    • Your static assets are located in src/main/resources/META-INF/resources.
    • +
    • Configure your application in src/main/resources/application.properties.
    • +
    • Quarkus now ships with a Dev UI (available in dev mode only)
    • +
    • Play with the provided code located in src/main/java:
    • +
    +
    +

    gRPC

    +

    Create your first gRPC service

    + +

    Related guide section...

    +This codestart implements a simple gRPC service that can be tested in the Dev UI (available in dev mode only). +
    +
    +

    RESTEasy JAX-RS

    +

    Easily start your RESTful Web Services

    +

    @Path: /hello

    +

    Related guide section...

    +
    +
    +

    WebSockets

    +

    WebSocket communication channel starter code

    + +

    Related guide section...

    +
    + +
    +
    +
    +

    Application

    +
      +
    • GroupId: de.verteiltearchitekturen
    • +
    • ArtifactId: quarkus_solution
    • +
    • Version: 1.0.0-SNAPSHOT
    • +
    • Quarkus Version: 2.6.3.Final
    • +
    +
    +
    +

    Do you like Quarkus?

    +
      +
    • Go give it a star on GitHub.
    • +
    +
    +
    +

    Selected extensions guides

    + +
    + +
    +
    + + \ No newline at end of file diff --git a/99-microservices/quarkus_solution/src/main/resources/application.properties b/99-microservices/quarkus_solution/src/main/resources/application.properties new file mode 100755 index 0000000..e69de29 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..baee873 --- /dev/null +++ b/LICENSE @@ -0,0 +1,170 @@ +Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International + + Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. + +Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. More considerations for licensors. + +Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public. + +Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. + +Section 1 – Definitions. + + a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. + + c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. + + e. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. + + i. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights under this Public License. + + k. NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. + + l. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. + + m. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. + + n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. + +Section 2 – Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: + + A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and + + B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. + + 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. + + 3. Term. The term of this Public License is specified in Section 6(a). + + 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. + + 5. Downstream recipients. + + A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. + + B. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply. + + C. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. + + 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this Public License. + + 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. + +Section 3 – License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified form), You must: + + A. retain the following if it is supplied by the Licensor with the Licensed Material: + + i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of warranties; + + v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; + + B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and + + C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. + + 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. + + b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply. + + 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply. + +Section 4 – Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; + + b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and + + c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. +For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. + +Section 5 – Disclaimer of Warranties and Limitation of Liability. + + a. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. + + b. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. + + c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. + +Section 6 – Term and Termination. + + a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. + +Section 7 – Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. + +Section 8 – Interpretation. + + a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. + + c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. + + d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. + +Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5fb1a32 --- /dev/null +++ b/README.md @@ -0,0 +1,29 @@ +# Verteilte Systeme (VS im WS: 6/7 CSB/IB, im SS: 6/7 IMB/UIB) + +Maven Projekte zum [Lehrbuch Verteilte Architekturen](https://verteiltearchitekturen.de/) +## Voraussetzungen +- [Java (OpenJDK JDK)](https://jdk.java.net/) (mindestens Version 17) +- [Maven](https://maven.apache.org/) (mindestens Version 3.5) +- [just](https://just.systems/) +- Docker/Podman o.ä. + +## Benutzung +- compilieren, testen und starten der Programme mit [``just *recipe*``](https://just.systems/) + +## Themen +- 2. UDP +- 3. TCP +- 5. JMS + - ist für [Apache ActiveMQ Classic 6.x](https://activemq.apache.org/components/classic/download/) vorbereitet (Jakarta JMS statt Javax JMS) +- 6. MQTT +- 7. HTTP +- 8. Servlet-Container + - ist mit [Eclipse Jetty 11.0.x](https://jetty.org/) statt [Apache Tomcat](https://tomcat.apache.org/) vorbereitet (Jakarta Servlet statt Javax Servlet) +- 9. Google Cloud AppEngine + - benötigt Account für [Google Cloud](https://cloud.google.com/) und [gcloud CLI](https://cloud.google.com/sdk/docs/install) installiert +- 15. ProtocolBuffer +- 18. RESTful Webservices +- 20. WebSockets +- 21. GraphQL +- 22. GRPC +- 22. GRPS/Quarkus diff --git a/justfile b/justfile new file mode 100644 index 0000000..6ca7111 --- /dev/null +++ b/justfile @@ -0,0 +1,18 @@ +# Justfile (https://just.systems/) for starting Maven standard targets + +default: clean compile package + +exec class args: compile + mvn exec:java -Dexec.args="{{args}}" -Dexec.mainClass={{class}} +# exec class args: +# java -cp target/app.jar {{class}} {{args}} +clean: + mvn clean +compile: + mvn compile +test: compile + mvn test +javadoc: + mvn javadoc:javadoc +package: + mvn package diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..db39272 --- /dev/null +++ b/pom.xml @@ -0,0 +1,55 @@ + + 4.0.0 + vs + parent + 1.0-SNAPSHOT + pom + + + 17 + UTF-8 + + + + org.junit.jupiter + junit-jupiter + 5.10.0 + test + + + org.projectlombok + lombok + 1.18.30 + provided + + + + app + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0 + + + org.apache.maven.plugins + maven-compiler-plugin + 3.9.0 + + + org.codehaus.mojo + exec-maven-plugin + 3.1.0 + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.5.0 + + private + en_US + + + + +