Init commit

This commit is contained in:
Stefan Nenzén 2025-03-25 13:26:36 +01:00
parent b1f5400b8f
commit d5d3b94e48
No known key found for this signature in database
59 changed files with 2853 additions and 0 deletions

2
.gitattributes vendored Normal file

@ -0,0 +1,2 @@
/mvnw text eol=lf
*.cmd text eol=crlf

36
.github/workflows/ci.yml vendored Normal file

@ -0,0 +1,36 @@
name: Build, Test & Checkstyle
on:
push:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up JDK 21
uses: actions/setup-java@v3
with:
java-version: '21'
distribution: 'temurin'
- name: Cache Maven packages
uses: actions/cache@v3
with:
path: ~/.m2
key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }}
restore-keys: |
${{ runner.os }}-maven-
- name: Build with Maven
run: mvn clean install
- name: Run tests
run: mvn test
- name: Run Checkstyle
run: mvn checkstyle:check

19
.mvn/wrapper/maven-wrapper.properties vendored Normal file

@ -0,0 +1,19 @@
# 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=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip

12
Dockerfile Normal file

@ -0,0 +1,12 @@
FROM debian:trixie
RUN apt-get update && apt-get install openjdk-21-jdk-headless curl -y --no-install-recommends
WORKDIR /home/apimposter
COPY pom.xml pom.xml
COPY mvnw mvnw
COPY .mvn/ .mvn/
RUN ./mvnw dependency:go-offline -B
COPY src/ src/
CMD ["./mvnw", "spring-boot:run", "-Pdocker", "-Dspring-boot.run.profiles=docker", "-Dspring-boot.run.jvmArguments=--enable-preview -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:8001"]

276
README.md Normal file

@ -0,0 +1,276 @@
# APImposter 🎭
**A small, flexible API mock service designed with microservice environments in mind.**
---
## What is APImposter?
APImposter is an easy-to-use service built with Spring Boot, enabling quick mocking of API responses from various systems. It allows you to organize your mock data in YAML files.
---
## Key Features
- **Structured Mock Data:** Organize your mock data in YAML files.
- **Automatic URL Mapping:** Automatically generates URL structure based on your folder hierarchy and YAML file names.
- **Hot Reloading:** Automatically reloads mock data files when they are changed.
- **Dynamic Responses and Global Placeholders:** Supports dynamic values in responses based on URL parameters and you can define global placeholders to reuse values across multiple responses and systems.
- **Conditional Responses:** Return different mock responses based on request data (headers, query, body, or path).
- **Swagger UI:** Automatically generated Swagger UI from YAML files.
- **Quick Setup:** Easy installation and configuration.
---
## Mocks Structure
YAML defined mocks are stored in a directory defined in `application.properties`. You can organize them in nested folders like this:
```
/mocks/
├── globals.yaml
├── system1/
│ ├── users.yaml
│ └── program.yaml
└── another-system/
├── endpoint1.yaml
└── subdir/
└── endpoint2.yaml
```
Example YAML files:
```yaml
# globals.yaml
globals:
currentUserId: "user-123"
```
```yaml
# system1/users.yaml
- method: "GET"
path: "/{id}"
response:
status: 200
headers:
Content-Type: "application/json"
body:
id: "{id}"
name: "Example User"
```
```yaml
# system1/program.yaml
- method: "GET"
path: "/"
delay: 500
response:
status: 200
headers:
Content-Type: "application/json"
body:
programId: 12345
globalUserId: "{globals.currentUserId}"
```
---
## Example Requests and Responses
| YAML file | Request | Response |
| --------------------------------------- |--------------------------------------------|-------------------------------------------|
| `mocks/system1/users.yaml` | `GET /<prefix>/system1/users/123` | `{ "id": "123", "name": "Example User" }` |
| `mocks/system1/program.yaml` | `GET /<prefix>/system1/program` | `{ "programId": 12345, "globalUserId": "user-123" }` |
| `mocks/another-system/subdir/endpoint2` | `GET /<prefix>/another-system/subdir/endpoint2/...` | *(defined response JSON)* |
Dynamic placeholders in responses (`{id}`) and global placeholders (`{globals.currentUserId}`) are automatically replaced with actual URL parameters or globally defined values.
Folders in the YAML file structure become part of the URL path automatically.
---
## Conditional Responses
APImposter supports **conditional responses**, allowing different mock responses to be returned **based on request values** — like query parameters, headers, path variables, or body fields.
This is useful for simulating realistic API behavior, such as authentication, filtering, or alternate success/error outcomes.
### Supported condition types:
- `path`: matches against path variables
- `query`: matches query parameters (`?filter=active`)
- `headers`: matches HTTP headers (case-insensitive)
- `body`: matches top-level JSON body fields (for POST/PUT)
### Example: conditionals by path
```yaml
- method: "GET"
path: "/users/{id}"
conditionalResponses:
- conditions:
path:
id: "1"
response:
status: 200
headers:
Content-Type: application/json
body:
id: 1
name: "Lennart"
- conditions:
path:
id: "2"
response:
status: 200
headers:
Content-Type: application/json
body:
id: 2
name: "Kurre"
response:
status: 404
headers:
Content-Type: application/json
body:
error: "User not found"
```
### Example: conditionals by header
```yaml
- method: "GET"
path: "/secure"
conditionalResponses:
- conditions:
headers:
authorization: "Bearer abc123"
response:
status: 200
headers:
Content-Type: application/json
body:
message: "Access granted"
response:
status: 401
headers:
Content-Type: application/json
body:
error: "Unauthorized"
```
### Example: conditionals by query parameter
```yaml
- method: "GET"
path: "/products"
conditionalResponses:
- conditions:
query:
category: "books"
response:
status: 200
headers: { Content-Type: "application/json" }
body:
products:
- id: "b1"
name: "Data Structures and Algorithms in Java"
- conditions:
query:
category: "tech"
response:
status: 200
headers: { Content-Type: "application/json" }
body:
products:
- id: "t1"
name: "Mechanical Keyboard"
response:
status: 200
headers: { Content-Type: "application/json" }
body:
products: []
```
### Example: conditionals by request body
```yaml
- method: "POST"
path: "/login"
conditionalResponses:
- conditions:
body:
username: "admin"
password: "secret"
response:
status: 200
headers:
Content-Type: application/json
body:
token: "abc123"
response:
status: 403
headers:
Content-Type: application/json
body:
error: "Invalid credentials"
```
### Testing with `curl`
```bash
curl http://localhost:8080/mocks/users/1
curl -H "Authorization: Bearer abc123" http://localhost:8080/mocks/secure
curl "http://localhost:8080/mocks/products?category=books"
curl -X POST http://localhost:8080/mocks/login \
-H "Content-Type: application/json" \
-d '{"username": "admin", "password": "secret"}'
```
Conditions are evaluated **in order**, and the **first matching block wins**. If no condition matches, the fallback `response:` is used.
---
## Configuration
In `application.properties` you can configure the following properties:
- `mock.file-path`: The path to the directory containing your mock data YAML files.
- `mock.reload-interval-ms`: The interval in milliseconds at which the service checks for changes in the mock data files.
- `mock.base-path`: The base path for the mock service. This is prepended to all generated URLs. Default is `/mocks`.
- `mock.default-delay-ms`: The default delay in milliseconds for responses. This can be overridden in the YAML files.
---
## Swagger UI
OpenAPI Specification is generated from the mock data YAML files and can
be accessed via Swagger UI. You will find it at:
```
http://localhost:8080/swagger
```
---
## Quick Start
Clone the project and run it simply with:
```shell
./mvnw spring-boot:run
```
or with Docker:
```shell
docker-compose up
```
---
🎭 **Good luck and happy mocking!** 🎭

