first commit

This commit is contained in:
Giancarmine Salucci
2025-06-06 22:44:47 +02:00
commit 5b9774df72
63 changed files with 4462 additions and 0 deletions

5
.dockerignore Normal file
View File

@@ -0,0 +1,5 @@
*
!target/*-runner
!target/*-runner.jar
!target/lib/*
!target/quarkus-app/*

62
.gitignore vendored Normal file
View File

@@ -0,0 +1,62 @@
#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/
# Quinoa
node_modules/
build/
dist/
.quinoa/
dist-ssr
*.local
# Logs
logs/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

1
.mvn/wrapper/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
maven-wrapper.jar

View File

@@ -0,0 +1,93 @@
/*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.concurrent.ThreadLocalRandom;
public final class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "3.3.2";
private static final boolean VERBOSE = Boolean.parseBoolean(System.getenv("MVNW_VERBOSE"));
public static void main(String[] args) {
log("Apache Maven Wrapper Downloader " + WRAPPER_VERSION);
if (args.length != 2) {
System.err.println(" - ERROR wrapperUrl or wrapperJarPath parameter missing");
System.exit(1);
}
try {
log(" - Downloader started");
final URL wrapperUrl = URI.create(args[0]).toURL();
final String jarPath = args[1].replace("..", ""); // Sanitize path
final Path wrapperJarPath = Paths.get(jarPath).toAbsolutePath().normalize();
downloadFileFromURL(wrapperUrl, wrapperJarPath);
log("Done");
} catch (IOException e) {
System.err.println("- Error downloading: " + e.getMessage());
if (VERBOSE) {
e.printStackTrace();
}
System.exit(1);
}
}
private static void downloadFileFromURL(URL wrapperUrl, Path wrapperJarPath)
throws IOException {
log(" - Downloading to: " + wrapperJarPath);
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
final String username = System.getenv("MVNW_USERNAME");
final char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
Path temp = wrapperJarPath
.getParent()
.resolve(wrapperJarPath.getFileName() + "."
+ Long.toUnsignedString(ThreadLocalRandom.current().nextLong()) + ".tmp");
try (InputStream inStream = wrapperUrl.openStream()) {
Files.copy(inStream, temp, StandardCopyOption.REPLACE_EXISTING);
Files.move(temp, wrapperJarPath, StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(temp);
}
log(" - Downloader complete");
}
private static void log(String msg) {
if (VERBOSE) {
System.out.println(msg);
}
}
}

20
.mvn/wrapper/maven-wrapper.properties vendored Normal file
View File

@@ -0,0 +1,20 @@
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
wrapperVersion=3.3.2
distributionType=source
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar

75
README.md Normal file
View File

@@ -0,0 +1,75 @@
# hotsjbot
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 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 its 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/hotsjbot-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
- 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.
- REST Jackson ([guide](https://quarkus.io/guides/rest#json-serialisation)): Jackson serialization support for Quarkus REST. This extension is not compatible with the quarkus-resteasy extension, or any of the extensions that depend on it
- Quinoa ([guide](https://quarkiverse.github.io/quarkiverse-docs/quarkus-quinoa/dev/index.html)): Develop, build, and serve your npm-compatible web applications such as React, Angular, Vue, Lit, Svelte, Astro, SolidJS, and others alongside Quarkus.
## Provided Code
### Quinoa
Quinoa codestart added a tiny Vite app in src/main/webui. The page is configured to be visible on <a href="/quinoa">/quinoa</a>.
[Related guide section...](https://quarkiverse.github.io/quarkiverse-docs/quarkus-quinoa/dev/index.html)
### REST
Easily start your REST Web Services
[Related guide section...](https://quarkus.io/guides/getting-started-reactive#reactive-jax-rs-resources)

36
configuration.json Normal file
View File

@@ -0,0 +1,36 @@
{
"name" : "Default",
"pages" : [ {
"name" : "Client",
"rois" : [ {
"name" : "Currencies",
"region" : {
"x" : 1240,
"y" : 0,
"width" : 982,
"height" : 90
},
"pois" : [ {
"name" : "Coin",
"searchRegion" : {
"x" : 405,
"y" : 0,
"width" : 245,
"height" : 80
},
"matcher" : {
"type" : "TEMPLATE",
"controls" : [ ]
},
"filters" : [ ],
"matchRegion" : null
} ],
"controls" : [ {
"name" : "Display Image",
"type" : "SELECT",
"options" : [ "Source", "Coin" ],
"value" : "Coin"
} ]
} ]
} ]
}

332
mvnw vendored Normal file
View File

@@ -0,0 +1,332 @@
#!/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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Apache Maven Wrapper startup batch script, version 3.3.2
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# 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 /usr/local/etc/mavenrc ]; then
. /usr/local/etc/mavenrc
fi
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
JAVA_HOME="$(/usr/libexec/java_home)"
export JAVA_HOME
else
JAVA_HOME="/Library/Java/Home"
export JAVA_HOME
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ]; then
if [ -r /etc/gentoo-release ]; then
JAVA_HOME=$(java-config --jre-home)
fi
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin; then
[ -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 "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] \
&& JAVA_HOME="$(
cd "$JAVA_HOME" || (
echo "cannot cd into $JAVA_HOME." >&2
exit 1
)
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="$(
\unset -f command 2>/dev/null
\command -v 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." >&2
fi
# 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" >&2
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/.." || exit 1
pwd
)
fi
# end of workaround
done
printf '%s' "$(
cd "$basedir" || exit 1
pwd
)"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
# Remove \r in case we run on Windows within Git Bash
# and check out the repository with auto CRLF management
# enabled. Otherwise, we may read lines that are delimited with
# \r\n and produce $'-Xarg\r' rather than -Xarg due to word
# splitting rules.
tr -s '\r\n' ' ' <"$1"
fi
}
log() {
if [ "$MVNW_VERBOSE" = true ]; then
printf '%s\n' "$1"
fi
}
BASE_DIR=$(find_maven_basedir "$(dirname "$0")")
if [ -z "$BASE_DIR" ]; then
exit 1
fi
MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
export MAVEN_PROJECTBASEDIR
log "$MAVEN_PROJECTBASEDIR"
##########################################################################################
# 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.
##########################################################################################
wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar"
if [ -r "$wrapperJarPath" ]; then
log "Found $wrapperJarPath"
else
log "Couldn't find $wrapperJarPath, downloading it ..."
if [ -n "$MVNW_REPOURL" ]; then
wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar"
else
wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar"
fi
while IFS="=" read -r key value; do
# Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' )
safeValue=$(echo "$value" | tr -d '\r')
case "$key" in wrapperUrl)
wrapperUrl="$safeValue"
break
;;
esac
done <"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
log "Downloading from: $wrapperUrl"
if $cygwin; then
wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath")
fi
if command -v wget >/dev/null; then
log "Found wget ... using wget"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
else
wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath"
fi
elif command -v curl >/dev/null; then
log "Found curl ... using curl"
[ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent"
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
else
curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath"
fi
else
log "Falling back to using Java to download"
javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java"
javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaSource=$(cygpath --path --windows "$javaSource")
javaClass=$(cygpath --path --windows "$javaClass")
fi
if [ -e "$javaSource" ]; then
if [ ! -e "$javaClass" ]; then
log " - Compiling MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/javac" "$javaSource")
fi
if [ -e "$javaClass" ]; then
log " - Running MavenWrapperDownloader.java ..."
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath"
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
# If specified, validate the SHA-256 sum of the Maven wrapper jar file
wrapperSha256Sum=""
while IFS="=" read -r key value; do
case "$key" in wrapperSha256Sum)
wrapperSha256Sum=$value
break
;;
esac
done <"$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties"
if [ -n "$wrapperSha256Sum" ]; then
wrapperSha256Result=false
if command -v sha256sum >/dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c >/dev/null 2>&1; then
wrapperSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c >/dev/null 2>&1; then
wrapperSha256Result=true
fi
else
echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2
echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $wrapperSha256Result = false ]; then
echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2
echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2
echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2
exit 1
fi
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 "$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
# shellcheck disable=SC2086 # safe args
exec "$JAVACMD" \
$MAVEN_OPTS \
$MAVEN_DEBUG_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

206
mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,206 @@
@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 http://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 Apache Maven Wrapper startup batch script, version 3.3.2
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@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 "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %*
if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\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. >&2
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. >&2
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo. >&2
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. >&2
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 WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar"
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET WRAPPER_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 WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %WRAPPER_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('%WRAPPER_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file
SET WRAPPER_SHA_256_SUM=""
FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B
)
IF NOT %WRAPPER_SHA_256_SUM%=="" (
powershell -Command "&{"^
"Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash;"^
"$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^
"If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^
" Write-Error 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^
" Write-Error 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^
" Write-Error 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^
" exit 1;"^
"}"^
"}"
if ERRORLEVEL 1 goto error
)
@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 "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat"
if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\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%
cmd /C exit /B %ERROR_CODE%

164
pom.xml Normal file
View File

@@ -0,0 +1,164 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>it.moze</groupId>
<artifactId>hotsjbot</artifactId>
<version>1.0.0-SNAPSHOT</version>
<properties>
<compiler-plugin.version>3.14.0</compiler-plugin.version>
<maven.compiler.release>21</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<quarkus.platform.artifact-id>quarkus-bom</quarkus.platform.artifact-id>
<quarkus.platform.group-id>io.quarkus.platform</quarkus.platform.group-id>
<quarkus.platform.version>3.22.3</quarkus.platform.version>
<skipITs>true</skipITs>
<surefire-plugin.version>3.5.2</surefire-plugin.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
<version>5.8.0</version>
</dependency>
<dependency>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>${quarkus.platform.artifact-id}</artifactId>
<version>${quarkus.platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest-jackson</artifactId>
</dependency>
<dependency>
<groupId>io.quarkiverse.quinoa</groupId>
<artifactId>quarkus-quinoa</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-arc</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-scheduler</artifactId>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<!-- JNA for Windows API access -->
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna</artifactId>
</dependency>
<dependency>
<groupId>net.java.dev.jna</groupId>
<artifactId>jna-platform</artifactId>
<version>5.13.0</version>
</dependency>
<dependency>
<groupId>org.openpnp</groupId>
<artifactId>opencv</artifactId>
<version>4.9.0-0</version>
</dependency>
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-websockets</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus.platform.version}</version>
<extensions>true</extensions>
<executions>
<execution>
<goals>
<goal>build</goal>
<goal>generate-code</goal>
<goal>generate-code-tests</goal>
<goal>native-image-agent</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>${compiler-plugin.version}</version>
<configuration>
<parameters>true</parameters>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<configuration>
<systemPropertyVariables>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
<maven.home>${maven.home}</maven.home>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<native.image.path>${project.build.directory}/${project.build.finalName}-runner</native.image.path>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
<maven.home>${maven.home}</maven.home>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>native</id>
<activation>
<property>
<name>native</name>
</property>
</activation>
<properties>
<skipITs>false</skipITs>
<quarkus.native.enabled>true</quarkus.native.enabled>
</properties>
</profile>
</profiles>
</project>

View File

@@ -0,0 +1,98 @@
####
# 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/hotsjbot-jvm .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/hotsjbot-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/hotsjbot-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") - Be aware that this will override
# the default JVM options, use `JAVA_OPTS_APPEND` to append options
# - 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/ubi9/openjdk-21:1.21
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" ]

View File

@@ -0,0 +1,94 @@
####
# 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/hotsjbot-legacy-jar .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/hotsjbot-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/hotsjbot-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") - Be aware that this will override
# the default JVM options, use `JAVA_OPTS_APPEND` to append options
# - 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/ubi9/openjdk-21:1.21
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" ]

View File

@@ -0,0 +1,29 @@
####
# 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/hotsjbot .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/hotsjbot
#
# The ` registry.access.redhat.com/ubi8/ubi-minimal:8.10` base image is based on UBI 9.
# To use UBI 8, switch to `quay.io/ubi8/ubi-minimal:8.10`.
###
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 --chmod=0755 target/*-runner /work/application
EXPOSE 8080
USER 1001
ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"]

View File

@@ -0,0 +1,32 @@
####
# 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/hotsjbot .
#
# Then run the container using:
#
# docker run -i --rm -p 8080:8080 quarkus/hotsjbot
#
# The `quay.io/quarkus/quarkus-micro-image:2.0` base image is based on UBI 9.
# To use UBI 8, switch to `quay.io/quarkus/quarkus-micro-image:2.0`.
###
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 --chmod=0755 target/*-runner /work/application
EXPOSE 8080
USER 1001
ENTRYPOINT ["./application", "-Dquarkus.http.host=0.0.0.0"]

View File

@@ -0,0 +1,51 @@
package it.moze.boundary.rest;
import it.moze.control.bot.Bot;
import it.moze.control.bot.ConfigurationService;
import it.moze.entity.bot.Configuration;
import jakarta.inject.Inject;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
@Path("/")
public class BotController {
@Inject
Bot bot;
@Inject
ConfigurationService configurationService;
@GET
@Path("/start")
@Produces(MediaType.TEXT_PLAIN)
public String start() {
bot.start();
return bot.status().name();
}
@GET
@Path("/stop")
@Produces(MediaType.TEXT_PLAIN)
public String stop() {
bot.stop();
return bot.status().name();
}
@GET
@Path("/configuration")
@Produces(MediaType.APPLICATION_JSON)
public Configuration getConfiguration() {
return configurationService.configuration();
}
@PUT
@Path("/configuration")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateConfiguration(Configuration configuration) {
configurationService.setConfiguration(configuration);
configurationService.saveConfiguration();
return Response.ok(configurationService.configuration()).build();
}
}

View File

@@ -0,0 +1,131 @@
package it.moze.boundary.screen;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import com.sun.jna.Memory;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinNT;
import io.quarkus.logging.Log;
import it.moze.boundary.screen.model.BitmapInfo;
import it.moze.boundary.screen.model._GDI32;
import it.moze.boundary.screen.model._User32;
import it.moze.entity.geometry.Rectangle;
/**
* Grabber - Java implementation of screenshot functionality similar to
* python-mss for Windows Based on the Python implementation from
* <a href="https://github.com/BoboTiG/python-mss/">...</a>
* <p>
* Requires: - OpenCV for Java - JNA for native Windows API access - Quarkus
* framework
*/
public class Grabber {
private static final int DIB_RGB_COLORS = 0;
private static final int SRCCOPY = 0xCC0020;
private static final int BI_RGB = 0;
public static void init() {
nu.pattern.OpenCV.loadLocally();
}
/**
* Captures a screenshot of the specified region and returns it as an OpenCV Mat
*
* @param region Rectangle defining the area to capture (x, y, width, height)
* @return OpenCV Mat containing the screenshot image (BGR format)
*/
public static Mat grab(Rectangle region) {
return grabRegion(region);
}
/**
* Returns a screenshot of the primary monitor
*
* @return OpenCV Mat containing the screenshot
*/
public static Mat grab() {
return grabRegion(getMonitors()[0]);
}
/**
* Utility method to get monitor information
*
* @return An array of Rectangles representing monitor bounds
*/
public static Rectangle[] getMonitors() {
// This could be expanded to match MSS's monitor detection functionality
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
Rectangle[] monitors = new Rectangle[screens.length];
for (int i = 0; i < screens.length; i++) {
java.awt.Rectangle bounds = screens[i].getDefaultConfiguration().getBounds();
monitors[i] = new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
}
return monitors;
}
private static Mat grabRegion(Rectangle region) {
int width = region.width();
int height = region.height();
int x = region.x();
int y = region.y();
// Get device context for the entire screen
WinDef.HDC hdcScreen = _User32.INSTANCE.GetDC(null);
// Create compatible device context and bitmap
WinDef.HDC hdcMemDC = _GDI32.INSTANCE.CreateCompatibleDC(hdcScreen);
WinDef.HBITMAP hBitmap = _GDI32.INSTANCE.CreateCompatibleBitmap(hdcScreen, width, height);
try {
// Select bitmap into memory DC
WinNT.HANDLE hOld = _GDI32.INSTANCE.SelectObject(hdcMemDC, hBitmap);
// Copy screen content to memory DC
_GDI32.INSTANCE.BitBlt(hdcMemDC, 0, 0, width, height, hdcScreen, x, y, SRCCOPY);
// Restore the memory DC
_GDI32.INSTANCE.SelectObject(hdcMemDC, hOld);
// Create bitmap info structure
BitmapInfo bmi = new BitmapInfo();
bmi.bmiHeader.biWidth = width;
bmi.bmiHeader.biHeight = -height; // Negative height means top-down bitmap
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32; // 4 bytes: BGRA
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.write();
// Calculate the size of the bitmap data
int bitmapDataSize = width * height * 4;
// Allocate memory for the bitmap data
Memory memory = new Memory(bitmapDataSize);
// Get bitmap bits
_GDI32.INSTANCE.GetDIBits(hdcMemDC, hBitmap, 0, height, memory, bmi, DIB_RGB_COLORS);
// Convert to OpenCV Mat
Mat mat = new Mat(height, width, CvType.CV_8UC4);
byte[] data = new byte[bitmapDataSize];
memory.read(0, data, 0, bitmapDataSize);
mat.put(0, 0, data);
return mat;
} catch (Exception e) {
Log.error("Unable to grab screenshot.", e);
throw new RuntimeException("Unable to grab screenshot", e);
} finally {
// Clean up resources
_GDI32.INSTANCE.DeleteObject(hBitmap);
_GDI32.INSTANCE.DeleteDC(hdcMemDC);
_User32.INSTANCE.ReleaseDC(null, hdcScreen);
}
}
}

