diff --git a/sample-apps/JavaRestletMySQL/.gitignore b/sample-apps/JavaRestletMySQL/.gitignore new file mode 100644 index 000000000..bf0824e59 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/.gitignore @@ -0,0 +1 @@ +*.log \ No newline at end of file diff --git a/sample-apps/JavaRestletMySQL/Makefile b/sample-apps/JavaRestletMySQL/Makefile new file mode 100644 index 000000000..fbc5053e1 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/Makefile @@ -0,0 +1,43 @@ +# Define variables +GRADLEW = ./gradlew +JAR_FILE = build/libs/demo-0.0.1-SNAPSHOT.jar +JAVA_AGENT = ../../dist/agent.jar + +# Default target +.PHONY: all +all: build + +# Build the project +.PHONY: build +build: + @echo "Building the project..." + chmod +x $(GRADLEW) + $(GRADLEW) build + +# Run the application with the Java agent +.PHONY: run +run: build + @echo "Running JavaRestletMySQL with Zen & ENV (http://localhost:8106)" + AIKIDO_TOKEN="token" \ + AIKIDO_REALTIME_ENDPOINT="http://localhost:5000/realtime" \ + AIKIDO_ENDPOINT="http://localhost:5000" \ + AIKIDO_BLOCK=1 \ + AIKIDO_LOG_LEVEL="debug" \ + nohup java -javaagent:$(JAVA_AGENT) -jar $(JAR_FILE) --server.port=8106 > output1.log & + +# Run the application without Zen +.PHONY: runWithoutZen +runWithoutZen: build + @echo "Running JavaRestletMySQL without Zen & ENV (http://localhost:8107)" + AIKIDO_TOKEN="random-invalid-token" \ + nohup java -jar $(JAR_FILE) --server.port=8107 > output2.log & + +# Clean the project +.PHONY: clean +clean: + @echo "Cleaning the project..." + $(GRADLEW) clean + +.PHONY: kill +kill: + pkill -f java diff --git a/sample-apps/JavaRestletMySQL/README.md b/sample-apps/JavaRestletMySQL/README.md new file mode 100644 index 000000000..c16baeb7d --- /dev/null +++ b/sample-apps/JavaRestletMySQL/README.md @@ -0,0 +1,2 @@ +# Restlet + MySQL vulnerable sample app +- Inserting a malicious dog : `Malicious Pet", "Gru from the Minions") -- ` diff --git a/sample-apps/JavaRestletMySQL/build.gradle b/sample-apps/JavaRestletMySQL/build.gradle new file mode 100644 index 000000000..726f266af --- /dev/null +++ b/sample-apps/JavaRestletMySQL/build.gradle @@ -0,0 +1,25 @@ +plugins { + id 'java' +} + +group = 'com.example' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' + targetCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.restlet:org.restlet:2.6.0' + //implementation 'org.restlet:org.restlet.ext.json:2.3.12' + //implementation 'org.restlet:org.restlet.ext.servlet:2.3.12' + implementation files('../../dist/agent_api.jar') + //compileOnly 'org.projectlombok:lombok' + implementation 'mysql:mysql-connector-java:8.0.33' + //annotationProcessor 'org.projectlombok:lombok' +} diff --git a/sample-apps/JavaRestletMySQL/gradle/gradle-daemon-jvm.properties b/sample-apps/JavaRestletMySQL/gradle/gradle-daemon-jvm.properties new file mode 100644 index 000000000..63e5bbdf4 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/gradle/gradle-daemon-jvm.properties @@ -0,0 +1,2 @@ +#This file is generated by updateDaemonJvm +toolchainVersion=21 diff --git a/sample-apps/JavaRestletMySQL/gradle/wrapper/gradle-wrapper.jar b/sample-apps/JavaRestletMySQL/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..a4b76b953 Binary files /dev/null and b/sample-apps/JavaRestletMySQL/gradle/wrapper/gradle-wrapper.jar differ diff --git a/sample-apps/JavaRestletMySQL/gradle/wrapper/gradle-wrapper.properties b/sample-apps/JavaRestletMySQL/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..0aaefbcaf --- /dev/null +++ b/sample-apps/JavaRestletMySQL/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/sample-apps/JavaRestletMySQL/gradlew b/sample-apps/JavaRestletMySQL/gradlew new file mode 100755 index 000000000..f5feea6d6 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/sample-apps/JavaRestletMySQL/gradlew.bat b/sample-apps/JavaRestletMySQL/gradlew.bat new file mode 100644 index 000000000..9b42019c7 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem 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, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/sample-apps/JavaRestletMySQL/settings.gradle b/sample-apps/JavaRestletMySQL/settings.gradle new file mode 100644 index 000000000..0a383dd84 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'demo' diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/DatabaseHelper.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/DatabaseHelper.java new file mode 100644 index 000000000..79e6c905c --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/DatabaseHelper.java @@ -0,0 +1,78 @@ +package com.example.demo; +import javax.sql.DataSource; + +import com.example.demo.models.Pet; + +import java.sql.*; +import java.util.ArrayList; + +public class DatabaseHelper { + private static Connection getDBConnection(String driver) { + // The url specifies the address of our database along with username and password credentials + final String url = "jdbc:" + driver + "://localhost:3306/db"; + final String user = "user"; // replace with your MySQL username + final String password = "password"; // replace with your MySQL password + try { + return DriverManager.getConnection(url, user, password); + } catch (SQLException e) { + System.out.println("Exception occurred in getDBConnection(): " + e); + return null; + } + } + + public static ArrayList getAllPets() { + ArrayList pets = new ArrayList<>(); + Connection conn = getDBConnection("mysql"); + if (conn == null) { + return pets; + } + try { + PreparedStatement stmt = conn.prepareStatement("SELECT * FROM pets"); + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + Integer id = rs.getInt("pet_id"); + String name = rs.getString("pet_name"); + String owner = rs.getString("owner"); + pets.add(new Pet(id, name, owner)); + } + } catch (SQLException e) { + System.out.println("Exception occurred in getAllPets(): " + e); + } + return pets; + } + public static Pet getPetById(Integer id) { + ArrayList pets = new ArrayList<>(); + Connection conn = getDBConnection("mysql"); + if (conn == null) { + return null; + } + try { + PreparedStatement stmt = conn.prepareStatement("SELECT * FROM pets WHERE pet_id=?"); + stmt.setInt(1, id); + ResultSet rs = stmt.executeQuery(); + while (rs.next()) { + Integer pet_id = rs.getInt("pet_id"); + String name = rs.getString("pet_name"); + String owner = rs.getString("owner"); + return new Pet(pet_id, name, owner); + } + } catch (SQLException e) { + System.out.println("Exception occurred in getPetById(...): " + e); + } + return new Pet(0, "Unknown", "Unknown"); + } + public static Integer createPetByName(String pet_name, String driver) { + String sql = "INSERT INTO pets (pet_name, owner) VALUES (\"" + pet_name + "\", \"Aikido Security\")"; + Connection conn = getDBConnection(driver); + if (conn == null) { + return 0; + } + try { + PreparedStatement insertStmt = conn.prepareStatement(sql); + return insertStmt.executeUpdate(); + } catch (SQLException e) { + System.out.println("Exception occurred in createPetByName(...): " + e); + } + return 0; + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/Main.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/Main.java new file mode 100644 index 000000000..d0132efe1 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/Main.java @@ -0,0 +1,13 @@ +package com.example.demo; + +import org.restlet.Component; +import org.restlet.data.Protocol; + +public class Main { + public static void main(String[] args) throws Exception { + Component component = new Component(); + component.getServers().add(Protocol.HTTP, 8106); + component.getDefaultHost().attach(new RestletApplication()); + component.start(); + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/RestletApplication.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/RestletApplication.java new file mode 100644 index 000000000..a546dc130 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/RestletApplication.java @@ -0,0 +1,36 @@ +package com.example.demo; + +import com.example.demo.resources.*; +import org.restlet.Application; +import org.restlet.Restlet; +import org.restlet.routing.Router; + +public class RestletApplication extends Application { + + @Override + public Restlet createInboundRoot() { + Router router = new Router(getContext()); + + router.attach("/static/{fileName}", ClasspathFileResources.class); + + router.attach("/", HtmlResources.HomeResource.class); + router.attach("/create", HtmlResources.CreateResource.class); + router.attach("/read_file", HtmlResources.ReadFileResource.class); + router.attach("/request", HtmlResources.RequestResource.class); + router.attach("/exec", HtmlResources.ExecResource.class); + router.attach("/pet_page/{id}", HtmlResources.PetPageResource.class); + router.attach("/test_ratelimiting_1", HtmlResources.TestRateLimitingResource.class); + + router.attach("/api/requests/get", RequestsResources.class); + + router.attach("/api/pets", PetsResources.class); + + router.attach("/api/files/read", FilesReadResource.class); + router.attach("/api/files/read_cookie", FilesReadCookieResource.class); + router.attach("/api/files/read_first_header", FilesReadFirstHeaderResource.class); + router.attach("/api/files/read_last_header", FilesReadLastHeader.class); + + router.attach("/api/commands/execute", CommandResources.class); + return router; + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/models/Pet.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/models/Pet.java new file mode 100644 index 000000000..64af42f90 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/models/Pet.java @@ -0,0 +1,12 @@ +package com.example.demo.models; +/* +Creating this table using SQL : +CREATE TABLE public.pets +( + pet_id integer NOT NULL GENERATED ALWAYS AS IDENTITY (START 1 INCREMENT 1 ), + name character varying(255) NOT NULL, + owner character varying(255) NOT NULL, + CONSTRAINT pet_pkey PRIMARY KEY (pet_id) +) + */ +public record Pet(Integer pet_id, String name, String owner) {} \ No newline at end of file diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/ClasspathFileResources.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/ClasspathFileResources.java new file mode 100644 index 000000000..acac29c50 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/ClasspathFileResources.java @@ -0,0 +1,29 @@ +package com.example.demo.resources; + +import org.restlet.data.MediaType; +import org.restlet.representation.StringRepresentation; +import org.restlet.resource.Get; +import org.restlet.resource.ServerResource; + +import java.io.IOException; +import java.io.InputStream; + +public class ClasspathFileResources extends ServerResource { + @Get + public StringRepresentation represent() { + String fileName = getAttribute("fileName"); + InputStream inputStream = getClass().getResourceAsStream("/templates/" + fileName); + + if (inputStream == null) { + return new StringRepresentation("File not found", MediaType.TEXT_PLAIN); + } + + try { + // Read the content of the file + String content = new String(inputStream.readAllBytes()); + return new StringRepresentation(content, MediaType.TEXT_HTML); + } catch (IOException e) { + return new StringRepresentation("Error reading file: " + e.getMessage(), MediaType.TEXT_PLAIN); + } + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/CommandResources.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/CommandResources.java new file mode 100644 index 000000000..efbc8da0a --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/CommandResources.java @@ -0,0 +1,51 @@ +package com.example.demo.resources; + +import org.restlet.data.MediaType; +import org.restlet.resource.Post; +import org.restlet.resource.ResourceException; +import org.restlet.resource.ServerResource; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class CommandResources extends ServerResource { + + private static class CommandsExecute { + public String userCommand; + + // Default constructor is needed for JSON deserialization + public CommandsExecute() {} + + public CommandsExecute(String userCommand) { + this.userCommand = userCommand; + } + } + + @Post("json") + public String execute(String jsonInput) throws IOException, InterruptedException { + CommandsExecute commandData = parseJson(jsonInput); + String command = commandData.userCommand; + System.out.println("Executing command: " + command); + + Process process = Runtime.getRuntime().exec(command); + StringBuilder output = new StringBuilder(); + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { + String line; + while ((line = reader.readLine()) != null) { + output.append(line).append("\n"); + } + } + + int exitCode = process.waitFor(); + output.append("Exit code: ").append(exitCode); + return output.toString(); + } + + private CommandsExecute parseJson(String jsonInput) { + // Simple JSON parsing (you can use a library like Jackson or Gson for more complex cases) + String command = jsonInput.replaceAll(".*\"userCommand\":\"([^\"]+)\".*", "$1"); + return new CommandsExecute(command); + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadCookieResource.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadCookieResource.java new file mode 100644 index 000000000..1384960a9 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadCookieResource.java @@ -0,0 +1,18 @@ +package com.example.demo.resources; + +import org.restlet.resource.Get; +import org.restlet.resource.ServerResource; + +import static com.example.demo.resources.FilesReadResource.readFile; + +public class FilesReadCookieResource extends ServerResource { + private String getCookieValue(String cookieName, String defaultValue) { + return getRequest().getCookies().getFirstValue(cookieName, defaultValue); + } + + @Get("json") + public String readCookie() { + String filePath = getCookieValue("fpath", ""); + return readFile(filePath); + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadFirstHeaderResource.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadFirstHeaderResource.java new file mode 100644 index 000000000..b3d3450a1 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadFirstHeaderResource.java @@ -0,0 +1,14 @@ +package com.example.demo.resources; + +import org.restlet.resource.Get; +import org.restlet.resource.ServerResource; + +import static com.example.demo.resources.FilesReadResource.readFile; + +public class FilesReadFirstHeaderResource extends ServerResource { + @Get("json") + public String firstHeader() { + String xpath = getRequest().getHeaders().getFirstValue("x-path", ""); + return readFile(xpath); + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadLastHeader.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadLastHeader.java new file mode 100644 index 000000000..40392166f --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadLastHeader.java @@ -0,0 +1,14 @@ +package com.example.demo.resources; + +import org.restlet.resource.Get; +import org.restlet.resource.ServerResource; + +import static com.example.demo.resources.FilesReadResource.readFile; + +public class FilesReadLastHeader extends ServerResource { + @Get("json") + public String lastHeader() { + String[] xpaths = getRequest().getHeaders().getValuesArray("x-path"); + return readFile(xpaths[xpaths.length - 1]); + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadResource.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadResource.java new file mode 100644 index 000000000..19e5ce238 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/FilesReadResource.java @@ -0,0 +1,52 @@ +package com.example.demo.resources; + +import org.restlet.resource.Post; +import org.restlet.resource.ServerResource; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.Scanner; + +public class FilesReadResource extends ServerResource { + + private static class FileRead { + public String fileName; + + // Default constructor is needed for JSON deserialization + public FileRead() {} + + public FileRead(String fileName) { + this.fileName = fileName; + } + } + + @Post("json") + public String read(String jsonInput) { + FileRead fileData = parseJson(jsonInput); + return readFile(fileData.fileName); + } + + static String readFile(String fileName) { + System.out.println("Reading file: " + fileName); + File specifiedFile = new File(fileName); + StringBuilder stringBuilder = new StringBuilder(); + Scanner myReader = null; + try { + myReader = new Scanner(specifiedFile); + while (myReader.hasNextLine()) { + stringBuilder.append(myReader.nextLine()); + stringBuilder.append('\n'); + } + myReader.close(); + } catch (FileNotFoundException e) { + throw new RuntimeException(e); + } + return stringBuilder.toString(); + } + + private FileRead parseJson(String jsonInput) { + // Simple JSON parsing (you can use a library like Jackson or Gson for more complex cases) + String fileName = jsonInput.replaceAll(".*\"fileName\":\"([^\"]+)\".*", "$1"); + return new FileRead(fileName); + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/HtmlResources.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/HtmlResources.java new file mode 100644 index 000000000..7aab695f4 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/HtmlResources.java @@ -0,0 +1,71 @@ +package com.example.demo.resources; + +import org.restlet.resource.Get; +import org.restlet.resource.ResourceException; +import org.restlet.resource.ServerResource; + +public final class HtmlResources { + public static class HomeResource extends ServerResource { + @Get + public String represent() { + // Redirect to a static HTML page + getResponse().redirectSeeOther("/static/index.html"); + return "Redirecting to index page"; + } + } + + public static class CreateResource extends ServerResource { + @Get + public String represent() { + // Redirect to a static HTML page + getResponse().redirectSeeOther("/static/create.html"); + return "Redirecting to create page"; + } + } + + public static class ReadFileResource extends ServerResource { + @Get + public String represent() { + // Redirect to a static HTML page + getResponse().redirectSeeOther("/static/read.html"); + return "Redirecting to read file page"; + } + } + + public static class RequestResource extends ServerResource { + @Get + public String represent() { + // Redirect to a static HTML page + getResponse().redirectSeeOther("/static/request.html"); + return "Redirecting to request page"; + } + } + + public static class ExecResource extends ServerResource { + @Get + public String represent() { + // Redirect to a static HTML page + getResponse().redirectSeeOther("/static/execute.html"); + return "Redirecting to execute page"; + } + } + + public static class PetPageResource extends ServerResource { + @Get + public String represent() { + String id = getAttribute("id"); + // Redirect to a static HTML page with the ID as a parameter + getResponse().redirectSeeOther("/static/pet_page.html?id=" + id); + return "Redirecting to pet page with id: " + id; + } + } + + public static class TestRateLimitingResource extends ServerResource { + @Get + public String represent() { + // Redirect to a static HTML page + getResponse().redirectSeeOther("/static/index.html"); + return "Redirecting to index page for end-to-end tests"; + } + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/PetsResources.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/PetsResources.java new file mode 100644 index 000000000..916de972a --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/PetsResources.java @@ -0,0 +1,57 @@ +package com.example.demo.resources; + +import com.example.demo.DatabaseHelper; +import com.example.demo.models.Pet; +import org.restlet.data.MediaType; +import org.restlet.resource.Get; +import org.restlet.resource.Post; +import org.restlet.resource.ResourceException; +import org.restlet.resource.ServerResource; + +import java.util.ArrayList; + +public class PetsResources extends ServerResource { + + @Get("json") + public ArrayList index() { + return DatabaseHelper.getAllPets(); + } + + @Get("json") + public Pet pet() { + Integer id = Integer.valueOf(getAttribute("id")); + return DatabaseHelper.getPetById(id); + } + + private static class PetCreate { + public String name; + + // Default constructor is needed for JSON deserialization + public PetCreate() {} + + public PetCreate(String name) { + this.name = name; + } + } + + private static class Rows { + public Integer rows; + + public Rows(Integer rows) { + this.rows = rows; + } + } + + @Post("json") + public Rows create(String jsonInput) { + PetCreate petData = parseJson(jsonInput); + Integer rowsCreated = DatabaseHelper.createPetByName(petData.name, "mysql"); + return new Rows(rowsCreated); + } + + private PetCreate parseJson(String jsonInput) { + // Simple JSON parsing (you can use a library like Jackson or Gson for more complex cases) + String name = jsonInput.replaceAll(".*\"name\":\"([^\"]+)\".*", "$1"); + return new PetCreate(name); + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/RequestsResources.java b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/RequestsResources.java new file mode 100644 index 000000000..c0f8ca3b7 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/java/com/example/demo/resources/RequestsResources.java @@ -0,0 +1,69 @@ +package com.example.demo.resources; + +import org.restlet.data.MediaType; +import org.restlet.resource.Post; +import org.restlet.resource.ResourceException; +import org.restlet.resource.ServerResource; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +public class RequestsResources extends ServerResource { + + private static class RequestsGet { + public String url; + + // Default constructor is needed for JSON deserialization + public RequestsGet() {} + + public RequestsGet(String url) { + this.url = url; + } + } + + @Post("json") + public String handlePost(String jsonInput) throws IOException { + RequestsGet requestsGet = parseJson(jsonInput); + String url = requestsGet.url; + System.out.println("Making request to: " + url); + return sendGetRequest(url); + } + + private RequestsGet parseJson(String jsonInput) { + // Simple JSON parsing (you can use a library like Jackson or Gson for more complex cases) + String url = jsonInput.replaceAll(".*\"url\":\"([^\"]+)\".*", "$1"); + return new RequestsGet(url); + } + + private static String sendGetRequest(String urlString) throws IOException { + StringBuilder result = new StringBuilder(); + URL url = new URL(urlString); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + + // Set the request method to GET + connection.setRequestMethod("GET"); + + // Get the response code + int responseCode = connection.getResponseCode(); + + // If the response code is 200 (HTTP_OK), read the response + if (responseCode == HttpURLConnection.HTTP_OK) { + BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String line; + while ((line = reader.readLine()) != null) { + result.append(line); + } + reader.close(); + } else { + System.out.println("GET request failed: " + responseCode); + } + + // Disconnect the connection + connection.disconnect(); + + return result.toString(); + } +} diff --git a/sample-apps/JavaRestletMySQL/src/main/resources/application.properties b/sample-apps/JavaRestletMySQL/src/main/resources/application.properties new file mode 100644 index 000000000..2109a440d --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=demo diff --git a/sample-apps/JavaRestletMySQL/src/main/resources/templates/create.html b/sample-apps/JavaRestletMySQL/src/main/resources/templates/create.html new file mode 100644 index 000000000..584bc6bae --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/resources/templates/create.html @@ -0,0 +1,95 @@ + + + + + + Add a New Dog + + + +
+