@ -0,0 +1,220 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<!--
Checkstyle configuration that checks the sun coding conventions from:
- the Java Language Specification at
https://docs.oracle.com/javase/specs/jls/se11/html/index.html
- the Sun Code Conventions at https://www.oracle.com/java/technologies/javase/codeconventions-contents.html
- the Javadoc guidelines at
https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html
- the JDK Api documentation https://docs.oracle.com/en/java/javase/11/
- some best practices
Checkstyle is very configurable. Be sure to read the documentation at
https://checkstyle.org (or in your downloaded distribution).
Most Checks are configurable, be sure to consult the documentation.
To completely disable a check, just comment it out or delete it from the file.
To suppress certain violations please review suppression filters.
Finally, it is worth reading the documentation.
-->
<module name="Checker">
<!--
If you set the basedir property below, then all reported file
names will be relative to the specified directory. See
https://checkstyle.org/config.html#Checker
<property name="basedir" value="${basedir}"/>
-->
<property name="severity" value="error"/>
<property name="fileExtensions" value="java, properties, xml"/>
<!-- Excludes all 'module-info.java' files -->
<!-- See https://checkstyle.org/filefilters/index.html -->
<module name="BeforeExecutionExclusionFileFilter">
<property name="fileNamePattern" value="module\-info\.java$"/>
</module>
<!-- https://checkstyle.org/filters/suppressionfilter.html -->
<module name="SuppressionFilter">
<property name="file" value="${org.checkstyle.sun.suppressionfilter.config}"
default="checkstyle-suppressions.xml" />
<property name="optional" value="true"/>
</module>
<!-- Checks that a package-info.java file exists for each package. -->
<!-- See https://checkstyle.org/checks/javadoc/javadocpackage.html#JavadocPackage -->
<!-- <module name="JavadocPackage"/>-->
<!-- Checks whether files end with a new line. -->
<!-- See https://checkstyle.org/checks/misc/newlineatendoffile.html -->
<module name="NewlineAtEndOfFile"/>
<!-- Checks that property files contain the same keys. -->
<!-- See https://checkstyle.org/checks/misc/translation.html -->
<module name="Translation"/>
<!-- Checks for Size Violations. -->
<!-- See https://checkstyle.org/checks/sizes/index.html -->
<module name="FileLength"/>
<module name="LineLength">
<property name="fileExtensions" value="java"/>
<property name="max" value="120"/>
</module>
<!-- Checks for whitespace -->
<!-- See https://checkstyle.org/checks/whitespace/index.html -->
<module name="FileTabCharacter"/>
<!-- Miscellaneous other checks. -->
<!-- See https://checkstyle.org/checks/misc/index.html -->
<module name="RegexpSingleline">
<property name="format" value="\s+$"/>
<property name="minimum" value="0"/>
<property name="maximum" value="0"/>
<property name="message" value="Line has trailing spaces."/>
</module>
<!-- Checks for Headers -->
<!-- See https://checkstyle.org/checks/header/index.html -->
<!-- <module name="Header"> -->
<!-- <property name="headerFile" value="${checkstyle.header.file}"/> -->
<!-- <property name="fileExtensions" value="java"/> -->
<!-- </module> -->
<module name="TreeWalker">
<!-- Checks for Javadoc comments. -->
<!-- See https://checkstyle.org/checks/javadoc/index.html -->
<module name="InvalidJavadocPosition"/>
<module name="JavadocMethod">
<property name="allowMissingParamTags" value="true"/>
<property name="allowMissingReturnTag" value="true"/>
</module>
<module name="JavadocType">
<property name="allowMissingParamTags" value="true"/>
</module>
<!-- <module name="JavadocVariable">-->
<!-- &lt;!&ndash; ignore private and package-private variables (fields) &ndash;&gt;-->
<!-- <property name="scope" value="package"/>-->
<!-- </module>-->
<module name="JavadocStyle"/>
<!-- <module name="MissingJavadocMethod">-->
<!-- <property name="allowMissingPropertyJavadoc" value="true"/>-->
<!-- <property name="tokens" value="METHOD_DEF, ANNOTATION_FIELD_DEF"/>-->
<!-- </module>-->
<!-- Checks for Naming Conventions. -->
<!-- See https://checkstyle.org/checks/naming/index.html -->
<module name="ConstantName"/>
<module name="LocalFinalVariableName"/>
<module name="LocalVariableName"/>
<module name="MemberName"/>
<module name="MethodName"/>
<module name="PackageName"/>
<module name="ParameterName"/>
<module name="StaticVariableName"/>
<module name="TypeName"/>
<!-- Checks for imports -->
<!-- See https://checkstyle.org/checks/imports/index.html -->
<module name="AvoidStarImport"/>
<module name="IllegalImport"/> <!-- defaults to sun.* packages -->
<module name="RedundantImport"/>
<module name="UnusedImports"/>
<!-- Checks for Size Violations. -->
<!-- See https://checkstyle.org/checks/sizes/index.html -->
<module name="MethodLength"/>
<module name="ParameterNumber"/>
<!-- Checks for whitespace -->
<!-- See https://checkstyle.org/checks/whitespace/index.html -->
<module name="EmptyForIteratorPad"/>
<module name="GenericWhitespace"/>
<module name="MethodParamPad"/>
<module name="NoWhitespaceAfter"/>
<module name="NoWhitespaceBefore"/>
<module name="OperatorWrap"/>
<module name="ParenPad"/>
<module name="TypecastParenPad"/>
<module name="WhitespaceAfter"/>
<module name="WhitespaceAround">
<property name="allowEmptyConstructors" value="true"/>
<property name="allowEmptyMethods" value="true"/>
<property name="allowEmptyTypes" value="true"/>
<property name="allowEmptyLambdas" value="true"/>
</module>
<!-- Modifier Checks -->
<!-- See https://checkstyle.org/checks/modifier/index.html -->
<module name="ModifierOrder"/>
<module name="RedundantModifier"/>
<!-- Checks for blocks. You know, those {}'s -->
<!-- See https://checkstyle.org/checks/blocks/index.html -->
<module name="AvoidNestedBlocks"/>
<module name="EmptyBlock"/>
<module name="LeftCurly">
<property name="option" value="nlow"/>
</module>
<module name="NeedBraces">
<property name="allowSingleLineStatement" value="true"/>
</module>
<module name="RightCurly"/>
<!-- Checks for common coding problems -->
<!-- See https://checkstyle.org/checks/coding/index.html -->
<module name="EmptyStatement"/>
<module name="EqualsHashCode"/>
<module name="HiddenField">
<property name="ignoreConstructorParameter" value="true"/>
<property name="ignoreSetter" value="true"/>
</module>
<module name="IllegalInstantiation"/>
<module name="InnerAssignment"/>
<module name="MagicNumber"/>
<module name="MissingSwitchDefault"/>
<module name="MultipleVariableDeclarations"/>
<module name="SimplifyBooleanExpression"/>
<module name="SimplifyBooleanReturn"/>
<!-- Checks for class design -->
<!-- See https://checkstyle.org/checks/design/index.html -->
<!-- <module name="DesignForExtension"/>-->
<module name="FinalClass"/>
<module name="HideUtilityClassConstructor"/>
<module name="InterfaceIsType"/>
<module name="VisibilityModifier"/>
<!-- Miscellaneous other checks. -->
<!-- See https://checkstyle.org/checks/misc/index.html -->
<module name="ArrayTypeStyle"/>
<!-- <module name="FinalParameters"/>-->
<module name="TodoComment"/>
<module name="UpperEll"/>
<!-- https://checkstyle.org/filters/suppressionxpathfilter.html -->
<module name="SuppressionXpathFilter">
<property name="file" value="${org.checkstyle.sun.suppressionxpathfilter.config}"
default="checkstyle-xpath-suppressions.xml" />
<property name="optional" value="true"/>
</module>
</module>
</module>

12
docker-compose.yml Normal file

@ -0,0 +1,12 @@
services:
apimposter:
build: .
container_name: apimposter
ports:
- "8080:8080"
volumes:
- ./mocks:/home/apimposter/mocks
environment:
- MOCK_FILE_PATH=/home/apimposter/mocks
- MOCK_BASE_PATH=/
- MOCK_RELOAD_INTERVAL_MS=3000

135
mocks/daisy/program.yaml Normal file

@ -0,0 +1,135 @@
- method: "GET"
path: "/"
response:
status: 200
headers:
Content-Type: "application/json"
body:
id: 12345
name: ...
code: ...
name_en: ...
responsibleDepartment:
name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- {}
- {}
- name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- {}
- {}
educationalInstitution:
name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- {}
- {}
- name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- {}
- {}
type: MAGISTER
level: FIRST_CYCLE
- method: "GET"
path: "/{id}"
response:
status: 200
headers:
Content-Type: "application/json"
body:
id: 12345
name: ...
code: ...
name_en: ...
responsibleDepartment:
name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- {}
- {}
- name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- {}
- {}
educationalInstitution:
name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- {}
- {}
- name_en: ...
id: 12345
designation: ...
closed: true
name: ...
units:
- {}
- {}
type: MASTER
level: FIRST_CYCLE
- method: "GET"
path: "/{id}/admissions"
response:
status: 500
headers:
Content-Type: "application/json"
body:
- conditioned: false
kull: 12345
discontinued: true
id: 12345
studentId: 12345
programId: 12345
admissionSemester: 12345

