From 62a48aefff16423b7829e64ee18cd81916a6b351 Mon Sep 17 00:00:00 2001 From: Shadi Date: Thu, 28 May 2026 16:08:42 +0200 Subject: [PATCH 01/10] Added initial API design document for analytics records API. --- task-1/analyticsapi/API_DESIGN.md | 650 ++++++++++++++++++++++++++++++ 1 file changed, 650 insertions(+) create mode 100644 task-1/analyticsapi/API_DESIGN.md diff --git a/task-1/analyticsapi/API_DESIGN.md b/task-1/analyticsapi/API_DESIGN.md new file mode 100644 index 0000000..1ed08b1 --- /dev/null +++ b/task-1/analyticsapi/API_DESIGN.md @@ -0,0 +1,650 @@ +# Analytics API Design + +## 1. Overview + +This API stores and manages privacy-respecting analytics records. + +An analytics record represents one anonymized event from an application, such as a button click, page view, search action, or form submission. + +The API stores data in memory using Java collections. No database is used in this version. + +The API does not store personal data such as names, emails, raw user IDs, account IDs, or IP addresses. + +--- + +## 2. Base URI + +```http +/api/v1/analytics-records +``` + +--- + +## 3. Main Resource + +The main resource is an **analytics record**. + +Each analytics record contains: + +| Field | Type | Description | +| ------------------- | ------------- | -------------------------------------------- | +| traceId | String | Server-generated unique record ID | +| eventType | String | Type of event, for example `BUTTON_CLICK` | +| eventSource | String | Source of the event, for example `HOME_PAGE` | +| anonymizedSessionId | String | Anonymous session identifier | +| timestamp | LocalDateTime | Time when the event occurred | + +--- + +## 4. Example Analytics Record Response + +```json +{ + "traceId": "8f5a2d10-91b7-4f7c-8b62-57e8b2e4f100", + "eventType": "BUTTON_CLICK", + "eventSource": "HOME_PAGE", + "anonymizedSessionId": "session-12345", + "timestamp": "2026-05-28T14:30:00" +} +``` + +--- + +# 5. Endpoints + +## 5.1 Create Analytics Record + +### Method and URI + +```http +POST /api/v1/analytics-records +``` + +### Description + +Creates a new analytics record. + +The client sends the event type, event source, anonymized session ID, and timestamp. +The server generates the `traceId`. + +### Request Body + +```json +{ + "eventType": "BUTTON_CLICK", + "eventSource": "HOME_PAGE", + "anonymizedSessionId": "session-12345", + "timestamp": "2026-05-28T14:30:00" +} +``` + +### Success Response + +Status code: + +```http +201 Created +``` + +Response body: + +```json +{ + "traceId": "8f5a2d10-91b7-4f7c-8b62-57e8b2e4f100", + "eventType": "BUTTON_CLICK", + "eventSource": "HOME_PAGE", + "anonymizedSessionId": "session-12345", + "timestamp": "2026-05-28T14:30:00" +} +``` + +### Validation Rules + +| Field | Rule | +| ------------------- | --------------------------- | +| eventType | Required, must not be blank | +| eventSource | Required, must not be blank | +| anonymizedSessionId | Required, must not be blank | +| timestamp | Required | + +--- + +## 5.2 List Analytics Records + +### Method and URI + +```http +GET /api/v1/analytics-records +``` + +### Description + +Returns all stored analytics records. + +This endpoint also supports filtering. + +### Supported Query Parameters + +| Parameter | Type | Required | Description | +| ----------- | ------------- | -------- | -------------------------------- | +| eventType | String | No | Filters records by event type | +| eventSource | String | No | Filters records by event source | +| startTime | LocalDateTime | No | Includes records from this time | +| endTime | LocalDateTime | No | Includes records until this time | + +### Example Request + +```http +GET /api/v1/analytics-records?eventType=BUTTON_CLICK&eventSource=HOME_PAGE +``` + +### Example Time Filter Request + +```http +GET /api/v1/analytics-records?startTime=2026-05-28T00:00:00&endTime=2026-05-28T23:59:59 +``` + +### Success Response + +Status code: + +```http +200 OK +``` + +Response body: + +```json +[ + { + "traceId": "8f5a2d10-91b7-4f7c-8b62-57e8b2e4f100", + "eventType": "BUTTON_CLICK", + "eventSource": "HOME_PAGE", + "anonymizedSessionId": "session-12345", + "timestamp": "2026-05-28T14:30:00" + } +] +``` + +--- + +## 5.3 Get Analytics Record By Trace ID + +### Method and URI + +```http +GET /api/v1/analytics-records/{traceId} +``` + +### Description + +Returns one analytics record by its server-generated trace ID. + +### Example Request + +```http +GET /api/v1/analytics-records/8f5a2d10-91b7-4f7c-8b62-57e8b2e4f100 +``` + +### Success Response + +Status code: + +```http +200 OK +``` + +Response body: + +```json +{ + "traceId": "8f5a2d10-91b7-4f7c-8b62-57e8b2e4f100", + "eventType": "BUTTON_CLICK", + "eventSource": "HOME_PAGE", + "anonymizedSessionId": "session-12345", + "timestamp": "2026-05-28T14:30:00" +} +``` + +### Error Response + +If the record does not exist: + +```http +404 Not Found +``` + +```json +{ + "status": 404, + "message": "Analytics record not found", + "path": "/api/v1/analytics-records/8f5a2d10-91b7-4f7c-8b62-57e8b2e4f100" +} +``` + +--- + +## 5.4 Replace Analytics Record + +### Method and URI + +```http +PUT /api/v1/analytics-records/{traceId} +``` + +### Description + +Fully replaces an existing analytics record. + +The `traceId` stays the same because it identifies the existing record. + +### Request Body + +```json +{ + "eventType": "PAGE_VIEW", + "eventSource": "PRODUCT_PAGE", + "anonymizedSessionId": "session-99999", + "timestamp": "2026-05-28T15:00:00" +} +``` + +### Success Response + +Status code: + +```http +200 OK +``` + +Response body: + +```json +{ + "traceId": "8f5a2d10-91b7-4f7c-8b62-57e8b2e4f100", + "eventType": "PAGE_VIEW", + "eventSource": "PRODUCT_PAGE", + "anonymizedSessionId": "session-99999", + "timestamp": "2026-05-28T15:00:00" +} +``` + +### Validation Rules + +| Field | Rule | +| ------------------- | --------------------------- | +| eventType | Required, must not be blank | +| eventSource | Required, must not be blank | +| anonymizedSessionId | Required, must not be blank | +| timestamp | Required | + +### Error Response + +If the record does not exist: + +```http +404 Not Found +``` + +--- + +## 5.5 Delete Analytics Record + +### Method and URI + +```http +DELETE /api/v1/analytics-records/{traceId} +``` + +### Description + +Deletes one analytics record by trace ID. + +### Success Response + +Status code: + +```http +204 No Content +``` + +No response body. + +### Error Response + +If the record does not exist: + +```http +404 Not Found +``` + +--- + +## 5.6 Get Analytics Summary + +### Method and URI + +```http +GET /api/v1/analytics-records/summary +``` + +### Description + +Returns a simple summary of stored analytics records. + +The summary includes: + +* Total number of records +* Totals grouped by event type +* Number of unique anonymized sessions + +### Supported Query Parameters + +| Parameter | Type | Required | Description | +| ----------- | ------------- | -------- | ---------------------------------------- | +| startTime | LocalDateTime | No | Includes records from this time | +| endTime | LocalDateTime | No | Includes records until this time | +| eventSource | String | No | Summary only for a specific event source | + +### Example Request + +```http +GET /api/v1/analytics-records/summary +``` + +### Example Filtered Request + +```http +GET /api/v1/analytics-records/summary?startTime=2026-05-28T00:00:00&endTime=2026-05-28T23:59:59 +``` + +### Success Response + +Status code: + +```http +200 OK +``` + +Response body: + +```json +{ + "totalRecords": 3, + "totalsByEventType": { + "BUTTON_CLICK": 2, + "PAGE_VIEW": 1 + }, + "uniqueSessions": 2 +} +``` + +--- + +# 6. Error Handling + +The API returns clear error responses for invalid input and missing resources. + +## 6.1 Validation Error + +Status code: + +```http +400 Bad Request +``` + +Example response: + +```json +{ + "status": 400, + "message": "Validation failed", + "errors": { + "eventType": "Event type must not be blank", + "timestamp": "Timestamp is required" + } +} +``` + +--- + +## 6.2 Resource Not Found Error + +Status code: + +```http +404 Not Found +``` + +Example response: + +```json +{ + "status": 404, + "message": "Analytics record not found", + "path": "/api/v1/analytics-records/unknown-id" +} +``` + +--- + +## 6.3 Invalid Date Range Error + +Status code: + +```http +400 Bad Request +``` + +Example response: + +```json +{ + "status": 400, + "message": "startTime must be before endTime" +} +``` + +--- + +# 7. Privacy Rules + +The API must not store personal information. + +The following fields are not allowed: + +* Name +* Email address +* Raw user ID +* Account ID +* IP address + +The API uses `anonymizedSessionId` to count unique sessions without storing real user identity. + +--- + +# 8. DTOs + +## 8.1 CreateAnalyticsRecordRequest + +Used for: + +```http +POST /api/v1/analytics-records +``` + +Fields: + +| Field | Type | +| ------------------- | ------------- | +| eventType | String | +| eventSource | String | +| anonymizedSessionId | String | +| timestamp | LocalDateTime | + +--- + +## 8.2 ReplaceAnalyticsRecordRequest + +Used for: + +```http +PUT /api/v1/analytics-records/{traceId} +``` + +Fields: + +| Field | Type | +| ------------------- | ------------- | +| eventType | String | +| eventSource | String | +| anonymizedSessionId | String | +| timestamp | LocalDateTime | + +--- + +## 8.3 AnalyticsRecordResponse + +Used for returning analytics records. + +Fields: + +| Field | Type | +| ------------------- | ------------- | +| traceId | String | +| eventType | String | +| eventSource | String | +| anonymizedSessionId | String | +| timestamp | LocalDateTime | + +--- + +## 8.4 AnalyticsSummaryResponse + +Used for returning summary data. + +Fields: + +| Field | Type | +| ----------------- | -------------------- | +| totalRecords | int | +| totalsByEventType | Map | +| uniqueSessions | int | + +--- + +# 9. Service Layer Responsibilities + +The service layer contains the business logic. + +The controller should stay thin and only call service methods. + +The service should handle: + +* Creating records +* Generating trace IDs +* Storing records in memory +* Listing records +* Filtering records +* Finding records by trace ID +* Replacing records +* Deleting records +* Creating summary data +* Throwing exceptions when records are not found + +--- + +# 10. In-Memory Storage + +The API stores records in memory using Java collections. + +Recommended structure: + +```java +Map records = new HashMap<>(); +``` + +The key is the `traceId`. + +This makes finding, replacing, and deleting records by ID easier. + +--- + +# 11. Status Codes Summary + +| Action | Status Code | +| ---------------- | --------------- | +| Create record | 201 Created | +| List records | 200 OK | +| Get record by ID | 200 OK | +| Replace record | 200 OK | +| Delete record | 204 No Content | +| Validation error | 400 Bad Request | +| Record not found | 404 Not Found | + +--- + +# 12. Unit Testing Plan + +Unit tests will focus on the service layer. + +Tests should cover: + +* Creating a record generates a trace ID +* Listing records returns stored records +* Filtering by event type works +* Filtering by event source works +* Filtering by time range works +* Getting a record by trace ID works +* Getting a missing record throws an exception +* Replacing a record updates the stored data +* Deleting a record removes it +* Summary returns correct total records +* Summary groups records by event type +* Summary counts unique anonymized sessions correctly + +--- + +# 13. Example API Flow + +## Step 1: Create a record + +```http +POST /api/v1/analytics-records +``` + +## Step 2: List all records + +```http +GET /api/v1/analytics-records +``` + +## Step 3: Filter records + +```http +GET /api/v1/analytics-records?eventType=BUTTON_CLICK +``` + +## Step 4: Get one record + +```http +GET /api/v1/analytics-records/{traceId} +``` + +## Step 5: Replace one record + +```http +PUT /api/v1/analytics-records/{traceId} +``` + +## Step 6: Delete one record + +```http +DELETE /api/v1/analytics-records/{traceId} +``` + +## Step 7: Get summary + +```http +GET /api/v1/analytics-records/summary +``` From 1f30f4c644816ca777d097ccb188ac6ffebfdb3a Mon Sep 17 00:00:00 2001 From: Shadi Date: Thu, 28 May 2026 16:08:59 +0200 Subject: [PATCH 02/10] Initialize AnalyticsAPI project with Spring Boot, API models, DTOs, Maven wrapper, and application configuration files. --- task-1/analyticsapi/.gitattributes | 2 + task-1/analyticsapi/.gitignore | 33 ++ .../.mvn/wrapper/maven-wrapper.properties | 3 + task-1/analyticsapi/mvnw | 295 ++++++++++++++++++ task-1/analyticsapi/mvnw.cmd | 189 +++++++++++ task-1/analyticsapi/pom.xml | 117 +++++++ .../analyticsapi/AnalyticsApiApplication.java | 13 + .../dto/AnalyticsRecordResponse.java | 23 ++ .../dto/AnalyticsSummaryResponse.java | 23 ++ .../dto/CreateAnalyticsRecordRequest.java | 25 ++ .../analyticsapi/dto/ErrorResponse.java | 21 ++ .../dto/ReplaceAnalyticsRecordRequest.java | 25 ++ .../analyticsapi/model/AnalyticsRecord.java | 18 ++ .../src/main/resources/application.yaml | 3 + .../AnalyticsApiApplicationTests.java | 13 + 15 files changed, 803 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 100755 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/hackyourfuture/analyticsapi/AnalyticsApiApplication.java create mode 100644 task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/AnalyticsRecordResponse.java create mode 100644 task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/AnalyticsSummaryResponse.java create mode 100644 task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/CreateAnalyticsRecordRequest.java create mode 100644 task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/ErrorResponse.java create mode 100644 task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/ReplaceAnalyticsRecordRequest.java create mode 100644 task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/model/AnalyticsRecord.java create mode 100644 task-1/analyticsapi/src/main/resources/application.yaml create mode 100644 task-1/analyticsapi/src/test/java/com/hackyourfuture/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/mvnw b/task-1/analyticsapi/mvnw new file mode 100755 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..819a86e --- /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.hackyourfuture + 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/hackyourfuture/analyticsapi/AnalyticsApiApplication.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/AnalyticsApiApplication.java new file mode 100644 index 0000000..c9b2a65 --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/AnalyticsApiApplication.java @@ -0,0 +1,13 @@ +package com.hackyourfuture.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/hackyourfuture/analyticsapi/dto/AnalyticsRecordResponse.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/AnalyticsRecordResponse.java new file mode 100644 index 0000000..299b96b --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/AnalyticsRecordResponse.java @@ -0,0 +1,23 @@ +package com.hackyourfuture.analyticsapi.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class AnalyticsRecordResponse { + + private String traceId; + private String eventType; + private String eventSource; + private String anonymizedSessionId; + private LocalDateTime timestamp; +} \ No newline at end of file diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/AnalyticsSummaryResponse.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/AnalyticsSummaryResponse.java new file mode 100644 index 0000000..6081576 --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/AnalyticsSummaryResponse.java @@ -0,0 +1,23 @@ +package com.hackyourfuture.analyticsapi.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.Map; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class AnalyticsSummaryResponse { + + private int totalRecords; + + private Map totalsByEventType; + + private int uniqueSessions; +} \ No newline at end of file diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/CreateAnalyticsRecordRequest.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/CreateAnalyticsRecordRequest.java new file mode 100644 index 0000000..1c8e5c8 --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/CreateAnalyticsRecordRequest.java @@ -0,0 +1,25 @@ +package com.hackyourfuture.analyticsapi.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +public class CreateAnalyticsRecordRequest { + + @NotBlank(message = "Event type must not be blank") + private String eventType; + + @NotBlank(message = "Event source must not be blank") + private String eventSource; + + @NotBlank(message = "Anonymized session ID must not be blank") + private String anonymizedSessionId; + + @NotNull(message = "Timestamp is required") + private LocalDateTime timestamp; +} \ No newline at end of file diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/ErrorResponse.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/ErrorResponse.java new file mode 100644 index 0000000..c2e3f98 --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/ErrorResponse.java @@ -0,0 +1,21 @@ +package com.hackyourfuture.analyticsapi.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class ErrorResponse { + + private int status; + + private String message; + + private String path; +} \ No newline at end of file diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/ReplaceAnalyticsRecordRequest.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/ReplaceAnalyticsRecordRequest.java new file mode 100644 index 0000000..b8260a3 --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/dto/ReplaceAnalyticsRecordRequest.java @@ -0,0 +1,25 @@ +package com.hackyourfuture.analyticsapi.dto; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +public class ReplaceAnalyticsRecordRequest { + + @NotBlank(message = "Event type must not be blank") + private String eventType; + + @NotBlank(message = "Event source must not be blank") + private String eventSource; + + @NotBlank(message = "Anonymized session ID must not be blank") + private String anonymizedSessionId; + + @NotNull(message = "Timestamp is required") + private LocalDateTime timestamp; +} \ No newline at end of file diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/model/AnalyticsRecord.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/model/AnalyticsRecord.java new file mode 100644 index 0000000..6427d8e --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/model/AnalyticsRecord.java @@ -0,0 +1,18 @@ +package com.hackyourfuture.analyticsapi.model; + +import lombok.*; + +import java.time.LocalDateTime; + +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class AnalyticsRecord { + private String traceId; + private String eventType; + private String eventSource; + private String anonymizedSessionId; + private LocalDateTime timestamp; +} 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/hackyourfuture/analyticsapi/AnalyticsApiApplicationTests.java b/task-1/analyticsapi/src/test/java/com/hackyourfuture/analyticsapi/AnalyticsApiApplicationTests.java new file mode 100644 index 0000000..b760401 --- /dev/null +++ b/task-1/analyticsapi/src/test/java/com/hackyourfuture/analyticsapi/AnalyticsApiApplicationTests.java @@ -0,0 +1,13 @@ +package com.hackyourfuture.analyticsapi; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AnalyticsApiApplicationTests { + + @Test + void contextLoads() { + } + +} From f14935ce04e9b79463d3e29d5face1af297ae279 Mon Sep 17 00:00:00 2001 From: Shadi Date: Thu, 28 May 2026 18:49:18 +0200 Subject: [PATCH 03/10] Add custom exceptions for analytics record not found and invalid date range --- .../AnalyticsRecordNotFoundException.java | 15 +++++++++++++++ .../exception/InvalidDateRangeException.java | 14 ++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/AnalyticsRecordNotFoundException.java create mode 100644 task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/InvalidDateRangeException.java diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/AnalyticsRecordNotFoundException.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/AnalyticsRecordNotFoundException.java new file mode 100644 index 0000000..ce74038 --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/AnalyticsRecordNotFoundException.java @@ -0,0 +1,15 @@ +package com.hackyourfuture.analyticsapi.exception; + + + +public class AnalyticsRecordNotFoundException extends RuntimeException { + + /** + * Creates a new exception indicating that an analytics record could not be located. + * + * @param message a human-readable description of the missing record (typically including its trace ID) + */ + public AnalyticsRecordNotFoundException(String message) { + super(message); + } +} \ No newline at end of file diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/InvalidDateRangeException.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/InvalidDateRangeException.java new file mode 100644 index 0000000..bcea91c --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/InvalidDateRangeException.java @@ -0,0 +1,14 @@ +package com.hackyourfuture.analyticsapi.exception; + +public class InvalidDateRangeException extends RuntimeException { + + /** + * Creates a new exception indicating that a supplied date range is invalid + * (for example, the start time is after the end time). + * + * @param message a human-readable description of why the date range is invalid + */ + public InvalidDateRangeException(String message) { + super(message); + } +} \ No newline at end of file From 243bd18ba417bfc44b39f77169c323f392d35cc1 Mon Sep 17 00:00:00 2001 From: Shadi Date: Thu, 28 May 2026 18:49:36 +0200 Subject: [PATCH 04/10] Implement AnalyticsRecordService with CRUD operations, filtering, and summary generation --- .../service/AnalyticsRecordService.java | 215 ++++++++++++++++++ 1 file changed, 215 insertions(+) create mode 100644 task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordService.java diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordService.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordService.java new file mode 100644 index 0000000..213f03a --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordService.java @@ -0,0 +1,215 @@ +package com.hackyourfuture.analyticsapi.service; + + +import com.hackyourfuture.analyticsapi.dto.AnalyticsRecordResponse; +import com.hackyourfuture.analyticsapi.dto.AnalyticsSummaryResponse; +import com.hackyourfuture.analyticsapi.dto.CreateAnalyticsRecordRequest; +import com.hackyourfuture.analyticsapi.dto.ReplaceAnalyticsRecordRequest; +import com.hackyourfuture.analyticsapi.model.AnalyticsRecord; +import org.springframework.stereotype.Service; +import com.hackyourfuture.analyticsapi.exception.AnalyticsRecordNotFoundException; +import java.time.LocalDateTime; +import java.util.*; + +import com.hackyourfuture.analyticsapi.exception.InvalidDateRangeException; + +@Service +public class AnalyticsRecordService { + + private final Map records = new HashMap<>(); + + /** + * Creates a new analytics record with a freshly generated trace ID and stores it. + * + * @param request the validated payload containing the record's fields + * @return the persisted record mapped to its response representation + */ + public AnalyticsRecordResponse createRecord(CreateAnalyticsRecordRequest request) { + String traceId = UUID.randomUUID().toString(); + + AnalyticsRecord record = AnalyticsRecord.builder() + .traceId(traceId) + .eventType(request.getEventType()) + .eventSource(request.getEventSource()) + .anonymizedSessionId(request.getAnonymizedSessionId()) + .timestamp(request.getTimestamp()) + .build(); + + records.put(traceId, record); + + return mapToResponse(record); + } + + /** + * Converts an internal {@link AnalyticsRecord} domain object into its outward + * facing {@link AnalyticsRecordResponse} representation. + * + * @param record the domain record to convert + * @return the response DTO populated from the given record + */ + private AnalyticsRecordResponse mapToResponse(AnalyticsRecord record) { + return AnalyticsRecordResponse.builder() + .traceId(record.getTraceId()) + .eventType(record.getEventType()) + .eventSource(record.getEventSource()) + .anonymizedSessionId(record.getAnonymizedSessionId()) + .timestamp(record.getTimestamp()) + .build(); + } + + /** + * Returns every stored analytics record as a list of response DTOs. + * + * @return the list of all analytics records (empty if none exist) + */ + public List getAllRecords() { + return records.values() + .stream() + .map(this::mapToResponse) + .toList(); + } + + /** + * Retrieves a single analytics record by its trace ID. + * + * @param traceId the unique identifier of the record to fetch + * @return the matching analytics record + * @throws AnalyticsRecordNotFoundException if no record exists for the given trace ID + */ + public AnalyticsRecordResponse getRecordByTraceId(String traceId) { + + AnalyticsRecord record = records.get(traceId); + + if (record == null) { + throw new AnalyticsRecordNotFoundException( + "Analytics record not found with trace ID: " + traceId + ); + } + + return mapToResponse(record); + } + /** + * Deletes the analytics record identified by the given trace ID. + * + * @param traceId the unique identifier of the record to delete + * @throws AnalyticsRecordNotFoundException if no record exists for the given trace ID + */ + public void deleteRecord(String traceId) { + + AnalyticsRecord record = records.get(traceId); + + if (record == null) { + throw new AnalyticsRecordNotFoundException( + "Analytics record not found with trace ID: " + traceId + ); + } + + records.remove(traceId); + } + + /** + * Fully replaces the analytics record identified by the given trace ID with + * the values from the supplied request. + * + * @param traceId the unique identifier of the record to replace + * @param request the validated payload containing the new field values + * @return the updated record mapped to its response representation + * @throws AnalyticsRecordNotFoundException if no record exists for the given trace ID + */ + public AnalyticsRecordResponse replaceRecord(String traceId, ReplaceAnalyticsRecordRequest request) { + + if (!records.containsKey(traceId)) { + throw new AnalyticsRecordNotFoundException( + "Analytics record not found with trace ID: " + traceId + ); + } + + AnalyticsRecord updatedRecord = AnalyticsRecord.builder() + .traceId(traceId) + .eventType(request.getEventType()) + .eventSource(request.getEventSource()) + .anonymizedSessionId(request.getAnonymizedSessionId()) + .timestamp(request.getTimestamp()) + .build(); + + records.put(traceId, updatedRecord); + + return mapToResponse(updatedRecord); + } + /** + * Returns the subset of analytics records that match all supplied filters. + * Each filter parameter is optional; {@code null} values are skipped. + * String comparisons for {@code eventType} and {@code eventSource} are + * case-insensitive. Timestamp bounds are inclusive on both ends. + * + * @param eventType optional event type to match (case-insensitive) + * @param eventSource optional event source to match (case-insensitive) + * @param startTime optional inclusive lower bound on record timestamp + * @param endTime optional inclusive upper bound on record timestamp + * @return the matching analytics records (empty list if none match) + * @throws InvalidDateRangeException if {@code startTime} is after {@code endTime} + */ + public List getFilteredRecords( + String eventType, + String eventSource, + LocalDateTime startTime, + LocalDateTime endTime + ) { + validateDateRange(startTime, endTime); + + return records.values() + .stream() + .filter(record -> eventType == null || record.getEventType().equalsIgnoreCase(eventType)) + .filter(record -> eventSource == null || record.getEventSource().equalsIgnoreCase(eventSource)) + .filter(record -> startTime == null || !record.getTimestamp().isBefore(startTime)) + .filter(record -> endTime == null || !record.getTimestamp().isAfter(endTime)) + .map(this::mapToResponse) + .toList(); + } + + /** + * Validates that the provided date range is well-formed when both bounds are + * supplied. A {@code null} bound is treated as unbounded and is therefore valid. + * + * @param startTime the lower bound of the range, or {@code null} if unbounded + * @param endTime the upper bound of the range, or {@code null} if unbounded + * @throws InvalidDateRangeException if both bounds are non-null and {@code startTime} + * is after {@code endTime} + */ + private void validateDateRange(LocalDateTime startTime, LocalDateTime endTime) { + if (startTime != null && endTime != null && startTime.isAfter(endTime)) { + throw new InvalidDateRangeException("startTime must be before endTime"); + } + + } + + /** + * Computes an aggregated summary of all stored analytics records, including + * the total record count, a count per event type, and the number of distinct + * anonymized sessions. + * + * @return the aggregated summary across all stored records + */ + public AnalyticsSummaryResponse getSummary() { + + Map totalsByEventType = new HashMap<>(); + + Set uniqueSessions = new HashSet<>(); + + for (AnalyticsRecord record : records.values()) { + + totalsByEventType.put( + record.getEventType(), + totalsByEventType.getOrDefault(record.getEventType(), 0) + 1 + ); + + uniqueSessions.add(record.getAnonymizedSessionId()); + } + + return AnalyticsSummaryResponse.builder() + .totalRecords(records.size()) + .totalsByEventType(totalsByEventType) + .uniqueSessions(uniqueSessions.size()) + .build(); + } +} \ No newline at end of file From 31ce3745fcee61e4af90e81a3311eac010904d6f Mon Sep 17 00:00:00 2001 From: Shadi Date: Thu, 28 May 2026 18:49:42 +0200 Subject: [PATCH 05/10] Add AnalyticsRecordController with endpoints for CRUD operations, filtering, and summary generation --- .../controller/AnalyticsRecordController.java | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java new file mode 100644 index 0000000..e093d5c --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java @@ -0,0 +1,149 @@ +package com.hackyourfuture.analyticsapi.controller; + +import com.hackyourfuture.analyticsapi.dto.AnalyticsRecordResponse; +import com.hackyourfuture.analyticsapi.dto.CreateAnalyticsRecordRequest; +import com.hackyourfuture.analyticsapi.dto.ReplaceAnalyticsRecordRequest; +import com.hackyourfuture.analyticsapi.model.AnalyticsRecord; +import com.hackyourfuture.analyticsapi.service.AnalyticsRecordService; +import jakarta.validation.Valid; +import org.springframework.web.bind.annotation.RequestParam; +import java.time.LocalDateTime; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.PathVariable; +import java.util.List; +import com.hackyourfuture.analyticsapi.dto.AnalyticsSummaryResponse; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.PutMapping; + +@RestController +@RequestMapping("/api/v1/analytics-records") +public class AnalyticsRecordController { + private final AnalyticsRecordService analyticsRecordService; + + /** + * Constructs the controller with its required service dependency. + * + * @param analyticsRecordService the service used to handle analytics record operations + */ + public AnalyticsRecordController(AnalyticsRecordService analyticsRecordService) { + this.analyticsRecordService = analyticsRecordService; + } + + + /** + * Creates a new analytics record from the supplied payload. + * + * @param request the validated request body containing the new record's fields + * @return a {@link ResponseEntity} with HTTP 201 (Created) wrapping the persisted record + */ + @PostMapping + public ResponseEntity + createRecord(@Valid @RequestBody CreateAnalyticsRecordRequest request) + { + AnalyticsRecordResponse response = + analyticsRecordService.createRecord(request); + return ResponseEntity + .status(HttpStatus.CREATED) + .body(response); + } + + /** + * Returns every analytics record currently stored. + * + * @return the list of all analytics records (empty if none exist) + */ + @GetMapping + public List getAllRecords() { + return analyticsRecordService.getAllRecords(); + } + + /** + * Retrieves a single analytics record by its trace ID. + * + * @param traceId the unique identifier of the record to fetch + * @return the matching analytics record + * @throws com.hackyourfuture.analyticsapi.exception.AnalyticsRecordNotFoundException + * if no record exists for the given trace ID + */ + @GetMapping("/{traceId}") + public AnalyticsRecordResponse getRecordByTraceId( + @PathVariable String traceId + ) { + return analyticsRecordService.getRecordByTraceId(traceId); + } + /** + * Deletes the analytics record identified by the given trace ID. + * + * @param traceId the unique identifier of the record to delete + * @return a {@link ResponseEntity} with HTTP 204 (No Content) on success + * @throws com.hackyourfuture.analyticsapi.exception.AnalyticsRecordNotFoundException + * if no record exists for the given trace ID + */ + @DeleteMapping("/{traceId}") + public ResponseEntity deleteRecord( + @PathVariable String traceId + ) { + analyticsRecordService.deleteRecord(traceId); + return ResponseEntity.noContent().build(); + } + + /** + * Replaces the entire content of an existing analytics record. + * + * @param traceId the unique identifier of the record to replace + * @param request the validated request body containing the new field values + * @return the updated analytics record + * @throws com.hackyourfuture.analyticsapi.exception.AnalyticsRecordNotFoundException + * if no record exists for the given trace ID + */ + @PutMapping("/{traceId}") + public AnalyticsRecordResponse replaceRecord( + @PathVariable String traceId, + @Valid @RequestBody ReplaceAnalyticsRecordRequest request + ) { + return analyticsRecordService.replaceRecord(traceId, request); + } + + /** + * Returns analytics records that match the supplied filter parameters. All + * filter parameters are optional; omitted parameters are not applied to the + * filter. + * + * @param eventType optional case-insensitive event type filter + * @param eventSource optional case-insensitive event source filter + * @param startTime optional inclusive lower bound on the record timestamp + * @param endTime optional inclusive upper bound on the record timestamp + * @return the list of analytics records matching all supplied filters + * @throws com.hackyourfuture.analyticsapi.exception.InvalidDateRangeException + * if {@code startTime} is after {@code endTime} + */ + @GetMapping("/filter") + public List getFilteredRecords( + @RequestParam(required = false) String eventType, + @RequestParam(required = false) String eventSource, + @RequestParam(required = false) LocalDateTime startTime, + @RequestParam(required = false) LocalDateTime endTime + ) { + return analyticsRecordService.getFilteredRecords( + eventType, + eventSource, + startTime, + endTime + ); + } + + /** + * Produces an aggregated summary across all stored analytics records, + * including total counts, per-event-type totals, and the number of unique + * anonymized sessions. + * + * @return the aggregated summary + */ + @GetMapping("/summary") + public AnalyticsSummaryResponse getSummary() { + return analyticsRecordService.getSummary(); + } +} From 30822a93625012aed1c19c5d18d8ba47a80fddee Mon Sep 17 00:00:00 2001 From: Shadi Date: Thu, 28 May 2026 18:49:48 +0200 Subject: [PATCH 06/10] Add GlobalExceptionHandler for centralized API error handling --- .../exception/GlobalExceptionHandler.java | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/GlobalExceptionHandler.java diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/GlobalExceptionHandler.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/GlobalExceptionHandler.java new file mode 100644 index 0000000..5b9340a --- /dev/null +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/GlobalExceptionHandler.java @@ -0,0 +1,86 @@ +package com.hackyourfuture.analyticsapi.exception; + + +import org.springframework.web.bind.MethodArgumentNotValidException; + +import java.util.HashMap; +import java.util.Map; +import com.hackyourfuture.analyticsapi.dto.ErrorResponse; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; + +@RestControllerAdvice +public class GlobalExceptionHandler { + + /** + * Handles {@link AnalyticsRecordNotFoundException} by producing a 404 Not Found + * error response that includes the exception message and the originating request path. + * + * @param ex the exception thrown when an analytics record could not be located + * @param request the current HTTP request, used to extract the request URI + * @return an {@link ErrorResponse} describing the not-found condition + */ + @ExceptionHandler(AnalyticsRecordNotFoundException.class) + public ErrorResponse handleAnalyticsRecordNotFoundException( + AnalyticsRecordNotFoundException ex, + HttpServletRequest request + ) { + + return ErrorResponse.builder() + .status(HttpStatus.NOT_FOUND.value()) + .message(ex.getMessage()) + .path(request.getRequestURI()) + .build(); + } + + /** + * Handles bean-validation failures raised on {@code @Valid} request bodies and + * returns a 400 Bad Request payload containing a per-field error map. + * + * @param ex the validation exception holding the field-level binding errors + * @return a map with the HTTP status, an overall message, and a field-keyed error map + */ + @ExceptionHandler(MethodArgumentNotValidException.class) + public Map handleValidationException( + MethodArgumentNotValidException ex + ) { + Map errors = new HashMap<>(); + + ex.getBindingResult() + .getFieldErrors() + .forEach(error -> errors.put( + error.getField(), + error.getDefaultMessage() + )); + + Map response = new HashMap<>(); + response.put("status", HttpStatus.BAD_REQUEST.value()); + response.put("message", "Validation failed"); + response.put("errors", errors); + + return response; + } + + /** + * Handles {@link InvalidDateRangeException} by producing a 400 Bad Request + * error response that includes the exception message and the originating request path. + * + * @param ex the exception thrown when a filter receives a malformed date range + * @param request the current HTTP request, used to extract the request URI + * @return an {@link ErrorResponse} describing the invalid-date-range condition + */ + @ExceptionHandler(InvalidDateRangeException.class) + public ErrorResponse handleInvalidDateRangeException( + InvalidDateRangeException ex, + HttpServletRequest request + ) { + + return ErrorResponse.builder() + .status(HttpStatus.BAD_REQUEST.value()) + .message(ex.getMessage()) + .path(request.getRequestURI()) + .build(); + } +} \ No newline at end of file From 58e7d497eebe824970bd2fc987c33c0a94829ba2 Mon Sep 17 00:00:00 2001 From: Shadi Date: Thu, 28 May 2026 18:49:55 +0200 Subject: [PATCH 07/10] Add unit tests for AnalyticsRecordService covering CRUD, filtering, and summary functionality --- .../service/AnalyticsRecordServiceTest.java | 170 ++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 task-1/analyticsapi/src/test/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordServiceTest.java diff --git a/task-1/analyticsapi/src/test/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordServiceTest.java b/task-1/analyticsapi/src/test/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordServiceTest.java new file mode 100644 index 0000000..d4b5dce --- /dev/null +++ b/task-1/analyticsapi/src/test/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordServiceTest.java @@ -0,0 +1,170 @@ +package com.hackyourfuture.analyticsapi.service; +import com.hackyourfuture.analyticsapi.dto.CreateAnalyticsRecordRequest; +import com.hackyourfuture.analyticsapi.dto.ReplaceAnalyticsRecordRequest; +import com.hackyourfuture.analyticsapi.exception.AnalyticsRecordNotFoundException; +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; + +import static org.junit.jupiter.api.Assertions.*; +import org.junit.jupiter.api.BeforeEach; + +class AnalyticsRecordServiceTest { + + private AnalyticsRecordService analyticsRecordService; + + @BeforeEach + void setUp() { + analyticsRecordService = new AnalyticsRecordService(); + } + + @Test + void createRecord_ShouldGenerateTraceId() { + + CreateAnalyticsRecordRequest request = + new CreateAnalyticsRecordRequest(); + + request.setEventType("BUTTON_CLICK"); + request.setEventSource("HOME_PAGE"); + request.setAnonymizedSessionId("session-123"); + request.setTimestamp(LocalDateTime.now()); + + var response = analyticsRecordService.createRecord(request); + + assertNotNull(response.getTraceId()); + + assertEquals("BUTTON_CLICK", response.getEventType()); + } + + @Test + void getAllRecords_ShouldReturnAllStoredRecords() { + + CreateAnalyticsRecordRequest request = + new CreateAnalyticsRecordRequest(); + + request.setEventType("BUTTON_CLICK"); + request.setEventSource("HOME_PAGE"); + request.setAnonymizedSessionId("session-123"); + request.setTimestamp(LocalDateTime.now()); + + analyticsRecordService.createRecord(request); + + var records = analyticsRecordService.getAllRecords(); + + assertEquals(1, records.size()); + } + + @Test + void getRecordByTraceId_ShouldThrowException_WhenRecordDoesNotExist() { + + assertThrows( + AnalyticsRecordNotFoundException.class, + () -> analyticsRecordService.getRecordByTraceId("fake-id") + ); + } + + @Test + void deleteRecord_ShouldRemoveRecord() { + + CreateAnalyticsRecordRequest request = new CreateAnalyticsRecordRequest(); + + request.setEventType("BUTTON_CLICK"); + request.setEventSource("HOME_PAGE"); + request.setAnonymizedSessionId("session-123"); + request.setTimestamp(LocalDateTime.now()); + + var createdRecord = analyticsRecordService.createRecord(request); + + analyticsRecordService.deleteRecord(createdRecord.getTraceId()); + + assertThrows( + AnalyticsRecordNotFoundException.class, + () -> analyticsRecordService.getRecordByTraceId(createdRecord.getTraceId()) + ); + } + + @Test + void replaceRecord_ShouldUpdateExistingRecord() { + + CreateAnalyticsRecordRequest createRequest = + new CreateAnalyticsRecordRequest(); + + createRequest.setEventType("BUTTON_CLICK"); + createRequest.setEventSource("HOME_PAGE"); + createRequest.setAnonymizedSessionId("session-123"); + createRequest.setTimestamp(LocalDateTime.now()); + + var createdRecord = + analyticsRecordService.createRecord(createRequest); + + ReplaceAnalyticsRecordRequest replaceRequest = + new ReplaceAnalyticsRecordRequest(); + + replaceRequest.setEventType("PAGE_VIEW"); + replaceRequest.setEventSource("PRODUCT_PAGE"); + replaceRequest.setAnonymizedSessionId("session-999"); + replaceRequest.setTimestamp(LocalDateTime.now()); + + var updatedRecord = analyticsRecordService.replaceRecord( + createdRecord.getTraceId(), + replaceRequest + ); + + assertEquals("PAGE_VIEW", updatedRecord.getEventType()); + + assertEquals("PRODUCT_PAGE", updatedRecord.getEventSource()); + } + + @Test + void getSummary_ShouldReturnCorrectSummary() { + + CreateAnalyticsRecordRequest request1 = + new CreateAnalyticsRecordRequest(); + + request1.setEventType("BUTTON_CLICK"); + request1.setEventSource("HOME_PAGE"); + request1.setAnonymizedSessionId("session-1"); + request1.setTimestamp(LocalDateTime.now()); + + CreateAnalyticsRecordRequest request2 = + new CreateAnalyticsRecordRequest(); + + request2.setEventType("BUTTON_CLICK"); + request2.setEventSource("PRODUCT_PAGE"); + request2.setAnonymizedSessionId("session-2"); + request2.setTimestamp(LocalDateTime.now()); + + CreateAnalyticsRecordRequest request3 = + new CreateAnalyticsRecordRequest(); + + request3.setEventType("PAGE_VIEW"); + request3.setEventSource("HOME_PAGE"); + request3.setAnonymizedSessionId("session-1"); + request3.setTimestamp(LocalDateTime.now()); + + analyticsRecordService.createRecord(request1); + analyticsRecordService.createRecord(request2); + analyticsRecordService.createRecord(request3); + + var summary = analyticsRecordService.getSummary(); + + assertEquals(3, summary.getTotalRecords()); + + assertEquals(2, + summary.getTotalsByEventType().get("BUTTON_CLICK")); + + assertEquals(1, + summary.getTotalsByEventType().get("PAGE_VIEW")); + + assertEquals(2, summary.getUniqueSessions()); + } + + @Test + void getSummary_ShouldHandleEmptyRecords() { + var summary = analyticsRecordService.getSummary(); + + assertEquals(0, summary.getTotalRecords()); + assertEquals(0, summary.getUniqueSessions()); + assertTrue(summary.getTotalsByEventType().isEmpty()); + } +} \ No newline at end of file From c65703b309b86ff6e6daf6329f644428586376fc Mon Sep 17 00:00:00 2001 From: Shadi Date: Thu, 28 May 2026 18:50:13 +0200 Subject: [PATCH 08/10] refactor code --- .../analyticsapi/controller/AnalyticsRecordController.java | 1 - 1 file changed, 1 deletion(-) diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java index e093d5c..41c46b4 100644 --- a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java @@ -3,7 +3,6 @@ import com.hackyourfuture.analyticsapi.dto.AnalyticsRecordResponse; import com.hackyourfuture.analyticsapi.dto.CreateAnalyticsRecordRequest; import com.hackyourfuture.analyticsapi.dto.ReplaceAnalyticsRecordRequest; -import com.hackyourfuture.analyticsapi.model.AnalyticsRecord; import com.hackyourfuture.analyticsapi.service.AnalyticsRecordService; import jakarta.validation.Valid; import org.springframework.web.bind.annotation.RequestParam; From b742f060d91b06682b9aac3f2edee7535db01f38 Mon Sep 17 00:00:00 2001 From: Shadi Date: Thu, 28 May 2026 18:51:05 +0200 Subject: [PATCH 09/10] Remove redundant blank line in AnalyticsRecordController. --- .../analyticsapi/controller/AnalyticsRecordController.java | 1 - 1 file changed, 1 deletion(-) diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java index 41c46b4..fc04719 100644 --- a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java @@ -1,5 +1,4 @@ package com.hackyourfuture.analyticsapi.controller; - import com.hackyourfuture.analyticsapi.dto.AnalyticsRecordResponse; import com.hackyourfuture.analyticsapi.dto.CreateAnalyticsRecordRequest; import com.hackyourfuture.analyticsapi.dto.ReplaceAnalyticsRecordRequest; From 135bd3923fae76a09fd6483d6dfca27b66ad4fa0 Mon Sep 17 00:00:00 2001 From: Shadi Date: Thu, 28 May 2026 19:18:14 +0200 Subject: [PATCH 10/10] Refactor to improve code formatting, remove redundant blank lines, and reorder imports across the project. --- .../analyticsapi/AnalyticsApiApplication.java | 6 +- .../controller/AnalyticsRecordController.java | 46 +++++----- .../AnalyticsRecordNotFoundException.java | 4 +- .../exception/GlobalExceptionHandler.java | 22 ++--- .../exception/InvalidDateRangeException.java | 2 +- .../service/AnalyticsRecordService.java | 90 +++++++++---------- .../service/AnalyticsRecordServiceTest.java | 59 ++++-------- 7 files changed, 94 insertions(+), 135 deletions(-) diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/AnalyticsApiApplication.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/AnalyticsApiApplication.java index c9b2a65..037068e 100644 --- a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/AnalyticsApiApplication.java +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/AnalyticsApiApplication.java @@ -6,8 +6,8 @@ @SpringBootApplication public class AnalyticsApiApplication { - public static void main(String[] args) { - SpringApplication.run(AnalyticsApiApplication.class, args); - } + public static void main(String[] args) { + SpringApplication.run(AnalyticsApiApplication.class, args); + } } diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java index fc04719..7a24085 100644 --- a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/controller/AnalyticsRecordController.java @@ -1,24 +1,30 @@ package com.hackyourfuture.analyticsapi.controller; + import com.hackyourfuture.analyticsapi.dto.AnalyticsRecordResponse; +import com.hackyourfuture.analyticsapi.dto.AnalyticsSummaryResponse; import com.hackyourfuture.analyticsapi.dto.CreateAnalyticsRecordRequest; import com.hackyourfuture.analyticsapi.dto.ReplaceAnalyticsRecordRequest; import com.hackyourfuture.analyticsapi.service.AnalyticsRecordService; import jakarta.validation.Valid; -import org.springframework.web.bind.annotation.RequestParam; -import java.time.LocalDateTime; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.bind.annotation.PathVariable; -import java.util.List; -import com.hackyourfuture.analyticsapi.dto.AnalyticsSummaryResponse; 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.LocalDateTime; +import java.util.List; @RestController @RequestMapping("/api/v1/analytics-records") public class AnalyticsRecordController { + private final AnalyticsRecordService analyticsRecordService; /** @@ -30,7 +36,6 @@ public AnalyticsRecordController(AnalyticsRecordService analyticsRecordService) this.analyticsRecordService = analyticsRecordService; } - /** * Creates a new analytics record from the supplied payload. * @@ -38,11 +43,10 @@ public AnalyticsRecordController(AnalyticsRecordService analyticsRecordService) * @return a {@link ResponseEntity} with HTTP 201 (Created) wrapping the persisted record */ @PostMapping - public ResponseEntity - createRecord(@Valid @RequestBody CreateAnalyticsRecordRequest request) - { - AnalyticsRecordResponse response = - analyticsRecordService.createRecord(request); + public ResponseEntity createRecord( + @Valid @RequestBody CreateAnalyticsRecordRequest request + ) { + AnalyticsRecordResponse response = analyticsRecordService.createRecord(request); return ResponseEntity .status(HttpStatus.CREATED) .body(response); @@ -67,11 +71,10 @@ public List getAllRecords() { * if no record exists for the given trace ID */ @GetMapping("/{traceId}") - public AnalyticsRecordResponse getRecordByTraceId( - @PathVariable String traceId - ) { + public AnalyticsRecordResponse getRecordByTraceId(@PathVariable String traceId) { return analyticsRecordService.getRecordByTraceId(traceId); } + /** * Deletes the analytics record identified by the given trace ID. * @@ -81,9 +84,7 @@ public AnalyticsRecordResponse getRecordByTraceId( * if no record exists for the given trace ID */ @DeleteMapping("/{traceId}") - public ResponseEntity deleteRecord( - @PathVariable String traceId - ) { + public ResponseEntity deleteRecord(@PathVariable String traceId) { analyticsRecordService.deleteRecord(traceId); return ResponseEntity.noContent().build(); } @@ -125,12 +126,7 @@ public List getFilteredRecords( @RequestParam(required = false) LocalDateTime startTime, @RequestParam(required = false) LocalDateTime endTime ) { - return analyticsRecordService.getFilteredRecords( - eventType, - eventSource, - startTime, - endTime - ); + return analyticsRecordService.getFilteredRecords(eventType, eventSource, startTime, endTime); } /** diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/AnalyticsRecordNotFoundException.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/AnalyticsRecordNotFoundException.java index ce74038..dc17d83 100644 --- a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/AnalyticsRecordNotFoundException.java +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/AnalyticsRecordNotFoundException.java @@ -1,7 +1,5 @@ package com.hackyourfuture.analyticsapi.exception; - - public class AnalyticsRecordNotFoundException extends RuntimeException { /** @@ -12,4 +10,4 @@ public class AnalyticsRecordNotFoundException extends RuntimeException { public AnalyticsRecordNotFoundException(String message) { super(message); } -} \ No newline at end of file +} diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/GlobalExceptionHandler.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/GlobalExceptionHandler.java index 5b9340a..27ac1ca 100644 --- a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/GlobalExceptionHandler.java +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/GlobalExceptionHandler.java @@ -1,16 +1,15 @@ package com.hackyourfuture.analyticsapi.exception; - -import org.springframework.web.bind.MethodArgumentNotValidException; - -import java.util.HashMap; -import java.util.Map; import com.hackyourfuture.analyticsapi.dto.ErrorResponse; import jakarta.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; +import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; +import java.util.HashMap; +import java.util.Map; + @RestControllerAdvice public class GlobalExceptionHandler { @@ -27,7 +26,6 @@ public ErrorResponse handleAnalyticsRecordNotFoundException( AnalyticsRecordNotFoundException ex, HttpServletRequest request ) { - return ErrorResponse.builder() .status(HttpStatus.NOT_FOUND.value()) .message(ex.getMessage()) @@ -43,17 +41,12 @@ public ErrorResponse handleAnalyticsRecordNotFoundException( * @return a map with the HTTP status, an overall message, and a field-keyed error map */ @ExceptionHandler(MethodArgumentNotValidException.class) - public Map handleValidationException( - MethodArgumentNotValidException ex - ) { + public Map handleValidationException(MethodArgumentNotValidException ex) { Map errors = new HashMap<>(); ex.getBindingResult() .getFieldErrors() - .forEach(error -> errors.put( - error.getField(), - error.getDefaultMessage() - )); + .forEach(error -> errors.put(error.getField(), error.getDefaultMessage())); Map response = new HashMap<>(); response.put("status", HttpStatus.BAD_REQUEST.value()); @@ -76,11 +69,10 @@ public ErrorResponse handleInvalidDateRangeException( InvalidDateRangeException ex, HttpServletRequest request ) { - return ErrorResponse.builder() .status(HttpStatus.BAD_REQUEST.value()) .message(ex.getMessage()) .path(request.getRequestURI()) .build(); } -} \ No newline at end of file +} diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/InvalidDateRangeException.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/InvalidDateRangeException.java index bcea91c..e10bcef 100644 --- a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/InvalidDateRangeException.java +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/exception/InvalidDateRangeException.java @@ -11,4 +11,4 @@ public class InvalidDateRangeException extends RuntimeException { public InvalidDateRangeException(String message) { super(message); } -} \ No newline at end of file +} diff --git a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordService.java b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordService.java index 213f03a..89bb44c 100644 --- a/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordService.java +++ b/task-1/analyticsapi/src/main/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordService.java @@ -1,17 +1,21 @@ package com.hackyourfuture.analyticsapi.service; - import com.hackyourfuture.analyticsapi.dto.AnalyticsRecordResponse; import com.hackyourfuture.analyticsapi.dto.AnalyticsSummaryResponse; import com.hackyourfuture.analyticsapi.dto.CreateAnalyticsRecordRequest; import com.hackyourfuture.analyticsapi.dto.ReplaceAnalyticsRecordRequest; +import com.hackyourfuture.analyticsapi.exception.AnalyticsRecordNotFoundException; +import com.hackyourfuture.analyticsapi.exception.InvalidDateRangeException; import com.hackyourfuture.analyticsapi.model.AnalyticsRecord; import org.springframework.stereotype.Service; -import com.hackyourfuture.analyticsapi.exception.AnalyticsRecordNotFoundException; -import java.time.LocalDateTime; -import java.util.*; -import com.hackyourfuture.analyticsapi.exception.InvalidDateRangeException; +import java.time.LocalDateTime; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; @Service public class AnalyticsRecordService { @@ -40,23 +44,6 @@ public AnalyticsRecordResponse createRecord(CreateAnalyticsRecordRequest request return mapToResponse(record); } - /** - * Converts an internal {@link AnalyticsRecord} domain object into its outward - * facing {@link AnalyticsRecordResponse} representation. - * - * @param record the domain record to convert - * @return the response DTO populated from the given record - */ - private AnalyticsRecordResponse mapToResponse(AnalyticsRecord record) { - return AnalyticsRecordResponse.builder() - .traceId(record.getTraceId()) - .eventType(record.getEventType()) - .eventSource(record.getEventSource()) - .anonymizedSessionId(record.getAnonymizedSessionId()) - .timestamp(record.getTimestamp()) - .build(); - } - /** * Returns every stored analytics record as a list of response DTOs. * @@ -77,7 +64,6 @@ public List getAllRecords() { * @throws AnalyticsRecordNotFoundException if no record exists for the given trace ID */ public AnalyticsRecordResponse getRecordByTraceId(String traceId) { - AnalyticsRecord record = records.get(traceId); if (record == null) { @@ -88,6 +74,7 @@ public AnalyticsRecordResponse getRecordByTraceId(String traceId) { return mapToResponse(record); } + /** * Deletes the analytics record identified by the given trace ID. * @@ -95,7 +82,6 @@ public AnalyticsRecordResponse getRecordByTraceId(String traceId) { * @throws AnalyticsRecordNotFoundException if no record exists for the given trace ID */ public void deleteRecord(String traceId) { - AnalyticsRecord record = records.get(traceId); if (record == null) { @@ -117,7 +103,6 @@ public void deleteRecord(String traceId) { * @throws AnalyticsRecordNotFoundException if no record exists for the given trace ID */ public AnalyticsRecordResponse replaceRecord(String traceId, ReplaceAnalyticsRecordRequest request) { - if (!records.containsKey(traceId)) { throw new AnalyticsRecordNotFoundException( "Analytics record not found with trace ID: " + traceId @@ -136,6 +121,7 @@ public AnalyticsRecordResponse replaceRecord(String traceId, ReplaceAnalyticsRec return mapToResponse(updatedRecord); } + /** * Returns the subset of analytics records that match all supplied filters. * Each filter parameter is optional; {@code null} values are skipped. @@ -167,22 +153,6 @@ public List getFilteredRecords( .toList(); } - /** - * Validates that the provided date range is well-formed when both bounds are - * supplied. A {@code null} bound is treated as unbounded and is therefore valid. - * - * @param startTime the lower bound of the range, or {@code null} if unbounded - * @param endTime the upper bound of the range, or {@code null} if unbounded - * @throws InvalidDateRangeException if both bounds are non-null and {@code startTime} - * is after {@code endTime} - */ - private void validateDateRange(LocalDateTime startTime, LocalDateTime endTime) { - if (startTime != null && endTime != null && startTime.isAfter(endTime)) { - throw new InvalidDateRangeException("startTime must be before endTime"); - } - - } - /** * Computes an aggregated summary of all stored analytics records, including * the total record count, a count per event type, and the number of distinct @@ -191,18 +161,14 @@ private void validateDateRange(LocalDateTime startTime, LocalDateTime endTime) { * @return the aggregated summary across all stored records */ public AnalyticsSummaryResponse getSummary() { - Map totalsByEventType = new HashMap<>(); - Set uniqueSessions = new HashSet<>(); for (AnalyticsRecord record : records.values()) { - totalsByEventType.put( record.getEventType(), totalsByEventType.getOrDefault(record.getEventType(), 0) + 1 ); - uniqueSessions.add(record.getAnonymizedSessionId()); } @@ -212,4 +178,36 @@ public AnalyticsSummaryResponse getSummary() { .uniqueSessions(uniqueSessions.size()) .build(); } -} \ No newline at end of file + + /** + * Validates that the provided date range is well-formed when both bounds are + * supplied. A {@code null} bound is treated as unbounded and is therefore valid. + * + * @param startTime the lower bound of the range, or {@code null} if unbounded + * @param endTime the upper bound of the range, or {@code null} if unbounded + * @throws InvalidDateRangeException if both bounds are non-null and {@code startTime} + * is after {@code endTime} + */ + private void validateDateRange(LocalDateTime startTime, LocalDateTime endTime) { + if (startTime != null && endTime != null && startTime.isAfter(endTime)) { + throw new InvalidDateRangeException("startTime must be before endTime"); + } + } + + /** + * Converts an internal {@link AnalyticsRecord} domain object into its outward + * facing {@link AnalyticsRecordResponse} representation. + * + * @param record the domain record to convert + * @return the response DTO populated from the given record + */ + private AnalyticsRecordResponse mapToResponse(AnalyticsRecord record) { + return AnalyticsRecordResponse.builder() + .traceId(record.getTraceId()) + .eventType(record.getEventType()) + .eventSource(record.getEventSource()) + .anonymizedSessionId(record.getAnonymizedSessionId()) + .timestamp(record.getTimestamp()) + .build(); + } +} diff --git a/task-1/analyticsapi/src/test/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordServiceTest.java b/task-1/analyticsapi/src/test/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordServiceTest.java index d4b5dce..59c3333 100644 --- a/task-1/analyticsapi/src/test/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordServiceTest.java +++ b/task-1/analyticsapi/src/test/java/com/hackyourfuture/analyticsapi/service/AnalyticsRecordServiceTest.java @@ -1,13 +1,17 @@ package com.hackyourfuture.analyticsapi.service; + import com.hackyourfuture.analyticsapi.dto.CreateAnalyticsRecordRequest; import com.hackyourfuture.analyticsapi.dto.ReplaceAnalyticsRecordRequest; import com.hackyourfuture.analyticsapi.exception.AnalyticsRecordNotFoundException; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.LocalDateTime; -import static org.junit.jupiter.api.Assertions.*; -import org.junit.jupiter.api.BeforeEach; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; class AnalyticsRecordServiceTest { @@ -20,10 +24,7 @@ void setUp() { @Test void createRecord_ShouldGenerateTraceId() { - - CreateAnalyticsRecordRequest request = - new CreateAnalyticsRecordRequest(); - + CreateAnalyticsRecordRequest request = new CreateAnalyticsRecordRequest(); request.setEventType("BUTTON_CLICK"); request.setEventSource("HOME_PAGE"); request.setAnonymizedSessionId("session-123"); @@ -32,16 +33,12 @@ void createRecord_ShouldGenerateTraceId() { var response = analyticsRecordService.createRecord(request); assertNotNull(response.getTraceId()); - assertEquals("BUTTON_CLICK", response.getEventType()); } @Test void getAllRecords_ShouldReturnAllStoredRecords() { - - CreateAnalyticsRecordRequest request = - new CreateAnalyticsRecordRequest(); - + CreateAnalyticsRecordRequest request = new CreateAnalyticsRecordRequest(); request.setEventType("BUTTON_CLICK"); request.setEventSource("HOME_PAGE"); request.setAnonymizedSessionId("session-123"); @@ -56,7 +53,6 @@ void getAllRecords_ShouldReturnAllStoredRecords() { @Test void getRecordByTraceId_ShouldThrowException_WhenRecordDoesNotExist() { - assertThrows( AnalyticsRecordNotFoundException.class, () -> analyticsRecordService.getRecordByTraceId("fake-id") @@ -65,9 +61,7 @@ void getRecordByTraceId_ShouldThrowException_WhenRecordDoesNotExist() { @Test void deleteRecord_ShouldRemoveRecord() { - CreateAnalyticsRecordRequest request = new CreateAnalyticsRecordRequest(); - request.setEventType("BUTTON_CLICK"); request.setEventSource("HOME_PAGE"); request.setAnonymizedSessionId("session-123"); @@ -85,21 +79,15 @@ void deleteRecord_ShouldRemoveRecord() { @Test void replaceRecord_ShouldUpdateExistingRecord() { - - CreateAnalyticsRecordRequest createRequest = - new CreateAnalyticsRecordRequest(); - + CreateAnalyticsRecordRequest createRequest = new CreateAnalyticsRecordRequest(); createRequest.setEventType("BUTTON_CLICK"); createRequest.setEventSource("HOME_PAGE"); createRequest.setAnonymizedSessionId("session-123"); createRequest.setTimestamp(LocalDateTime.now()); - var createdRecord = - analyticsRecordService.createRecord(createRequest); - - ReplaceAnalyticsRecordRequest replaceRequest = - new ReplaceAnalyticsRecordRequest(); + var createdRecord = analyticsRecordService.createRecord(createRequest); + ReplaceAnalyticsRecordRequest replaceRequest = new ReplaceAnalyticsRecordRequest(); replaceRequest.setEventType("PAGE_VIEW"); replaceRequest.setEventSource("PRODUCT_PAGE"); replaceRequest.setAnonymizedSessionId("session-999"); @@ -111,32 +99,24 @@ void replaceRecord_ShouldUpdateExistingRecord() { ); assertEquals("PAGE_VIEW", updatedRecord.getEventType()); - assertEquals("PRODUCT_PAGE", updatedRecord.getEventSource()); } @Test void getSummary_ShouldReturnCorrectSummary() { - - CreateAnalyticsRecordRequest request1 = - new CreateAnalyticsRecordRequest(); - + CreateAnalyticsRecordRequest request1 = new CreateAnalyticsRecordRequest(); request1.setEventType("BUTTON_CLICK"); request1.setEventSource("HOME_PAGE"); request1.setAnonymizedSessionId("session-1"); request1.setTimestamp(LocalDateTime.now()); - CreateAnalyticsRecordRequest request2 = - new CreateAnalyticsRecordRequest(); - + CreateAnalyticsRecordRequest request2 = new CreateAnalyticsRecordRequest(); request2.setEventType("BUTTON_CLICK"); request2.setEventSource("PRODUCT_PAGE"); request2.setAnonymizedSessionId("session-2"); request2.setTimestamp(LocalDateTime.now()); - CreateAnalyticsRecordRequest request3 = - new CreateAnalyticsRecordRequest(); - + CreateAnalyticsRecordRequest request3 = new CreateAnalyticsRecordRequest(); request3.setEventType("PAGE_VIEW"); request3.setEventSource("HOME_PAGE"); request3.setAnonymizedSessionId("session-1"); @@ -149,13 +129,8 @@ void getSummary_ShouldReturnCorrectSummary() { var summary = analyticsRecordService.getSummary(); assertEquals(3, summary.getTotalRecords()); - - assertEquals(2, - summary.getTotalsByEventType().get("BUTTON_CLICK")); - - assertEquals(1, - summary.getTotalsByEventType().get("PAGE_VIEW")); - + assertEquals(2, summary.getTotalsByEventType().get("BUTTON_CLICK")); + assertEquals(1, summary.getTotalsByEventType().get("PAGE_VIEW")); assertEquals(2, summary.getUniqueSessions()); } @@ -167,4 +142,4 @@ void getSummary_ShouldHandleEmptyRecords() { assertEquals(0, summary.getUniqueSessions()); assertTrue(summary.getTotalsByEventType().isEmpty()); } -} \ No newline at end of file +}