diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 3b41682..0000000 --- a/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -/mvnw text eol=lf -*.cmd text eol=crlf diff --git a/.gitignore b/.gitignore index 667aaef..1b8974b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,33 +1,19 @@ -HELP.md +# Build output target/ -.mvn/wrapper/maven-wrapper.jar -!**/src/main/**/target/ -!**/src/test/**/target/ -### STS ### -.apt_generated -.classpath -.factorypath -.project -.settings -.springBeans -.sts4-cache +# Logs +logs/ +*.log +*.log.gz -### IntelliJ IDEA ### -.idea -*.iws +# IDE +.idea/ +.vscode/ *.iml -*.ipr - -### NetBeans ### -/nbproject/private/ -/nbbuild/ -/dist/ -/nbdist/ -/.nb-gradle/ -build/ -!**/src/main/**/build/ -!**/src/test/**/build/ +.classpath +.project +.settings/ -### VS Code ### -.vscode/ +# OS +Thumbs.db +.DS_Store diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index 5291372..0000000 --- a/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,3 +0,0 @@ -wrapperVersion=3.3.4 -distributionType=only-script -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.15/apache-maven-3.9.15-bin.zip diff --git a/LINUX_DEPLOY.md b/LINUX_DEPLOY.md new file mode 100644 index 0000000..9ff39c3 --- /dev/null +++ b/LINUX_DEPLOY.md @@ -0,0 +1,183 @@ +# Oracle Linux deployment guide + +This is the complete procedure that satisfies the "deployable on Oracle Linux" +requirement of the evaluation document. + +--- + +## 0. Prerequisites on the Linux box + +- Oracle Linux 8 or 9 (or any RHEL-family distribution). +- Network access to the public yum repos (for installing Java and Maven). +- Oracle XE 21c already installed, with: + - the listener up on port `1521` + - the pluggable database `XEPDB1` reachable + - the `SYS` password set to `1234` (so it matches `application.properties`) +- An OS user with `sudo` rights for the install step. + +Confirm Oracle is up before doing anything else: + +```bash +lsnrctl status +sqlplus sys/1234@//localhost:1521/XEPDB1 as sysdba <<< "select 1 from dual;" +``` + +If both succeed you are ready. + +--- + +## 1. Transfer the project zip from Windows + +On Windows (only the first time): + +```cmd +cd "C:\Users\walaa\JSON API\maryam-measurement-api" +make-zip.bat +``` + +`maryam-measurement-api.zip` is produced one folder up (`C:\Users\walaa\JSON API\maryam-measurement-api.zip`). + +Copy it to the Linux box: + +```cmd +scp "..\maryam-measurement-api.zip" maryam@:/tmp/ +``` + +--- + +## 2. Unpack and run the installer on Linux + +```bash +ssh maryam@ +cd /tmp +unzip maryam-measurement-api.zip -d maryam-measurement-api +cd maryam-measurement-api +chmod +x deployment/linux-install.sh +./deployment/linux-install.sh +``` + +That single script performs every step: + +1. Installs OpenJDK 17 and Maven via `dnf` (idempotent). +2. Creates the `maryam` OS user, `/opt/maryam-measurement-api`, + `/var/log/maryam-measurement-api`. +3. Builds the jar with `mvn clean package`. +4. Creates the `MARYAM_APP` database user and schema by running + `deployment/oracle_xe_setup.sql` against `XEPDB1`. +5. Installs `/etc/systemd/system/maryam-measurement-api.service`, then + `systemctl daemon-reload && enable && restart`. +6. Runs the eight PDF smoke tests and prints `OK`/`FAIL` per case. + +When it finishes you should see eight `OK` lines. + +--- + +## 3. Switch the app to the dedicated user + +The installer created `MARYAM_APP`. Edit +`/opt/maryam-measurement-api/application.properties`: + +```properties +spring.datasource.username=MARYAM_APP +spring.datasource.password=1234 +``` + +Restart: + +```bash +sudo systemctl restart maryam-measurement-api +sudo systemctl status maryam-measurement-api +``` + +--- + +## 4. Verify the service + +```bash +# health +curl http://localhost:8080/maryam/actuator/health +# version info +cat /opt/maryam-measurement-api/version.txt # bundled inside the jar; see /v3/api-docs for the live value +# logs +sudo journalctl -u maryam-measurement-api -n 50 --no-pager +ls -lh /var/log/maryam-measurement-api/ +``` + +--- + +## 5. The full PDF acceptance test + +These are the exact requests the evaluator runs against the deployed service. +Run them on the Linux box (or from your laptop against `http://:8080/maryam`): + +```bash +H=http://localhost:8080/maryam + +# Conversion - eight PDF examples +curl "$H/convert-measurements?input=aa" # [1] +curl "$H/convert-measurements?input=abbcc" # [2,6] +curl "$H/convert-measurements?input=dz_a_aazzaaa" # [28,53,1] +curl "$H/convert-measurements?input=a_" # [0] +curl "$H/convert-measurements?input=abcdabcdab" # [2,7,7] +curl "$H/convert-measurements?input=abcdabcdab_" # [2,7,7,0] +curl "$H/convert-measurements?input=zdaaaaaaaabaaaaaaaabaaaaaaaabbaa" # [34] +curl "$H/convert-measurements?input=za_a_a_a_a_a_a_a_a_a_a_a_a_azaaa" # [40,1] + +# History - CRUD +curl "$H/history" # list +curl "$H/history/1" # one +curl -X PUT "$H/history/1" \ + -H "Content-Type: application/json" \ + -d '{"input":"aa","output":"[1]"}' # replace +curl -X PATCH "$H/history/1" \ + -H "Content-Type: application/json" \ + -d '{"output":"[1]"}' # partial +curl -X DELETE "$H/history/2" # one +curl -X DELETE "$H/history" # all + +# Swagger UI +xdg-open http://localhost:8080/maryam/swagger-ui/index.html || \ + echo "Open http://:8080/maryam/swagger-ui/index.html in a browser" +``` + +--- + +## 6. Verifying the database side + +```bash +sqlplus maryam_app/1234@//localhost:1521/XEPDB1 +``` + +```sql +SQL> SELECT id, request_ts, source_ip, SUBSTR(input_value,1,40) AS input, + SUBSTR(output_value,1,40) AS output + FROM maryam_conversion_history + ORDER BY id; +``` + +This proves the data really lives in Oracle XE - one of the explicit evaluation +points. + +--- + +## 7. Troubleshooting + +| Symptom | Likely cause | Fix | +|------------------------------------------------------------|-------------------------------------------|-------------------------------------------------------------------------------------------| +| `ORA-12541: no listener` | Listener not running | `sudo systemctl restart oracle-xe-21c` (or whichever unit Oracle XE installed) | +| `ORA-01017: invalid username/password` | Password mismatch | Edit `/opt/maryam-measurement-api/application.properties` to the correct password | +| Port 8080 already in use | Another process bound | Change `server.port` in `application.properties`, then `systemctl restart` | +| `Failed to start maryam-measurement-api.service` | Java path wrong in the unit | Edit `/etc/systemd/system/maryam-measurement-api.service`, fix `JAVA_HOME` and `ExecStart` | +| `curl: (7) Failed to connect` | Firewall | `sudo firewall-cmd --add-port=8080/tcp --permanent && sudo firewall-cmd --reload` | + +--- + +## 8. Uninstall + +```bash +sudo systemctl stop maryam-measurement-api +sudo systemctl disable maryam-measurement-api +sudo rm /etc/systemd/system/maryam-measurement-api.service +sudo rm -rf /opt/maryam-measurement-api /var/log/maryam-measurement-api +sudo userdel -r maryam +``` diff --git a/README.md b/README.md index b1cccfd..df1e999 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,153 @@ -## Submission Instructions - -To submit your Oracle JAVA Spring Boot Maven project as a solution, please follow these steps: - -### Step 1: Install git on your PC -- Install "git" as shown in this tutorial: [How to install git](https://youtu.be/iYkLrXobBbA?si=_l0haibv_X9NpIjJ) -- Open command prompt and run - ```bash - git version - ``` -- If you see the version, then git is successfully installed. - -### Step 2: Fork the Repository -- Navigate to [this repository](https://github.com/CodelineAtyab/oraclequantapi) provided by Codeline. -- Click on the "Fork" button at the top-right corner of the page to create a copy of the repository under your own GitHub account. - -### Step 3: Clone the Forked Repository -- Open your terminal or command prompt. -- Clone the forked repository to your local machine using the following command: - ```bash - git clone https://github.com/your-username/repo-name.git - ``` - -### Step 4: Create a new branch -- Navigate to the cloned repository directory - ```bash - cd repo-name - ``` -- Create a new branch for your code submissions (Replace your-name with your name in your-name-submission-branch): - ```bash - git checkout -b your-name-submission-branch - ``` - - -### Step 5: Add Your Code -- Implement the API - -### Step 6: Commit your changes -- Run the following commands in order to commit your changes: - ```bash - git add * - git commit -m "Meaningful commit message here" - ``` - -### Step 7: Push Your Branch to GitHub -- Run the following commands to upload the changes to the forked github repository (Replace your-name with your name in your-name-submission-branch): - ```bash - git push origin your-name-submission-branch - ``` - -### Step 8: Create a Pull Request -- Go to your forked repository on GitHub. -- You should see a prompt to create a pull request. Click on "Compare & pull request". -- Provide a title and description for your pull request, then click "Create pull request". - -### Step 9: Notify Codeline -- Notify on slack that you have created a PR for your solution. - -## Note: If you face any issues in the process above, Please do the following: -- Watch [this youtube tutorial](https://www.youtube.com/watch?v=a_FLqX3vGR4) -- Contact Ikhlas or Atyab. +# MARYAM Measurement Conversion API + +A Spring Boot REST service that decodes encoded measurement strings into +numeric package totals and persists every request in Oracle XE. + +--- + +## What it does + +Send an encoded string to `/convert-measurements`. The API decodes it into +a list of package totals and returns them as JSON. Every request is also +written to an audit table in Oracle XE. + +Example: + +``` +GET /convert-measurements?input=abcdabcdab -> [2, 7, 7] +GET /convert-measurements?input=dz_a_aazzaaa -> [28, 53, 1] +``` + +### Endpoints + +| Method | Path | Purpose | +|----------|---------------------------------------|----------------------------------------| +| GET | `/convert-measurements?input=...` | Decode + persist | +| GET | `/history` | List all history records | +| GET | `/history/{id}` | One history record | +| PUT | `/history/{id}` | Replace a history record | +| PATCH | `/history/{id}` | Partial update | +| DELETE | `/history/{id}` | Delete one history record | +| DELETE | `/history` | Clear the entire history table | +| GET | `/swagger-ui/index.html` | Interactive API docs | +| GET | `/actuator/health` | Liveness probe | + +Base URL when running locally: `http://localhost:8080/maryam` + +--- + +## Tech stack + +Java 17 · Spring Boot 3.2 · Spring Data JPA · Oracle XE 21c · +SpringDoc OpenAPI · Logback · Maven. + +--- + +## How to set it up + +### 1. Prerequisites + +- Oracle OpenJDK 17 +- Maven 3.9+ +- Oracle XE 21c reachable at `localhost:1521/XEPDB1` +- SYS/SYSTEM password set to `1234` (matches `application.properties`) + +### 2. Build + +```bash +mvn clean package +``` + +Produces `target/maryam-measurement-api.jar`. + +### 3. Run + +```bash +java -jar target/maryam-measurement-api.jar +``` + +Service starts on `http://localhost:8080/maryam`. + +### 4. Try it + +```bash +curl "http://localhost:8080/maryam/convert-measurements?input=aa" # [1] +curl http://localhost:8080/maryam/history +``` + +Open Swagger: `http://localhost:8080/maryam/swagger-ui/index.html` + +--- + +## Deploying on Oracle Linux + +See `LINUX_DEPLOY.md` for the full step-by-step. Short version: + +```bash +# on the Oracle Linux box +sudo dnf install -y java-17-openjdk maven +unzip maryam-measurement-api.zip && cd maryam-measurement-api +mvn clean package -DskipTests +sudo cp target/maryam-measurement-api.jar /opt/maryam-measurement-api/ +sudo cp src/main/resources/application.properties /opt/maryam-measurement-api/ +sudo cp deployment/maryam-measurement-api.service /etc/systemd/system/ +sudo systemctl daemon-reload +sudo systemctl enable --now maryam-measurement-api +``` + +The PDF requires the jar to be running as a managed service on Oracle Linux +reachable over SSH - the unit file above does exactly that. + +--- + +## Configuration + +`src/main/resources/application.properties`: + +| Property | Default | +|-----------------------------------|------------------------------------------------------| +| `server.port` | 8080 | +| `server.servlet.context-path` | `/maryam` | +| `spring.datasource.url` | `jdbc:oracle:thin:@//localhost:1521/XEPDB1` | +| `spring.datasource.username` | `SYSTEM` | +| `spring.datasource.password` | `1234` | +| `spring.jpa.hibernate.ddl-auto` | `update` (auto-creates the history table) | +| Log file | `logs/maryam-measurement-api.log` (rolling, 30 days) | + +For a quick demo without Oracle, run with the H2 profile: + +```bash +java -jar target/maryam-measurement-api.jar --spring.profiles.active=dev +``` + +--- + +## Project layout + +``` +src/main/java/om/maryam/measurement/ +├── MaryamMeasurementApplication.java +├── algorithm/ decoder (pure, unit-tested) +├── controller/ REST endpoints +├── service/ business contracts + impl +├── repository/ Spring Data JPA +├── entity/ JPA entity +├── dto/ request/response DTOs +├── exception/ domain exceptions + global handler +├── config/ OpenAPI metadata +└── util/ client-IP resolver +``` + +Architecture is layered (controller -> service -> repository -> Oracle), +each layer depends only on the one beneath it through interfaces. + +--- + +## Running tests + +```bash +mvn test +``` + +`MeasurementDecoderTest` runs all eight examples from the evaluation document +and blocks the build if any of them regress. diff --git a/README2.md b/README2.md new file mode 100644 index 0000000..7168410 --- /dev/null +++ b/README2.md @@ -0,0 +1,32 @@ +Edge Cases & Unexpected Behavior + + +Case 1: cba → [3] +c = 3 → header: expects 3 items +b = 2 → item 1 +a = 1 → item 2 +input exhausted before item 3 — decoder sums what it has +packet total = 2+1 = 3 +Note: Header promised 3 items but only 2 were available. Decoder is lenient — no exception thrown. + + +Case 2: az → [26] +a = 1 → header: expects 1 item +z = 26 → continuation flag, but input ends here +decoder treats z as a complete value of 26 +packet total = 26 +Note: z normally requires a following character to terminate. When input ends after z, decoder accepts 26 as-is. + + +Case 3: _a → [0, 0] +_ = 0 → header: expects 0 items +packet 1 total = 0 + +a = 1 → header: expects 1 item +input exhausted — no items available +packet 2 total = 0 +Note: Header with no items following it produces 0. + + +Summary +The decoder never throws an exception on malformed input. It gracefully handles truncated streams, dangling z continuations, and unfulfilled item counts by summing whatever is available. \ No newline at end of file diff --git a/deployment/linux-install.sh b/deployment/linux-install.sh new file mode 100644 index 0000000..4922d13 --- /dev/null +++ b/deployment/linux-install.sh @@ -0,0 +1,86 @@ +#!/usr/bin/env bash +# =================================================================== +# One-shot installer for the MARYAM Measurement Conversion API on +# Oracle Linux 8 / 9 (or RHEL). +# +# Prerequisites on the target box: +# - Oracle XE 21c already installed and listening on 1521 +# - SYS password = 1234 (matches application.properties) +# - You unzipped the project somewhere and are running this script +# from inside the project root. +# +# What it does: +# 1. Installs OpenJDK 17 and Maven if missing. +# 2. Creates the maryam OS user, /opt and /var/log layout. +# 3. Builds the jar with `mvn clean package`. +# 4. Creates the MARYAM_APP database user and schema. +# 5. Installs and starts the systemd service. +# 6. Runs the eight PDF smoke tests. +# =================================================================== +set -euo pipefail + +APP_USER=maryam +APP_DIR=/opt/maryam-measurement-api +LOG_DIR=/var/log/maryam-measurement-api +SERVICE=maryam-measurement-api +PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +echo ">> 1/6 Installing OpenJDK 17 and Maven" +sudo dnf install -y java-17-openjdk java-17-openjdk-devel maven >/dev/null + +echo ">> 2/6 Creating OS user and filesystem layout" +id "$APP_USER" >/dev/null 2>&1 || sudo useradd -m -s /bin/bash "$APP_USER" +sudo mkdir -p "$APP_DIR" "$LOG_DIR" +sudo chown -R "$APP_USER":"$APP_USER" "$APP_DIR" "$LOG_DIR" + +echo ">> 3/6 Building the jar" +cd "$PROJECT_ROOT" +mvn -q clean package -DskipTests + +echo ">> 4/6 Provisioning the database (MARYAM_APP user)" +if command -v sqlplus >/dev/null 2>&1; then + sqlplus -L sys/1234@//localhost:1521/XEPDB1 as sysdba \ + @deployment/oracle_xe_setup.sql || \ + echo " (setup script reported an issue, continuing - check manually)" +else + echo " sqlplus not on PATH; skipping schema provisioning." + echo " Run it manually: sqlplus sys/1234@//localhost:1521/XEPDB1 as sysdba @deployment/oracle_xe_setup.sql" +fi + +echo ">> 5/6 Installing the systemd unit" +sudo cp target/maryam-measurement-api.jar "$APP_DIR/" +sudo cp src/main/resources/application.properties "$APP_DIR/" +sudo cp deployment/maryam-measurement-api.service "/etc/systemd/system/" +sudo chown -R "$APP_USER":"$APP_USER" "$APP_DIR" + +sudo systemctl daemon-reload +sudo systemctl enable "$SERVICE" >/dev/null +sudo systemctl restart "$SERVICE" +sleep 5 +sudo systemctl --no-pager status "$SERVICE" | head -n 10 + +echo "" +echo ">> 6/6 Smoke testing the eight PDF examples" +for pair in \ + "aa|[1]" \ + "abbcc|[2,6]" \ + "dz_a_aazzaaa|[28,53,1]" \ + "a_|[0]" \ + "abcdabcdab|[2,7,7]" \ + "abcdabcdab_|[2,7,7,0]" \ + "zdaaaaaaaabaaaaaaaabaaaaaaaabbaa|[34]" \ + "za_a_a_a_a_a_a_a_a_a_a_a_a_azaaa|[40,1]" +do + IN="${pair%%|*}" + EXP="${pair##*|}" + GOT=$(curl -s "http://localhost:8080/maryam/convert-measurements?input=$IN") + if [ "$GOT" = "$EXP" ]; then + echo " OK $IN -> $GOT" + else + echo " FAIL $IN expected $EXP got $GOT" + fi +done + +echo "" +echo "Install complete. Try: curl http://localhost:8080/maryam/history" +echo "Service logs: sudo journalctl -u $SERVICE -f" diff --git a/deployment/maryam-measurement-api.service b/deployment/maryam-measurement-api.service new file mode 100644 index 0000000..2c5b9b8 --- /dev/null +++ b/deployment/maryam-measurement-api.service @@ -0,0 +1,24 @@ +[Unit] +Description=MARYAM Measurement Conversion API +After=network.target oracle-xe.service +Requires=network.target + +[Service] +Type=simple +User=maryam +Group=maryam +WorkingDirectory=/opt/maryam-measurement-api +Environment="JAVA_HOME=/usr/lib/jvm/jdk-17" +Environment="LOG_DIR=/var/log/maryam-measurement-api" +Environment="SPRING_PROFILES_ACTIVE=prod" +ExecStart=/usr/lib/jvm/jdk-17/bin/java \ + -Xms256m -Xmx768m \ + -Dfile.encoding=UTF-8 \ + -jar /opt/maryam-measurement-api/maryam-measurement-api.jar +SuccessExitStatus=143 +Restart=on-failure +RestartSec=10 +LimitNOFILE=65536 + +[Install] +WantedBy=multi-user.target diff --git a/deployment/oracle_xe_setup.sql b/deployment/oracle_xe_setup.sql new file mode 100644 index 0000000..13d23eb --- /dev/null +++ b/deployment/oracle_xe_setup.sql @@ -0,0 +1,43 @@ +-- =================================================================== +-- MARYAM Measurement API - Oracle XE bootstrap (OPTIONAL) +-- +-- The application can run directly against SYSTEM/1234 on XEPDB1; this +-- script is only required if you want a dedicated low-privilege user for +-- the application, which is the recommended production setup. +-- +-- Run as SYSDBA: +-- sqlplus sys/1234@//localhost:1521/XEPDB1 as sysdba @oracle_xe_setup.sql +-- =================================================================== + +ALTER SESSION SET CONTAINER = XEPDB1; + +BEGIN + EXECUTE IMMEDIATE 'DROP USER MARYAM_APP CASCADE'; +EXCEPTION WHEN OTHERS THEN NULL; +END; +/ + +CREATE USER MARYAM_APP IDENTIFIED BY "1234" + DEFAULT TABLESPACE USERS + TEMPORARY TABLESPACE TEMP + QUOTA UNLIMITED ON USERS; + +GRANT CONNECT, RESOURCE, CREATE SESSION, CREATE TABLE, + CREATE SEQUENCE, CREATE VIEW TO MARYAM_APP; + +CONNECT MARYAM_APP/"1234"@//localhost:1521/XEPDB1; + +CREATE SEQUENCE MARYAM_CONV_HIST_SEQ START WITH 1 INCREMENT BY 1 NOCACHE NOCYCLE; + +CREATE TABLE MARYAM_CONVERSION_HISTORY ( + ID NUMBER(19) PRIMARY KEY, + REQUEST_TS TIMESTAMP(6) NOT NULL, + SOURCE_IP VARCHAR2(64) NOT NULL, + INPUT_VALUE CLOB NOT NULL, + OUTPUT_VALUE CLOB NOT NULL +); + +CREATE INDEX IDX_MARYAM_HIST_TS ON MARYAM_CONVERSION_HISTORY(REQUEST_TS); + +COMMIT; +EXIT; diff --git a/dist/maryam-measurement-api.jar b/dist/maryam-measurement-api.jar new file mode 100644 index 0000000..cb7b75a Binary files /dev/null and b/dist/maryam-measurement-api.jar differ diff --git a/dist/version.txt b/dist/version.txt new file mode 100644 index 0000000..3726fc7 --- /dev/null +++ b/dist/version.txt @@ -0,0 +1,5 @@ +MARYAM Measurement Conversion API +Version : 1.0.0 +Build : 2026-05-21 +Java : OpenJDK 17 +Stack : Spring Boot 3.2.5, Hibernate, Oracle XE, SpringDoc OpenAPI diff --git a/mvnw b/mvnw deleted file mode 100644 index bd8896b..0000000 --- a/mvnw +++ /dev/null @@ -1,295 +0,0 @@ -#!/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.4 -# -# 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:]' -} - -scriptDir="$(dirname "$0")" -scriptName="$(basename "$0")" - -# 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 <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" -[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.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${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; -esac - -# apply MVNW_REPOURL and calculate MAVEN_HOME -# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ -[ -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 - -# Find the actual extracted directory name (handles snapshots where filename != directory name) -actualDistributionDir="" - -# First try the expected directory name (for regular distributions) -if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then - if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then - actualDistributionDir="$distributionUrlNameMain" - fi -fi - -# If not found, search for any directory with the Maven executable (for snapshots) -if [ -z "$actualDistributionDir" ]; then - # enable globbing to iterate over items - set +f - for dir in "$TMP_DOWNLOAD_DIR"/*; do - if [ -d "$dir" ]; then - if [ -f "$dir/bin/$MVN_CMD" ]; then - actualDistributionDir="$(basename "$dir")" - break - fi - fi - done - set -f -fi - -if [ -z "$actualDistributionDir" ]; then - verbose "Contents of $TMP_DOWNLOAD_DIR:" - verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" - die "Could not find Maven distribution directory in extracted archive" -fi - -verbose "Found extracted Maven distribution directory: $actualDistributionDir" -printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" -mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" - -clean || : -exec_maven "$@" diff --git a/mvnw.cmd b/mvnw.cmd deleted file mode 100644 index 92450f9..0000000 --- a/mvnw.cmd +++ /dev/null @@ -1,189 +0,0 @@ -<# : 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.4 -@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-,maven-mvnd--}/ -if ($env:MVNW_REPOURL) { - $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/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_M2_PATH = "$HOME/.m2" -if ($env:MAVEN_USER_HOME) { - $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" -} - -if (-not (Test-Path -Path $MAVEN_M2_PATH)) { - New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null -} - -$MAVEN_WRAPPER_DISTS = $null -if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { - $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" -} else { - $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" -} - -$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" -$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::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 - -# Find the actual extracted directory name (handles snapshots where filename != directory name) -$actualDistributionDir = "" - -# First try the expected directory name (for regular distributions) -$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" -$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" -if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { - $actualDistributionDir = $distributionUrlNameMain -} - -# If not found, search for any directory with the Maven executable (for snapshots) -if (!$actualDistributionDir) { - Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { - $testPath = Join-Path $_.FullName "bin/$MVN_CMD" - if (Test-Path -Path $testPath -PathType Leaf) { - $actualDistributionDir = $_.Name - } - } -} - -if (!$actualDistributionDir) { - Write-Error "Could not find Maven distribution directory in extracted archive" -} - -Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" -Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -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" diff --git a/pom.xml b/pom.xml index 20909d2..0593ce3 100644 --- a/pom.xml +++ b/pom.xml @@ -1,54 +1,88 @@ - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 3.5.14 - - - com.oraclequantapi - oraclequantapi - 0.0.1-SNAPSHOT - - - - - - - - - - - - - - - - - 17 - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.2.5 + + + + om.maryam + maryam-measurement-api + 1.0.0 + jar + + MARYAM Measurement Conversion API + Enterprise REST service that decodes encoded measurement strings into numeric package totals, + persists request history in Oracle XE, and exposes full CRUD operations. + + + 17 + 17 + 17 + UTF-8 + 2.5.0 + 23.4.0.24.05 + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + org.springframework.boot + spring-boot-starter-validation + + + + org.springframework.boot + spring-boot-starter-actuator + + + + com.oracle.database.jdbc + ojdbc11 + ${ojdbc.version} + + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + ${springdoc.version} + + + + com.h2database + h2 + runtime + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + maryam-measurement-api + + + org.springframework.boot + spring-boot-maven-plugin + + + diff --git a/screenshots/1.png b/screenshots/1.png new file mode 100644 index 0000000..a5663fa Binary files /dev/null and b/screenshots/1.png differ diff --git a/screenshots/2.png b/screenshots/2.png new file mode 100644 index 0000000..7a24cf0 Binary files /dev/null and b/screenshots/2.png differ diff --git a/src/main/java/com/oraclequantapi/oraclequantapi/OraclequantapiApplication.java b/src/main/java/com/oraclequantapi/oraclequantapi/OraclequantapiApplication.java deleted file mode 100644 index 5e28689..0000000 --- a/src/main/java/com/oraclequantapi/oraclequantapi/OraclequantapiApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.oraclequantapi.oraclequantapi; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class OraclequantapiApplication { - - public static void main(String[] args) { - SpringApplication.run(OraclequantapiApplication.class, args); - } - -} diff --git a/src/main/java/om/maryam/measurement/MaryamMeasurementApplication.java b/src/main/java/om/maryam/measurement/MaryamMeasurementApplication.java new file mode 100644 index 0000000..637bb9f --- /dev/null +++ b/src/main/java/om/maryam/measurement/MaryamMeasurementApplication.java @@ -0,0 +1,18 @@ +package om.maryam.measurement; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Entry point of the MARYAM Measurement Conversion API. + * + * Bootstraps Spring Boot auto-configuration, component scanning, + * embedded Tomcat, JPA and Swagger. + */ +@SpringBootApplication +public class MaryamMeasurementApplication { + + public static void main(String[] args) { + SpringApplication.run(MaryamMeasurementApplication.class, args); + } +} diff --git a/src/main/java/om/maryam/measurement/algorithm/MeasurementDecoder.java b/src/main/java/om/maryam/measurement/algorithm/MeasurementDecoder.java new file mode 100644 index 0000000..eaaf0ae --- /dev/null +++ b/src/main/java/om/maryam/measurement/algorithm/MeasurementDecoder.java @@ -0,0 +1,126 @@ +package om.maryam.measurement.algorithm; + +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Pure, side-effect free decoder for the OracleQuant measurement encoding. + * + * Encoding rules (derived from the evaluation specification): + * + * - Letters carry a value : a = 1, b = 2, ... z = 26. + * - '_' (underscore) : terminates the current "varint" with value 0. + * - 'z' is a continuation : when 'z' is encountered while reading a value + * it contributes 26 to the running value AND + * instructs the reader to continue with the next + * character. Any other character terminates the + * value. + * + * The stream is a sequence of packets. Each packet starts with a varint that + * represents how many additional varints (call them "items") belong to the + * packet. The packet's reported total is the sum of those items. The + * algorithm then continues with the next packet until the input is exhausted. + * + * Worked example for "dz_a_aazzaaa" (expected [28, 53, 1]): + * + * Packet 1 : + * header 'd' -> count = 4 + * item 1: 'z' '_' -> 26 + 0 = 26 + * item 2: 'a' -> 1 + * item 3: '_' -> 0 + * item 4: 'a' -> 1 + * packet total = 28 + * Packet 2 : + * header 'a' -> count = 1 + * item 1: 'z' 'z' 'a' -> 26+26+1 = 53 + * Packet 3 : + * header 'a' -> count = 1 + * item 1: 'a' -> 1 + * + * This component is stateless and therefore thread-safe; a single shared + * Spring bean is sufficient for all incoming requests. + */ +@Component +public class MeasurementDecoder { + + private static final char CONTINUATION = 'z'; + private static final char TERMINATOR = '_'; + + /** + * Decode an encoded measurement string into the list of packet totals. + * + * @param input the encoded payload (may be {@code null} or empty). + * @return an immutable list of packet totals. An empty input yields an + * empty list (never {@code null}). + */ + public List decode(String input) { + if (input == null || input.isEmpty()) { + return Collections.emptyList(); + } + + final Cursor cursor = new Cursor(input); + final List packets = new ArrayList<>(); + + while (cursor.hasMore()) { + final int count = readVarint(cursor); + int total = 0; + for (int i = 0; i < count && cursor.hasMore(); i++) { + total += readVarint(cursor); + } + packets.add(total); + } + return Collections.unmodifiableList(packets); + } + + /** + * Reads a single variable-length integer at the current cursor position. + * The cursor is advanced past every consumed character. + */ + private int readVarint(Cursor cursor) { + int value = 0; + while (cursor.hasMore()) { + final char c = cursor.next(); + if (c == TERMINATOR) { + return value; + } + value += charValue(c); + if (c != CONTINUATION) { + return value; + } + } + return value; + } + + /** + * Maps a lowercase letter to its 1-based positional value. + * Non-letters fall through to 0 which is the safe neutral value. + */ + private int charValue(char c) { + if (c >= 'a' && c <= 'z') { + return (c - 'a') + 1; + } + return 0; + } + + /** Tiny mutable cursor over a {@link String}. */ + private static final class Cursor { + private final String data; + private int index; + + Cursor(String data) { + this.data = data; + this.index = 0; + } + + boolean hasMore() { + return index < data.length(); + } + + char next() { + return data.charAt(index++); + } + } +} diff --git a/src/main/java/om/maryam/measurement/config/OpenApiConfig.java b/src/main/java/om/maryam/measurement/config/OpenApiConfig.java new file mode 100644 index 0000000..9b93182 --- /dev/null +++ b/src/main/java/om/maryam/measurement/config/OpenApiConfig.java @@ -0,0 +1,25 @@ +package om.maryam.measurement.config; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * OpenAPI metadata for the API. Kept intentionally minimal so the + * generated documentation focuses on the endpoints, not on branding. + * + * - Swagger UI : /maryam/swagger-ui/index.html + * - JSON spec : /maryam/v3/api-docs + */ +@Configuration +public class OpenApiConfig { + + @Bean + public OpenAPI maryamOpenApi() { + return new OpenAPI().info(new Info() + .title("MARYAM Measurement Conversion API") + .description("Decodes encoded measurement strings into numeric package totals.") + .version("1.0.0")); + } +} diff --git a/src/main/java/om/maryam/measurement/controller/HistoryController.java b/src/main/java/om/maryam/measurement/controller/HistoryController.java new file mode 100644 index 0000000..4c91b94 --- /dev/null +++ b/src/main/java/om/maryam/measurement/controller/HistoryController.java @@ -0,0 +1,70 @@ +package om.maryam.measurement.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import om.maryam.measurement.dto.HistoryDto; +import om.maryam.measurement.dto.HistoryUpdateRequest; +import om.maryam.measurement.service.HistoryService; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * CRUD endpoints over the persisted conversion history. + * Base path: /history. + */ +@RestController +@RequestMapping(path = "/history", + produces = MediaType.APPLICATION_JSON_VALUE) +@Tag(name = "Conversion History") +public class HistoryController { + + private final HistoryService historyService; + + public HistoryController(HistoryService historyService) { + this.historyService = historyService; + } + + @Operation(summary = "Return every history record currently stored.") + @GetMapping + public ResponseEntity> findAll() { + return ResponseEntity.ok(historyService.findAll()); + } + + @Operation(summary = "Return a single history record by id.") + @GetMapping("/{id}") + public ResponseEntity findById(@PathVariable Long id) { + return ResponseEntity.ok(historyService.findById(id)); + } + + @Operation(summary = "Replace an existing history record.") + @PutMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity update(@PathVariable Long id, + @Valid @RequestBody HistoryUpdateRequest request) { + return ResponseEntity.ok(historyService.update(id, request)); + } + + @Operation(summary = "Partially update an existing history record.") + @PatchMapping(path = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE) + public ResponseEntity patch(@PathVariable Long id, + @RequestBody HistoryUpdateRequest request) { + return ResponseEntity.ok(historyService.patch(id, request)); + } + + @Operation(summary = "Delete a single history record by id.") + @DeleteMapping("/{id}") + public ResponseEntity deleteOne(@PathVariable Long id) { + historyService.deleteById(id); + return ResponseEntity.noContent().build(); + } + + @Operation(summary = "Clear the entire history table.") + @DeleteMapping + public ResponseEntity clearAll() { + historyService.deleteAll(); + return ResponseEntity.noContent().build(); + } +} diff --git a/src/main/java/om/maryam/measurement/controller/MeasurementController.java b/src/main/java/om/maryam/measurement/controller/MeasurementController.java new file mode 100644 index 0000000..3b12bc6 --- /dev/null +++ b/src/main/java/om/maryam/measurement/controller/MeasurementController.java @@ -0,0 +1,51 @@ +package om.maryam.measurement.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.constraints.NotNull; +import om.maryam.measurement.service.MeasurementService; +import om.maryam.measurement.util.ClientIpResolver; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +/** + * Public REST endpoint that performs measurement decoding. + * + * Exposed at GET /maryam/convert-measurements?input=.... + * The response body is a raw JSON array of integers, exactly matching the + * evaluation contract (e.g. {@code [2,7,7]}). + */ +@RestController +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) +@Tag(name = "Measurement Conversion") +public class MeasurementController { + + private final MeasurementService measurementService; + private final ClientIpResolver ipResolver; + + public MeasurementController(MeasurementService measurementService, + ClientIpResolver ipResolver) { + this.measurementService = measurementService; + this.ipResolver = ipResolver; + } + + @Operation(summary = "Convert an encoded measurement string into package totals.") + @GetMapping("/convert-measurements") + public ResponseEntity> convert( + @Parameter(description = "Encoded measurement payload", example = "abcdabcdab") + @RequestParam("input") @NotNull String input, + HttpServletRequest request) { + + final String ip = ipResolver.resolve(request); + final List result = measurementService.convertAndRecord(input, ip); + return ResponseEntity.ok(result); + } +} diff --git a/src/main/java/om/maryam/measurement/dto/ApiError.java b/src/main/java/om/maryam/measurement/dto/ApiError.java new file mode 100644 index 0000000..538e738 --- /dev/null +++ b/src/main/java/om/maryam/measurement/dto/ApiError.java @@ -0,0 +1,75 @@ +package om.maryam.measurement.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * Uniform error envelope returned for every non-2xx response. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ApiError { + + @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") + private LocalDateTime timestamp; + + private int status; + private String error; + private String message; + private String path; + private List details; + + public ApiError() { } + + public ApiError(LocalDateTime timestamp, int status, String error, + String message, String path, List details) { + this.timestamp = timestamp; + this.status = status; + this.error = error; + this.message = message; + this.path = path; + this.details = details; + } + + public static Builder builder() { return new Builder(); } + + public static final class Builder { + private LocalDateTime timestamp; + private int status; + private String error; + private String message; + private String path; + private List details; + + public Builder timestamp(LocalDateTime timestamp) { this.timestamp = timestamp; return this; } + public Builder status(int status) { this.status = status; return this; } + public Builder error(String error) { this.error = error; return this; } + public Builder message(String message) { this.message = message; return this; } + public Builder path(String path) { this.path = path; return this; } + public Builder details(List details) { this.details = details; return this; } + + public ApiError build() { + return new ApiError(timestamp, status, error, message, path, details); + } + } + + public LocalDateTime getTimestamp() { return timestamp; } + public void setTimestamp(LocalDateTime t) { this.timestamp = t; } + + public int getStatus() { return status; } + public void setStatus(int status) { this.status = status; } + + public String getError() { return error; } + public void setError(String error) { this.error = error; } + + public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } + + public String getPath() { return path; } + public void setPath(String path) { this.path = path; } + + public List getDetails() { return details; } + public void setDetails(List details) { this.details = details; } +} diff --git a/src/main/java/om/maryam/measurement/dto/ConversionResponse.java b/src/main/java/om/maryam/measurement/dto/ConversionResponse.java new file mode 100644 index 0000000..93775e0 --- /dev/null +++ b/src/main/java/om/maryam/measurement/dto/ConversionResponse.java @@ -0,0 +1,22 @@ +package om.maryam.measurement.dto; + +import java.util.List; + +/** + * Wrapper for the decoded conversion result. + * The raw API endpoint returns the list directly (e.g. [2,7,7]) as required + * by the evaluation specification. This DTO is retained for internal reuse. + */ +public class ConversionResponse { + + private List result; + + public ConversionResponse() { } + + public ConversionResponse(List result) { + this.result = result; + } + + public List getResult() { return result; } + public void setResult(List result) { this.result = result; } +} diff --git a/src/main/java/om/maryam/measurement/dto/HistoryDto.java b/src/main/java/om/maryam/measurement/dto/HistoryDto.java new file mode 100644 index 0000000..8469bf8 --- /dev/null +++ b/src/main/java/om/maryam/measurement/dto/HistoryDto.java @@ -0,0 +1,67 @@ +package om.maryam.measurement.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; + +import java.time.LocalDateTime; + +/** + * Transport object representing a persisted history record returned by the API. + * Decouples the JPA entity from the public REST contract. + */ +public class HistoryDto { + + private Long id; + + @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") + private LocalDateTime timestamp; + + private String sourceIpAddress; + private String input; + private String output; + + public HistoryDto() { } + + public HistoryDto(Long id, LocalDateTime timestamp, String sourceIpAddress, + String input, String output) { + this.id = id; + this.timestamp = timestamp; + this.sourceIpAddress = sourceIpAddress; + this.input = input; + this.output = output; + } + + public static Builder builder() { return new Builder(); } + + public static final class Builder { + private Long id; + private LocalDateTime timestamp; + private String sourceIpAddress; + private String input; + private String output; + + public Builder id(Long id) { this.id = id; return this; } + public Builder timestamp(LocalDateTime timestamp) { this.timestamp = timestamp; return this; } + public Builder sourceIpAddress(String sourceIpAddress) { this.sourceIpAddress = sourceIpAddress; return this; } + public Builder input(String input) { this.input = input; return this; } + public Builder output(String output) { this.output = output; return this; } + + public HistoryDto build() { + return new HistoryDto(id, timestamp, sourceIpAddress, input, output); + } + } + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + + public LocalDateTime getTimestamp() { return timestamp; } + public void setTimestamp(LocalDateTime timestamp) { this.timestamp = timestamp; } + + public String getSourceIpAddress() { return sourceIpAddress; } + public void setSourceIpAddress(String sourceIpAddress){ this.sourceIpAddress = sourceIpAddress; } + + public String getInput() { return input; } + public void setInput(String input) { this.input = input; } + + public String getOutput() { return output; } + public void setOutput(String output) { this.output = output; } +} diff --git a/src/main/java/om/maryam/measurement/dto/HistoryUpdateRequest.java b/src/main/java/om/maryam/measurement/dto/HistoryUpdateRequest.java new file mode 100644 index 0000000..771850f --- /dev/null +++ b/src/main/java/om/maryam/measurement/dto/HistoryUpdateRequest.java @@ -0,0 +1,29 @@ +package om.maryam.measurement.dto; + +import jakarta.validation.constraints.NotBlank; + +/** + * Payload used for PUT/PATCH update of an existing history record. + * Only mutable business fields are exposed. + */ +public class HistoryUpdateRequest { + + @NotBlank(message = "input must not be blank") + private String input; + + @NotBlank(message = "output must not be blank") + private String output; + + public HistoryUpdateRequest() { } + + public HistoryUpdateRequest(String input, String output) { + this.input = input; + this.output = output; + } + + public String getInput() { return input; } + public void setInput(String input) { this.input = input; } + + public String getOutput() { return output; } + public void setOutput(String output) { this.output = output; } +} diff --git a/src/main/java/om/maryam/measurement/entity/ConversionHistory.java b/src/main/java/om/maryam/measurement/entity/ConversionHistory.java new file mode 100644 index 0000000..76ffb21 --- /dev/null +++ b/src/main/java/om/maryam/measurement/entity/ConversionHistory.java @@ -0,0 +1,95 @@ +package om.maryam.measurement.entity; + +import jakarta.persistence.*; + +import java.time.LocalDateTime; + +/** + * JPA entity that persists every measurement conversion request. + * + * Table: MARYAM_CONVERSION_HISTORY + * Sequence: MARYAM_CONV_HIST_SEQ + */ +@Entity +@Table(name = "MARYAM_CONVERSION_HISTORY") +public class ConversionHistory { + + @Id + @SequenceGenerator(name = "maryam_conv_hist_seq", + sequenceName = "MARYAM_CONV_HIST_SEQ", + allocationSize = 1) + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "maryam_conv_hist_seq") + @Column(name = "ID") + private Long id; + + @Column(name = "REQUEST_TS", nullable = false) + private LocalDateTime timestamp; + + @Column(name = "SOURCE_IP", length = 64, nullable = false) + private String sourceIpAddress; + + @Lob + @Column(name = "INPUT_VALUE", nullable = false) + private String input; + + @Lob + @Column(name = "OUTPUT_VALUE", nullable = false) + private String output; + + public ConversionHistory() { } + + public ConversionHistory(Long id, LocalDateTime timestamp, String sourceIpAddress, + String input, String output) { + this.id = id; + this.timestamp = timestamp; + this.sourceIpAddress = sourceIpAddress; + this.input = input; + this.output = output; + } + + @PrePersist + public void prePersist() { + if (this.timestamp == null) { + this.timestamp = LocalDateTime.now(); + } + } + + /* ----------------------------- builder ----------------------------- */ + + public static Builder builder() { return new Builder(); } + + public static final class Builder { + private Long id; + private LocalDateTime timestamp; + private String sourceIpAddress; + private String input; + private String output; + + public Builder id(Long id) { this.id = id; return this; } + public Builder timestamp(LocalDateTime timestamp) { this.timestamp = timestamp; return this; } + public Builder sourceIpAddress(String sourceIpAddress) { this.sourceIpAddress = sourceIpAddress; return this; } + public Builder input(String input) { this.input = input; return this; } + public Builder output(String output) { this.output = output; return this; } + + public ConversionHistory build() { + return new ConversionHistory(id, timestamp, sourceIpAddress, input, output); + } + } + + /* ----------------------------- getters / setters ------------------ */ + + public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + + public LocalDateTime getTimestamp() { return timestamp; } + public void setTimestamp(LocalDateTime timestamp) { this.timestamp = timestamp; } + + public String getSourceIpAddress() { return sourceIpAddress; } + public void setSourceIpAddress(String sourceIpAddress){ this.sourceIpAddress = sourceIpAddress; } + + public String getInput() { return input; } + public void setInput(String input) { this.input = input; } + + public String getOutput() { return output; } + public void setOutput(String output) { this.output = output; } +} diff --git a/src/main/java/om/maryam/measurement/exception/GlobalExceptionHandler.java b/src/main/java/om/maryam/measurement/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..bd80eb3 --- /dev/null +++ b/src/main/java/om/maryam/measurement/exception/GlobalExceptionHandler.java @@ -0,0 +1,93 @@ +package om.maryam.measurement.exception; + +import jakarta.servlet.http.HttpServletRequest; +import om.maryam.measurement.dto.ApiError; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.MissingServletRequestParameterException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * Single source of truth for HTTP error responses. + * + * Every handler maps to a uniform {@link ApiError} envelope, keeps the + * stack-trace out of the client response, and emits a structured log entry + * for the operations team. + */ +@RestControllerAdvice +public class GlobalExceptionHandler { + + private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); + + @ExceptionHandler(HistoryNotFoundException.class) + public ResponseEntity handleNotFound(HistoryNotFoundException ex, + HttpServletRequest request) { + return build(HttpStatus.NOT_FOUND, ex.getMessage(), request, null); + } + + @ExceptionHandler(MissingServletRequestParameterException.class) + public ResponseEntity handleMissingParam(MissingServletRequestParameterException ex, + HttpServletRequest request) { + return build(HttpStatus.BAD_REQUEST, + "Missing required parameter '" + ex.getParameterName() + "'", + request, null); + } + + @ExceptionHandler(MethodArgumentTypeMismatchException.class) + public ResponseEntity handleTypeMismatch(MethodArgumentTypeMismatchException ex, + HttpServletRequest request) { + return build(HttpStatus.BAD_REQUEST, + "Parameter '" + ex.getName() + "' has invalid value '" + ex.getValue() + "'", + request, null); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity handleValidation(MethodArgumentNotValidException ex, + HttpServletRequest request) { + List details = ex.getBindingResult().getFieldErrors().stream() + .map(f -> f.getField() + ": " + f.getDefaultMessage()) + .toList(); + return build(HttpStatus.BAD_REQUEST, "Validation failed", request, details); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity handleUnreadable(HttpMessageNotReadableException ex, + HttpServletRequest request) { + return build(HttpStatus.BAD_REQUEST, "Malformed JSON request body", request, null); + } + + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegal(IllegalArgumentException ex, + HttpServletRequest request) { + return build(HttpStatus.BAD_REQUEST, ex.getMessage(), request, null); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity handleAny(Exception ex, HttpServletRequest request) { + log.error("Unhandled exception while processing {}", request.getRequestURI(), ex); + return build(HttpStatus.INTERNAL_SERVER_ERROR, + "An unexpected error occurred. Please contact MARYAM support.", request, null); + } + + private ResponseEntity build(HttpStatus status, String message, + HttpServletRequest request, List details) { + ApiError body = ApiError.builder() + .timestamp(LocalDateTime.now()) + .status(status.value()) + .error(status.getReasonPhrase()) + .message(message) + .path(request != null ? request.getRequestURI() : "") + .details(details) + .build(); + return ResponseEntity.status(status).body(body); + } +} diff --git a/src/main/java/om/maryam/measurement/exception/HistoryNotFoundException.java b/src/main/java/om/maryam/measurement/exception/HistoryNotFoundException.java new file mode 100644 index 0000000..669c715 --- /dev/null +++ b/src/main/java/om/maryam/measurement/exception/HistoryNotFoundException.java @@ -0,0 +1,11 @@ +package om.maryam.measurement.exception; + +/** + * Thrown when a {@code ConversionHistory} row cannot be located by id. + */ +public class HistoryNotFoundException extends RuntimeException { + + public HistoryNotFoundException(Long id) { + super("History record with id=" + id + " was not found"); + } +} diff --git a/src/main/java/om/maryam/measurement/repository/ConversionHistoryRepository.java b/src/main/java/om/maryam/measurement/repository/ConversionHistoryRepository.java new file mode 100644 index 0000000..309dd24 --- /dev/null +++ b/src/main/java/om/maryam/measurement/repository/ConversionHistoryRepository.java @@ -0,0 +1,13 @@ +package om.maryam.measurement.repository; + +import om.maryam.measurement.entity.ConversionHistory; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +/** + * Spring Data JPA repository for {@link ConversionHistory}. + * All CRUD primitives are inherited from {@link JpaRepository}. + */ +@Repository +public interface ConversionHistoryRepository extends JpaRepository { +} diff --git a/src/main/java/om/maryam/measurement/service/HistoryService.java b/src/main/java/om/maryam/measurement/service/HistoryService.java new file mode 100644 index 0000000..faaa623 --- /dev/null +++ b/src/main/java/om/maryam/measurement/service/HistoryService.java @@ -0,0 +1,24 @@ +package om.maryam.measurement.service; + +import om.maryam.measurement.dto.HistoryDto; +import om.maryam.measurement.dto.HistoryUpdateRequest; + +import java.util.List; + +/** + * CRUD operations over the persisted conversion history. + */ +public interface HistoryService { + + List findAll(); + + HistoryDto findById(Long id); + + HistoryDto update(Long id, HistoryUpdateRequest request); + + HistoryDto patch(Long id, HistoryUpdateRequest request); + + void deleteById(Long id); + + void deleteAll(); +} diff --git a/src/main/java/om/maryam/measurement/service/MeasurementService.java b/src/main/java/om/maryam/measurement/service/MeasurementService.java new file mode 100644 index 0000000..14e6a12 --- /dev/null +++ b/src/main/java/om/maryam/measurement/service/MeasurementService.java @@ -0,0 +1,21 @@ +package om.maryam.measurement.service; + +import java.util.List; + +/** + * Decodes an encoded measurement payload and records the request. + * + * The contract is intentionally narrow so the controller layer can stay free + * of any persistence or algorithm concerns. + */ +public interface MeasurementService { + + /** + * Decode the supplied encoded string and persist an audit row. + * + * @param encoded the encoded measurement payload + * @param sourceIp the remote client IP captured by the controller + * @return the list of decoded package totals + */ + List convertAndRecord(String encoded, String sourceIp); +} diff --git a/src/main/java/om/maryam/measurement/service/impl/HistoryServiceImpl.java b/src/main/java/om/maryam/measurement/service/impl/HistoryServiceImpl.java new file mode 100644 index 0000000..5a0309e --- /dev/null +++ b/src/main/java/om/maryam/measurement/service/impl/HistoryServiceImpl.java @@ -0,0 +1,100 @@ +package om.maryam.measurement.service.impl; + +import om.maryam.measurement.dto.HistoryDto; +import om.maryam.measurement.dto.HistoryUpdateRequest; +import om.maryam.measurement.entity.ConversionHistory; +import om.maryam.measurement.exception.HistoryNotFoundException; +import om.maryam.measurement.repository.ConversionHistoryRepository; +import om.maryam.measurement.service.HistoryService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +/** + * CRUD facade over {@link ConversionHistoryRepository}. + * + * Entities are never returned outside of this layer; they are translated to + * {@link HistoryDto} so the persistence model can evolve independently of + * the REST contract. + */ +@Service +public class HistoryServiceImpl implements HistoryService { + + private static final Logger log = LoggerFactory.getLogger(HistoryServiceImpl.class); + + private final ConversionHistoryRepository repository; + + public HistoryServiceImpl(ConversionHistoryRepository repository) { + this.repository = repository; + } + + @Override + @Transactional(readOnly = true) + public List findAll() { + return repository.findAll().stream().map(this::toDto).toList(); + } + + @Override + @Transactional(readOnly = true) + public HistoryDto findById(Long id) { + return repository.findById(id).map(this::toDto) + .orElseThrow(() -> new HistoryNotFoundException(id)); + } + + @Override + @Transactional + public HistoryDto update(Long id, HistoryUpdateRequest request) { + ConversionHistory entity = repository.findById(id) + .orElseThrow(() -> new HistoryNotFoundException(id)); + entity.setInput(request.getInput()); + entity.setOutput(request.getOutput()); + log.info("Replaced history id={} with new payload", id); + return toDto(entity); + } + + @Override + @Transactional + public HistoryDto patch(Long id, HistoryUpdateRequest request) { + ConversionHistory entity = repository.findById(id) + .orElseThrow(() -> new HistoryNotFoundException(id)); + if (request.getInput() != null && !request.getInput().isBlank()) { + entity.setInput(request.getInput()); + } + if (request.getOutput() != null && !request.getOutput().isBlank()) { + entity.setOutput(request.getOutput()); + } + log.info("Patched history id={}", id); + return toDto(entity); + } + + @Override + @Transactional + public void deleteById(Long id) { + if (!repository.existsById(id)) { + throw new HistoryNotFoundException(id); + } + repository.deleteById(id); + log.info("Deleted history id={}", id); + } + + @Override + @Transactional + public void deleteAll() { + long count = repository.count(); + repository.deleteAll(); + log.warn("Cleared history table - {} record(s) removed", count); + } + + private HistoryDto toDto(ConversionHistory e) { + return HistoryDto.builder() + .id(e.getId()) + .timestamp(e.getTimestamp()) + .sourceIpAddress(e.getSourceIpAddress()) + .input(e.getInput()) + .output(e.getOutput()) + .build(); + } +} diff --git a/src/main/java/om/maryam/measurement/service/impl/MeasurementServiceImpl.java b/src/main/java/om/maryam/measurement/service/impl/MeasurementServiceImpl.java new file mode 100644 index 0000000..94212cd --- /dev/null +++ b/src/main/java/om/maryam/measurement/service/impl/MeasurementServiceImpl.java @@ -0,0 +1,56 @@ +package om.maryam.measurement.service.impl; + +import om.maryam.measurement.algorithm.MeasurementDecoder; +import om.maryam.measurement.entity.ConversionHistory; +import om.maryam.measurement.repository.ConversionHistoryRepository; +import om.maryam.measurement.service.MeasurementService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.LocalDateTime; +import java.util.List; + +/** + * Default {@link MeasurementService} implementation. + * + * Responsibilities: + * 1. Delegate the algorithm to {@link MeasurementDecoder} (single + * responsibility - no string parsing leaks into the service). + * 2. Persist a fully populated audit row inside a transaction. + */ +@Service +public class MeasurementServiceImpl implements MeasurementService { + + private static final Logger log = LoggerFactory.getLogger(MeasurementServiceImpl.class); + + private final MeasurementDecoder decoder; + private final ConversionHistoryRepository historyRepository; + + public MeasurementServiceImpl(MeasurementDecoder decoder, + ConversionHistoryRepository historyRepository) { + this.decoder = decoder; + this.historyRepository = historyRepository; + } + + @Override + @Transactional + public List convertAndRecord(String encoded, String sourceIp) { + log.debug("Decoding measurement payload (length={}) from ip={}", + encoded == null ? 0 : encoded.length(), sourceIp); + + final List result = decoder.decode(encoded); + + final ConversionHistory entity = ConversionHistory.builder() + .timestamp(LocalDateTime.now()) + .sourceIpAddress(sourceIp) + .input(encoded == null ? "" : encoded) + .output(result.toString()) + .build(); + historyRepository.save(entity); + + log.info("Decoded input='{}' -> {} (id={})", encoded, result, entity.getId()); + return result; + } +} diff --git a/src/main/java/om/maryam/measurement/util/ClientIpResolver.java b/src/main/java/om/maryam/measurement/util/ClientIpResolver.java new file mode 100644 index 0000000..e45ed83 --- /dev/null +++ b/src/main/java/om/maryam/measurement/util/ClientIpResolver.java @@ -0,0 +1,38 @@ +package om.maryam.measurement.util; + +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +/** + * Resolves the originating client IP address. + * + * Honors the most common reverse-proxy headers in priority order, falling + * back to {@link HttpServletRequest#getRemoteAddr()} when no header is set. + */ +@Component +public class ClientIpResolver { + + private static final String[] HEADERS = { + "X-Forwarded-For", + "Proxy-Client-IP", + "WL-Proxy-Client-IP", + "HTTP_X_FORWARDED_FOR", + "HTTP_CLIENT_IP", + "X-Real-IP" + }; + + public String resolve(HttpServletRequest request) { + if (request == null) { + return "unknown"; + } + for (String header : HEADERS) { + String value = request.getHeader(header); + if (StringUtils.hasText(value) && !"unknown".equalsIgnoreCase(value)) { + int comma = value.indexOf(','); + return comma > 0 ? value.substring(0, comma).trim() : value.trim(); + } + } + return request.getRemoteAddr(); + } +} diff --git a/src/main/resources/application-dev.properties b/src/main/resources/application-dev.properties new file mode 100644 index 0000000..73886be --- /dev/null +++ b/src/main/resources/application-dev.properties @@ -0,0 +1,15 @@ +# ============================================================ +# Dev profile - in-memory H2 (no Oracle required) +# Activate with: --spring.profiles.active=dev +# ============================================================ +spring.datasource.url=jdbc:h2:mem:maryam;MODE=Oracle;DB_CLOSE_DELAY=-1 +spring.datasource.username=sa +spring.datasource.password= +spring.datasource.driver-class-name=org.h2.Driver + +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.hibernate.ddl-auto=create-drop + +# H2 web console at http://localhost:8080/maryam/h2-console +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 99d0060..5b46df8 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1 +1,57 @@ -spring.application.name=oraclequantapi +# ============================================================ +# MARYAM Measurement API - Application Configuration +# ============================================================ +spring.application.name=maryam-measurement-api +server.port=8080 +server.servlet.context-path=/maryam + +# ------------------------------------------------------------ +# Oracle XE Datasource +# ------------------------------------------------------------ +spring.datasource.url=jdbc:oracle:thin:@//localhost:1521/XEPDB1 +spring.datasource.username=SYSTEM +spring.datasource.password=Test1234 +spring.datasource.driver-class-name=oracle.jdbc.OracleDriver + +spring.datasource.hikari.maximum-pool-size=15 +spring.datasource.hikari.minimum-idle=3 +spring.datasource.hikari.idle-timeout=30000 +spring.datasource.hikari.connection-timeout=20000 +spring.datasource.hikari.pool-name=MaryamHikariPool + +# ------------------------------------------------------------ +# JPA / Hibernate +# ------------------------------------------------------------ +spring.jpa.database-platform=org.hibernate.dialect.OracleDialect +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=false +spring.jpa.properties.hibernate.format_sql=true +spring.jpa.properties.hibernate.jdbc.batch_size=25 +spring.jpa.open-in-view=false + +# ------------------------------------------------------------ +# Swagger / OpenAPI - compact, low-fuss presentation +# ------------------------------------------------------------ +springdoc.api-docs.path=/v3/api-docs +springdoc.swagger-ui.path=/swagger-ui.html +springdoc.swagger-ui.operationsSorter=method +springdoc.swagger-ui.tagsSorter=alpha +springdoc.swagger-ui.docExpansion=none +springdoc.swagger-ui.defaultModelsExpandDepth=-1 +springdoc.swagger-ui.displayRequestDuration=true +springdoc.swagger-ui.filter=true +springdoc.swagger-ui.disable-swagger-default-url=true +springdoc.swagger-ui.supportedSubmitMethods=get,post,put,patch,delete + +# ------------------------------------------------------------ +# Actuator +# ------------------------------------------------------------ +management.endpoints.web.exposure.include=health,info,metrics +management.endpoint.health.show-details=when_authorized +info.app.name=MARYAM Measurement Conversion API +info.app.version=1.0.0 + +# ------------------------------------------------------------ +# Logging - rolling file appender configured in logback-spring.xml +# ------------------------------------------------------------ +logging.config=classpath:logback-spring.xml diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml new file mode 100644 index 0000000..05956a0 --- /dev/null +++ b/src/main/resources/logback-spring.xml @@ -0,0 +1,36 @@ + + + + + + + + + + ${LOG_PATTERN} + + + + + ${LOG_DIR}/${APP_NAME}.log + + ${LOG_DIR}/${APP_NAME}.%d{yyyy-MM-dd}.%i.log.gz + 20MB + 30 + 2GB + + + ${LOG_PATTERN} + + + + + + + + + + + + diff --git a/src/main/resources/version.txt b/src/main/resources/version.txt new file mode 100644 index 0000000..3726fc7 --- /dev/null +++ b/src/main/resources/version.txt @@ -0,0 +1,5 @@ +MARYAM Measurement Conversion API +Version : 1.0.0 +Build : 2026-05-21 +Java : OpenJDK 17 +Stack : Spring Boot 3.2.5, Hibernate, Oracle XE, SpringDoc OpenAPI diff --git a/src/test/java/com/oraclequantapi/oraclequantapi/OraclequantapiApplicationTests.java b/src/test/java/com/oraclequantapi/oraclequantapi/OraclequantapiApplicationTests.java deleted file mode 100644 index 2de285b..0000000 --- a/src/test/java/com/oraclequantapi/oraclequantapi/OraclequantapiApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.oraclequantapi.oraclequantapi; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class OraclequantapiApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/src/test/java/om/maryam/measurement/MeasurementDecoderTest.java b/src/test/java/om/maryam/measurement/MeasurementDecoderTest.java new file mode 100644 index 0000000..9b78597 --- /dev/null +++ b/src/test/java/om/maryam/measurement/MeasurementDecoderTest.java @@ -0,0 +1,64 @@ +package om.maryam.measurement; + +import om.maryam.measurement.algorithm.MeasurementDecoder; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Validates the decoder against every example from the evaluation document. + */ +class MeasurementDecoderTest { + + private final MeasurementDecoder decoder = new MeasurementDecoder(); + + @Test + void decode_singleLetter() { + assertThat(decoder.decode("aa")).isEqualTo(List.of(1)); + } + + @Test + void decode_twoPackets() { + assertThat(decoder.decode("abbcc")).isEqualTo(List.of(2, 6)); + } + + @Test + void decode_continuationAndTerminator() { + assertThat(decoder.decode("dz_a_aazzaaa")).isEqualTo(List.of(28, 53, 1)); + } + + @Test + void decode_lonelyTerminator() { + assertThat(decoder.decode("a_")).isEqualTo(List.of(0)); + } + + @Test + void decode_threeIdenticalPackets() { + assertThat(decoder.decode("abcdabcdab")).isEqualTo(List.of(2, 7, 7)); + } + + @Test + void decode_trailingUnderscoreCreatesEmptyPacket() { + assertThat(decoder.decode("abcdabcdab_")).isEqualTo(List.of(2, 7, 7, 0)); + } + + @Test + void decode_largeCountViaZChain() { + assertThat(decoder.decode("zdaaaaaaaabaaaaaaaabaaaaaaaabbaa")) + .isEqualTo(List.of(34)); + } + + @Test + void decode_zMixedWithUnderscores() { + assertThat(decoder.decode("za_a_a_a_a_a_a_a_a_a_a_a_a_azaaa")) + .isEqualTo(List.of(40, 1)); + } + + @Test + void decode_emptyInput() { + assertThat(decoder.decode("")).isEmpty(); + assertThat(decoder.decode(null)).isEmpty(); + } +}