2
mocks/globals.yaml Normal file

@ -0,0 +1,2 @@
globals:
currentUserId: "user-1234"

20
mocks/test/api.yaml Normal file

@ -0,0 +1,20 @@
- method: "GET"
path: "/"
response:
status: 200
headers:
Content-Type: "application/json"
body:
name: "api test endpoint 1"
- method: "GET"
path: "/{id}"
response:
status: 200
headers:
Content-Type: "application/json"
body:
id: "{id}"
name: "Example User"
globalUserId: "{globals.currentUserId}"

26
mocks/test/login.yaml Normal file

@ -0,0 +1,26 @@
- method: "POST"
path: "/"
conditionalResponses:
- conditions:
body:
username: "admin"
password: "wrong"
response:
status: 403
headers: { Content-Type: "application/json" }
body:
error: "Invalid credentials"
- conditions:
body:
username: "admin"
password: "secret"
response:
status: 200
headers: { Content-Type: "application/json" }
body:
token: "abc123"
response:
status: 400
headers: { Content-Type: "application/json" }
body:
error: "Bad request"

28
mocks/test/products.yaml Normal file

@ -0,0 +1,28 @@
- method: "GET"
path: "/"
conditionalResponses:
- conditions:
query:
category: "books"
response:
status: 200
headers: { Content-Type: "application/json" }
body:
products:
- id: "b1"
name: "Data Structures and Algorithms in Java"
- conditions:
query:
category: "tech"
response:
status: 200
headers: { Content-Type: "application/json" }
body:
products:
- id: "t1"
name: "Mechanical Keyboard"
response:
status: 200
headers: { Content-Type: "application/json" }
body:
products: []

16
mocks/test/secure.yaml Normal file

@ -0,0 +1,16 @@
- method: "GET"
path: "/"
conditionalResponses:
- conditions:
headers:
Authorization: "Bearer abc123"
response:
status: 200
headers: { Content-Type: "application/json" }
body:
message: "Access granted"
response:
status: 401
headers: { Content-Type: "application/json" }
body:
error: "Unauthorized"

9
mocks/test/test.yaml Normal file

@ -0,0 +1,9 @@
- method: "GET"
path: "/"
delay: 1000
response:
status: 200
headers:
Content-Type: "application/json"
body:
name: "api test"

26
mocks/test/users.yaml Normal file

@ -0,0 +1,26 @@
- method: "GET"
path: "/{id}"
conditionalResponses:
- conditions:
path:
id: "1"
response:
status: 200
headers: { Content-Type: "application/json" }
body:
id: 1
name: "Lennart"
- conditions:
path:
id: "2"
response:
status: 200
headers: { Content-Type: "application/json" }
body:
id: 2
name: "Kurre"
response:
status: 404
headers: { Content-Type: "application/json" }
body:
error: "User not found"

259
mvnw vendored Executable file

@ -0,0 +1,259 @@
#!/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
#
# Optional ENV vars
# -----------------
# JAVA_HOME - location of a JDK home dir, required when download maven via java source
# MVNW_REPOURL - repo url base for downloading maven distribution
# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output
# ----------------------------------------------------------------------------
set -euf
[ "${MVNW_VERBOSE-}" != debug ] || set -x
# OS specific support.
native_path() { printf %s\\n "$1"; }
case "$(uname)" in
CYGWIN* | MINGW*)
[ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")"
native_path() { cygpath --path --windows "$1"; }
;;
esac
# set JAVACMD and JAVACCMD
set_java_home() {
# For Cygwin and MinGW, ensure paths are in Unix format before anything is touched
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"
JAVACCMD="$JAVA_HOME/jre/sh/javac"
else
JAVACMD="$JAVA_HOME/bin/java"
JAVACCMD="$JAVA_HOME/bin/javac"
if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then
echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2
echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2
return 1
fi
fi
else
JAVACMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v java
)" || :
JAVACCMD="$(
'set' +e
'unset' -f command 2>/dev/null
'command' -v javac
)" || :
if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then
echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2
return 1
fi
fi
}
# hash string like Java String::hashCode
hash_string() {
str="${1:-}" h=0
while [ -n "$str" ]; do
char="${str%"${str#?}"}"
h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296))
str="${str#?}"
done
printf %x\\n $h
}
verbose() { :; }
[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; }
die() {
printf %s\\n "$1" >&2
exit 1
}
trim() {
# MWRAPPER-139:
# Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds.
# Needed for removing poorly interpreted newline sequences when running in more
# exotic environments such as mingw bash on Windows.
printf "%s" "${1}" | tr -d '[:space:]'
}
# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties
while IFS="=" read -r key value; do
case "${key-}" in
distributionUrl) distributionUrl=$(trim "${value-}") ;;
distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;;
esac
done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties"
[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties"
case "${distributionUrl##*/}" in
maven-mvnd-*bin.*)
MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/
case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in
*AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;;
:Darwin*x86_64) distributionPlatform=darwin-amd64 ;;
:Darwin*arm64) distributionPlatform=darwin-aarch64 ;;
:Linux*x86_64*) distributionPlatform=linux-amd64 ;;
*)
echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2
distributionPlatform=linux-amd64
;;
esac
distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip"
;;
maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;;
*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;;
esac
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}"
distributionUrlName="${distributionUrl##*/}"
distributionUrlNameMain="${distributionUrlName%.*}"
distributionUrlNameMain="${distributionUrlNameMain%-bin}"
MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}"
MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")"
exec_maven() {
unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || :
exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD"
}
if [ -d "$MAVEN_HOME" ]; then
verbose "found existing MAVEN_HOME at $MAVEN_HOME"
exec_maven "$@"
fi
case "${distributionUrl-}" in
*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;;
*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;;
esac
# prepare tmp dir
if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then
clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; }
trap clean HUP INT TERM EXIT
else
die "cannot create temp dir"
fi
mkdir -p -- "${MAVEN_HOME%/*}"
# Download and Install Apache Maven
verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
verbose "Downloading from: $distributionUrl"
verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
# select .zip or .tar.gz
if ! command -v unzip >/dev/null; then
distributionUrl="${distributionUrl%.zip}.tar.gz"
distributionUrlName="${distributionUrl##*/}"
fi
# verbose opt
__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR=''
[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v
# normalize http auth
case "${MVNW_PASSWORD:+has-password}" in
'') MVNW_USERNAME='' MVNW_PASSWORD='' ;;
has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;;
esac
if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then
verbose "Found wget ... using wget"
wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl"
elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then
verbose "Found curl ... using curl"
curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl"
elif set_java_home; then
verbose "Falling back to use Java to download"
javaSource="$TMP_DOWNLOAD_DIR/Downloader.java"
targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName"
cat >"$javaSource" <<-END
public class Downloader extends java.net.Authenticator
{
protected java.net.PasswordAuthentication getPasswordAuthentication()
{
return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() );
}
public static void main( String[] args ) throws Exception
{
setDefault( new Downloader() );
java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() );
}
}
END
# For Cygwin/MinGW, switch paths to Windows format before running javac and java
verbose " - Compiling Downloader.java ..."
"$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java"
verbose " - Running Downloader.java ..."
"$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")"
fi
# If specified, validate the SHA-256 sum of the Maven distribution zip file
if [ -n "${distributionSha256Sum-}" ]; then
distributionSha256Result=false
if [ "$MVN_CMD" = mvnd.sh ]; then
echo "Checksum validation is not supported for maven-mvnd." >&2
echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
elif command -v sha256sum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then
distributionSha256Result=true
fi
elif command -v shasum >/dev/null; then
if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then
distributionSha256Result=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 'distributionSha256Sum' from your maven-wrapper.properties." >&2
exit 1
fi
if [ $distributionSha256Result = false ]; then
echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2
echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2
exit 1
fi
fi
# unzip and move
if command -v unzip >/dev/null; then
unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip"
else
tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar"
fi
printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url"
mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME"
clean || :
exec_maven "$@"