View File

@@ -0,0 +1,14 @@
package it.moze.boundary.screen.model;
import com.sun.jna.Structure;
@Structure.FieldOrder({ "bmiHeader", "bmiColors" })
public class BitmapInfo extends Structure {
public BitmapInfoHeader bmiHeader;
public byte[] bmiColors = new byte[4];
public BitmapInfo() {
bmiHeader = new BitmapInfoHeader();
bmiHeader.biSize = bmiHeader.size();
}
}

View File

@@ -0,0 +1,19 @@
package it.moze.boundary.screen.model;
import com.sun.jna.Structure;
@Structure.FieldOrder({ "biSize", "biWidth", "biHeight", "biPlanes", "biBitCount", "biCompression", "biSizeImage",
"biXPelsPerMeter", "biYPelsPerMeter", "biClrUsed", "biClrImportant" })
public class BitmapInfoHeader extends Structure {
public int biSize;
public int biWidth;
public int biHeight;
public short biPlanes;
public short biBitCount;
public int biCompression;
public int biSizeImage;
public int biXPelsPerMeter;
public int biYPelsPerMeter;
public int biClrUsed;
public int biClrImportant;
}

View File

@@ -0,0 +1,28 @@
package it.moze.boundary.screen.model;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.GDI32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.win32.W32APIOptions;
public interface _GDI32 extends GDI32 {
_GDI32 INSTANCE = Native.load("gdi32", _GDI32.class, W32APIOptions.DEFAULT_OPTIONS);
WinDef.HDC CreateCompatibleDC(WinDef.HDC hdc);
WinDef.HBITMAP CreateCompatibleBitmap(WinDef.HDC hdc, int width, int height);
boolean DeleteDC(WinDef.HDC hdc);
WinNT.HANDLE SelectObject(WinDef.HDC hdc, WinNT.HANDLE hObject);
boolean BitBlt(WinDef.HDC hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, WinDef.HDC hdcSrc, int nXSrc,
int nYSrc, int dwRop);
boolean DeleteObject(WinNT.HANDLE hObject);
int GetDIBits(WinDef.HDC hdc, WinDef.HBITMAP hbmp, int uStartScan, int cScanLines, Pointer lpvBits, BitmapInfo lpbi,
int uUsage);
}

