From 6e2396d24b43387ebe7a241e7f8c69f875280186 Mon Sep 17 00:00:00 2001 From: Miuroro Date: Thu, 28 May 2026 23:09:16 +0200 Subject: [PATCH 1/8] added initial Spring Boot Analytics API implementation with models, DTOs, service, controller, and exception handling --- task-1/AnalyticsAPI/.gitattributes | 2 + task-1/AnalyticsAPI/.gitignore | 33 ++ .../.mvn/wrapper/maven-wrapper.properties | 3 + task-1/AnalyticsAPI/API_DESIGN.md | 241 ++++++++++++++ task-1/AnalyticsAPI/mvnw | 295 ++++++++++++++++++ task-1/AnalyticsAPI/mvnw.cmd | 189 +++++++++++ task-1/AnalyticsAPI/pom.xml | 117 +++++++ .../AnalyticsAPI/AnalyticsApiApplication.java | 13 + .../controllers/AnalyticsController.java | 73 +++++ .../dto/Request/AnalyticsRequest.java | 27 ++ .../dto/Response/AnalyticsResponse.java | 19 ++ .../dto/Summary/AnalyticsSummary.java | 17 + .../exceptions/GlobalExceptionHandler.java | 91 ++++++ .../exceptions/ResourceNotFoundException.java | 8 + .../AnalyticsAPI/model/AnalyticsRecord.java | 19 ++ .../services/AnalyticsService.java | 142 +++++++++ .../src/main/resources/application.yaml | 3 + .../AnalyticsApiApplicationTests.java | 164 ++++++++++ 18 files changed, 1456 insertions(+) create mode 100644 task-1/AnalyticsAPI/.gitattributes create mode 100644 task-1/AnalyticsAPI/.gitignore create mode 100644 task-1/AnalyticsAPI/.mvn/wrapper/maven-wrapper.properties create mode 100644 task-1/AnalyticsAPI/API_DESIGN.md create mode 100644 task-1/AnalyticsAPI/mvnw create mode 100644 task-1/AnalyticsAPI/mvnw.cmd create mode 100644 task-1/AnalyticsAPI/pom.xml create mode 100644 task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplication.java create mode 100644 task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java create mode 100644 task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Request/AnalyticsRequest.java create mode 100644 task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Response/AnalyticsResponse.java create mode 100644 task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java create mode 100644 task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/GlobalExceptionHandler.java create mode 100644 task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/ResourceNotFoundException.java create mode 100644 task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/model/AnalyticsRecord.java create mode 100644 task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java create mode 100644 task-1/AnalyticsAPI/src/main/resources/application.yaml create mode 100644 task-1/AnalyticsAPI/src/test/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplicationTests.java diff --git a/task-1/AnalyticsAPI/.gitattributes b/task-1/AnalyticsAPI/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/task-1/AnalyticsAPI/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/task-1/AnalyticsAPI/.gitignore b/task-1/AnalyticsAPI/.gitignore new file mode 100644 index 0000000..667aaef --- /dev/null +++ b/task-1/AnalyticsAPI/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/task-1/AnalyticsAPI/.mvn/wrapper/maven-wrapper.properties b/task-1/AnalyticsAPI/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..216df05 --- /dev/null +++ b/task-1/AnalyticsAPI/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,3 @@ +wrapperVersion=3.3.4 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip diff --git a/task-1/AnalyticsAPI/API_DESIGN.md b/task-1/AnalyticsAPI/API_DESIGN.md new file mode 100644 index 0000000..62c012b --- /dev/null +++ b/task-1/AnalyticsAPI/API_DESIGN.md @@ -0,0 +1,241 @@ +# Analytics API Design + +This document defines the REST contract for the Week 4 Analytics API. + +## Goals + +- Accept privacy-respecting analytics events. +- Store records in memory. +- Support listing, filtering, fetching, replacing, deleting, and summarizing records. +- Keep controllers thin and push business logic into the service layer. + +## Base Path + +All endpoints are rooted at `/api/v1/analytics`. + +## Resource Model + +An analytics record contains: + +- `id`: server-generated trace ID, immutable string +- `timestamp`: when the event occurred, ISO-8601 date-time +- `eventType`: the type of event, non-empty string +- `eventSource`: the source of the event, non-empty string +- `sessionId`: anonymized session identifier, non-empty string + +## Endpoints + +### 1. Create a record + +`POST /api/v1/analytics` + +Creates a new analytics record. The server generates `id`. + +Request body: + +```json +{ + "timestamp": "2026-05-28T10:15:30Z", + "eventType": "page_view", + "eventSource": "web", + "sessionId": "sess_91f2f1" +} +``` + +Response: `201 Created` + +```json +{ + "id": "trace_8f2c1b7d3a8a4d7f", + "timestamp": "2026-05-28T10:15:30Z", + "eventType": "page_view", + "eventSource": "web", + "sessionId": "sess_91f2f1" +} +``` + +Validation rules: + +- `timestamp` is required and must be a valid ISO-8601 date-time. +- `eventType` is required and must not be blank. +- `eventSource` is required and must not be blank. +- `sessionId` is required and must not be blank. + +Status codes: + +- `201 Created` when stored successfully. +- `400 Bad Request` when validation fails. + +### 2. List and filter records + +`GET /api/v1/analytics` + +Returns all stored records or a filtered subset. + +Supported query parameters: + +- `eventType`: filter by event type +- `eventSource`: filter by event source +- `sessionId`: filter by anonymized session ID +- `startTime`: include records at or after this timestamp +- `endTime`: include records at or before this timestamp + +Example: + +`GET /api/v1/analytics?eventType=page_view&startTime=2026-05-28T00:00:00Z&endTime=2026-05-28T23:59:59Z` + +Response: `200 OK` + +```json +[ + { + "id": "trace_8f2c1b7d3a8a4d7f", + "timestamp": "2026-05-28T10:15:30Z", + "eventType": "page_view", + "eventSource": "web", + "sessionId": "sess_91f2f1" + } +] +``` + +Validation rules: + +- `startTime` and `endTime` must be valid ISO-8601 date-time values when provided. +- If both are present, `startTime` must be less than or equal to `endTime`. + +Status codes: + +- `200 OK` for a successful query. +- `400 Bad Request` for invalid filter values. + +### 3. Fetch one record + +`GET /api/v1/analytics/{id}` + +Returns a single record by server-generated ID. + +Response: `200 OK` + +```json +{ + "id": "trace_8f2c1b7d3a8a4d7f", + "timestamp": "2026-05-28T10:15:30Z", + "eventType": "page_view", + "eventSource": "web", + "sessionId": "sess_91f2f1" +} +``` + +Status codes: + +- `200 OK` when found. +- `404 Not Found` when the ID does not exist. + +### 4. Replace one record + +`PUT /api/v1/analytics/{id}` + +Fully replaces an existing record. The path parameter identifies the record to update. The request body supplies the new data. + +Request body: + +```json +{ + "timestamp": "2026-05-28T12:00:00Z", + "eventType": "click", + "eventSource": "mobile", + "sessionId": "sess_91f2f1" +} +``` + +Response: `200 OK` + +```json +{ + "id": "trace_8f2c1b7d3a8a4d7f", + "timestamp": "2026-05-28T12:00:00Z", + "eventType": "click", + "eventSource": "mobile", + "sessionId": "sess_91f2f1" +} +``` + +Rules: + +- The `id` is not accepted in the request body. +- The replacement must satisfy the same validation rules as create. + +Status codes: + +- `200 OK` when updated. +- `400 Bad Request` when validation fails. +- `404 Not Found` when the record does not exist. + +### 5. Delete one record + +`DELETE /api/v1/analytics/{id}` + +Deletes a record by ID. + +Status codes: + +- `204 No Content` when deleted. +- `404 Not Found` when the record does not exist. + +### 6. Summary + +`GET /api/v1/analytics/summary` + +Returns a simple analytics summary for the currently stored records. + +Response: `200 OK` + +```json +{ + "totalRecords": 3, + "totalsByEventType": { + "page_view": 2, + "click": 1 + }, + "uniqueSessions": 2 +} +``` + +Summary rules: + +- `totalRecords` is the number of records included in the summary. +- `totalsByEventType` groups counts by `eventType`. +- `uniqueSessions` counts distinct anonymized `sessionId` values. + +## Error Response Format + +All validation and lookup failures should return a consistent JSON error body. + +```json +{ + "timestamp": "2026-05-28T10:15:30Z", + "status": 400, + "error": "Bad Request", + "message": "timestamp must be a valid ISO-8601 date-time", + "path": "/api/v1/analytics" +} +``` + +Common error responses: + +- `400 Bad Request` for invalid input or invalid filter ranges. +- `404 Not Found` for missing records. + +## Validation Summary + +- Empty or blank `eventType`, `eventSource`, or `sessionId` are rejected. +- Invalid date-time values are rejected. +- `startTime` cannot be later than `endTime`. +- IDs are generated by the server and never accepted from the client on create. + +## Notes For Implementation + +- Use DTOs for request and response payloads. +- Keep persistence in memory using a collection such as `Map`. +- Put filtering, replacement, deletion, and summary logic in the service layer. +- Use a global exception handler to keep error responses consistent. diff --git a/task-1/AnalyticsAPI/mvnw b/task-1/AnalyticsAPI/mvnw new file mode 100644 index 0000000..bd8896b --- /dev/null +++ b/task-1/AnalyticsAPI/mvnw @@ -0,0 +1,295 @@ +#!/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/task-1/AnalyticsAPI/mvnw.cmd b/task-1/AnalyticsAPI/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/task-1/AnalyticsAPI/mvnw.cmd @@ -0,0 +1,189 @@ +<# : 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/task-1/AnalyticsAPI/pom.xml b/task-1/AnalyticsAPI/pom.xml new file mode 100644 index 0000000..6dc66e8 --- /dev/null +++ b/task-1/AnalyticsAPI/pom.xml @@ -0,0 +1,117 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 4.0.6 + + + com.weekfourassignment + AnalyticsAPI + 0.0.1-SNAPSHOT + + + + + + + + + + + + + + + + + 25 + + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-starter-webmvc + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + 3.0.2 + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-validation-test + test + + + org.springframework.boot + spring-boot-starter-webmvc-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + default-compile + compile + + compile + + + + + org.projectlombok + lombok + + + + + + default-testCompile + test-compile + + testCompile + + + + + org.projectlombok + lombok + + + + + + + + + + diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplication.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplication.java new file mode 100644 index 0000000..eddfc75 --- /dev/null +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplication.java @@ -0,0 +1,13 @@ +package com.weekfourassignment.AnalyticsAPI; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AnalyticsApiApplication { + + public static void main(String[] args) { + SpringApplication.run(AnalyticsApiApplication.class, args); + } + +} diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java new file mode 100644 index 0000000..a7d8038 --- /dev/null +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java @@ -0,0 +1,73 @@ +package com.weekfourassignment.AnalyticsAPI.controllers; + +import com.weekfourassignment.AnalyticsAPI.dto.Request.AnalyticsRequest; +import com.weekfourassignment.AnalyticsAPI.dto.Response.AnalyticsResponse; +import com.weekfourassignment.AnalyticsAPI.dto.Summary.AnalyticsSummary; +import com.weekfourassignment.AnalyticsAPI.services.AnalyticsService; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.format.annotation.DateTimeFormat; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.time.OffsetDateTime; +import java.util.List; + +@RestController +@RequestMapping("/api/v1/analytics") +@RequiredArgsConstructor +public class AnalyticsController { + + private final AnalyticsService analyticsService; + + @PostMapping + public ResponseEntity createRecord(@Valid @RequestBody AnalyticsRequest request) { + return ResponseEntity.status(HttpStatus.CREATED).body(analyticsService.createRecord(request)); + } + + @GetMapping + public ResponseEntity> getRecords( + @RequestParam(required = false) String eventType, + @RequestParam(required = false) String eventSource, + @RequestParam(required = false) String sessionId, + @RequestParam(required = false) + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime startTime, + @RequestParam(required = false) + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime endTime + ) { + return ResponseEntity.ok(analyticsService.getRecords(eventType, eventSource, sessionId, startTime, endTime)); + } + + @GetMapping("/{id}") + public ResponseEntity getRecordById(@PathVariable String id) { + return ResponseEntity.ok(analyticsService.getRecordById(id)); + } + + @PutMapping("/{id}") + public ResponseEntity replaceRecord( + @PathVariable String id, + @Valid @RequestBody AnalyticsRequest request + ) { + return ResponseEntity.ok(analyticsService.replaceRecord(id, request)); + } + + @DeleteMapping("/{id}") + public ResponseEntity deleteRecord(@PathVariable String id) { + analyticsService.deleteRecord(id); + return ResponseEntity.noContent().build(); + } + + @GetMapping("/summary") + public ResponseEntity getSummary() { + return ResponseEntity.ok(analyticsService.getSummary()); + } +} diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Request/AnalyticsRequest.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Request/AnalyticsRequest.java new file mode 100644 index 0000000..07d1676 --- /dev/null +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Request/AnalyticsRequest.java @@ -0,0 +1,27 @@ +package com.weekfourassignment.AnalyticsAPI.dto.Request; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.OffsetDateTime; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class AnalyticsRequest { + + @NotNull + private OffsetDateTime timestamp; + + @NotBlank + private String eventType; + + @NotBlank + private String eventSource; + + @NotBlank + private String sessionId; +} diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Response/AnalyticsResponse.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Response/AnalyticsResponse.java new file mode 100644 index 0000000..f922861 --- /dev/null +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Response/AnalyticsResponse.java @@ -0,0 +1,19 @@ +package com.weekfourassignment.AnalyticsAPI.dto.Response; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.OffsetDateTime; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class AnalyticsResponse { + + private String id; + private OffsetDateTime timestamp; + private String eventType; + private String eventSource; + private String sessionId; +} diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java new file mode 100644 index 0000000..b320784 --- /dev/null +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java @@ -0,0 +1,17 @@ +package com.weekfourassignment.AnalyticsAPI.dto.Summary; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.Map; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class AnalyticsSummary { + + private long totalRecords; + private Map totalsByEventType; + private long uniqueSessions; +} diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/GlobalExceptionHandler.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/GlobalExceptionHandler.java new file mode 100644 index 0000000..bdde8bd --- /dev/null +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/GlobalExceptionHandler.java @@ -0,0 +1,91 @@ +package com.weekfourassignment.AnalyticsAPI.exceptions; + +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.ConstraintViolationException; +import org.springframework.http.converter.HttpMessageNotReadableException; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; + +import java.time.OffsetDateTime; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Collectors; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + @ExceptionHandler(ResourceNotFoundException.class) + public ResponseEntity> handleResourceNotFound( + ResourceNotFoundException exception, + HttpServletRequest request + ) { + return buildErrorResponse(HttpStatus.NOT_FOUND, exception.getMessage(), request.getRequestURI()); + } + + @ExceptionHandler(MethodArgumentNotValidException.class) + public ResponseEntity> handleValidationErrors( + MethodArgumentNotValidException exception, + HttpServletRequest request + ) { + String message = exception.getBindingResult().getFieldErrors().stream() + .map(error -> error.getField() + " " + error.getDefaultMessage()) + .collect(Collectors.joining(", ")); + + if (message.isBlank()) { + message = "Validation failed"; + } + + return buildErrorResponse(HttpStatus.BAD_REQUEST, message, request.getRequestURI()); + } + + @ExceptionHandler(ConstraintViolationException.class) + public ResponseEntity> handleConstraintViolations( + ConstraintViolationException exception, + HttpServletRequest request + ) { + String message = exception.getConstraintViolations().stream() + .map(violation -> violation.getPropertyPath() + " " + violation.getMessage()) + .collect(Collectors.joining(", ")); + + if (message.isBlank()) { + message = "Validation failed"; + } + + return buildErrorResponse(HttpStatus.BAD_REQUEST, message, request.getRequestURI()); + } + + @ExceptionHandler({IllegalArgumentException.class, MethodArgumentTypeMismatchException.class}) + public ResponseEntity> handleBadRequest(RuntimeException exception, HttpServletRequest request) { + return buildErrorResponse(HttpStatus.BAD_REQUEST, exception.getMessage(), request.getRequestURI()); + } + + @ExceptionHandler(HttpMessageNotReadableException.class) + public ResponseEntity> handleUnreadableMessage( + HttpMessageNotReadableException exception, + HttpServletRequest request + ) { + String message = "Invalid timestamp format. Use ISO-8601 format like 2026-05-28T10:05:30Z."; + + return buildErrorResponse(HttpStatus.BAD_REQUEST, message, request.getRequestURI()); + } + + @ExceptionHandler(Exception.class) + public ResponseEntity> handleUnexpected(Exception exception, HttpServletRequest request) { + return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred", request.getRequestURI()); + } + + private ResponseEntity> buildErrorResponse(HttpStatus status, String message, String path) { + Map body = new LinkedHashMap<>(); + body.put("timestamp", OffsetDateTime.now()); + body.put("status", status.value()); + body.put("error", status.getReasonPhrase()); + body.put("message", message); + body.put("path", path); + + return ResponseEntity.status(status).body(body); + } +} diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/ResourceNotFoundException.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/ResourceNotFoundException.java new file mode 100644 index 0000000..61b804c --- /dev/null +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/ResourceNotFoundException.java @@ -0,0 +1,8 @@ +package com.weekfourassignment.AnalyticsAPI.exceptions; + +public class ResourceNotFoundException extends RuntimeException { + + public ResourceNotFoundException(String message) { + super(message); + } +} diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/model/AnalyticsRecord.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/model/AnalyticsRecord.java new file mode 100644 index 0000000..f760056 --- /dev/null +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/model/AnalyticsRecord.java @@ -0,0 +1,19 @@ +package com.weekfourassignment.AnalyticsAPI.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.OffsetDateTime; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class AnalyticsRecord { + + private String id; + private OffsetDateTime timestamp; + private String eventType; + private String eventSource; + private String sessionId; +} \ No newline at end of file diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java new file mode 100644 index 0000000..eba07f4 --- /dev/null +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java @@ -0,0 +1,142 @@ +package com.weekfourassignment.AnalyticsAPI.services; + +import com.weekfourassignment.AnalyticsAPI.dto.Request.AnalyticsRequest; +import com.weekfourassignment.AnalyticsAPI.dto.Response.AnalyticsResponse; +import com.weekfourassignment.AnalyticsAPI.dto.Summary.AnalyticsSummary; +import com.weekfourassignment.AnalyticsAPI.exceptions.ResourceNotFoundException; +import com.weekfourassignment.AnalyticsAPI.model.AnalyticsRecord; +import org.springframework.stereotype.Service; + +import java.time.OffsetDateTime; +import java.util.Collection; +import java.util.Comparator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Collectors; + +@Service +public class AnalyticsService { + + private final Map records = new ConcurrentHashMap<>(); + private final AtomicLong traceSequence = new AtomicLong(0L); + + public AnalyticsResponse createRecord(AnalyticsRequest request) { + AnalyticsRecord record = toRecord(generateId(), request); + records.put(record.getId(), record); + return toResponse(record); + } + + public List getRecords(String eventType, String eventSource, String sessionId, + OffsetDateTime startTime, OffsetDateTime endTime) { + validateTimeRange(startTime, endTime); + + return records.values().stream() + .filter(record -> matchesTextFilter(record.getEventType(), eventType)) + .filter(record -> matchesTextFilter(record.getEventSource(), eventSource)) + .filter(record -> matchesTextFilter(record.getSessionId(), sessionId)) + .filter(record -> matchesStartTime(record.getTimestamp(), startTime)) + .filter(record -> matchesEndTime(record.getTimestamp(), endTime)) + .sorted(Comparator.comparing(AnalyticsRecord::getTimestamp).reversed() + .thenComparing(AnalyticsRecord::getId)) + .map(this::toResponse) + .collect(Collectors.toList()); + } + + public AnalyticsResponse getRecordById(String id) { + return toResponse(findRecord(id)); + } + + public AnalyticsResponse replaceRecord(String id, AnalyticsRequest request) { + if (!records.containsKey(id)) { + throw new ResourceNotFoundException("Analytics record not found with id: " + id); + } + + AnalyticsRecord updatedRecord = toRecord(id, request); + records.put(id, updatedRecord); + return toResponse(updatedRecord); + } + + public void deleteRecord(String id) { + AnalyticsRecord removed = records.remove(id); + if (removed == null) { + throw new ResourceNotFoundException("Analytics record not found with id: " + id); + } + } + + public AnalyticsSummary getSummary() { + Collection currentRecords = records.values(); + + Map totalsByEventType = currentRecords.stream() + .collect(Collectors.groupingBy( + AnalyticsRecord::getEventType, + LinkedHashMap::new, + Collectors.counting())); + + long uniqueSessions = currentRecords.stream() + .map(AnalyticsRecord::getSessionId) + .filter(Objects::nonNull) + .distinct() + .count(); + + return new AnalyticsSummary(currentRecords.size(), totalsByEventType, uniqueSessions); + } + + private AnalyticsRecord findRecord(String id) { + AnalyticsRecord record = records.get(id); + if (record == null) { + throw new ResourceNotFoundException("Analytics record not found with id: " + id); + } + return record; + } + + private AnalyticsRecord toRecord(String id, AnalyticsRequest request) { + return new AnalyticsRecord( + id, + request.getTimestamp(), + request.getEventType(), + request.getEventSource(), + request.getSessionId() + ); + } + + private AnalyticsResponse toResponse(AnalyticsRecord record) { + return new AnalyticsResponse( + record.getId(), + record.getTimestamp(), + record.getEventType(), + record.getEventSource(), + record.getSessionId() + ); + } + + private String generateId() { + long sequence = traceSequence.incrementAndGet(); + return "trace_" + sequence + "_" + UUID.randomUUID().toString().replace("-", ""); + } + + private boolean matchesTextFilter(String value, String filter) { + if (filter == null || filter.isBlank()) { + return true; + } + return value != null && value.equals(filter.trim()); + } + + private boolean matchesStartTime(OffsetDateTime timestamp, OffsetDateTime startTime) { + return startTime == null || !timestamp.isBefore(startTime); + } + + private boolean matchesEndTime(OffsetDateTime timestamp, OffsetDateTime endTime) { + return endTime == null || !timestamp.isAfter(endTime); + } + + private void validateTimeRange(OffsetDateTime startTime, OffsetDateTime endTime) { + if (startTime != null && endTime != null && startTime.isAfter(endTime)) { + throw new IllegalArgumentException("startTime must be less than or equal to endTime"); + } + } +} diff --git a/task-1/AnalyticsAPI/src/main/resources/application.yaml b/task-1/AnalyticsAPI/src/main/resources/application.yaml new file mode 100644 index 0000000..d1a18fb --- /dev/null +++ b/task-1/AnalyticsAPI/src/main/resources/application.yaml @@ -0,0 +1,3 @@ +spring: + application: + name: AnalyticsAPI diff --git a/task-1/AnalyticsAPI/src/test/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplicationTests.java b/task-1/AnalyticsAPI/src/test/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplicationTests.java new file mode 100644 index 0000000..f44b892 --- /dev/null +++ b/task-1/AnalyticsAPI/src/test/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplicationTests.java @@ -0,0 +1,164 @@ +package com.weekfourassignment.AnalyticsAPI; + +import com.weekfourassignment.AnalyticsAPI.dto.Request.AnalyticsRequest; +import com.weekfourassignment.AnalyticsAPI.dto.Response.AnalyticsResponse; +import com.weekfourassignment.AnalyticsAPI.dto.Summary.AnalyticsSummary; +import com.weekfourassignment.AnalyticsAPI.exceptions.ResourceNotFoundException; +import com.weekfourassignment.AnalyticsAPI.services.AnalyticsService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +import java.time.OffsetDateTime; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@SpringBootTest +class AnalyticsApiApplicationTests { + + private AnalyticsService analyticsService; + + @BeforeEach + void setUp() { + analyticsService = new AnalyticsService(); + } + + @Test + void contextLoads() { + } + + @Test + void createRecordStoresAndReturnsGeneratedId() { + AnalyticsResponse response = analyticsService.createRecord(request( + "2026-05-28T10:15:30Z", + "page_view", + "web", + "sess-1" + )); + + assertTrue(response.getId().startsWith("trace_")); + assertEquals(OffsetDateTime.parse("2026-05-28T10:15:30Z"), response.getTimestamp()); + assertEquals("page_view", response.getEventType()); + assertEquals("web", response.getEventSource()); + assertEquals("sess-1", response.getSessionId()); + assertEquals(response, analyticsService.getRecordById(response.getId())); + } + + @Test + void getRecordsFiltersByTypeSourceSessionAndTimeRange() { + analyticsService.createRecord(request("2026-05-28T08:00:00Z", "page_view", "web", "sess-1")); + analyticsService.createRecord(request("2026-05-28T09:00:00Z", "click", "web", "sess-1")); + analyticsService.createRecord(request("2026-05-28T10:00:00Z", "page_view", "mobile", "sess-2")); + + List filtered = analyticsService.getRecords( + "page_view", + "web", + "sess-1", + OffsetDateTime.parse("2026-05-28T07:30:00Z"), + OffsetDateTime.parse("2026-05-28T08:30:00Z") + ); + + assertEquals(1, filtered.size()); + assertEquals("page_view", filtered.get(0).getEventType()); + assertEquals("web", filtered.get(0).getEventSource()); + assertEquals("sess-1", filtered.get(0).getSessionId()); + } + + @Test + void getRecordByIdThrowsWhenMissing() { + assertThrows(ResourceNotFoundException.class, () -> analyticsService.getRecordById("missing")); + } + + @Test + void replaceRecordFullyOverwritesExistingRecord() { + AnalyticsResponse created = analyticsService.createRecord(request( + "2026-05-28T10:15:30Z", + "page_view", + "web", + "sess-1" + )); + + AnalyticsResponse updated = analyticsService.replaceRecord(created.getId(), request( + "2026-05-28T12:00:00Z", + "click", + "mobile", + "sess-2" + )); + + assertEquals(created.getId(), updated.getId()); + assertEquals(OffsetDateTime.parse("2026-05-28T12:00:00Z"), updated.getTimestamp()); + assertEquals("click", updated.getEventType()); + assertEquals("mobile", updated.getEventSource()); + assertEquals("sess-2", updated.getSessionId()); + } + + @Test + void deleteRecordRemovesRecordAndThrowsWhenMissing() { + AnalyticsResponse created = analyticsService.createRecord(request( + "2026-05-28T10:15:30Z", + "page_view", + "web", + "sess-1" + )); + + analyticsService.deleteRecord(created.getId()); + + assertThrows(ResourceNotFoundException.class, () -> analyticsService.getRecordById(created.getId())); + assertThrows(ResourceNotFoundException.class, () -> analyticsService.deleteRecord(created.getId())); + } + + @Test + void getSummaryCountsTotalRecordsEventTypesAndUniqueSessions() { + analyticsService.createRecord(request("2026-05-28T08:00:00Z", "page_view", "web", "sess-1")); + analyticsService.createRecord(request("2026-05-28T09:00:00Z", "page_view", "mobile", "sess-1")); + analyticsService.createRecord(request("2026-05-28T10:00:00Z", "click", "web", "sess-2")); + + AnalyticsSummary summary = analyticsService.getSummary(); + + assertEquals(3L, summary.getTotalRecords()); + assertEquals(2L, summary.getTotalsByEventType().get("page_view")); + assertEquals(1L, summary.getTotalsByEventType().get("click")); + assertEquals(2L, summary.getUniqueSessions()); + } + + @Test + void getRecordsRejectsInvalidTimeRange() { + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> + analyticsService.getRecords( + null, + null, + null, + OffsetDateTime.parse("2026-05-28T12:00:00Z"), + OffsetDateTime.parse("2026-05-28T10:00:00Z") + ) + ); + + assertTrue(exception.getMessage().contains("startTime")); + } + + @Test + void getRecordsReturnsAllWhenNoFiltersAreProvided() { + analyticsService.createRecord(request("2026-05-28T08:00:00Z", "page_view", "web", "sess-1")); + analyticsService.createRecord(request("2026-05-28T09:00:00Z", "click", "web", "sess-2")); + + List allRecords = analyticsService.getRecords(null, null, null, null, null); + + assertEquals(2, allRecords.size()); + assertFalse(allRecords.get(0).getId().isBlank()); + assertFalse(allRecords.get(1).getId().isBlank()); + } + + private AnalyticsRequest request(String timestamp, String eventType, String eventSource, String sessionId) { + return new AnalyticsRequest( + OffsetDateTime.parse(timestamp), + eventType, + eventSource, + sessionId + ); + } + +} From bd97f53a4ae909922f46954a449bbc1c6befcf97 Mon Sep 17 00:00:00 2001 From: Miuroro Date: Thu, 28 May 2026 23:22:30 +0200 Subject: [PATCH 2/8] removed unused empty test package folders for services and exceptions --- .../AnalyticsApiApplicationTests.java | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/task-1/AnalyticsAPI/src/test/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplicationTests.java b/task-1/AnalyticsAPI/src/test/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplicationTests.java index f44b892..1cc2219 100644 --- a/task-1/AnalyticsAPI/src/test/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplicationTests.java +++ b/task-1/AnalyticsAPI/src/test/java/com/weekfourassignment/AnalyticsAPI/AnalyticsApiApplicationTests.java @@ -96,6 +96,14 @@ void replaceRecordFullyOverwritesExistingRecord() { assertEquals("sess-2", updated.getSessionId()); } + @Test + void replaceRecordThrowsWhenRecordDoesNotExist() { + assertThrows(ResourceNotFoundException.class, () -> analyticsService.replaceRecord( + "missing", + request("2026-05-28T12:00:00Z", "click", "mobile", "sess-2") + )); + } + @Test void deleteRecordRemovesRecordAndThrowsWhenMissing() { AnalyticsResponse created = analyticsService.createRecord(request( @@ -125,6 +133,26 @@ void getSummaryCountsTotalRecordsEventTypesAndUniqueSessions() { assertEquals(2L, summary.getUniqueSessions()); } + @Test + void getSummaryReturnsZeroesWhenNoRecordsExist() { + AnalyticsSummary summary = analyticsService.getSummary(); + + assertEquals(0L, summary.getTotalRecords()); + assertTrue(summary.getTotalsByEventType().isEmpty()); + assertEquals(0L, summary.getUniqueSessions()); + } + + @Test + void getSummaryIgnoresNullSessionIdsWhenCountingUniqueSessions() { + analyticsService.createRecord(request("2026-05-28T08:00:00Z", "page_view", "web", null)); + analyticsService.createRecord(request("2026-05-28T09:00:00Z", "page_view", "mobile", "sess-1")); + analyticsService.createRecord(request("2026-05-28T10:00:00Z", "click", "web", null)); + + AnalyticsSummary summary = analyticsService.getSummary(); + + assertEquals(1L, summary.getUniqueSessions()); + } + @Test void getRecordsRejectsInvalidTimeRange() { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> @@ -152,6 +180,53 @@ void getRecordsReturnsAllWhenNoFiltersAreProvided() { assertFalse(allRecords.get(1).getId().isBlank()); } + @Test + void getRecordsIncludesValuesEqualToTimeBoundaries() { + analyticsService.createRecord(request("2026-05-28T10:00:00Z", "page_view", "web", "sess-1")); + analyticsService.createRecord(request("2026-05-28T11:00:00Z", "page_view", "web", "sess-1")); + analyticsService.createRecord(request("2026-05-28T12:00:00Z", "page_view", "web", "sess-1")); + + List filtered = analyticsService.getRecords( + null, + null, + null, + OffsetDateTime.parse("2026-05-28T11:00:00Z"), + OffsetDateTime.parse("2026-05-28T12:00:00Z") + ); + + assertEquals(2, filtered.size()); + assertEquals(OffsetDateTime.parse("2026-05-28T12:00:00Z"), filtered.get(0).getTimestamp()); + assertEquals(OffsetDateTime.parse("2026-05-28T11:00:00Z"), filtered.get(1).getTimestamp()); + } + + @Test + void getRecordsTrimsFilterValuesAndTreatsBlankAsNoFilter() { + analyticsService.createRecord(request("2026-05-28T08:00:00Z", "page_view", "web", "sess-1")); + analyticsService.createRecord(request("2026-05-28T09:00:00Z", "click", "mobile", "sess-2")); + + List trimmedMatch = analyticsService.getRecords(" page_view ", " web ", " sess-1 ", null, null); + List blankFilters = analyticsService.getRecords(" ", "\t", "\n", null, null); + + assertEquals(1, trimmedMatch.size()); + assertEquals("page_view", trimmedMatch.get(0).getEventType()); + assertEquals(2, blankFilters.size()); + } + + @Test + void getRecordsOrdersByTimestampDescendingThenIdAscending() { + analyticsService.createRecord(request("2026-05-28T10:00:00Z", "page_view", "web", "sess-1")); + analyticsService.createRecord(request("2026-05-28T10:00:00Z", "click", "web", "sess-2")); + analyticsService.createRecord(request("2026-05-28T09:00:00Z", "purchase", "mobile", "sess-3")); + + List allRecords = analyticsService.getRecords(null, null, null, null, null); + + assertEquals(3, allRecords.size()); + assertEquals(OffsetDateTime.parse("2026-05-28T10:00:00Z"), allRecords.get(0).getTimestamp()); + assertEquals(OffsetDateTime.parse("2026-05-28T10:00:00Z"), allRecords.get(1).getTimestamp()); + assertTrue(allRecords.get(0).getId().compareTo(allRecords.get(1).getId()) < 0); + assertEquals(OffsetDateTime.parse("2026-05-28T09:00:00Z"), allRecords.get(2).getTimestamp()); + } + private AnalyticsRequest request(String timestamp, String eventType, String eventSource, String sessionId) { return new AnalyticsRequest( OffsetDateTime.parse(timestamp), From 9de4fefed0b3f9afb082865bd0bff1d43ec29bd4 Mon Sep 17 00:00:00 2001 From: Miuroro Date: Wed, 3 Jun 2026 11:49:41 +0200 Subject: [PATCH 3/8] renamed record variables to avoid Java keyword confusion --- .../services/AnalyticsService.java | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java index eba07f4..d2d127c 100644 --- a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java @@ -26,9 +26,9 @@ public class AnalyticsService { private final AtomicLong traceSequence = new AtomicLong(0L); public AnalyticsResponse createRecord(AnalyticsRequest request) { - AnalyticsRecord record = toRecord(generateId(), request); - records.put(record.getId(), record); - return toResponse(record); + AnalyticsRecord aRecord = toRecord(generateId(), request); + records.put(aRecord.getId(), aRecord); + return toResponse(aRecord); } public List getRecords(String eventType, String eventSource, String sessionId, @@ -87,11 +87,11 @@ public AnalyticsSummary getSummary() { } private AnalyticsRecord findRecord(String id) { - AnalyticsRecord record = records.get(id); - if (record == null) { + AnalyticsRecord aRecord = records.get(id); + if (aRecord == null) { throw new ResourceNotFoundException("Analytics record not found with id: " + id); } - return record; + return aRecord; } private AnalyticsRecord toRecord(String id, AnalyticsRequest request) { @@ -104,13 +104,13 @@ private AnalyticsRecord toRecord(String id, AnalyticsRequest request) { ); } - private AnalyticsResponse toResponse(AnalyticsRecord record) { + private AnalyticsResponse toResponse(AnalyticsRecord aRecord) { return new AnalyticsResponse( - record.getId(), - record.getTimestamp(), - record.getEventType(), - record.getEventSource(), - record.getSessionId() + aRecord.getId(), + aRecord.getTimestamp(), + aRecord.getEventType(), + aRecord.getEventSource(), + aRecord.getSessionId() ); } From 4ca27e616337176c111b8dd8ab118d6e3a8ff853 Mon Sep 17 00:00:00 2001 From: Miuroro Date: Wed, 3 Jun 2026 11:56:53 +0200 Subject: [PATCH 4/8] edited line 47 in AnalyticsService.java to make the list immutable --- .../AnalyticsAPI/services/AnalyticsService.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java index d2d127c..9011f9b 100644 --- a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/services/AnalyticsService.java @@ -44,7 +44,7 @@ public List getRecords(String eventType, String eventSource, .sorted(Comparator.comparing(AnalyticsRecord::getTimestamp).reversed() .thenComparing(AnalyticsRecord::getId)) .map(this::toResponse) - .collect(Collectors.toList()); + .toList(); } public AnalyticsResponse getRecordById(String id) { From 5a9b5481dea1fd58e0fa6f314d330e8f602b13b1 Mon Sep 17 00:00:00 2001 From: Miuroro Date: Wed, 3 Jun 2026 12:15:09 +0200 Subject: [PATCH 5/8] fix:accept both startTime and startDate query params --- .../controllers/AnalyticsController.java | 28 +++++++++++++++++-- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java index a7d8038..5da484c 100644 --- a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java @@ -39,12 +39,19 @@ public ResponseEntity> getRecords( @RequestParam(required = false) String eventType, @RequestParam(required = false) String eventSource, @RequestParam(required = false) String sessionId, - @RequestParam(required = false) + @RequestParam(name = "startTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime startTime, - @RequestParam(required = false) + @RequestParam(name = "startDate", required = false) + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime startDate, + @RequestParam(name = "endTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime endTime + @RequestParam(name = "endDate", required = false) + @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime endDate ) { - return ResponseEntity.ok(analyticsService.getRecords(eventType, eventSource, sessionId, startTime, endTime)); + OffsetDateTime effectiveStartTime = resolveTimestamp(startTime, startDate, "startTime", "startDate"); + OffsetDateTime effectiveEndTime = resolveTimestamp(endTime, endDate, "endTime", "endDate"); + + return ResponseEntity.ok(analyticsService.getRecords(eventType, eventSource, sessionId, effectiveStartTime, effectiveEndTime)); } @GetMapping("/{id}") @@ -70,4 +77,19 @@ public ResponseEntity deleteRecord(@PathVariable String id) { public ResponseEntity getSummary() { return ResponseEntity.ok(analyticsService.getSummary()); } + + private OffsetDateTime resolveTimestamp( + OffsetDateTime primaryValue, + OffsetDateTime aliasValue, + String primaryName, + String aliasName + ) { + if (primaryValue == null) { + return aliasValue; + } + if (aliasValue == null || primaryValue.equals(aliasValue)) { + return primaryValue; + } + throw new IllegalArgumentException(primaryName + " and " + aliasName + " cannot both be provided with different values"); + } } From 9dc57a3c459ac8c2894c56403487b6bef87d500a Mon Sep 17 00:00:00 2001 From: Miuroro Date: Wed, 3 Jun 2026 12:19:25 +0200 Subject: [PATCH 6/8] removed unnecessary @NoArgsConstructor from analytics summary --- .../AnalyticsAPI/dto/Summary/AnalyticsSummary.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java index b320784..2ebaf45 100644 --- a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java @@ -2,12 +2,10 @@ import lombok.AllArgsConstructor; import lombok.Data; -import lombok.NoArgsConstructor; import java.util.Map; @Data -@NoArgsConstructor @AllArgsConstructor public class AnalyticsSummary { From 6d31abf0128cd8bf1bc05548bc0983349c6905e0 Mon Sep 17 00:00:00 2001 From: Miuroro Date: Wed, 3 Jun 2026 12:27:56 +0200 Subject: [PATCH 7/8] simplified analytics summary to use required-args constructor and removed @AllArgsConstructor --- .../AnalyticsAPI/dto/Summary/AnalyticsSummary.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java index 2ebaf45..4da4c3c 100644 --- a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/dto/Summary/AnalyticsSummary.java @@ -1,15 +1,13 @@ package com.weekfourassignment.AnalyticsAPI.dto.Summary; -import lombok.AllArgsConstructor; import lombok.Data; import java.util.Map; @Data -@AllArgsConstructor public class AnalyticsSummary { - private long totalRecords; - private Map totalsByEventType; - private long uniqueSessions; + private final long totalRecords; + private final Map totalsByEventType; + private final long uniqueSessions; } From b93f1212b498349044523d2d4d243cca2457cf69 Mon Sep 17 00:00:00 2001 From: Miuroro Date: Wed, 3 Jun 2026 12:47:06 +0200 Subject: [PATCH 8/8] aligned analytics API contract, improved error handling, and standardized string-based responses --- .../controllers/AnalyticsController.java | 24 +----------- .../exceptions/GlobalExceptionHandler.java | 38 ++++++++++++------- 2 files changed, 25 insertions(+), 37 deletions(-) diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java index 5da484c..af5142b 100644 --- a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/controllers/AnalyticsController.java @@ -41,17 +41,10 @@ public ResponseEntity> getRecords( @RequestParam(required = false) String sessionId, @RequestParam(name = "startTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime startTime, - @RequestParam(name = "startDate", required = false) - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime startDate, @RequestParam(name = "endTime", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime endTime - @RequestParam(name = "endDate", required = false) - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) OffsetDateTime endDate ) { - OffsetDateTime effectiveStartTime = resolveTimestamp(startTime, startDate, "startTime", "startDate"); - OffsetDateTime effectiveEndTime = resolveTimestamp(endTime, endDate, "endTime", "endDate"); - - return ResponseEntity.ok(analyticsService.getRecords(eventType, eventSource, sessionId, effectiveStartTime, effectiveEndTime)); + return ResponseEntity.ok(analyticsService.getRecords(eventType, eventSource, sessionId, startTime, endTime)); } @GetMapping("/{id}") @@ -77,19 +70,4 @@ public ResponseEntity deleteRecord(@PathVariable String id) { public ResponseEntity getSummary() { return ResponseEntity.ok(analyticsService.getSummary()); } - - private OffsetDateTime resolveTimestamp( - OffsetDateTime primaryValue, - OffsetDateTime aliasValue, - String primaryName, - String aliasName - ) { - if (primaryValue == null) { - return aliasValue; - } - if (aliasValue == null || primaryValue.equals(aliasValue)) { - return primaryValue; - } - throw new IllegalArgumentException(primaryName + " and " + aliasName + " cannot both be provided with different values"); - } } diff --git a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/GlobalExceptionHandler.java b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/GlobalExceptionHandler.java index bdde8bd..eaff17d 100644 --- a/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/GlobalExceptionHandler.java +++ b/task-1/AnalyticsAPI/src/main/java/com/weekfourassignment/AnalyticsAPI/exceptions/GlobalExceptionHandler.java @@ -11,7 +11,6 @@ import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import java.time.OffsetDateTime; -import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; @@ -19,7 +18,7 @@ public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) - public ResponseEntity> handleResourceNotFound( + public ResponseEntity> handleResourceNotFound( ResourceNotFoundException exception, HttpServletRequest request ) { @@ -27,7 +26,7 @@ public ResponseEntity> handleResourceNotFound( } @ExceptionHandler(MethodArgumentNotValidException.class) - public ResponseEntity> handleValidationErrors( + public ResponseEntity> handleValidationErrors( MethodArgumentNotValidException exception, HttpServletRequest request ) { @@ -43,7 +42,7 @@ public ResponseEntity> handleValidationErrors( } @ExceptionHandler(ConstraintViolationException.class) - public ResponseEntity> handleConstraintViolations( + public ResponseEntity> handleConstraintViolations( ConstraintViolationException exception, HttpServletRequest request ) { @@ -59,12 +58,12 @@ public ResponseEntity> handleConstraintViolations( } @ExceptionHandler({IllegalArgumentException.class, MethodArgumentTypeMismatchException.class}) - public ResponseEntity> handleBadRequest(RuntimeException exception, HttpServletRequest request) { + public ResponseEntity> handleBadRequest(RuntimeException exception, HttpServletRequest request) { return buildErrorResponse(HttpStatus.BAD_REQUEST, exception.getMessage(), request.getRequestURI()); } @ExceptionHandler(HttpMessageNotReadableException.class) - public ResponseEntity> handleUnreadableMessage( + public ResponseEntity> handleUnreadableMessage( HttpMessageNotReadableException exception, HttpServletRequest request ) { @@ -74,18 +73,29 @@ public ResponseEntity> handleUnreadableMessage( } @ExceptionHandler(Exception.class) - public ResponseEntity> handleUnexpected(Exception exception, HttpServletRequest request) { + public ResponseEntity> handleUnexpected(Exception exception, HttpServletRequest request) { return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred", request.getRequestURI()); } - private ResponseEntity> buildErrorResponse(HttpStatus status, String message, String path) { - Map body = new LinkedHashMap<>(); - body.put("timestamp", OffsetDateTime.now()); - body.put("status", status.value()); - body.put("error", status.getReasonPhrase()); - body.put("message", message); - body.put("path", path); + private ResponseEntity> buildErrorResponse(HttpStatus status, String message, String path) { + String safeMessage = normalizeText(message, status.getReasonPhrase()); + String safePath = normalizeText(path, "/"); + + Map body = Map.of( + "timestamp", OffsetDateTime.now().toString(), + "status", Integer.toString(status.value()), + "error", status.getReasonPhrase(), + "message", safeMessage, + "path", safePath + ); return ResponseEntity.status(status).body(body); } + + private String normalizeText(String value, String fallback) { + if (value == null || value.isBlank()) { + return fallback; + } + return value; + } }