149
mvnw.cmd vendored Normal file

@ -0,0 +1,149 @@
<# : batch portion
@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 Optional ENV vars
@REM MVNW_REPOURL - repo url base for downloading maven distribution
@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven
@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output
@REM ----------------------------------------------------------------------------
@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0)
@SET __MVNW_CMD__=
@SET __MVNW_ERROR__=
@SET __MVNW_PSMODULEP_SAVE=%PSModulePath%
@SET PSModulePath=
@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @(
IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B)
)
@SET PSModulePath=%__MVNW_PSMODULEP_SAVE%
@SET __MVNW_PSMODULEP_SAVE=
@SET __MVNW_ARG0_NAME__=
@SET MVNW_USERNAME=
@SET MVNW_PASSWORD=
@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*)
@echo Cannot start maven from wrapper >&2 && exit /b 1
@GOTO :EOF
: end batch / begin powershell #>
$ErrorActionPreference = "Stop"
if ($env:MVNW_VERBOSE -eq "true") {
$VerbosePreference = "Continue"
}
# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties
$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl
if (!$distributionUrl) {
Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties"
}
switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) {
"maven-mvnd-*" {
$USE_MVND = $true
$distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip"
$MVN_CMD = "mvnd.cmd"
break
}
default {
$USE_MVND = $false
$MVN_CMD = $script -replace '^mvnw','mvn'
break
}
}
# apply MVNW_REPOURL and calculate MAVEN_HOME
# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-<version>,maven-mvnd-<version>-<platform>}/<hash>
if ($env:MVNW_REPOURL) {
$MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" }
$distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')"
}
$distributionUrlName = $distributionUrl -replace '^.*/',''
$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$',''
$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain"
if ($env:MAVEN_USER_HOME) {
$MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain"
}
$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join ''
$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME"
if (Test-Path -Path "$MAVEN_HOME" -PathType Container) {
Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME"
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"
exit $?
}
if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) {
Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl"
}
# prepare tmp dir
$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile
$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir"
$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null
trap {
if ($TMP_DOWNLOAD_DIR.Exists) {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
}
New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null
# Download and Install Apache Maven
Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..."
Write-Verbose "Downloading from: $distributionUrl"
Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName"
$webclient = New-Object System.Net.WebClient
if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) {
$webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD)
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null
# If specified, validate the SHA-256 sum of the Maven distribution zip file
$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum
if ($distributionSha256Sum) {
if ($USE_MVND) {
Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties."
}
Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash
if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) {
Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property."
}
}
# unzip and move
Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null
Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null
try {
Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null
} catch {
if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) {
Write-Error "fail to move MAVEN_HOME"
}
} finally {
try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null }
catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" }
}
Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD"

155
pom.xml Normal file

@ -0,0 +1,155 @@
<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.4</version>
<relativePath/>
</parent>
<groupId>dsv.su</groupId>
<artifactId>apimposter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>apimposter</name>
<description>Mocking APIs</description>
<packaging>war</packaging>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>8.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-models</artifactId>
<version>2.2.15</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
<configuration>
<argLine>
-javaagent:"${settings.localRepository}/net/bytebuddy/byte-buddy-agent/1.15.11/byte-buddy-agent-1.15.11.jar"
</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
<version>3.3.0</version>
<configuration>
<configLocation>checkstyle-configuration.xml</configLocation>
<maxAllowedViolations>0</maxAllowedViolations>
<failOnViolation>true</failOnViolation>
</configuration>
<dependencies>
<dependency>
<groupId>com.puppycrawl.tools</groupId>
<artifactId>checkstyle</artifactId>
<version>10.12.3</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>docker</id>
<properties>
<packaging.type>jar</packaging.type>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludeDevtools>false</excludeDevtools>
<layers>
<enabled>true</enabled>
</layers>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>tomcat</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<spring.profiles.active>tomcat</spring.profiles.active>
<packaging.type>war</packaging.type>
</properties>
<build>
<finalName>ROOT</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

@ -0,0 +1,14 @@
package dsv.su.apimposter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class ApImposterApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ApImposterApplication.class, args);
}
}

@ -0,0 +1,27 @@
package dsv.su.apimposter.config;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.resource.NoResourceFoundException;
/**
* Handles exceptions and fallback errors in the REST layer.
*/
@ControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(NoResourceFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public Map<String, Object> handleNoResourceFound(NoResourceFoundException ex) {
return Map.of(
"error", "Not Found",
"message", "The requested resource could not be found.",
"path", ex.getResourcePath()
);
}
}

@ -0,0 +1,25 @@
package dsv.su.apimposter.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import dsv.su.apimposter.controller.MockRequestInterceptor;
/**
* Spring Web MVC configuration class that registers a custom interceptor.
* This config ensures {@link MockRequestInterceptor} is invoked on every request,
* allowing it to handle mock endpoints dynamically based on the mock base path.
* Other requests (static files, Swagger, etc.) are unaffected and routed normally.
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private MockRequestInterceptor mockRequestInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(mockRequestInterceptor).addPathPatterns("/**");
}
}

@ -0,0 +1,157 @@
package dsv.su.apimposter.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import dsv.su.apimposter.model.MockResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import dsv.su.apimposter.model.MockEndpoint;
import dsv.su.apimposter.model.MockRequestContext;
import dsv.su.apimposter.service.MockService;
/**
* Intercepts incoming HTTP requests and dynamically serves mock responses
* based on definitions loaded from YAML files.
* This class ensures that dynamic mock endpoints can be served even when
* {@code mock.base-path=/}, without interfering with static resources
* or Swagger UI.
* Requests under the configured {@code mock.base-path} are matched against
* loaded mock definitions.
* All other requests are passed through untouched.
*/
@Component
public class MockRequestInterceptor implements HandlerInterceptor {
private final MockService mockService;
private final AntPathMatcher pathMatcher = new AntPathMatcher();
@Value("${mock.base-path:/mock}")
private String mockBasePath;
@Value("${mock.default-delay-ms:0}")
private long defaultDelay;
/**
* Constructs the interceptor and prepares the path matcher.
*/
public MockRequestInterceptor(MockService mockService) {
this.mockService = mockService;
pathMatcher.setTrimTokens(false);
}
/**
* Handles incoming requests before they reach any controller.
* If the path starts with {@code mock.base-path} and matches a known mock endpoint,
* the interceptor returns the mocked response directly and skips further processing.
* @param request the incoming HTTP request
* @param response the response to write to
* @param handler the matched Spring handler (ignored here)
* @return {@code false} if the request was handled here, {@code true} otherwise
*/
@Override
public boolean preHandle(HttpServletRequest request, @NonNull HttpServletResponse response,
@NonNull Object handler) throws IOException
{
String method = request.getMethod();
String requestUri = normalizePath(request.getRequestURI());
// If the request is outside the mock base path, allow it to continue
String basePath = mockBasePath.equals("/") ? "" : mockBasePath;
if (!requestUri.startsWith(basePath)) return true;
// Extract the mock-relative path (e.g., "/users/1")
String relativePath = requestUri.replaceFirst(basePath, "/");
// Try to find a matching mock endpoint for the given method and path
Optional<MockEndpoint> match = mockService.getMatchedEndpoint(method, relativePath);
if (match.isEmpty()) return true; // No match let the request continue
MockEndpoint endpoint = match.get();
// Extract path variables from the matched URI pattern (e.g. {id} -> 123)
Map<String, String> pathVars = pathMatcher.extractUriTemplateVariables(endpoint.getPath(), relativePath);
// Parse query parameters (?foo=bar) only first value per key is used
Map<String, String> queryParams = request.getParameterMap().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()[0]));
// Extract headers, converting to lowercase for case-insensitive matching
Map<String, String> headers = Collections.list(request.getHeaderNames()).stream()
.collect(Collectors.toMap(
h -> h.toLowerCase(Locale.ROOT),
request::getHeader
));
// If applicable, parse request body (only for POST/PUT with JSON content)
Map<String, String> bodyFields = new HashMap<>();
if (("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method))
&& MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(request.getContentType()))
{
try (BufferedReader reader = request.getReader()) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String requestBody = sb.toString();
ObjectMapper mapper = new ObjectMapper();
Map<?, ?> raw = mapper.readValue(requestBody, Map.class);
raw.forEach((k, v) -> bodyFields.put(String.valueOf(k), String.valueOf(v)));
} catch (Exception e) {
// Ignore fallback will handle it
}
}
// Bundle extracted values into a structured context object
MockRequestContext context = new MockRequestContext(pathVars, queryParams, headers, bodyFields);
// Determine which response (default or conditional) to use
MockResponse selected = mockService.resolveResponse(endpoint, context);
// Apply response delay (configured or per-endpoint)
long delay = (endpoint.getDelay() >= 0) ? endpoint.getDelay() : defaultDelay;
if (delay > 0) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// Replace placeholders in the mock response body with path/global values
Object body = mockService.replacePlaceholders(selected.body(), pathVars);
// Write the mock response: headers, status, and JSON body
selected.headers().forEach(response::setHeader);
response.setStatus(selected.status());
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.getWriter().write(mockService.toJson(body));
return false; // Request has been fully handled
}
/**
* Helper for replacing trailing slashes and collapsing repeated slashes.
* Ensures consistent URI matching.
*/
private String normalizePath(String path) {
path = path.replaceAll("//+", "/");
return (path.endsWith("/") && path.length() > 1)
? path.substring(0, path.length() - 1)
: path;
}
}