View File

@@ -0,0 +1,14 @@
package it.moze.boundary.screen.model;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.win32.W32APIOptions;
public interface _User32 extends User32 {
_User32 INSTANCE = Native.load("user32", _User32.class, W32APIOptions.DEFAULT_OPTIONS);
WinDef.HDC GetDC(WinDef.HWND hWnd);
int ReleaseDC(WinDef.HWND hWnd, WinDef.HDC hDC);
}

View File

@@ -0,0 +1,86 @@
package it.moze.boundary.socket;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.quarkus.logging.Log;
import it.moze.control.bot.Bot;
import it.moze.entity.vision.Capture;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.ServerEndpoint;
import io.quarkus.scheduler.Scheduled;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@ServerEndpoint("/bot")
@ApplicationScoped
public class BotWebSocket {
private final Set<Session> sessions = Collections.newSetFromMap(new ConcurrentHashMap<>());
private final ObjectMapper objectMapper;
@Inject
Bot bot;
public BotWebSocket(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
this.objectMapper.registerModule(new JavaTimeModule());
}
@OnOpen
public void onOpen(Session session) {
sessions.add(session);
Log.info("New WebSocket connection: " + session.getId());
}
@OnClose
public void onClose(Session session) {
sessions.remove(session);
Log.info("WebSocket connection closed: " + session.getId());
}
@OnMessage
public void onMessage(String message, Session session) {
Log.info("Message received from client: " + message);
}
// Broadcasts a capture message with type "capture"
public void broadcast(Capture capture) {
try {
Map<String, Object> msg = new HashMap<>();
msg.put("type", "capture");
msg.put("data", capture);
String json = objectMapper.writeValueAsString(msg);
for (Session session : sessions) {
session.getAsyncRemote().sendText(json);
}
} catch (Exception e) {
Log.error("Error broadcasting capture", e);
}
}
// Broadcasts a status message with type "status" every 100ms
@Scheduled(every = "PT0.1S")
void broadcastBotStatus() {
if (sessions.isEmpty()) return;
try {
Map<String, Object> msg = new HashMap<>();
msg.put("type", "status");
msg.put("status", bot.status());
String json = objectMapper.writeValueAsString(msg);
for (Session session : sessions) {
session.getAsyncRemote().sendText(json);
}
} catch (Exception e) {
Log.error("Error broadcasting bot status", e);
}
}
}

View File

@@ -0,0 +1,85 @@
package it.moze.control.bot;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import io.quarkus.logging.Log;
import it.moze.boundary.socket.BotWebSocket;
import it.moze.control.bot.consumer.ScreenConsumerRunnable;
import it.moze.control.bot.producer.ScreenGrabberRunnable;
import it.moze.control.vision.ScreenshotService;
import it.moze.entity.bot.Roi;
import it.moze.entity.bot.constant.BotStatus;
import it.moze.entity.vision.Capture;
import jakarta.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class Bot {
private BotStatus status = BotStatus.STOPPED;
private final ScreenshotService screenshotService;
private final ConfigurationService configurationService;
private final BotWebSocket botWebsocket;
private final BlockingQueue<Capture> capturesQueue = new LinkedBlockingQueue<>(10);
private ScheduledExecutorService producersExecutor;
private Thread consumerThread;
public Bot(BotWebSocket botWebsocket, ConfigurationService configurationService, ScreenshotService screenshotService) {
this.screenshotService = screenshotService;
this.configurationService = configurationService;
this.botWebsocket = botWebsocket;
}
public void start() {
if (status == BotStatus.STARTED) {
Log.warn("Bot is already started.");
return;
}
Log.info("Starting producers and consumer...");
List<Roi> rois = configurationService.configuration().pages().get(0).rois();
producersExecutor = Executors.newScheduledThreadPool(rois.size());
// Reinitialize the consumer thread
consumerThread = Thread.ofVirtual().name("consumer").unstarted(new ScreenConsumerRunnable(capturesQueue, this.botWebsocket));
// Start producers
rois.forEach(roi -> {
producersExecutor.scheduleAtFixedRate(new ScreenGrabberRunnable(roi, capturesQueue, screenshotService), 0, 16,
TimeUnit.MILLISECONDS);
});
// Start consumer thread
consumerThread.start();
status = BotStatus.STARTED;
}
public void stop() {
if (status == BotStatus.STOPPED) {
Log.warn("Bot is already stopped.");
return;
}
Log.info("Stopping producers executor...");
try {
producersExecutor.shutdown(); // Initiates an orderly shutdown
if (!producersExecutor.awaitTermination(1, TimeUnit.SECONDS)) {
producersExecutor.shutdownNow(); // Force shutdown if tasks don't finish in time
}
} catch (InterruptedException e) {
producersExecutor.shutdownNow();
Thread.currentThread().interrupt();
}
Log.info("Stopping consumers executor...");
consumerThread.interrupt(); // Interrupt the consumer thread
try {
consumerThread.join(); // Wait for the consumer thread to terminate
} catch (InterruptedException e) {
consumerThread.interrupt();
Thread.currentThread().interrupt();
}
status = BotStatus.STOPPED;
}
public BotStatus status() {
return status;
}
}

