diff --git a/.github/workflows/deploy-k8s.yml b/.github/workflows/deploy-k8s.yml index 0f52412..78719fa 100644 --- a/.github/workflows/deploy-k8s.yml +++ b/.github/workflows/deploy-k8s.yml @@ -57,8 +57,9 @@ jobs: helm upgrade --install bytebite ./helm/bytebite \ --namespace team-bytebite \ --set client.image.tag=${{ steps.vars.outputs.image_tag }} \ - --set server.image.tag=${{ steps.vars.outputs.image_tag }} \ + --set apiGateway.image.tag=${{ steps.vars.outputs.image_tag }} \ + --set userService.image.tag=${{ steps.vars.outputs.image_tag }} \ + --set groceryService.image.tag=${{ steps.vars.outputs.image_tag }} \ --set genai.image.tag=${{ steps.vars.outputs.image_tag }} \ --set genai.openaiApiKey="${{ secrets.OPENAI_API_KEY }}" \ - --atomic \ - --timeout 5m + --atomic diff --git a/.github/workflows/test-build-push.yml b/.github/workflows/test-build-push.yml index efa2b3d..1b8cbbd 100644 --- a/.github/workflows/test-build-push.yml +++ b/.github/workflows/test-build-push.yml @@ -15,6 +15,9 @@ jobs: test: name: Run Java Tests runs-on: ubuntu-latest + strategy: + matrix: + service: [api-gateway, user-service, grocery-service] steps: - name: Checkout uses: actions/checkout@v4 @@ -27,15 +30,29 @@ jobs: cache: maven - name: Run tests with Maven - run: cd server && ./mvnw -B test + run: cd server/${{ matrix.service }} && ./mvnw -B test build: - name: Build ${{ matrix.service }} + name: Build ${{ matrix.image }} needs: test runs-on: ubuntu-latest strategy: matrix: - service: [client, server, gen-ai] + include: + - image: client + context: ./client + - image: api-gateway + context: ./server/api-gateway + - image: user-service + context: ./server/user-service + - image: grocery-service + context: ./server/grocery-service + - image: gen-ai + context: ./gen-ai + - image: user-db + context: ./databases/user-db + - image: grocery-db + context: ./databases/grocery-db steps: - name: Checkout uses: actions/checkout@v4 @@ -57,7 +74,7 @@ jobs: uses: docker/metadata-action@v5 with: # metadata-action lowercases the image name for ghcr.io automatically. - images: ghcr.io/${{ github.repository }}/${{ matrix.service }} + images: ghcr.io/${{ github.repository }}/${{ matrix.image }} tags: | type=raw,value=latest,enable={{is_default_branch}} type=ref,event=branch @@ -66,8 +83,8 @@ jobs: - name: Build and push Docker image uses: docker/build-push-action@v6 with: - context: ./${{ matrix.service }} - file: ./${{ matrix.service }}/Dockerfile + context: ${{ matrix.context }} + file: ${{ matrix.context }}/Dockerfile push: ${{ github.ref == 'refs/heads/main' }} tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} diff --git a/.gitignore b/.gitignore index 1856b3f..66c2978 100644 --- a/.gitignore +++ b/.gitignore @@ -17,9 +17,9 @@ client/node_modules/ client/dist/ client/.vite/ -# ── server (Java Spring Boot) ───────────────────────────────── -server/target/ -server/.mvn/wrapper/maven-wrapper.jar +# ── server (Java microservices) ─────────────────────────────── +server/*/target/ +server/*/.mvn/wrapper/maven-wrapper.jar *.class *.jar *.war diff --git a/README.md b/README.md index e874f41..6de601b 100644 --- a/README.md +++ b/README.md @@ -38,9 +38,13 @@ Unlike traditional apps that rely on rigid "If/Then" logic or specific formattin ``` team-bytebite/ -├── client/ # React + Vite frontend -├── server/ # Java Spring Boot backend API -└── gen-ai/ # Python FastAPI service for AI-based recipe and shopping list generation +├── client/ # React + Vite frontend +├── gen-ai/ # Python FastAPI AI generation service +├── server/ # Java Spring Boot microservices +│ ├── api-gateway/ # Public entrypoint — routes requests to backend services +│ ├── user-service/ # User domain service +│ └── grocery-service/ # Grocery and recipe domain service +└── databases/ # Database image definitions and init schemas ``` ## Services @@ -48,8 +52,14 @@ team-bytebite/ ### `client` — React / Vite The user-facing web application. Provides a dish name input and displays the generated shopping list. Communicates with the backend via REST. -### `server` — Java Spring Boot -The core backend API. Manages users, recipes, and shopping lists. Orchestrates requests between the client and the gen-ai service. +### `api-gateway` — Java Spring Boot +The public backend entrypoint. Receives frontend API requests and forwards them to the owning backend service. + +### `user-service` — Java Spring Boot +Owns user-related data and connects to the user database. + +### `grocery-service` — Java Spring Boot +Owns recipes, grocery lists, and grocery items. Connects to the grocery database and calls the gen-ai service when ingredient generation is needed. ### `gen-ai` — Python FastAPI The AI generation service. Receives a dish name from the server and returns a shopping list with all required ingredients using LLM integrations. @@ -71,13 +81,25 @@ pip install -r requirements.txt uvicorn main:app --reload ``` -**2. Server** (port 8080) +**2. User Service** (port 8083) ```bash -cd server +cd server/user-service ./mvnw spring-boot:run ``` -**3. Client** (port 5173) +**3. Grocery Service** (port 8082) +```bash +cd server/grocery-service +./mvnw spring-boot:run +``` + +**4. API Gateway** (port 8080) +```bash +cd server/api-gateway +./mvnw spring-boot:run +``` + +**5. Client** (port 5173) ```bash cd client npm install @@ -100,3 +122,33 @@ docker compose up --build Open http://localhost:8081 Drop `--build` on subsequent starts if nothing has changed. To stop: `docker compose down`. + +--- + +### Kubernetes + +#### Local Kubernetes Deployment +... + + +#### Kubernetes Deployment to the AET cluster + +Prerequisite: The `team-bytebite` namespace must exist in the cluster. + +Deployment is automated via GitHub Actions: + +- **Automatic:** every push to `main` triggers the build workflow, which triggers the deploy workflow on success. +- **Manual:** go to Actions → *Deploy to Kubernetes* → *Run workflow* to manually start the deploy workflow. + + +Alternatively, you can do manual deployment with Helm: +(Requires `helm` and a valid kubeconfig) + +```bash +helm upgrade --install bytebite ./helm/bytebite \ + --namespace team-bytebite \ + --set genai.openaiApiKey="sk-..." \ + --atomic +``` + +The app is available at https://team-bytebite.stud.k8s.aet.cit.tum.de diff --git a/client/nginx.conf b/client/nginx.conf index 2a55370..2a44253 100644 --- a/client/nginx.conf +++ b/client/nginx.conf @@ -8,8 +8,8 @@ server { try_files $uri $uri/ /index.html; } - location /generate { - proxy_pass http://server:8080; + location /api/ { + proxy_pass http://api-gateway:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; diff --git a/compose.yaml b/compose.yaml index ef50db8..193d019 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,7 +1,8 @@ services: user-db: + image: ${REGISTRY:-ghcr.io/aet-devops26/team-bytebite}/user-db:${IMAGE_TAG:-latest} build: - context: ./docker/user-db + context: ./databases/user-db container_name: bytebite-user-db environment: POSTGRES_DB: ${USER_DB_NAME:-bytebite_user} @@ -16,8 +17,9 @@ services: retries: 5 grocery-db: + image: ${REGISTRY:-ghcr.io/aet-devops26/team-bytebite}/grocery-db:${IMAGE_TAG:-latest} build: - context: ./docker/grocery-db + context: ./databases/grocery-db container_name: bytebite-grocery-db environment: POSTGRES_DB: ${GROCERY_DB_NAME:-bytebite_grocery} @@ -37,15 +39,16 @@ services: build: context: ./gen-ai container_name: bytebite-gen-ai - ports: - - "8000:8000" + expose: + - "8000" environment: OPENAI_API_KEY: ${OPENAI_API_KEY} user-service: + image: ${REGISTRY:-ghcr.io/aet-devops26/team-bytebite}/user-service:${IMAGE_TAG:-latest} build: - context: ./user-service + context: ./server/user-service container_name: bytebite-user-service expose: - "8080" @@ -59,8 +62,9 @@ services: condition: service_healthy grocery-service: + image: ${REGISTRY:-ghcr.io/aet-devops26/team-bytebite}/grocery-service:${IMAGE_TAG:-latest} build: - context: ./grocery-service + context: ./server/grocery-service container_name: bytebite-grocery-service expose: - "8080" @@ -77,8 +81,9 @@ services: condition: service_started api-gateway: + image: ${REGISTRY:-ghcr.io/aet-devops26/team-bytebite}/api-gateway:${IMAGE_TAG:-latest} build: - context: ./api-gateway + context: ./server/api-gateway container_name: bytebite-api-gateway ports: - "8080:8080" @@ -91,8 +96,6 @@ services: condition: service_started grocery-service: condition: service_started - gen-ai: - condition: service_started client: image: ${REGISTRY:-ghcr.io/aet-devops26/team-bytebite}/client:${IMAGE_TAG:-latest} diff --git a/docker/grocery-db/Dockerfile b/databases/grocery-db/Dockerfile similarity index 100% rename from docker/grocery-db/Dockerfile rename to databases/grocery-db/Dockerfile diff --git a/docker/grocery-db/init.sql b/databases/grocery-db/init.sql similarity index 100% rename from docker/grocery-db/init.sql rename to databases/grocery-db/init.sql diff --git a/docker/user-db/Dockerfile b/databases/user-db/Dockerfile similarity index 100% rename from docker/user-db/Dockerfile rename to databases/user-db/Dockerfile diff --git a/docker/user-db/init.sql b/databases/user-db/init.sql similarity index 100% rename from docker/user-db/init.sql rename to databases/user-db/init.sql diff --git a/documentation/database/DBSchemaDiagram.drawio b/documentation/DBSchemaDiagram.drawio similarity index 100% rename from documentation/database/DBSchemaDiagram.drawio rename to documentation/DBSchemaDiagram.drawio diff --git a/documentation/database/SchemaDiagram.jpg b/documentation/DBSchemaDiagram.jpg similarity index 100% rename from documentation/database/SchemaDiagram.jpg rename to documentation/DBSchemaDiagram.jpg diff --git a/helm/bytebite/README.md b/helm/bytebite/README.md index d476341..a8e1157 100644 --- a/helm/bytebite/README.md +++ b/helm/bytebite/README.md @@ -1,6 +1,6 @@ # ByteBite Helm Chart -Deploys the ByteBite application (client, server, gen-ai) to Kubernetes. +Deploys the ByteBite application (client, api-gateway, user-service, grocery-service, gen-ai) to Kubernetes. ## Prerequisites @@ -29,5 +29,7 @@ helm uninstall bytebite --namespace team-bytebite | `ingress.tls` | Enable TLS via cert-manager | `true` | | `genai.openaiApiKey` | OpenAI API key for the gen-ai service | `""` | | `client.image.tag` | Client image tag | `latest` | -| `server.image.tag` | Server image tag | `latest` | +| `apiGateway.image.tag` | API gateway image tag | `latest` | +| `userService.image.tag` | User service image tag | `latest` | +| `groceryService.image.tag` | Grocery service image tag | `latest` | | `genai.image.tag` | Gen-AI image tag | `latest` | diff --git a/helm/bytebite/templates/api-gateway-deployment.yaml b/helm/bytebite/templates/api-gateway-deployment.yaml new file mode 100644 index 0000000..84d2f67 --- /dev/null +++ b/helm/bytebite/templates/api-gateway-deployment.yaml @@ -0,0 +1,33 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: bytebite-api-gateway + namespace: {{ .Values.namespace }} +spec: + replicas: {{ .Values.apiGateway.replicaCount }} + selector: + matchLabels: + app: bytebite-api-gateway-selector + template: + metadata: + labels: + app: bytebite-api-gateway-selector + spec: + containers: + - name: api-gateway + image: "{{ .Values.apiGateway.image.repository }}:{{ .Values.apiGateway.image.tag }}" + imagePullPolicy: {{ .Values.apiGateway.image.pullPolicy }} + resources: + limits: + cpu: "500m" + memory: "512Mi" + requests: + cpu: "200m" + memory: "256Mi" + ports: + - containerPort: {{ .Values.apiGateway.service.targetPort }} + env: + - name: GROCERY_SERVICE_BASE_URL + value: "http://grocery-service:{{ .Values.groceryService.service.port }}" + - name: USER_SERVICE_BASE_URL + value: "http://user-service:{{ .Values.userService.service.port }}" diff --git a/helm/bytebite/templates/api-gateway-service.yaml b/helm/bytebite/templates/api-gateway-service.yaml new file mode 100644 index 0000000..11d8f0e --- /dev/null +++ b/helm/bytebite/templates/api-gateway-service.yaml @@ -0,0 +1,13 @@ +apiVersion: v1 +kind: Service +metadata: + name: api-gateway-service + namespace: {{ .Values.namespace }} +spec: + selector: + app: bytebite-api-gateway-selector + ports: + - port: {{ .Values.apiGateway.service.port }} + targetPort: {{ .Values.apiGateway.service.targetPort }} + protocol: TCP + type: {{ .Values.apiGateway.service.type }} diff --git a/helm/bytebite/templates/client-configmap.yaml b/helm/bytebite/templates/client-configmap.yaml index df9a622..0c9b3cd 100644 --- a/helm/bytebite/templates/client-configmap.yaml +++ b/helm/bytebite/templates/client-configmap.yaml @@ -12,4 +12,10 @@ data: location / { try_files $uri $uri/ /index.html; } + location /api/ { + proxy_pass http://api-gateway-service:{{ .Values.apiGateway.service.port }}; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + } } diff --git a/helm/bytebite/templates/server-deployment.yaml b/helm/bytebite/templates/grocery-service-deployment.yaml similarity index 52% rename from helm/bytebite/templates/server-deployment.yaml rename to helm/bytebite/templates/grocery-service-deployment.yaml index 3011432..1e759f2 100644 --- a/helm/bytebite/templates/server-deployment.yaml +++ b/helm/bytebite/templates/grocery-service-deployment.yaml @@ -1,22 +1,22 @@ apiVersion: apps/v1 kind: Deployment metadata: - name: bytebite-server + name: bytebite-grocery-service namespace: {{ .Values.namespace }} spec: - replicas: {{ .Values.server.replicaCount }} + replicas: {{ .Values.groceryService.replicaCount }} selector: matchLabels: - app: bytebite-server-selector + app: bytebite-grocery-service-selector template: metadata: labels: - app: bytebite-server-selector + app: bytebite-grocery-service-selector spec: containers: - - name: server - image: "{{ .Values.server.image.repository }}:{{ .Values.server.image.tag }}" - imagePullPolicy: {{ .Values.server.image.pullPolicy }} + - name: grocery-service + image: "{{ .Values.groceryService.image.repository }}:{{ .Values.groceryService.image.tag }}" + imagePullPolicy: {{ .Values.groceryService.image.pullPolicy }} resources: limits: cpu: "500m" @@ -25,7 +25,7 @@ spec: cpu: "200m" memory: "256Mi" ports: - - containerPort: {{ .Values.server.service.targetPort }} + - containerPort: {{ .Values.groceryService.service.targetPort }} env: - name: GENAI_BASE_URL value: "http://genai-service:{{ .Values.genai.service.port }}" diff --git a/helm/bytebite/templates/grocery-service-service.yaml b/helm/bytebite/templates/grocery-service-service.yaml new file mode 100644 index 0000000..ee7b6ef --- /dev/null +++ b/helm/bytebite/templates/grocery-service-service.yaml @@ -0,0 +1,13 @@ +apiVersion: v1 +kind: Service +metadata: + name: grocery-service + namespace: {{ .Values.namespace }} +spec: + selector: + app: bytebite-grocery-service-selector + ports: + - port: {{ .Values.groceryService.service.port }} + targetPort: {{ .Values.groceryService.service.targetPort }} + protocol: TCP + type: {{ .Values.groceryService.service.type }} diff --git a/helm/bytebite/templates/ingress.yaml b/helm/bytebite/templates/ingress.yaml index 817ab6d..6790331 100644 --- a/helm/bytebite/templates/ingress.yaml +++ b/helm/bytebite/templates/ingress.yaml @@ -27,11 +27,11 @@ spec: name: client-service port: number: {{ .Values.client.service.port }} - - path: /generate + - path: /api pathType: Prefix backend: service: - name: server-service + name: api-gateway-service port: - number: {{ .Values.server.service.port }} + number: {{ .Values.apiGateway.service.port }} {{- end }} diff --git a/helm/bytebite/templates/server-service.yaml b/helm/bytebite/templates/server-service.yaml deleted file mode 100644 index f3190e2..0000000 --- a/helm/bytebite/templates/server-service.yaml +++ /dev/null @@ -1,13 +0,0 @@ -apiVersion: v1 -kind: Service -metadata: - name: server-service - namespace: {{ .Values.namespace }} -spec: - selector: - app: bytebite-server-selector - ports: - - port: {{ .Values.server.service.port }} - targetPort: {{ .Values.server.service.targetPort }} - protocol: TCP - type: {{ .Values.server.service.type }} diff --git a/helm/bytebite/templates/user-service-deployment.yaml b/helm/bytebite/templates/user-service-deployment.yaml new file mode 100644 index 0000000..64e5a56 --- /dev/null +++ b/helm/bytebite/templates/user-service-deployment.yaml @@ -0,0 +1,28 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: bytebite-user-service + namespace: {{ .Values.namespace }} +spec: + replicas: {{ .Values.userService.replicaCount }} + selector: + matchLabels: + app: bytebite-user-service-selector + template: + metadata: + labels: + app: bytebite-user-service-selector + spec: + containers: + - name: user-service + image: "{{ .Values.userService.image.repository }}:{{ .Values.userService.image.tag }}" + imagePullPolicy: {{ .Values.userService.image.pullPolicy }} + resources: + limits: + cpu: "500m" + memory: "512Mi" + requests: + cpu: "200m" + memory: "256Mi" + ports: + - containerPort: {{ .Values.userService.service.targetPort }} diff --git a/helm/bytebite/templates/user-service-service.yaml b/helm/bytebite/templates/user-service-service.yaml new file mode 100644 index 0000000..ab5e62f --- /dev/null +++ b/helm/bytebite/templates/user-service-service.yaml @@ -0,0 +1,13 @@ +apiVersion: v1 +kind: Service +metadata: + name: user-service + namespace: {{ .Values.namespace }} +spec: + selector: + app: bytebite-user-service-selector + ports: + - port: {{ .Values.userService.service.port }} + targetPort: {{ .Values.userService.service.targetPort }} + protocol: TCP + type: {{ .Values.userService.service.type }} diff --git a/helm/bytebite/values.yaml b/helm/bytebite/values.yaml index d5ae8f6..977973b 100644 --- a/helm/bytebite/values.yaml +++ b/helm/bytebite/values.yaml @@ -12,9 +12,31 @@ client: targetPort: 80 replicaCount: 1 -server: +apiGateway: image: - repository: ghcr.io/aet-devops26/team-bytebite/server + repository: ghcr.io/aet-devops26/team-bytebite/api-gateway + tag: latest + pullPolicy: Always + service: + type: ClusterIP + port: 8080 + targetPort: 8080 + replicaCount: 1 + +userService: + image: + repository: ghcr.io/aet-devops26/team-bytebite/user-service + tag: latest + pullPolicy: Always + service: + type: ClusterIP + port: 8080 + targetPort: 8080 + replicaCount: 1 + +groceryService: + image: + repository: ghcr.io/aet-devops26/team-bytebite/grocery-service tag: latest pullPolicy: Always service: diff --git a/server/.dockerignore b/server/api-gateway/.dockerignore similarity index 100% rename from server/.dockerignore rename to server/api-gateway/.dockerignore diff --git a/server/.gitattributes b/server/api-gateway/.gitattributes similarity index 100% rename from server/.gitattributes rename to server/api-gateway/.gitattributes diff --git a/server/.gitignore b/server/api-gateway/.gitignore similarity index 100% rename from server/.gitignore rename to server/api-gateway/.gitignore diff --git a/server/.mvn/wrapper/maven-wrapper.properties b/server/api-gateway/.mvn/wrapper/maven-wrapper.properties similarity index 100% rename from server/.mvn/wrapper/maven-wrapper.properties rename to server/api-gateway/.mvn/wrapper/maven-wrapper.properties diff --git a/server/Dockerfile b/server/api-gateway/Dockerfile similarity index 100% rename from server/Dockerfile rename to server/api-gateway/Dockerfile diff --git a/server/README.md b/server/api-gateway/README.md similarity index 100% rename from server/README.md rename to server/api-gateway/README.md diff --git a/server/mvnw b/server/api-gateway/mvnw similarity index 100% rename from server/mvnw rename to server/api-gateway/mvnw diff --git a/server/mvnw.cmd b/server/api-gateway/mvnw.cmd similarity index 100% rename from server/mvnw.cmd rename to server/api-gateway/mvnw.cmd diff --git a/server/api-gateway/pom.xml b/server/api-gateway/pom.xml new file mode 100644 index 0000000..f3d3cc0 --- /dev/null +++ b/server/api-gateway/pom.xml @@ -0,0 +1,83 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.5 + + + com.bytebite + api-gateway + 0.0.1-SNAPSHOT + api-gateway + + + + + + + + + + + + + + + + 21 + 2024.0.1 + + + + + org.springframework.cloud + spring-cloud-dependencies + ${spring-cloud.version} + pom + import + + + + + + org.springframework.cloud + spring-cloud-starter-gateway + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mockito + mockito-core + + + org.mockito + mockito-junit-jupiter + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + -Djdk.attach.allowAttachSelf=true + + + + + + diff --git a/server/src/main/java/com/bytebite/server/ServerApplication.java b/server/api-gateway/src/main/java/com/bytebite/server/ServerApplication.java similarity index 100% rename from server/src/main/java/com/bytebite/server/ServerApplication.java rename to server/api-gateway/src/main/java/com/bytebite/server/ServerApplication.java diff --git a/server/api-gateway/src/main/resources/application.yml b/server/api-gateway/src/main/resources/application.yml new file mode 100644 index 0000000..adda9c1 --- /dev/null +++ b/server/api-gateway/src/main/resources/application.yml @@ -0,0 +1,17 @@ +server: + port: 8080 + +spring: + application: + name: api-gateway + cloud: + gateway: + routes: + - id: grocery-service + uri: ${GROCERY_SERVICE_BASE_URL:http://localhost:8082} + predicates: + - Path=/api/recipes/** + - id: user-service + uri: ${USER_SERVICE_BASE_URL:http://localhost:8083} + predicates: + - Path=/api/users/** \ No newline at end of file diff --git a/server/src/test/java/com/bytebite/server/ServerApplicationTests.java b/server/api-gateway/src/test/java/com/bytebite/server/ServerApplicationTests.java similarity index 100% rename from server/src/test/java/com/bytebite/server/ServerApplicationTests.java rename to server/api-gateway/src/test/java/com/bytebite/server/ServerApplicationTests.java diff --git a/server/grocery-service/.dockerignore b/server/grocery-service/.dockerignore new file mode 100644 index 0000000..1be2196 --- /dev/null +++ b/server/grocery-service/.dockerignore @@ -0,0 +1,6 @@ +target +.idea +.git +*.iml +.DS_Store +.mvn \ No newline at end of file diff --git a/server/grocery-service/.gitattributes b/server/grocery-service/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/server/grocery-service/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/server/grocery-service/.gitignore b/server/grocery-service/.gitignore new file mode 100644 index 0000000..667aaef --- /dev/null +++ b/server/grocery-service/.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/server/grocery-service/.mvn/wrapper/maven-wrapper.properties b/server/grocery-service/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..5291372 --- /dev/null +++ b/server/grocery-service/.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.15/apache-maven-3.9.15-bin.zip diff --git a/server/grocery-service/Dockerfile b/server/grocery-service/Dockerfile new file mode 100644 index 0000000..533a08b --- /dev/null +++ b/server/grocery-service/Dockerfile @@ -0,0 +1,19 @@ +# Build stage +FROM maven:3.9-eclipse-temurin-21 AS build +WORKDIR /app + +COPY pom.xml . +RUN mvn dependency:go-offline + +COPY src ./src +RUN mvn clean package -DskipTests + +# Runtime stage +FROM eclipse-temurin:21-jre +WORKDIR /app + +COPY --from=build /app/target/*.jar app.jar + +EXPOSE 8080 + +ENTRYPOINT ["java", "-jar", "app.jar"] diff --git a/server/grocery-service/README.md b/server/grocery-service/README.md new file mode 100644 index 0000000..f159c37 --- /dev/null +++ b/server/grocery-service/README.md @@ -0,0 +1,32 @@ +# server + +Java Spring Boot backend API for ByteBite. + +## Prerequisites + +- Java 21 + +## Setup & Run + +**macOS / Linux** +```bash +./mvnw spring-boot:run # starts on http://localhost:8080 +``` + +**Windows** +```cmd +mvnw.cmd spring-boot:run +``` + +## Other Commands + +| | macOS / Linux | Windows | +|-|---------------|---------| +| Build | `./mvnw package` | `mvnw.cmd package` | +| Test | `./mvnw test` | `mvnw.cmd test` | + +## Endpoints + +| Method | Path | Description | +|--------|-----------|---------------| +| GET | /health | Health check | diff --git a/server/grocery-service/mvnw b/server/grocery-service/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/server/grocery-service/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/server/grocery-service/mvnw.cmd b/server/grocery-service/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/server/grocery-service/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/server/grocery-service/pom.xml b/server/grocery-service/pom.xml new file mode 100644 index 0000000..43845e4 --- /dev/null +++ b/server/grocery-service/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.4.5 + + + com.bytebite + grocery-service + 0.0.1-SNAPSHOT + grocery-service + + + + + + + + + + + + + + + + 21 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.mockito + mockito-core + + + org.mockito + mockito-junit-jupiter + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + -Djdk.attach.allowAttachSelf=true + + + + + + diff --git a/server/src/main/java/com/bytebite/server/GenAiClient.java b/server/grocery-service/src/main/java/com/bytebite/server/GenAiClient.java similarity index 100% rename from server/src/main/java/com/bytebite/server/GenAiClient.java rename to server/grocery-service/src/main/java/com/bytebite/server/GenAiClient.java diff --git a/server/src/main/java/com/bytebite/server/GenerateController.java b/server/grocery-service/src/main/java/com/bytebite/server/GenerateController.java similarity index 100% rename from server/src/main/java/com/bytebite/server/GenerateController.java rename to server/grocery-service/src/main/java/com/bytebite/server/GenerateController.java diff --git a/server/src/main/java/com/bytebite/server/HealthController.java b/server/grocery-service/src/main/java/com/bytebite/server/HealthController.java similarity index 100% rename from server/src/main/java/com/bytebite/server/HealthController.java rename to server/grocery-service/src/main/java/com/bytebite/server/HealthController.java diff --git a/server/grocery-service/src/main/java/com/bytebite/server/ServerApplication.java b/server/grocery-service/src/main/java/com/bytebite/server/ServerApplication.java new file mode 100644 index 0000000..13d5438 --- /dev/null +++ b/server/grocery-service/src/main/java/com/bytebite/server/ServerApplication.java @@ -0,0 +1,13 @@ +package com.bytebite.server; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ServerApplication { + + public static void main(String[] args) { + SpringApplication.run(ServerApplication.class, args); + } + +} diff --git a/server/src/main/java/com/bytebite/server/dto/GenerateRequest.java b/server/grocery-service/src/main/java/com/bytebite/server/dto/GenerateRequest.java similarity index 100% rename from server/src/main/java/com/bytebite/server/dto/GenerateRequest.java rename to server/grocery-service/src/main/java/com/bytebite/server/dto/GenerateRequest.java diff --git a/server/src/main/java/com/bytebite/server/dto/IngredientDTO.java b/server/grocery-service/src/main/java/com/bytebite/server/dto/IngredientDTO.java similarity index 100% rename from server/src/main/java/com/bytebite/server/dto/IngredientDTO.java rename to server/grocery-service/src/main/java/com/bytebite/server/dto/IngredientDTO.java diff --git a/server/src/main/java/com/bytebite/server/dto/RecipeResponseDTO.java b/server/grocery-service/src/main/java/com/bytebite/server/dto/RecipeResponseDTO.java similarity index 100% rename from server/src/main/java/com/bytebite/server/dto/RecipeResponseDTO.java rename to server/grocery-service/src/main/java/com/bytebite/server/dto/RecipeResponseDTO.java diff --git a/server/grocery-service/src/main/resources/application.properties b/server/grocery-service/src/main/resources/application.properties new file mode 100644 index 0000000..6920a85 --- /dev/null +++ b/server/grocery-service/src/main/resources/application.properties @@ -0,0 +1,3 @@ +spring.application.name=grocery-service +server.port=8082 +genai.base-url=http://localhost:8000 diff --git a/server/grocery-service/src/test/java/com/bytebite/server/ServerApplicationTests.java b/server/grocery-service/src/test/java/com/bytebite/server/ServerApplicationTests.java new file mode 100644 index 0000000..2d6d85b --- /dev/null +++ b/server/grocery-service/src/test/java/com/bytebite/server/ServerApplicationTests.java @@ -0,0 +1,13 @@ +package com.bytebite.server; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ServerApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/server/src/main/java/com/bytebite/server/WebConfig.java b/server/src/main/java/com/bytebite/server/WebConfig.java deleted file mode 100644 index 4b79ea3..0000000 --- a/server/src/main/java/com/bytebite/server/WebConfig.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.bytebite.server; - -import org.springframework.context.annotation.Configuration; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -@Configuration -public class WebConfig implements WebMvcConfigurer { - - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/**") - .allowedOriginPatterns("*") - .allowedMethods("GET", "POST"); - } -} diff --git a/server/src/main/resources/application.properties b/server/src/main/resources/application.properties deleted file mode 100644 index 823f225..0000000 --- a/server/src/main/resources/application.properties +++ /dev/null @@ -1,2 +0,0 @@ -spring.application.name=server -genai.base-url=http://localhost:8000 diff --git a/server/user-service/.dockerignore b/server/user-service/.dockerignore new file mode 100644 index 0000000..1be2196 --- /dev/null +++ b/server/user-service/.dockerignore @@ -0,0 +1,6 @@ +target +.idea +.git +*.iml +.DS_Store +.mvn \ No newline at end of file diff --git a/server/user-service/.gitattributes b/server/user-service/.gitattributes new file mode 100644 index 0000000..3b41682 --- /dev/null +++ b/server/user-service/.gitattributes @@ -0,0 +1,2 @@ +/mvnw text eol=lf +*.cmd text eol=crlf diff --git a/server/user-service/.gitignore b/server/user-service/.gitignore new file mode 100644 index 0000000..667aaef --- /dev/null +++ b/server/user-service/.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/server/user-service/.mvn/wrapper/maven-wrapper.properties b/server/user-service/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..5291372 --- /dev/null +++ b/server/user-service/.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.15/apache-maven-3.9.15-bin.zip diff --git a/server/user-service/Dockerfile b/server/user-service/Dockerfile new file mode 100644 index 0000000..533a08b --- /dev/null +++ b/server/user-service/Dockerfile @@ -0,0 +1,19 @@ +# Build stage +FROM maven:3.9-eclipse-temurin-21 AS build +WORKDIR /app + +COPY pom.xml . +RUN mvn dependency:go-offline + +COPY src ./src +RUN mvn clean package -DskipTests + +# Runtime stage +FROM eclipse-temurin:21-jre +WORKDIR /app + +COPY --from=build /app/target/*.jar app.jar + +EXPOSE 8080 + +ENTRYPOINT ["java", "-jar", "app.jar"] diff --git a/server/user-service/README.md b/server/user-service/README.md new file mode 100644 index 0000000..f159c37 --- /dev/null +++ b/server/user-service/README.md @@ -0,0 +1,32 @@ +# server + +Java Spring Boot backend API for ByteBite. + +## Prerequisites + +- Java 21 + +## Setup & Run + +**macOS / Linux** +```bash +./mvnw spring-boot:run # starts on http://localhost:8080 +``` + +**Windows** +```cmd +mvnw.cmd spring-boot:run +``` + +## Other Commands + +| | macOS / Linux | Windows | +|-|---------------|---------| +| Build | `./mvnw package` | `mvnw.cmd package` | +| Test | `./mvnw test` | `mvnw.cmd test` | + +## Endpoints + +| Method | Path | Description | +|--------|-----------|---------------| +| GET | /health | Health check | diff --git a/server/user-service/mvnw b/server/user-service/mvnw new file mode 100755 index 0000000..bd8896b --- /dev/null +++ b/server/user-service/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/server/user-service/mvnw.cmd b/server/user-service/mvnw.cmd new file mode 100644 index 0000000..92450f9 --- /dev/null +++ b/server/user-service/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/server/pom.xml b/server/user-service/pom.xml similarity index 70% rename from server/pom.xml rename to server/user-service/pom.xml index 0634534..ab18d00 100644 --- a/server/pom.xml +++ b/server/user-service/pom.xml @@ -9,9 +9,9 @@ com.bytebite - server + user-service 0.0.1-SNAPSHOT - server + user-service @@ -39,6 +39,16 @@ org.springframework.boot spring-boot-starter-test test + + + org.mockito + mockito-core + + + org.mockito + mockito-junit-jupiter + + @@ -48,6 +58,13 @@ org.springframework.boot spring-boot-maven-plugin + + org.apache.maven.plugins + maven-surefire-plugin + + -Djdk.attach.allowAttachSelf=true + + diff --git a/server/user-service/src/main/java/com/bytebite/server/HealthController.java b/server/user-service/src/main/java/com/bytebite/server/HealthController.java new file mode 100644 index 0000000..d57cdec --- /dev/null +++ b/server/user-service/src/main/java/com/bytebite/server/HealthController.java @@ -0,0 +1,15 @@ +package com.bytebite.server; + +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Map; + +@RestController +public class HealthController { + + @GetMapping("/health") + public Map health() { + return Map.of("status", "ok"); + } +} diff --git a/server/user-service/src/main/java/com/bytebite/server/ServerApplication.java b/server/user-service/src/main/java/com/bytebite/server/ServerApplication.java new file mode 100644 index 0000000..13d5438 --- /dev/null +++ b/server/user-service/src/main/java/com/bytebite/server/ServerApplication.java @@ -0,0 +1,13 @@ +package com.bytebite.server; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class ServerApplication { + + public static void main(String[] args) { + SpringApplication.run(ServerApplication.class, args); + } + +} diff --git a/server/user-service/src/main/resources/application.properties b/server/user-service/src/main/resources/application.properties new file mode 100644 index 0000000..fb46f13 --- /dev/null +++ b/server/user-service/src/main/resources/application.properties @@ -0,0 +1,2 @@ +spring.application.name=user-service +server.port=8083 diff --git a/server/user-service/src/test/java/com/bytebite/server/ServerApplicationTests.java b/server/user-service/src/test/java/com/bytebite/server/ServerApplicationTests.java new file mode 100644 index 0000000..2d6d85b --- /dev/null +++ b/server/user-service/src/test/java/com/bytebite/server/ServerApplicationTests.java @@ -0,0 +1,13 @@ +package com.bytebite.server; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class ServerApplicationTests { + + @Test + void contextLoads() { + } + +}