Add a New Dog

+
+ + + +
+
+ + + + diff --git a/sample-apps/JavaRestletMySQL/src/main/resources/templates/execute.html b/sample-apps/JavaRestletMySQL/src/main/resources/templates/execute.html new file mode 100644 index 000000000..466a87b23 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/resources/templates/execute.html @@ -0,0 +1,95 @@ + + + + + + Execute a command + + + +
+

Execute command:

+
+ + + +
+
+ + + + diff --git a/sample-apps/JavaRestletMySQL/src/main/resources/templates/index.html b/sample-apps/JavaRestletMySQL/src/main/resources/templates/index.html new file mode 100644 index 000000000..9f347939f --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/resources/templates/index.html @@ -0,0 +1,91 @@ + + + + + + Pets Overview + + + +
+

Pets Overview

+ Add a New Dog +
    +
    + + + + diff --git a/sample-apps/JavaRestletMySQL/src/main/resources/templates/pet_page.html b/sample-apps/JavaRestletMySQL/src/main/resources/templates/pet_page.html new file mode 100644 index 000000000..97731dbfc --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/resources/templates/pet_page.html @@ -0,0 +1,107 @@ + + + + + + Pet Details + + + +
    +

    Pet Details

    +
    +
    Pet ID:
    +
    Name:
    +
    Owner:
    +
    + Back to Pets Overview +
    + + + + diff --git a/sample-apps/JavaRestletMySQL/src/main/resources/templates/read.html b/sample-apps/JavaRestletMySQL/src/main/resources/templates/read.html new file mode 100644 index 000000000..37c2afac4 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/resources/templates/read.html @@ -0,0 +1,95 @@ + + + + + + Read a file + + + +
    +

    Read file:

    +
    + + + +
    +
    + + + + diff --git a/sample-apps/JavaRestletMySQL/src/main/resources/templates/request.html b/sample-apps/JavaRestletMySQL/src/main/resources/templates/request.html new file mode 100644 index 000000000..2f0137280 --- /dev/null +++ b/sample-apps/JavaRestletMySQL/src/main/resources/templates/request.html @@ -0,0 +1,95 @@ + + + + + + Make a GET Request + + + +
    +

    Make a GET Request:

    +
    + + + +
    +
    + + + + diff --git a/sample-apps/README.md b/sample-apps/README.md index 98b2e7f6b..bb282b5f8 100644 --- a/sample-apps/README.md +++ b/sample-apps/README.md @@ -31,6 +31,7 @@ Here is an overview of all of our sample apps together with their port numbers. - [Javalin App with Postgres](./JavalinPostgres) on port [`8088`](http://localhost:8088/) - [Javalin App with MySQL (Kotlin)](./JavalinMySQLKotlin/) on port [`8098`](http://localhost:8098) - [Ktor app with Postgres (Netty)](./KtorPostgresNetty) on port [`8096`](http://localhost:8096) +- [Restlet app with MySQL (Java)](./JavaRestletMySQL/) on port [`8106`](http://localhost:8106) #### Clojure - [Ring app with Postgres](./RingClojurePostgres) on port [`8102`](http://localhost:8102/)