View File

@@ -0,0 +1,81 @@
package it.moze.control.bot;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.quarkus.logging.Log;
import it.moze.entity.bot.Configuration;
import it.moze.entity.bot.MatcherConfiguration;
import it.moze.entity.bot.Page;
import it.moze.entity.bot.Poi;
import it.moze.entity.bot.Roi;
import it.moze.entity.geometry.Rectangle;
import jakarta.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class ConfigurationService {
@ConfigProperty(name = "bot.configuration.file", defaultValue = "src/main/resources/configuration.json")
String configurationFile;
@ConfigProperty(name = "bot.default.configuration.file", defaultValue = "src/main/resources/default_configuration.json")
String defaultConfigurationFile;
private final ObjectMapper objectMapper;
private volatile Configuration configuration = new Configuration("Default", List.of(new Page("Client", List.of(new Roi("Currencies",
Rectangle.fromCorners(1240, 0, 2222, 90),
List.of(new Poi("Coin", new Rectangle(405, 0, 245, 80), new MatcherConfiguration("coin.png", List.of()))))))));;
public ConfigurationService() {
this.objectMapper = new ObjectMapper();
this.objectMapper.registerModule(new JavaTimeModule());
loadConfiguration();
}
private void loadConfiguration() {
if(Objects.isNull(configurationFile) && Objects.isNull(defaultConfigurationFile)) {
return;
}
Log.info("Loading configuration...");
File config = new File(configurationFile);
File defaultConfig = new File(defaultConfigurationFile);
try {
if (config.exists()) {
Log.info("Loading custom configuration from " + config.getAbsolutePath());
configuration = objectMapper.readValue(config, Configuration.class);
} else if (defaultConfig.exists()) {
Log.info("Loading default configuration from " + defaultConfig.getAbsolutePath());
configuration = objectMapper.readValue(defaultConfig, Configuration.class);
}
} catch (IOException e) {
Log.error("Failed to load configuration", e);
throw new RuntimeException("Failed to load configuration", e);
}
}
public void saveConfiguration() {
Log.info("Saving configuration to " + configurationFile);
try {
objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(configurationFile), configuration);
} catch (IOException e) {
throw new RuntimeException("Failed to save configuration", e);
}
}
public Configuration configuration() {
return configuration;
}
public void setConfiguration(Configuration configuration) {
this.configuration = configuration;
}
}

View File

@@ -0,0 +1,32 @@
package it.moze.control.bot.consumer;
import io.quarkus.logging.Log;
import it.moze.boundary.socket.BotWebSocket;
import it.moze.entity.vision.Capture;
import java.util.concurrent.BlockingQueue;
public class ScreenConsumerRunnable implements Runnable {
private final BlockingQueue<Capture> capturesQueue;
private final BotWebSocket boteWebSocket;
public ScreenConsumerRunnable(BlockingQueue<Capture> capturesQueue, BotWebSocket boteWebSocket) {
this.capturesQueue = capturesQueue;
this.boteWebSocket = boteWebSocket;
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
Capture capture;
try {
capture = capturesQueue.take();
boteWebSocket.broadcast(capture);
} catch (InterruptedException e) {
Log.warn("Consumer thread interrupted.");
}
}
}
}

View File