@ -0,0 +1,56 @@
package dsv.su.apimposter.controller;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.core.util.Json;
import io.swagger.v3.oas.models.OpenAPI;
import dsv.su.apimposter.service.OpenApiService;
/**
* Controller responsible for serving the generated OpenAPI specification
* and redirecting to the Swagger UI.
* This controller exposes the dynamically built OpenAPI spec (based on mock endpoints)
* at {@code /openapi.json}, and provides a redirect for convenience to the Swagger UI
* hosted under {@code /swagger/index.html}.
*/
@Controller
public class OpenApiController {
private final OpenApiService openApiService;
/**
* Constructs the controller with a reference to the OpenAPI builder component.
* @param openApiService the service responsible for generating the OpenAPI specification
*/
public OpenApiController(OpenApiService openApiService) {
this.openApiService = openApiService;
}
/**
* Serves the generated OpenAPI specification as a JSON document.
* This endpoint is typically used by Swagger UI or other OpenAPI-compatible tools
* to render and document the available mock endpoints.
* @return the {@link OpenAPI} specification in JSON format
*/
@GetMapping(value = "/openapi.json", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public String getOpenApiSpec() throws JsonProcessingException {
ObjectMapper mapper = Json.mapper();
return mapper.writeValueAsString(openApiService.getOpenAPI());
}
/**
* Redirects from {@code /swagger} or {@code /swagger/} to the Swagger UI index page.
* This improves UX by allowing users to navigate to {@code /swagger} without needing
* to specify {@code index.html} explicitly.
* @return a redirect to {@code /swagger/index.html}
*/
@GetMapping({"/swagger", "/swagger/"})
public String redirectToSwaggerUI() {
return "redirect:/swagger/index.html";
}
}

@ -0,0 +1,182 @@
package dsv.su.apimposter.io;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Stream;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;
import dsv.su.apimposter.model.MockEndpoint;
import dsv.su.apimposter.service.OpenApiService;
/**
* Component responsible for loading, parsing, and monitoring changes to mock YAML files.
* Loads global variables and mock endpoint definitions, and triggers OpenAPI spec rebuilds on changes.
*/
@Component
public class MockFileLoader {
private static final Logger LOGGER = LoggerFactory.getLogger(MockFileLoader.class);
private final MockFileParser parser;
private final MockValidator validator;
private final OpenApiService openApiService;
private final Yaml yaml = new Yaml();
private final List<MockEndpoint> endpoints = new CopyOnWriteArrayList<>();
private final Map<String, Object> globals = new HashMap<>();
@Value("${mock.file-path}")
private String mockFilePath;
private Path mockDir;
private volatile int lastHash = 0;
/**
* Constructs the file loader with its required dependencies.
* @param parser the YAML file parser for mock endpoints
* @param validator the validator used to validate parsed data
* @param openApiService the service used to update the OpenAPI spec
*/
public MockFileLoader(MockFileParser parser, MockValidator validator, OpenApiService openApiService) {
this.parser = parser;
this.validator = validator;
this.openApiService = openApiService;
}
/**
* Loads the initial mock data from disk.
* Called once during Spring context initialization.
*/
@PostConstruct
public void init() {
this.mockDir = Paths.get(mockFilePath);
reload();
}
/**
* Periodically checks if any mock YAML files have changed and triggers reload if needed.
* The interval is configured via `mock.reload-interval-ms`.
*/
@Scheduled(fixedDelayString = "${mock.reload-interval-ms}")
public void reloadIfChanged() {
if (hasChanged()) {
LOGGER.info("🔄 Reloading mock files...");
reload();
}
}
/**
* Returns the currently loaded mock endpoints.
* @return list of parsed and validated mock endpoints
*/
public List<MockEndpoint> getEndpoints() {
return endpoints;
}
/**
* Returns the currently loaded global placeholder values.
* @return map of global variables defined in globals.yaml
*/
public Map<String, Object> getGlobals() {
return globals;
}
/**
* Computes a hash based on last-modified times of all YAML files in the mock directory.
* @return true if a file has changed since last check, false otherwise
*/
private boolean hasChanged() {
try (Stream<Path> files = Files.walk(mockDir)) {
int currentHash = Arrays.hashCode(
files.filter(p -> p.toString().endsWith(".yaml"))
.sorted()
.mapToLong(p -> {
try {
FileTime time = Files.getLastModifiedTime(p);
return time.toMillis();
} catch (IOException e) {
return 0L;
}
}).toArray()
);
if (currentHash != lastHash) {
lastHash = currentHash;
return true;
}
} catch (IOException e) {
LOGGER.error("Failed to check mock file changes: {}", e.getMessage());
}
return false;
}
/**
* Reloads all mock data from disk: endpoints, globals, and OpenAPI documentation.
*/
private void reload() {
endpoints.clear();
globals.clear();
try (Stream<Path> files = Files.walk(mockDir)) {
files.filter(p -> p.toString().endsWith(".yaml"))
.forEach(this::processFile);
openApiService.rebuild(endpoints);
} catch (IOException e) {
LOGGER.error("❌ Failed to reload mock files: {}", e.getMessage());
}
}
/**
* Processes a single YAML file by its relative name.
* @param file the YAML file to process
*/
private void processFile(Path file) {
String relativePath = mockDir.relativize(file).toString()
.replace("\\", "/")
.replace(".yaml", "");
if ("globals".equals(relativePath)) {
loadGlobals(file);
} else {
parser.parseFile(file, relativePath, endpoints, validator);
}
}
/**
* Loads global placeholder values from a YAML file named {@code globals.yaml}.
* Expects the structure:
* <pre>
* globals:
* key1: value1
* key2: value2
* </pre>
* @param file the path to {@code globals.yaml}
*/
private void loadGlobals(Path file) {
try (InputStream input = Files.newInputStream(file)) {
Object root = yaml.load(input);
if (root instanceof Map<?, ?> top && top.get("globals") instanceof Map<?, ?> globalMap) {
globalMap.forEach((k, v) -> {
if (k instanceof String key) {
globals.put(key, v);
}
});
}
} catch (Exception e) {
LOGGER.error("❌ Failed to load globals from {}: {}", file, e.getMessage());
}
}
}

@ -0,0 +1,78 @@
package dsv.su.apimposter.io;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import dsv.su.apimposter.model.MockEndpoint;
/**
* Component responsible for parsing individual mock YAML files into {@link MockEndpoint} instances.
* This parser handles reading YAML files, converting their contents to Java objects,
* validating each endpoint, and assembling the full URL path for registration.
*/
@Component
public class MockFileParser {
private static final Logger LOGGER = LoggerFactory.getLogger(MockFileParser.class);
private final ObjectMapper mapper = new ObjectMapper();
// SnakeYAML parser with default loader options
private final Yaml yaml = new Yaml(new LoaderOptions());
/**
* Parses a single YAML file containing mock endpoint definitions.
* Each endpoint is validated and then added to the provided list of endpoints.
* If a path is missing or set to "/", the relative path of the file is used as the endpoint's base path.
* Example file structure:
* <pre>
* - method: "GET"
* path: "/{id}"
* response:
* status: 200
* headers:
* Content-Type: "application/json"
* body:
* id: "{id}"
* </pre>
* @param file the YAML file to parse
* @param relativePath the file path relative to the mock root directory, used to build base paths
* @param endpoints the list where successfully parsed endpoints will be added
* @param validator the component responsible for validating each parsed endpoint
*/
public void parseFile(Path file, String relativePath, List<MockEndpoint> endpoints, MockValidator validator) {
String basePath = "/" + relativePath;
try (InputStream input = Files.newInputStream(file)) {
List<?> rawList = yaml.load(input);
for (Object obj : rawList) {
try {
// Convert raw YAML object to MockEndpoint
MockEndpoint endpoint = mapper.convertValue(obj, MockEndpoint.class);
// Validate the endpoint before registering it
validator.validate(endpoint, file);
// Build full path: base path + endpoint path (if any)
String path = endpoint.getPath();
if (path == null || path.equals("/")) {
endpoint.setPath(basePath);
} else {
endpoint.setPath(basePath + (path.startsWith("/") ? path : "/" + path));
}
endpoints.add(endpoint);
} catch (Exception e) {
LOGGER.error("⚠️ Skipping invalid endpoint in " + file + ": " + e.getMessage());
}
}
} catch (Exception e) {
LOGGER.error("❌ Failed to parse " + file + ": " + e.getMessage());
}
}
}

@ -0,0 +1,79 @@
package dsv.su.apimposter.io;
import java.nio.file.Path;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validator;
import dsv.su.apimposter.model.MockEndpoint;
import dsv.su.apimposter.model.HttpMethod;
/**
* Component responsible for validating individual {@link MockEndpoint} definitions.
* This validator performs two layers of validation:
* 1. Bean validation using annotations (e.g., @NotNull, @Pattern)
* 2. Manual validation for supported HTTP methods and correct path formatting
*/
@Component
public class MockValidator {
/**
* Jakarta Bean Validator (e.g., Hibernate Validator) injected by Spring.
* Used to perform constraint-based validation of fields in {@link MockEndpoint}.
*/
private final Validator validator;
/**
* Spring Boot constructor-based injection.
* Called automatically when this class is used as a component.
*
* @param validator Jakarta Validator injected by Spring
*/
@Autowired
public MockValidator(Validator validator) {
this.validator = validator;
}
/**
* Default constructor for use in tests when Spring context is not available.
* Creates a Jakarta Validator manually.
*/
public MockValidator() {
this.validator = jakarta.validation.Validation.buildDefaultValidatorFactory().getValidator();
}
/**
* Validates a single {@link MockEndpoint} object.
* This method checks:
* <ul>
* <li>Any constraint violations defined by annotations on {@link MockEndpoint}</li>
* <li>That the HTTP method is one of the allowed ones</li>
* <li>That the path, if defined, starts with a forward slash ("/")</li>
* </ul>
* If any of these validations fail, an {@link IllegalArgumentException} is thrown
* with a descriptive message including the originating file name.
* @param endpoint the mock endpoint to validate
* @param file the YAML file from which this endpoint was loaded, used for error context
*/
public void validate(MockEndpoint endpoint, Path file) {
Set<ConstraintViolation<MockEndpoint>> violations = validator.validate(endpoint);
if (!violations.isEmpty()) {
String errors = violations.stream()
.map(v -> v.getPropertyPath() + " " + v.getMessage())
.reduce((a, b) -> a + ", " + b)
.orElse("Unknown error");
throw new IllegalArgumentException("Validation failed in " + file + ": " + errors);
}
HttpMethod method = endpoint.getMethod();
if (method == null) {
throw new IllegalArgumentException("Missing or invalid HTTP method in " + file);
}
String path = endpoint.getPath();
if (path != null && !path.startsWith("/")) {
throw new IllegalArgumentException("Path must start with '/' in " + file + ": " + path);
}
}
}

@ -0,0 +1,13 @@
package dsv.su.apimposter.model;
import java.util.Map;
/**
* Represents a set of matching conditions for a conditional response.
*/
public record Condition(
Map<String, String> query,
Map<String, String> headers,
Map<String, String> body,
Map<String, String> path
) {}

@ -0,0 +1,14 @@
package dsv.su.apimposter.model;
import jakarta.validation.constraints.NotNull;
/**
* Represents a conditionally matched response based on query, header, body, or path conditions.
*/
public record ConditionalResponse(
// Conditions that must be matched for this response to apply
Condition conditions,
// The response to return if the conditions are met
@NotNull MockResponse response
) {}

@ -0,0 +1,25 @@
package dsv.su.apimposter.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* Represents an HTTP method (GET, POST, PUT, DELETE, PATCH).
*/
public enum HttpMethod {
GET, POST, PUT, DELETE, PATCH;
@JsonCreator
public static HttpMethod fromString(String value) {
try {
return HttpMethod.valueOf(value.toUpperCase());
} catch (Exception e) {
throw new IllegalArgumentException("Invalid HTTP method: " + value);
}
}
@JsonValue
public String toValue() {
return this.name();
}
}

@ -0,0 +1,70 @@
package dsv.su.apimposter.model;
import jakarta.validation.constraints.NotNull;
import java.util.List;
/**
* Represents a single mocked API endpoint, including HTTP method, path, conditionals and response details.
*/
public class MockEndpoint {
// The HTTP method for this mock endpoint (e.g., GET, POST)
@NotNull
private HttpMethod method;
// The URL path for the endpoint, potentially including path variables (e.g., /user/{id})
@NotNull
private String path;
// The mock response to return when this endpoint is matched
@NotNull
private MockResponse response;
// Optional delay in milliseconds before returning a response
private long delay = -1;
// Optional list of conditional responses based on request attributes
private List<ConditionalResponse> conditionalResponses;
public MockEndpoint() {}
public HttpMethod getMethod() {
return method;
}
public void setMethod(HttpMethod method) {
this.method = method;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public MockResponse getResponse() {
return response;
}
public void setResponse(MockResponse response) {
this.response = response;
}
public long getDelay() {
return delay;
}
public void setDelay(long delay) {
this.delay = delay;
}
public List<ConditionalResponse> getConditionalResponses() {
return conditionalResponses;
}
public void setConditionalResponses(List<ConditionalResponse> conditionalResponses) {
this.conditionalResponses = conditionalResponses;
}
}

@ -0,0 +1,14 @@
package dsv.su.apimposter.model;
import java.util.Map;
/**
* Represents a structured view of key request data used
* for matching mock conditions: path variables, query parameters,
* headers, and body fields.
*/
public record MockRequestContext(Map<String, String> pathVariables, Map<String, String> queryParameters,
Map<String, String> headers, Map<String, String> bodyFields)
{
}

@ -0,0 +1,18 @@
package dsv.su.apimposter.model;
import jakarta.validation.constraints.NotNull;
import java.util.Map;
/**
* Represents the response returned by a mock endpoint, including status, headers, and body content.
*/
public record MockResponse(
// The HTTP status code to return (e.g., 200, 500)
@NotNull int status,
// HTTP headers to include in the response
@NotNull Map<String, String> headers,
// The body of the response; can be a map, list, string, or other JSON-compatible object
@NotNull Object body
) {}

@ -0,0 +1,155 @@
package dsv.su.apimposter.service;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import dsv.su.apimposter.model.Condition;
import dsv.su.apimposter.model.ConditionalResponse;
import dsv.su.apimposter.model.HttpMethod;
import dsv.su.apimposter.model.MockRequestContext;
import dsv.su.apimposter.model.MockResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import dsv.su.apimposter.io.MockFileLoader;
import dsv.su.apimposter.model.MockEndpoint;
/**
* Service responsible for matching incoming requests to mock endpoints
* and dynamically generating mock responses, including placeholder replacement.
*/
@Service
public class MockService {
private final MockFileLoader loader;
private final AntPathMatcher pathMatcher = new AntPathMatcher();
/**
* Initializes the mock service with a reference to the file loader,
* which holds the live endpoint and global placeholder data.
* @param loader The mock file loader.
*/
public MockService(MockFileLoader loader) {
this.loader = loader;
}
/**
* Attempts to find a mock endpoint matching the given HTTP method and path.
* @param method The HTTP method (e.g., "GET", "POST").
* @param path The normalized request path.
* @return Optional containing the matching MockEndpoint if found.
*/
public Optional<MockEndpoint> getMatchedEndpoint(String method, String path) {
HttpMethod inputMethod;
try {
inputMethod = HttpMethod.valueOf(method.toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
return Optional.empty(); // Unknown method treat as no match
}
return loader.getEndpoints().stream()
.filter(ep -> ep.getMethod() == inputMethod
&& pathMatcher.match(ep.getPath(), path))
.findFirst();
}
/**
* Resolves the appropriate mock response for a request, evaluating conditional
* rules if defined. Falls back to the default response if no conditions match.
* @param endpoint The matched mock endpoint.
* @param ctx The full request context (headers, path vars, body, query).
* @return The selected mock response.
*/
public MockResponse resolveResponse(MockEndpoint endpoint, MockRequestContext ctx) {
if (endpoint.getConditionalResponses() != null) {
for (ConditionalResponse cr : endpoint.getConditionalResponses()) {
if (cr.conditions() == null) continue;
Condition cond = cr.conditions();
if (!matches(cond.query(), ctx.queryParameters())) continue;
if (!matches(cond.headers(), ctx.headers())) continue;
if (!matches(cond.body(), ctx.bodyFields())) continue;
if (!matches(cond.path(), ctx.pathVariables())) continue;
return cr.response(); // First matching conditional wins
}
}
return endpoint.getResponse(); // No match use fallback
}
/**
* Performs a simple key-value match between expected and actual values.
* Keys are compared in a case-insensitive manner. All expected entries must match.
* @param expected Key-value map of required conditions.
* @param actual Actual data from the request.
* @return True if all expected entries match the actual data.
*/
private boolean matches(Map<String, String> expected, Map<String, String> actual) {
if (expected == null) return true; // No condition defined pass
if (actual == null) return false;
for (Map.Entry<String, String> entry : expected.entrySet()) {
String key = entry.getKey().toLowerCase(Locale.ROOT);
String value = entry.getValue();
if (!value.equals(actual.get(key))) return false;
}
return true;
}
/**
* Recursively replaces placeholders in the mock response body with actual values
* from path variables and global placeholders.
* @param body The response body template.
* @param pathVariables Extracted values from the request URL path.
* @return Response body with all placeholders replaced.
*/
public Object replacePlaceholders(Object body, Map<String, String> pathVariables) {
Map<String, Object> globals = loader.getGlobals();
if (body instanceof Map<?, ?>) {
Map<String, Object> map = new LinkedHashMap<>();
((Map<?, ?>) body).forEach((key, value) ->
map.put(key.toString(), replacePlaceholders(value, pathVariables))
);
return map;
} else if (body instanceof List<?>) {
return ((List<?>) body).stream()
.map(item -> replacePlaceholders(item, pathVariables))
.toList();
} else if (body instanceof String str) {
for (var entry : pathVariables.entrySet()) {
str = str.replace("{" + entry.getKey() + "}", entry.getValue());
}
for (var entry : globals.entrySet()) {
str = str.replace("{globals." + entry.getKey() + "}", entry.getValue().toString());
}
return str;
}
return body;
}
/**
* Serializes a Java object into a JSON string.
* If serialization fails, returns an error wrapper instead.
* @param obj The object to serialize.
* @return JSON string or fallback error JSON.
*/
public String toJson(Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (JsonProcessingException e) {
return "{\"error\":\"Failed to serialize response\"}";
}
}
}

@ -0,0 +1,157 @@
package dsv.su.apimposter.service;
import java.util.ArrayList;
import java.util.List;
import dsv.su.apimposter.model.MockResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.Paths;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.responses.ApiResponses;
import io.swagger.v3.oas.models.Operation;
import dsv.su.apimposter.model.MockEndpoint;
import dsv.su.apimposter.controller.OpenApiController;
import dsv.su.apimposter.model.HttpMethod;
/**
* Service responsible for dynamically generating an OpenAPI specification
* based on the currently loaded mock endpoints.
* This class builds a complete {@link OpenAPI} model that is exposed via
* {@link OpenApiController} as a JSON response.
*/
@Service
public class OpenApiService {
// The latest generated OpenAPI spec, thread-safe via volatile
private volatile OpenAPI openAPI = new OpenAPI();
@Value("${mock.base-path:/mocks}")
private String mockBasePath;
/**
* Rebuilds the internal OpenAPI model based on the given mock endpoints and global data.
* This method is called whenever the mock files are initially loaded or reloaded.
* It constructs all paths, operations, tags, and response examples.
* @param endpoints the list of current mock endpoints
*/
public void rebuild(List<MockEndpoint> endpoints) {
OpenAPI api = new OpenAPI()
.info(new Info().title("APImposter").version("1.0"))
.paths(new Paths());
for (MockEndpoint endpoint : endpoints) {
String path = formatPath(mockBasePath + endpoint.getPath());
Operation operation = new Operation()
.summary(endpoint.getMethod() + " " + path)
.responses(response(endpoint.getResponse()))
.tags(List.of(extractTag(path)))
.parameters(pathParams(path));
PathItem item = getPathItem(endpoint, operation);
api.getPaths().addPathItem(path, item);
}
this.openAPI = api;
}
/**
* Builds an OpenAPI {@link PathItem} object for a given mock endpoint and operation.
* @param endpoint the mock endpoint to describe
* @param operation the operation to associate with the endpoint
* @return the generated {@link PathItem}
*/
private static PathItem getPathItem(MockEndpoint endpoint, Operation operation) {
HttpMethod method = endpoint.getMethod();
return switch (method) {
case GET -> new PathItem().get(operation);
case POST -> new PathItem().post(operation);
case PUT -> new PathItem().put(operation);
case DELETE -> new PathItem().delete(operation);
case PATCH -> new PathItem().patch(operation);
};
}
/**
* Returns the most recently built OpenAPI specification.
* @return the current {@link OpenAPI} object
*/
public OpenAPI getOpenAPI() {
return openAPI;
}
/**
* Builds the OpenAPI {@link ApiResponses} object for a given mock response.
* Includes status code, content type, and example response body.
* @param response the mock response to describe
* @return the generated {@link ApiResponses}
*/
private ApiResponses response(MockResponse response) {
ApiResponse apiResponse = new ApiResponse()
.description("Mock response")
.content(new Content().addMediaType("application/json",
new MediaType().example(response.body())));
ApiResponses responses = new ApiResponses();
responses.addApiResponse(String.valueOf(response.status()), apiResponse);
return responses;
}
/**
* Extracts path parameters from a URL path and returns them as OpenAPI {@link Parameter} objects.
* For example, given "/foo/{id}", it extracts "id".
* @param path the path string potentially containing parameters
* @return a list of path parameters
*/
private List<Parameter> pathParams(String path) {
List<Parameter> params = new ArrayList<>();
int i = 0;
while ((i = path.indexOf('{', i)) != -1) {
int end = path.indexOf('}', i);
if (end == -1) break;
String name = path.substring(i + 1, end);
params.add(new Parameter().in("path").name(name).required(true).schema(new StringSchema()));
i = end + 1;
}
return params;
}
/**
* Derives a tag from the first part of the path (after the base path), used to group endpoints.
* For example, "/mocks/daisy/user" "daisy".
* @param fullPath the full API path
* @return the derived tag name
*/
private String extractTag(String fullPath) {
String normalizedPath = formatPath(fullPath); // collapse slashes and trim trailing slash
String effectivePath = normalizedPath;
// Strip mockBasePath only if it's not "/"
if (!mockBasePath.equals("/") && normalizedPath.startsWith(mockBasePath)) {
effectivePath = normalizedPath.substring(mockBasePath.length());
}
// Ensure it starts clean
if (!effectivePath.startsWith("/")) {
effectivePath = "/" + effectivePath;
}
String[] segments = effectivePath.split("/");
for (String segment : segments) {
if (!segment.isBlank()) {
return segment;
}
}
return "default"; // fallback if empty or just slashes
}
/**
* Formats a path by collapsing duplicate slashes and removing trailing slashes.
* @param path the raw path
* @return the cleaned path
*/
private String formatPath(String path) {
return path.replaceAll("//+", "/").replaceAll("/$", "");
}
}

@ -0,0 +1,9 @@
spring.application.name=apimposter
spring.profiles.active=mock
mock.file-path=/Users/admin/Code/dsv/apimposter/mocks
mock.reload-interval-ms=3000
mock.base-path=/
mock.default-delay-ms=200
logging.level.root=INFO
logging.level.dsv.su.apimposter=DEBUG
logging.level.org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver=ERROR

Binary file not shown.

After

(image error) Size: 665 B

Binary file not shown.

After

(image error) Size: 628 B

@ -0,0 +1,16 @@
html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 0;
background: #fafafa;
}

@ -0,0 +1,19 @@
<!-- HTML for static distribution bundle build -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Swagger UI</title>
<link rel="stylesheet" type="text/css" href="./swagger-ui.css" />
<link rel="stylesheet" type="text/css" href="index.css" />
<link rel="icon" type="image/png" href="./favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="./favicon-16x16.png" sizes="16x16" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="./swagger-ui-bundle.js" charset="UTF-8"> </script>
<script src="./swagger-ui-standalone-preset.js" charset="UTF-8"> </script>
<script src="./swagger-initializer.js" charset="UTF-8"> </script>
</body>
</html>

@ -0,0 +1,79 @@
<!doctype html>
<html lang="en-US">
<head>
<title>Swagger UI: OAuth2 Redirect</title>
</head>
<body>
<script>
'use strict';
function run () {
var oauth2 = window.opener.swaggerUIRedirectOauth2;
var sentState = oauth2.state;
var redirectUrl = oauth2.redirectUrl;
var isValid, qp, arr;
if (/code|token|error/.test(window.location.hash)) {
qp = window.location.hash.substring(1).replace('?', '&');
} else {
qp = location.search.substring(1);
}
arr = qp.split("&");
arr.forEach(function (v,i,_arr) { _arr[i] = '"' + v.replace('=', '":"') + '"';});
qp = qp ? JSON.parse('{' + arr.join() + '}',
function (key, value) {
return key === "" ? value : decodeURIComponent(value);
}
) : {};
isValid = qp.state === sentState;
if ((
oauth2.auth.schema.get("flow") === "accessCode" ||
oauth2.auth.schema.get("flow") === "authorizationCode" ||
oauth2.auth.schema.get("flow") === "authorization_code"
) && !oauth2.auth.code) {
if (!isValid) {
oauth2.errCb({
authId: oauth2.auth.name,
source: "auth",
level: "warning",
message: "Authorization may be unsafe, passed state was changed in server. The passed state wasn't returned from auth server."
});
}
if (qp.code) {
delete oauth2.state;
oauth2.auth.code = qp.code;
oauth2.callback({auth: oauth2.auth, redirectUrl: redirectUrl});
} else {
let oauthErrorMsg;
if (qp.error) {
oauthErrorMsg = "["+qp.error+"]: " +
(qp.error_description ? qp.error_description+ ". " : "no accessCode received from the server. ") +
(qp.error_uri ? "More info: "+qp.error_uri : "");
}
oauth2.errCb({
authId: oauth2.auth.name,
source: "auth",
level: "error",
message: oauthErrorMsg || "[Authorization failed]: no accessCode received from the server."
});
}
} else {
oauth2.callback({auth: oauth2.auth, token: qp, isValid: isValid, redirectUrl: redirectUrl});
}
window.close();
}
if (document.readyState !== 'loading') {
run();
} else {
document.addEventListener('DOMContentLoaded', function () {
run();
});
}
</script>
</body>
</html>

@ -0,0 +1,20 @@
window.onload = function() {
//<editor-fold desc="Changeable Configuration Block">
// the following lines will be replaced by docker/configurator, when it runs in a docker-container
window.ui = SwaggerUIBundle({
url: "/openapi.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});
//</editor-fold>
};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -0,0 +1,13 @@
package dsv.su.apimposter;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ApImposterApplicationTests {
@Test
void contextLoads() {
}
}

@ -0,0 +1,89 @@
package dsv.su.apimposter;
import dsv.su.apimposter.io.MockFileParser;
import dsv.su.apimposter.io.MockValidator;
import dsv.su.apimposter.model.MockEndpoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.yaml.snakeyaml.Yaml;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static dsv.su.apimposter.model.HttpMethod.GET;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Integration tests for {@link MockFileParser} and {@link MockValidator}.
* Validates parsing and validation of test YAML files.
*/
class MockFileParserTest {
private MockFileParser parser;
private MockValidator validator;
private List<MockEndpoint> endpoints;
@BeforeEach
void setUp() {
parser = new MockFileParser();
validator = new MockValidator();
endpoints = new ArrayList<>();
}
@Test
void shouldParseValidMockFile() {
Path file = Path.of("src/test/resources/test-mocks/test.yaml");
assertDoesNotThrow(() -> {
parser.parseFile(file, "test-mocks/test", endpoints, validator);
});
assertEquals(1, endpoints.size());
assertEquals("/test-mocks/test/hello", endpoints.getFirst().getPath());
assertEquals(GET, endpoints.getFirst().getMethod());
}
@Test
void shouldFailOnInvalidMockFile() {
Path file = Path.of("src/test/resources/test-mocks-invalid/invalid.yaml");
assertDoesNotThrow(() -> {
parser.parseFile(file, "test-mocks-invalid/invalid", endpoints, validator);
});
assertTrue(endpoints.isEmpty(), "Invalid endpoint should be skipped due to missing method");
}
@Test
void shouldLoadGlobalsYaml() {
Path file = Path.of("src/test/resources/test-globals/globals.yaml");
Map<String, Object> globals = new HashMap<>();
try (var input = Files.newInputStream(file)) {
Object raw = new Yaml().load(input);
if (raw instanceof Map<?, ?> topLevel) {
Object section = topLevel.get("globals");
if (section instanceof Map<?, ?> globalsMap) {
for (Map.Entry<?, ?> entry : globalsMap.entrySet()) {
if (entry.getKey() instanceof String key) {
globals.put(key, entry.getValue());
}
}
}
}
} catch (Exception e) {
fail("Failed to load globals.yaml: " + e.getMessage());
}
assertEquals("test", globals.get("env"));
assertEquals("1.0", globals.get("version"));
}
}

@ -0,0 +1,86 @@
package dsv.su.apimposter;
import dsv.su.apimposter.io.MockFileLoader;
import dsv.su.apimposter.service.MockService;
import dsv.su.apimposter.model.MockEndpoint;
import dsv.su.apimposter.model.MockResponse;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static dsv.su.apimposter.model.HttpMethod.GET;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit tests for {@link MockService} to verify matching and placeholder replacement.
*/
class MockServiceTest {
private MockService mockService;
@BeforeEach
void setup() {
List<MockEndpoint> endpoints = new ArrayList<>();
MockEndpoint mock = new MockEndpoint();
mock.setMethod(GET);
mock.setPath("/greet/{name}");
MockResponse response = new MockResponse(
200,
Map.of("Content-Type", "application/json"),
Map.of("message", "Hi {name}, env={globals.env}")
);
mock.setResponse(response);
endpoints.add(mock);
Map<String, Object> globals = Map.of("env", "test");
// Create an inline mock of MockFileLoader
MockFileLoader fakeLoader = new MockFileLoader(null, null, null) {
@Override
public List<MockEndpoint> getEndpoints() {
return endpoints;
}
@Override
public Map<String, Object> getGlobals() {
return globals;
}
};
mockService = new MockService(fakeLoader);
}
@Test
void shouldMatchEndpoint() {
Optional<MockEndpoint> result = mockService.getMatchedEndpoint("GET", "/greet/Alice");
assertTrue(result.isPresent());
assertEquals("/greet/{name}", result.get().getPath());
}
@Test
void shouldReplacePlaceholdersCorrectly() {
MockEndpoint matched = mockService.getMatchedEndpoint("GET", "/greet/Alice").orElseThrow();
Map<String, String> pathVars = Map.of("name", "Alice");
Object result = mockService.replacePlaceholders(matched.getResponse().body(), pathVars);
assertInstanceOf(Map.class, result);
Map<?, ?> body = (Map<?, ?>) result;
assertEquals("Hi Alice, env=test", body.get("message"));
}
@Test
void shouldReturnEmptyIfNoMatch() {
Optional<MockEndpoint> result = mockService.getMatchedEndpoint("POST", "/greet/Alice");
assertTrue(result.isEmpty());
}
}

@ -0,0 +1,3 @@
globals:
env: test
version: "1.0"

@ -0,0 +1,5 @@
- path: /bad
response:
status: 200
body:
ok: false

@ -0,0 +1,8 @@
- method: GET
path: /hello
response:
status: 200
headers:
Content-Type: application/json
body:
message: "Hello world"