@@ -0,0 +1,28 @@
package it.moze.control.bot.producer;
import java.util.concurrent.BlockingQueue;
import it.moze.control.vision.ScreenshotService;
import it.moze.entity.bot.Roi;
import it.moze.entity.vision.Capture;
public class ScreenGrabberRunnable implements Runnable {
private final ScreenshotService screenService;
private final Roi roi;
private final BlockingQueue<Capture> capturesQueue;
public ScreenGrabberRunnable(Roi roi, BlockingQueue<Capture> capturesQueue, ScreenshotService screenService) {
this.screenService = screenService;
this.roi = roi;
this.capturesQueue = capturesQueue;
}
@Override
public void run() {
try {
this.capturesQueue.put(screenService.capture(this.roi.name(), this.roi.region()));
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}

View File

@@ -0,0 +1,15 @@
package it.moze.control.config;
import io.quarkus.logging.Log;
import io.quarkus.runtime.Startup;
import jakarta.annotation.PostConstruct;
@Startup
public class OpenCVLoader {
@PostConstruct
void init() {
Log.info("Loading OpenCV library...");
nu.pattern.OpenCV.loadLocally();
}
}

View File

@@ -0,0 +1,25 @@
package it.moze.control.vision;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import it.moze.boundary.screen.Grabber;
import it.moze.entity.geometry.Rectangle;
import it.moze.entity.vision.Capture;
import jakarta.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class ScreenshotService {
private final Map<String, Capture> captures = new HashMap<>();
public Capture capture(String regionName, Rectangle region) {
Capture capture = Capture.of(getCapture(regionName, region), Grabber.grab(region));
captures.put(regionName, capture);
return capture;
}
private Capture getCapture(String regionName, Rectangle region) {
return Optional.ofNullable(captures.get(regionName)).orElseGet(() -> new Capture(regionName, region, null));
}
}

View File

@@ -0,0 +1,4 @@
package it.moze.control.vision.match;
public final class ColorMatcher implements Matcher {
}

View File

@@ -0,0 +1,19 @@
package it.moze.control.vision.match;
import it.moze.entity.bot.Poi;
import it.moze.entity.bot.Roi;
import it.moze.entity.vision.Capture;
public sealed class Matcher permits TemplateMatcher, ColorMatcher {
private final Roi roi;
private final Poi poi;
private final Capture capture;
public Matcher(Roi roi, Poi poi, Capture capture) {
this.roi = roi;
this.poi = poi;
this.capture = capture;
}
}

View File

@@ -0,0 +1,4 @@
package it.moze.control.vision.match;
public final class TemplateMatcher implements Matcher {
}

View File

@@ -0,0 +1,43 @@
package it.moze.entity.bot;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Configuration {
private String name;
private List<Page> pages;
public Configuration() {
// No-arg constructor for Jackson
this.pages = new ArrayList<>();
}
public Configuration(String name, List<Page> pages) {
this.name = name;
this.pages = pages;
}
@JsonProperty
public String name() {
return name;
}
@JsonProperty
public List<Page> pages() {
return pages;
}
public void pages(List<Page> pages) {
this.pages = pages;
}
public void addPage(Page page) {
this.pages.add(page);
}
public void removePage(Page page) {
this.pages.remove(page);
}
}

View File

@@ -0,0 +1,69 @@
package it.moze.entity.bot;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import it.moze.entity.bot.constant.ControlType;
public class Control {
private String name;
private ControlType type;
private List<String> options;
private String value;
public Control() {
this.options = new ArrayList<>();
}
public Control(String name, ControlType type) {
this.name = name;
this.type = type;
this.options = List.of();
}
public Control(String name, List<String> options) {
this.name = name;
this.type = ControlType.SELECT;
this.options = options;
}
public Control(String name, List<String> options, String defaultValue) {
this.name = name;
this.type = ControlType.SELECT;
this.value = defaultValue;
this.options = options;
}
public Control(String name, ControlType type, String defaultValue) {
this.name = name;
this.type = type;
this.value = defaultValue;
this.options = List.of();
}
@JsonProperty
public String name() {
return name;
}
@JsonProperty
public ControlType type() {
return type;
}
@JsonProperty
public String value() {
return value;
}
public void value(String value) {
this.value = value;
}
@JsonProperty
public List<String> options() {
return options;
}
}

View File

@@ -0,0 +1,39 @@
package it.moze.entity.bot;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import it.moze.entity.bot.constant.FilterType;
public class Filter {
private String name;
private FilterType type;
private List<Control> controls;
public Filter() {
this.controls = new ArrayList<>();
}
public Filter(String name, FilterType type, List<Control> controls) {
this.name = name;
this.type = type;
this.controls = controls;
}
@JsonProperty
public String name() {
return name;
}
@JsonProperty
public FilterType type() {
return type;
}
@JsonProperty
public List<Control> controls() {
return controls;
}
}

View File

@@ -0,0 +1,100 @@
package it.moze.entity.bot;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import it.moze.entity.bot.constant.MatcherType;
import it.moze.entity.vision.serde.Base64JpegToMatDeserializer;
import it.moze.entity.vision.serde.MatToBase64JpegSerializer;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
public class MatcherConfiguration {
private MatcherType type;
private List<Control> controls;
private String templateName;
@JsonIgnore
private Mat templateMat;
public MatcherConfiguration() {
this.controls = new ArrayList<>();
}
public MatcherConfiguration(MatcherType type, List<Control> controls) {
this.type = type;
this.controls = controls;
}
public MatcherConfiguration(String templateName, List<Control> controls) {
this.type = MatcherType.TEMPLATE;
this.templateName = templateName;
this.controls = controls;
loadTemplateMat();
}
@JsonProperty
public MatcherType type() {
return type;
}
@JsonProperty
public List<Control> controls() {
return controls;
}
@JsonProperty
public String templateName() {
return templateName;
}
public void templateName(String templateName) {
if(templateName == null || templateName.isBlank()) {
throw new IllegalArgumentException("Template name cannot be null or blank");
}
if(type != MatcherType.TEMPLATE) {
return;
}
this.templateName = templateName;
}
public Mat templateMat() {
return this.templateMat;
}
/**
* Loads the template image as a Mat using OpenCV, given the templateName.
* Returns null if not found or not a TEMPLATE matcher.
*/
@JsonIgnore
private Mat loadTemplateMat() {
if (type != MatcherType.TEMPLATE || templateName == null || templateName.isBlank()) {
return null;
}
if (templateMat != null) {
return templateMat;
}
File file = new File("src/main/resources/templates/" + templateName);
if (!file.exists()) {
throw new IllegalArgumentException("Template file not found: " + file.getAbsolutePath());
}
templateMat = Imgcodecs.imread(file.getAbsolutePath(), Imgcodecs.IMREAD_COLOR);
return templateMat;
}
/**
* Returns the template image as a base64-encoded JPEG string for JSON serialization.
*/
@JsonProperty("templateImage")
@JsonSerialize(using = MatToBase64JpegSerializer.class)
@JsonDeserialize(using = Base64JpegToMatDeserializer.class)
public Mat templateImage() {
return loadTemplateMat();
}
}

View File

@@ -0,0 +1,10 @@
package it.moze.entity.bot;
import java.util.List;
public record Page(
String name,
List<Roi> rois
) {
}

View File

@@ -0,0 +1,77 @@
package it.moze.entity.bot;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.smallrye.common.constraint.Nullable;
import it.moze.entity.geometry.Rectangle;
public class Poi {
private String name;
private Rectangle searchRegion;
private MatcherConfiguration matcher;
private List<Filter> filters;
private Rectangle matchRegion;
public Poi() {
this.filters = new ArrayList<>();
}
public Poi(String name, Rectangle searchRegion, MatcherConfiguration matcher) {
this.name = name;
this.searchRegion = searchRegion;
this.matcher = matcher;
this.filters = new ArrayList<>();
}
public Poi(String name, Rectangle searchRegion, List<Filter> filters, MatcherConfiguration matcher) {
this.name = name;
this.searchRegion = searchRegion;
this.filters = filters;
this.matcher = matcher;
}
@JsonProperty
@Nullable
public Rectangle matchRegion() {
return matchRegion;
}
public void matchRegion(Rectangle matchRegion) {
this.matchRegion = matchRegion;
}
@JsonProperty
public String name() {
return name;
}
@JsonProperty
public Rectangle searchRegion() {
return searchRegion;
}
@JsonProperty
public MatcherConfiguration matcher() {
return matcher;
}
@JsonProperty
public List<Filter> filters() {
return filters;
}
public void filters(List<Filter> filters) {
this.filters = filters;
}
public void addFilter(Filter filter) {
this.filters.add(filter);
}
public void removeFilter(Filter filter) {
this.filters.remove(filter);
}
}

View File

@@ -0,0 +1,61 @@
package it.moze.entity.bot;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import it.moze.entity.geometry.Rectangle;
public class Roi {
private static final String SOURCE = "Source";
private String name;
private Rectangle region;
private List<Poi> pois;
private List<Control> controls;
public Roi() {
this.pois = new ArrayList<>();
this.controls = new ArrayList<>();
}
public Roi(String name, Rectangle region, List<Poi> pois) {
this.name = name;
this.region = region;
this.pois = pois;
this.controls = List.of(new Control("Display Image", displayImageOptions(), SOURCE));
}
@JsonProperty
public String name() {
return name;
}
@JsonProperty
public Rectangle region() {
return region;
}
@JsonProperty
public List<Poi> pois() {
return pois;
}
@JsonProperty
public List<Control> controls() {
return controls;
}
public void controls(List<Control> controls) {
this.controls = controls;
}
private List<String> displayImageOptions() {
List<String> options = new ArrayList<>();
options.add(SOURCE);
if (this.pois != null) {
this.pois.stream().map(Poi::name).forEach(options::add);
}
return options;
}
}

View File

@@ -0,0 +1,6 @@
package it.moze.entity.bot.constant;
public enum BotStatus {
STARTED,
STOPPED;
}

View File

@@ -0,0 +1,8 @@
package it.moze.entity.bot.constant;
public enum ControlType {
TOGGLE,
NUMBER,
SELECT,
RANGE
}

View File

@@ -0,0 +1,6 @@
package it.moze.entity.bot.constant;
public enum FilterType {
BW,
THRESHOLD
}

View File

@@ -0,0 +1,6 @@
package it.moze.entity.bot.constant;
public enum MatcherType {
TEMPLATE,
COLOR
}

View File

@@ -0,0 +1,12 @@
package it.moze.entity.geometry;
public record Rectangle(
int x,
int y,
int width,
int height
) {
public static Rectangle fromCorners(int x, int y, int x1, int y1) {
return new Rectangle(x, y, x1 - x, y1 - y);
}
}

View File

@@ -0,0 +1,27 @@
package it.moze.entity.vision;
import org.opencv.core.Mat;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import it.moze.entity.geometry.Rectangle;
import it.moze.entity.vision.serde.MatToBase64JpegSerializer;
import java.time.Instant;
public record Capture(
String regionName,
Rectangle region,
@JsonSerialize(using = MatToBase64JpegSerializer.class)
Mat image,
Instant timestamp
) {
public Capture(String regionName, Rectangle region, Mat image) {
this(regionName, region, image, Instant.now());
}
public static Capture of(Capture capture, Mat image) {
return new Capture(capture.regionName, capture.region, image);
}
}

View File

@@ -0,0 +1,29 @@
package it.moze.entity.vision.serde;
import java.io.IOException;
import java.util.Base64;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
public class Base64JpegToMatDeserializer extends JsonDeserializer<Mat> {
@Override
public Mat deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
String base64 = p.getValueAsString();
if (base64 == null || base64.isEmpty()) {
return null;
}
byte[] imageBytes = Base64.getDecoder().decode(base64);
MatOfByte mob = new MatOfByte(imageBytes);
Mat mat = Imgcodecs.imdecode(mob, Imgcodecs.IMREAD_COLOR);
if (mat == null || mat.empty()) {
throw new IOException("Failed to decode base64 JPEG to Mat");
}
return mat;
}
}

View File

@@ -0,0 +1,26 @@
package it.moze.entity.vision.serde;
import java.io.IOException;
import java.util.Base64;
import org.opencv.core.Mat;
import org.opencv.core.MatOfByte;
import org.opencv.imgcodecs.Imgcodecs;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class MatToBase64JpegSerializer extends JsonSerializer<Mat> {
@Override
public void serialize(Mat mat, JsonGenerator gen, SerializerProvider serializers) throws IOException {
if (mat == null) {
gen.writeNull();
return;
}
MatOfByte bytes = new MatOfByte();
Imgcodecs.imencode(".jpg", mat, bytes);
String base64Image = Base64.getEncoder().encodeToString(bytes.toArray());
gen.writeString(base64Image);
}
}

View File

@@ -0,0 +1,6 @@
quarkus.quinoa.package-manager-install.node-version=20.10.0
quarkus.quinoa.package-manager-install=true
quarkus.quinoa.ui-root-path=/quinoa
quarkus.http.cors.enabled=true
quarkus.http.cors.origins=*
quarkus.http.host=0.0.0.0

View File

@@ -0,0 +1,38 @@
{
"name" : "Default",
"pages" : [ {
"name" : "Client",
"rois" : [ {
"name" : "Currencies",
"region" : {
"x" : 1240,
"y" : 0,
"width" : 982,
"height" : 90
},
"pois" : [ {
"name" : "Coin",
"searchRegion" : {
"x" : 405,
"y" : 0,
"width" : 245,
"height" : 80
},
"matcher" : {
"type" : "TEMPLATE",
"controls" : [ ],
"templateName" : "coin.png",
"templateImage" : "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsICQoKCgoKBggLDAsKDAkKCgr/2wBDAQICAgICAgUDAwUKBwYHCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgr/wAARCAAMAAwDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD9DPgp8N/DNr4Ph8ReItIsNVv9ZhFxdXV8ivtJ+7DGp4jjQYUKuAMV5J8a/DHirwJ46l0rwbqtrBp88K3ENncwpP8AZixOY0LgkJkFgvQbjXnXjv4zfEPwJLp1v4a154La9tobr7IRujgeRA7CPPIXJ4BJrtNN1aS80Sw1vX7WLVb3UbUXFxdagXZgSzLtXaygKAowMdzX+cFsVhsZLEYqfPSltHffVaNWVl2/U/oueGWFpqvKzUulv89D/9k="
},
"filters" : [ ],
"matchRegion" : null
} ],
"controls" : [ {
"name" : "Display Image",
"type" : "SELECT",
"options" : [ "Source", "Coin" ],
"value" : "Source"
} ]
} ]
} ]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,9 @@
export function createButton({ id, text, onClick, style = '', render = (el, data) => {} }) {
const btn = document.createElement('button');
btn.id = id;
btn.textContent = text;
btn.style = style;
btn.addEventListener('click', onClick);
btn.render = (data) => render(btn, data);
return btn;
}

View File

@@ -0,0 +1,156 @@
import { createControlComponent } from './control.js';
import { createFilterComponent } from './filter.js';
import { createMatcherComponent } from './matcher.js';
const lastTimestamps = {};
const dirtyRois = new Set();
const imageSizeState = {}; // regionName -> true (real size) or false (scaled)
// Helper to check if values have changed
function isRoiDirty(regionName) {
return dirtyRois.has(regionName);
}
function setRoiDirty(regionName, dirty) {
if (dirty) dirtyRois.add(regionName);
else dirtyRois.delete(regionName);
}
// Attach change listeners to controls
function attachChangeListeners(regionName, regionDiv, onChange) {
const inputs = regionDiv.querySelectorAll('input,select,textarea');
inputs.forEach(input => {
input.addEventListener('input', () => {
setRoiDirty(regionName, true);
const saveBtn = regionDiv.querySelector('.save-btn');
if (saveBtn) saveBtn.style.display = 'block';
});
});
}
// Toggle image size and update class
function toggleImageSize(regionName, regionDiv) {
imageSizeState[regionName] = !imageSizeState[regionName];
const img = regionDiv.querySelector('.capture-image img');
if (img) {
if (imageSizeState[regionName]) {
img.classList.add('real-size');
} else {
img.classList.remove('real-size');
}
}
// Update switch UI
const switchBtn = regionDiv.querySelector('.switch-btn');
if (switchBtn) {
switchBtn.classList.toggle('active', !!imageSizeState[regionName]);
switchBtn.setAttribute('aria-checked', !!imageSizeState[regionName]);
switchBtn.querySelector('.switch-label').textContent = imageSizeState[regionName] ? 'Real Size' : 'Scaled';
}
}
// Render all cards and their controls/filters/matchers
export function renderCaptureCards(configuration, onSave) {
const container = document.getElementById('captures');
container.innerHTML = '';
const rois = configuration.pages.flatMap(page => page.rois);
rois.forEach((roi, roiIdx) => {
let regionDiv = document.createElement('div');
regionDiv.id = roi.name;
regionDiv.className = 'grid-item capture-flex';
// Controls
let controlsHtml = (roi.controls || []).map((c, idx) =>
`<div class="control-section">${createControlComponent(c, `${roi.name}-ctrl-${idx}`)}</div>`
).join('');
// POIs, filters, matchers
let poisHtml = (roi.pois || []).map((poi, poiIdx) => {
const filtersHtml = (poi.filters || []).map((f, fIdx) =>
`<div class="filter-section">${createFilterComponent(f, `${roi.name}-poi-${poiIdx}-filter-${fIdx}`)}</div>`
).join('');
const matcherHtml = poi.matcher
? `<div class="matcher-section">${createMatcherComponent(poi.matcher, `${roi.name}-poi-${poiIdx}-matcher`)}</div>`
: '';
return `
<div class="poi-card">
<div class="poi-title">${poi.name}</div>
<div class="poi-filters">${filtersHtml}</div>
<div class="poi-matcher">${matcherHtml}</div>
</div>
`;
}).join('');
// Save button
const saveBtnId = `${roi.name}-save-btn`;
const saveBtnDisplay = isRoiDirty(roi.name) ? 'block' : 'none';
// Switch button for image size
const switchBtnId = `${roi.name}-switch-btn`;
const isReal = !!imageSizeState[roi.name];
regionDiv.innerHTML = `
<div class="capture-left">
<h3>${roi.name}</h3>
<div class="capture-image"></div>
<div class="capture-meta"></div>
<button id="${switchBtnId}" class="switch-btn${isReal ? ' active' : ''}" type="button" aria-checked="${isReal}">
<span class="switch-slider"></span>
<span class="switch-label">${isReal ? 'Real Size' : 'Scaled'}</span>
</button>
</div>
<div class="capture-right">
<div class="roi-controls">${controlsHtml}</div>
<div class="roi-pois">${poisHtml}</div>
<button id="${saveBtnId}" class="save-btn" style="display:${saveBtnDisplay}">Save</button>
</div>
`;
container.appendChild(regionDiv);
// Attach save handler
const saveBtn = document.getElementById(saveBtnId);
saveBtn.onclick = () => {
setRoiDirty(roi.name, false);
saveBtn.style.display = 'none';
onSave(roi.name);
};
// Attach change listeners to controls to show Save button on change
attachChangeListeners(roi.name, regionDiv);
// Attach switch handler
const switchBtn = document.getElementById(switchBtnId);
switchBtn.onclick = () => toggleImageSize(roi.name, regionDiv);
});
}
// Only update image, FPS, delta
export function updateCaptureCardImage(capture) {
let regionDiv = document.getElementById(capture.regionName);
if (!regionDiv) return;
// FPS calculation
const currentTimestamp = new Date(capture.timestamp).getTime();
const lastTimestamp = lastTimestamps[capture.regionName] || currentTimestamp;
const delta = currentTimestamp - lastTimestamp;
const fps = delta > 0 ? (1000 / delta).toFixed(2) : 'N/A';
lastTimestamps[capture.regionName] = currentTimestamp;
// Update image and meta only
let imgDiv = regionDiv.querySelector('.capture-image');
if (!imgDiv) {
imgDiv = document.createElement('div');
imgDiv.className = 'capture-image';
regionDiv.appendChild(imgDiv);
}
// Add or remove real-size class based on state
const isReal = !!imageSizeState[capture.regionName];
imgDiv.innerHTML = `<img src="data:image/jpeg;base64,${capture.image}" alt="${capture.regionName}" class="${isReal ? 'real-size' : ''}" />`;
let metaDiv = regionDiv.querySelector('.capture-meta');
if (!metaDiv) {
metaDiv = document.createElement('div');
metaDiv.className = 'capture-meta';
regionDiv.appendChild(metaDiv);
}
metaDiv.innerHTML = `<p>FPS: ${fps}</p><p>Delta: ${delta} ms</p>`;
}

View File

@@ -0,0 +1,26 @@
export function createControlComponent(control, id) {
switch (control.type) {
case 'SELECT':
return `
<label>${control.name}
<select id="${id}">
${control.options.map(opt => `<option value="${opt}" ${opt === control.value ? 'selected' : ''}>${opt}</option>`).join('')}
</select>
</label>
`;
case 'CHECKBOX':
return `
<label>
<input type="checkbox" id="${id}" ${control.value === 'true' ? 'checked' : ''}/> ${control.name}
</label>
`;
case 'TEXT':
return `
<label>${control.name}
<input type="text" id="${id}" value="${control.value || ''}" />
</label>
`;
default:
return `<span>${control.name} (${control.type})</span>`;
}
}

View File

@@ -0,0 +1,12 @@
import { createControlComponent } from './control.js';
export function createFilterComponent(filter, idPrefix) {
return `
<div class="filter">
<div class="filter-title">${filter.name} (${filter.type})</div>
<div class="filter-controls">
${(filter.controls || []).map((c, cIdx) => createControlComponent(c, `${idPrefix}-ctrl-${cIdx}`)).join('')}
</div>
</div>
`;
}

View File

@@ -0,0 +1,60 @@
import { createControlComponent } from './control.js';
const templateImageSizeState = {}; // idPrefix -> true (real size) or false (scaled)
function toggleTemplateImageSize(idPrefix) {
templateImageSizeState[idPrefix] = !templateImageSizeState[idPrefix];
const img = document.getElementById(`${idPrefix}-template-img`);
if (img) {
if (templateImageSizeState[idPrefix]) {
img.classList.add('real-size');
} else {
img.classList.remove('real-size');
}
}
// Update switch UI
const switchBtn = document.getElementById(`${idPrefix}-template-switch-btn`);
if (switchBtn) {
switchBtn.classList.toggle('active', !!templateImageSizeState[idPrefix]);
switchBtn.setAttribute('aria-checked', !!templateImageSizeState[idPrefix]);
switchBtn.querySelector('.switch-label').textContent = templateImageSizeState[idPrefix] ? 'Real Size' : 'Scaled';
}
}
export function createMatcherComponent(matcher, idPrefix) {
let controlsHtml = (matcher.controls || []).map((c, mIdx) => createControlComponent(c, `${idPrefix}-ctrl-${mIdx}`)).join('');
let templateImgHtml = '';
let switchHtml = '';
if (matcher.templateImage) {
const isReal = !!templateImageSizeState[idPrefix];
switchHtml = `
<button id="${idPrefix}-template-switch-btn" class="switch-btn${isReal ? ' active' : ''}" type="button" aria-checked="${isReal}">
<span class="switch-slider"></span>
<span class="switch-label">${isReal ? 'Real Size' : 'Scaled'}</span>
</button>
`;
templateImgHtml = `
<div class="template-image">
<img id="${idPrefix}-template-img" src="data:image/jpeg;base64,${matcher.templateImage}" alt="template" class="${isReal ? 'real-size' : ''}" />
${switchHtml}
</div>
`;
}
let templateHtml = matcher.templateName
? `<div>Template: ${matcher.templateName}</div>${templateImgHtml}`
: '';
// Attach toggle after rendering
setTimeout(() => {
const switchBtn = document.getElementById(`${idPrefix}-template-switch-btn`);
if (switchBtn) {
switchBtn.onclick = () => toggleTemplateImageSize(idPrefix);
}
}, 0);
return `
<div class="matcher">
<div class="matcher-title">${matcher.type}</div>
${templateHtml}
<div class="matcher-controls">${controlsHtml}</div>
</div>
`;
}

16
src/main/webui/index.html Normal file
View File

@@ -0,0 +1,16 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Quinoa App</title>
</head>
<body>
<header id="header"></header>
<main id="app">
<div id="captures" class="grid-container"></div>
</main>
<script type="module" src="/main.js"></script>
</body>
</html>

86
src/main/webui/main.js Normal file
View File

@@ -0,0 +1,86 @@
import './style.css';
import { ApiService } from './services/apiService.js';
import { SocketService } from './services/socketService.js';
import { createButton } from './components/button.js';
import { renderCaptureCards, updateCaptureCardImage } from './components/captureCard.js';
const api = new ApiService('http://192.168.1.10:8080');
const socketService = new SocketService('ws://192.168.1.10:8080/bot');
let configuration = null;
let botStatus = 'STOPPED';
async function loadAndRenderConfig() {
configuration = await api.getConfiguration();
botStatus = await api.getStatus();
renderCaptureCards(configuration, onSave);
}
async function onSave(regionName) {
// Collect values from controls for this region/card and update configuration object
const updatedConfig = collectUpdatedConfiguration(regionName, configuration);
await api.updateConfiguration(updatedConfig);
await loadAndRenderConfig();
}
// Utility to collect updated values from DOM and update configuration object
function collectUpdatedConfiguration(regionName, config) {
// Deep clone config to avoid mutating the original
const newConfig = JSON.parse(JSON.stringify(config));
const roi = newConfig.pages.flatMap(page => page.rois).find(r => r.name === regionName);
if (!roi) return newConfig;
// Controls
if (roi.controls) {
roi.controls.forEach((control, idx) => {
const id = `${regionName}-ctrl-${idx}`;
const el = document.getElementById(id);
if (el) control.value = el.value || (el.checked ? 'true' : 'false');
});
}
// POIs, filters, matchers
if (roi.pois) {
roi.pois.forEach((poi, poiIdx) => {
// Filters
if (poi.filters) {
poi.filters.forEach((filter, fIdx) => {
if (filter.controls) {
filter.controls.forEach((control, cIdx) => {
const id = `${regionName}-poi-${poiIdx}-filter-${fIdx}-ctrl-${cIdx}`;
const el = document.getElementById(id);
if (el) control.value = el.value || (el.checked ? 'true' : 'false');
});
}
});
}
// Matcher
if (poi.matcher && poi.matcher.controls) {
poi.matcher.controls.forEach((control, mIdx) => {
const id = `${regionName}-poi-${poiIdx}-matcher-ctrl-${mIdx}`;
const el = document.getElementById(id);
if (el) control.value = el.value || (el.checked ? 'true' : 'false');
});
}
});
}
return newConfig;
}
const header = document.querySelector('#header');
const startStopBtn = createButton({
id: 'start-stop-bot',
text: 'Start Bot',
onClick: async () => botStatus === 'STARTED' ? await api.stopBot() : await api.startBot(),
render: (btn, status) => btn.textContent = status === 'STARTED' ? 'Stop Bot' : 'Start Bot'
});
header.appendChild(startStopBtn);
window.addEventListener('DOMContentLoaded', async () => {
await loadAndRenderConfig();
socketService.setCaptureHandler(capture => updateCaptureCardImage(capture));
socketService.setStatusHandler(status => {
botStatus = status;
startStopBtn.render(botStatus);
});
socketService.connect();
});

1195
src/main/webui/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,14 @@
{
"name": "quinoa-starter",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite --base=/quinoa --host=0.0.0.0",
"build": "vite --base=/quinoa build",
"preview": "vite --base=/quinoa preview "
},
"devDependencies": {
"vite": "^5.4.17"
}
}

View File

@@ -0,0 +1 @@
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><defs><style>.cls-1{fill:#4695eb;}.cls-2{fill:#ff004a;}.cls-3{fill:#fff;}</style></defs><title>quarkus_icon_rgb_1024px_reverse</title><polygon class="cls-1" points="669.34 180.57 512 271.41 669.34 362.25 669.34 180.57"/><polygon class="cls-2" points="354.66 180.57 354.66 362.25 512 271.41 354.66 180.57"/><polygon class="cls-3" points="669.34 362.25 512 271.41 354.66 362.25 512 453.09 669.34 362.25"/><polygon class="cls-1" points="188.76 467.93 346.1 558.76 346.1 377.09 188.76 467.93"/><polygon class="cls-2" points="346.1 740.44 503.43 649.6 346.1 558.76 346.1 740.44"/><polygon class="cls-3" points="346.1 377.09 346.1 558.76 503.43 649.6 503.43 467.93 346.1 377.09"/><polygon class="cls-1" points="677.9 740.44 677.9 558.76 520.57 649.6 677.9 740.44"/><polygon class="cls-2" points="835.24 467.93 677.9 377.09 677.9 558.76 835.24 467.93"/><polygon class="cls-3" points="520.57 649.6 677.9 558.76 677.9 377.09 520.57 467.93 520.57 649.6"/><path class="cls-1" d="M853.47,1H170.53C77.29,1,1,77.29,1,170.53V853.47C1,946.71,77.29,1023,170.53,1023h467.7L512,716.39,420.42,910H170.53C139.9,910,114,884.1,114,853.47V170.53C114,139.9,139.9,114,170.53,114H853.47C884.1,114,910,139.9,910,170.53V853.47C910,884.1,884.1,910,853.47,910H705.28l46.52,113H853.47c93.24,0,169.53-76.29,169.53-169.53V170.53C1023,77.29,946.71,1,853.47,1Z"/></svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,29 @@
export class ApiService {
constructor(baseUrl) {
this.baseUrl = baseUrl;
}
startBot() {
return fetch(`${this.baseUrl}/start`).then(res => res.text());
}
stopBot() {
return fetch(`${this.baseUrl}/stop`).then(res => res.text());
}
getConfiguration() {
return fetch(`${this.baseUrl}/configuration`).then(res => res.json());
}
getStatus() {
return fetch(`${this.baseUrl}/status`).then(res => res.text());
}
updateConfiguration(config) {
return fetch(`${this.baseUrl}/configuration`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config)
}).then(res => res.json());
}
}

View File

@@ -0,0 +1,30 @@
export class SocketService {
constructor(url) {
this.url = url;
this.socket = null;
this.onCapture = null;
this.onStatus = null;
}
connect() {
this.socket = new WebSocket(this.url);
this.socket.onopen = () => console.log('WebSocket connection established');
this.socket.onclose = () => console.log('WebSocket connection closed');
this.socket.onmessage = (event) => {
const msg = JSON.parse(event.data);
if (msg.type === 'capture' && this.onCapture) {
this.onCapture(msg.data);
} else if (msg.type === 'status' && this.onStatus) {
this.onStatus(msg.status);
}
};
}
setCaptureHandler(handler) {
this.onCapture = handler;
}
setStatusHandler(handler) {
this.onStatus = handler;
}
}

303
src/main/webui/style.css Normal file
View File

@@ -0,0 +1,303 @@
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
body {
margin: 0;
display: flex;
flex-direction: column;
place-items: center;
min-width: 320px;
min-height: 100vh;
font-family: Arial, sans-serif;
}
h1 {
font-size: 3.2em;
line-height: 1.1;
}
#app {
max-width: 1280px;
margin: 0 auto;
padding: 20px;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vanilla:hover {
filter: drop-shadow(0 0 2em #f7df1eaa);
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
margin-bottom: 20px;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}
.grid-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
.grid-item {
border: 1px solid black;
padding: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.grid-item img {
width: 100%;
height: auto;
display: block;
}
.grid-item h3 {
margin: 0;
cursor: pointer;
text-decoration: underline;
}
@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
.roi-controls {
border: 2px solid #4e7ac7;
border-radius: 6px;
background: #232b3a;
margin: 12px 0 18px 0;
padding: 10px 8px;
}
.control-section {
border-bottom: 1px solid #3a4252;
padding: 8px 0;
margin-bottom: 6px;
}
.control-section:last-child {
border-bottom: none;
}
.control-section label {
font-weight: 500;
color: #b3c7e6;
margin-right: 8px;
}
.poi-card {
border: 2px solid #888;
border-radius: 8px;
margin: 18px 0 18px 0;
padding: 12px;
background: #23272e;
box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.poi-title {
font-weight: bold;
font-size: 1.1em;
margin-bottom: 8px;
color: #6fa8dc;
}
.filter-section {
border-left: 4px solid #6fa8dc;
margin: 8px 0;
padding: 8px 0 8px 12px;
background: #2c2f36;
}
.matcher-section {
border-left: 4px solid #f6b26b;
margin: 8px 0;
padding: 8px 0 8px 12px;
background: #2c2f36;
}
.poi-filters, .poi-matcher {
margin-bottom: 6px;
}
.capture-flex {
display: flex;
flex-direction: row;
align-items: flex-start;
gap: 24px;
}
.capture-left {
flex: 0 0 220px;
display: flex;
flex-direction: column;
align-items: flex-start;
}
.capture-left h3 {
margin-bottom: .3rem;
}
.capture-right {
flex: 1 1 0;
display: flex;
flex-direction: column;
align-items: flex-end;
min-width: 0;
}
.capture-right .roi-controls,
.capture-right .roi-pois {
align-self: stretch;
}
.save-btn {
align-self: flex-end;
margin-top: 16px;
display: block;
}
.switch-btn {
display: inline-flex;
align-items: center;
background: #232b3a;
border: 1px solid #4e7ac7;
border-radius: 16px;
padding: 4px 12px 4px 4px;
cursor: pointer;
margin-top: 12px;
margin-bottom: 0;
transition: background 0.2s, border-color 0.2s;
outline: none;
min-width: 80px;
user-select: none;
}
.switch-btn .switch-slider {
width: 28px;
height: 16px;
background: #888;
border-radius: 10px;
margin-right: 8px;
position: relative;
transition: background 0.2s;
}
.switch-btn.active .switch-slider {
background: #4e7ac7;
}
.switch-btn .switch-slider::before {
content: "";
position: absolute;
left: 2px;
top: 2px;
width: 12px;
height: 12px;
background: #fff;
border-radius: 50%;
transition: left 0.2s;
}
.switch-btn.active .switch-slider::before {
left: 14px;
}
.switch-btn .switch-label {
font-size: 0.95em;
color: #b3c7e6;
font-weight: 500;
}
.capture-image img {
width: 100%;
height: auto;
display: block;
max-width: 100%;
border-radius: 6px;
transition: box-shadow 0.2s;
}
.capture-image img.real-size {
width: auto;
max-width: none;
height: auto;
box-shadow: 0 0 0 2px #4e7ac7;
}
.template-image {
margin-top: 6px;
margin-bottom: 6px;
display: flex;
flex-direction: column;
align-items: flex-start;
}
.template-image img {
max-width: 120px;
max-height: 120px;
border-radius: 4px;
border: 1px solid #444;
background: #181c22;
margin-bottom: 6px;
transition: box-shadow 0.2s, max-width 0.2s, max-height 0.2s;
}
.template-image img.real-size {
max-width: none;
max-height: none;
width: auto;
height: auto;
box-shadow: 0 0 0 2px #4e7ac7;
}

View File

@@ -0,0 +1,78 @@
package it.moze.grab;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.opencv.core.Mat;
import it.moze.boundary.screen.Grabber;
import it.moze.entity.geometry.Rectangle;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
class GrabberTest {
@BeforeAll
static void initOpenCv() {
Grabber.init();
}
@Test
void shouldGrabFullScreen() {
// When
Mat actual = Grabber.grab();
// Then
assertNotNull(actual);
assertTrue(actual.rows() > 0);
assertTrue(actual.cols() > 0);
assertEquals(actual.channels(), 4);
}
@Test
void shouldGrabRegion() {
// Given
Rectangle region = new Rectangle(0, 0, 640, 480);
// When
Mat actual = Grabber.grab(region);
// Then
assertNotNull(actual);
assertEquals(actual.rows(), 480);
assertEquals(actual.cols(), 640);
assertEquals(actual.channels(), 4);
}
@Test
void shouldGetMonitors() {
// when
Rectangle[] monitors = Grabber.getMonitors();
//then
assertNotEquals(monitors.length, 0);
Rectangle primaryMonitor = monitors[0];
assertEquals(primaryMonitor.x(), 0);
assertEquals(primaryMonitor.y(), 0);
assertTrue(primaryMonitor.width() > 0);
assertTrue(primaryMonitor.height() > 0);
}
@Test
void shouldGrabFullScreenUnderThreshold() {
// Given
long thresholdMillis = 100;
int tries = 100;
// When
List<Long> deltas = Stream.generate(() -> 0).limit(tries).map(i -> {
long startTime = System.currentTimeMillis();
Grabber.grab();
return System.currentTimeMillis() - startTime;
}).toList();
long averageDuration = deltas.stream()
.collect(Collectors.averagingLong(Long::longValue))
.longValue();
// Then
assertTrue(averageDuration < thresholdMillis, "Average frame time exceeded threshold: " + averageDuration + "ms");
}
}