diff --git a/.adr-dir b/.adr-dir deleted file mode 100644 index 0d38988..0000000 --- a/.adr-dir +++ /dev/null @@ -1 +0,0 @@ -doc/architecture/decisions diff --git a/.deployment/docker-compose.yml b/.deployment/docker-compose.yml deleted file mode 100644 index 68ec014..0000000 --- a/.deployment/docker-compose.yml +++ /dev/null @@ -1,139 +0,0 @@ -version: "3.0" - -services: - reverse-proxy: - image: traefik:v2.1.3 - command: - - --entrypoints.web.address=:80 - - --entrypoints.websecure.address=:443 - - --providers.docker=true - - --certificatesResolvers.le.acme.httpChallenge.entryPoint=web - - --certificatesresolvers.le.acme.email=martin.eigenmann@unisg.ch - - --certificatesresolvers.le.acme.storage=/acme.json - - --providers.docker.exposedByDefault=false - - --serversTransport.insecureSkipVerify=true - ports: - - "80:80" - - "443:443" - volumes: - - /var/run/docker.sock:/var/run/docker.sock - - ./acme.json:/acme.json - restart: unless-stopped - labels: - - "traefik.enable=true" - - "traefik.http.routers.http-catchall.rule=hostregexp(`{host:.+}`)" - - "traefik.http.routers.http-catchall.entrypoints=web" - - "traefik.http.routers.http-catchall.middlewares=redirect-to-https" - - "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https" - - tapas-tasks: - image: openjdk - command: "java -jar /data/tapas-tasks-0.0.1-SNAPSHOT.jar" - restart: unless-stopped - volumes: - - ./:/data/ - environment: - roster.uri: http://roster:8082 - labels: - - "traefik.enable=true" - - "traefik.http.routers.tapas-tasks.rule=Host(`tapas-tasks.${PUB_IP}.nip.io`)" - - "traefik.http.routers.tapas-tasks.service=tapas-tasks" - - "traefik.http.services.tapas-tasks.loadbalancer.server.port=8081" - - "traefik.http.routers.tapas-tasks.tls=true" - - "traefik.http.routers.tapas-tasks.entryPoints=web,websecure" - - "traefik.http.routers.tapas-tasks.tls.certresolver=le" - - tapas-auction-house: - image: openjdk - command: "java -jar /data/tapas-auction-house-0.0.1-SNAPSHOT.jar" - restart: unless-stopped - volumes: - - ./:/data/ - environment: - mqtt.broker.uri: tcp://broker.hivemq.com:1883 - labels: - - "traefik.enable=true" - - "traefik.http.routers.tapas-auction-house.rule=Host(`tapas-auction-house.${PUB_IP}.nip.io`)" - - "traefik.http.routers.tapas-auction-house.service=tapas-auction-house" - - "traefik.http.services.tapas-auction-house.loadbalancer.server.port=8086" - - "traefik.http.routers.tapas-auction-house.tls=true" - - "traefik.http.routers.tapas-auction-house.entryPoints=web,websecure" - - "traefik.http.routers.tapas-auction-house.tls.certresolver=le" - - roster: - image: openjdk - command: "java -jar /data/roster-0.0.1-SNAPSHOT.jar" - restart: unless-stopped - volumes: - - ./:/data/ - environment: - task-list.uri: http://tapas-tasks:8081 - executor-robot.uri: http://executor-robot:8084 - executor-computation.uri: http://executor-computation:8085 - mqtt.broker.uri: tcp://broker.hivemq.com:1883 - labels: - - "traefik.enable=true" - - "traefik.http.routers.roster.rule=Host(`roster.${PUB_IP}.nip.io`)" - - "traefik.http.routers.roster.service=roster" - - "traefik.http.services.roster.loadbalancer.server.port=8082" - - "traefik.http.routers.roster.tls=true" - - "traefik.http.routers.roster.entryPoints=web,websecure" - - "traefik.http.routers.roster.tls.certresolver=le" - - executor-pool: - image: openjdk - command: "java -jar /data/executor-pool-0.0.1-SNAPSHOT.jar" - restart: unless-stopped - volumes: - - ./:/data/ - environment: - mqtt.broker.uri: tcp://broker.hivemq.com:1883 - labels: - - "traefik.enable=true" - - "traefik.http.routers.executor-pool.rule=Host(`executor-pool.${PUB_IP}.nip.io`)" - - "traefik.http.routers.executor-pool.service=executor-pool" - - "traefik.http.services.executor-pool.loadbalancer.server.port=8083" - - "traefik.http.routers.executor-pool.tls=true" - - "traefik.http.routers.executor-pool.entryPoints=web,websecure" - - "traefik.http.routers.executor-pool.tls.certresolver=le" - - executor-computation: - image: openjdk - command: "java -jar /data/executor-computation-0.0.1-SNAPSHOT.jar" - restart: unless-stopped - depends_on: - - executor-pool - - roster - volumes: - - ./:/data/ - environment: - executor_pool_uri: http://executor-pool:8083 - roster_uri: http://roster:8082 - labels: - - "traefik.enable=true" - - "traefik.http.routers.executor-computation.rule=Host(`executor-computation.${PUB_IP}.nip.io`)" - - "traefik.http.routers.executor-computation.service=executor-computation" - - "traefik.http.services.executor-computation.loadbalancer.server.port=8084" - - "traefik.http.routers.executor-computation.tls=true" - - "traefik.http.routers.executor-computation.entryPoints=web,websecure" - - "traefik.http.routers.executor-computation.tls.certresolver=le" - executor-robot: - image: openjdk - command: "java -jar /data/executor-robot-0.0.1-SNAPSHOT.jar" - restart: unless-stopped - depends_on: - - executor-pool - - roster - volumes: - - ./:/data/ - environment: - executor_pool_uri: http://executor-pool:8083 - roster_uri: http://roster:8082 - labels: - - "traefik.enable=true" - - "traefik.http.routers.executor-robot.rule=Host(`executor-robot.${PUB_IP}.nip.io`)" - - "traefik.http.routers.executor-robot.service=executor-robot" - - "traefik.http.services.executor-robot.loadbalancer.server.port=8085" - - "traefik.http.routers.executor-robot.tls=true" - - "traefik.http.routers.executor-robot.entryPoints=web,websecure" - - "traefik.http.routers.executor-robot.tls.certresolver=le" diff --git a/.editorconfig b/.editorconfig deleted file mode 100644 index c4f3e5b..0000000 --- a/.editorconfig +++ /dev/null @@ -1,9 +0,0 @@ -root = true - -[*] -charset = utf-8 -indent_style = space -indent_size = 4 -trim_trailing_whitespace = true -end_of_line = lf -insert_final_newline = true diff --git a/.github/workflows/build-and-deploy.yml b/.github/workflows/build-and-deploy.yml index 7290452..ee925ca 100644 --- a/.github/workflows/build-and-deploy.yml +++ b/.github/workflows/build-and-deploy.yml @@ -4,104 +4,83 @@ name: Build and Deploy on: - push: - branches: - - main - - workflow_dispatch: + push: + branches: + - main jobs: - build: - runs-on: ubuntu-latest - permissions: - contents: read + build: + runs-on: ubuntu-latest + permissions: + contents: read - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 11 - uses: actions/setup-java@v2 - with: - java-version: "11" - distribution: "adopt" + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 11 + uses: actions/setup-java@v2 + with: + java-version: '11' + distribution: 'adopt' - - run: mkdir ./target + + - run: mkdir ./target - - name: Cache Maven packages - uses: actions/cache@v1 - with: - path: ~/.m2 - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-m2 + - name: Build with Maven + run: mvn -f tapas-tasks/pom.xml --batch-mode --update-snapshots verify + - run: cp ./tapas-tasks/target/tapas-tasks-0.0.1-SNAPSHOT.jar ./target - - name: Build common library - run: mvn -f common/pom.xml --batch-mode --update-snapshots install + - name: Build with Maven + run: mvn -f tapas-auction-house/pom.xml --batch-mode --update-snapshots verify + - run: cp ./tapas-auction-house/target/tapas-auction-house-0.0.1-SNAPSHOT.jar ./target - - name: Build roster service - run: mvn -f roster/pom.xml --batch-mode --update-snapshots verify - - run: cp ./roster/target/roster-0.0.1-SNAPSHOT.jar ./target + - name: Build with Maven + run: mvn -f app/pom.xml --batch-mode --update-snapshots verify + - run: cp ./app/target/app-0.1.0.jar ./target - - name: Build executor-pool service - run: mvn -f executor-pool/pom.xml --batch-mode --update-snapshots verify - - run: cp ./executor-pool/target/executor-pool-0.0.1-SNAPSHOT.jar ./target + - run: cp docker-compose.yml ./target + - name: Archive artifacts + uses: actions/upload-artifact@v1 + with: + name: app + path: ./target/ + + + deploy: + runs-on: ubuntu-latest + needs: [build, ] + steps: + - name: Download app artifacts + uses: actions/download-artifact@v1 + with: + name: app + - name: Copy host via scp + uses: appleboy/scp-action@master + env: + HOST: ${{ secrets.SSH_HOST }} + USERNAME: ${{ secrets.SSH_USER }} + PORT: 22 + KEY: ${{ secrets.SSH_PRIVATE_KEY }} + with: + source: "app/*" + target: "/home/${{ secrets.SSH_USER }}/" + strip_components: 1 + rm: false + overwrite: true - - name: Build executor-base library - run: mvn -f executor-base/pom.xml --batch-mode --update-snapshots install - - - name: Build executor-computation service - run: mvn -f executor-computation/pom.xml --batch-mode --update-snapshots verify - - run: cp ./executor-computation/target/executor-computation-0.0.1-SNAPSHOT.jar ./target - - - name: Build executor-robot service - run: mvn -f executor-robot/pom.xml --batch-mode --update-snapshots verify - - run: cp ./executor-robot/target/executor-robot-0.0.1-SNAPSHOT.jar ./target - - - name: Build tapas-task service - run: mvn -f tapas-tasks/pom.xml --batch-mode --update-snapshots verify - - run: cp ./tapas-tasks/target/tapas-tasks-0.0.1-SNAPSHOT.jar ./target - - - name: Build tapas-auction-house service - run: mvn -f tapas-auction-house/pom.xml --batch-mode --update-snapshots verify - - run: cp ./tapas-auction-house/target/tapas-auction-house-0.0.1-SNAPSHOT.jar ./target - - - run: cp ./.deployment/docker-compose.yml ./target - - name: Archive artifacts - uses: actions/upload-artifact@v1 - with: - name: app - path: ./target/ - - deploy: - runs-on: ubuntu-latest - needs: [build] - steps: - - name: Download app artifacts - uses: actions/download-artifact@v1 - with: - name: app - - name: Copy host via scp - uses: appleboy/scp-action@master - env: - HOST: ${{ secrets.SSH_HOST }} - USERNAME: ${{ secrets.SSH_USER }} - PORT: 22 - KEY: ${{ secrets.SSH_PRIVATE_KEY }} - with: - source: "app/*" - target: "/home/${{ secrets.SSH_USER }}/" - strip_components: 1 - rm: false - overwrite: true - - - name: Executing remote command - uses: appleboy/ssh-action@master - with: - host: ${{ secrets.SSH_HOST }} - USERNAME: ${{ secrets.SSH_USER }} - PORT: 22 - KEY: ${{ secrets.SSH_PRIVATE_KEY }} - script: | - cd /home/${{ secrets.SSH_USER }}/ - touch acme.json - sudo chmod 0600 acme.json - sudo echo "PUB_IP=$(wget -qO- http://ipecho.net/plain | xargs echo)" | sed -e 's/\./-/g' > .env - sudo docker-compose up -d --build --force-recreate + - name: Executing remote command + uses: appleboy/ssh-action@master + with: + host: ${{ secrets.SSH_HOST }} + USERNAME: ${{ secrets.SSH_USER }} + PORT: 22 + KEY: ${{ secrets.SSH_PRIVATE_KEY }} + script: | + cd /home/${{ secrets.SSH_USER }}/ + touch acme.json + sudo chmod 0600 acme.json + sudo docker-compose down --remove-orphans + sudo echo "PUB_IP=$(wget -qO- http://ipecho.net/plain | xargs echo)" | sed -e 's/\./-/g' > .env + sudo docker-compose up -d + + + diff --git a/.github/workflows/ci.executor-computation.yml b/.github/workflows/ci.executor-computation.yml deleted file mode 100644 index 5832883..0000000 --- a/.github/workflows/ci.executor-computation.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: CI executor-computation -on: - push: - branches: [main, dev] - paths: - - "executor-base/**" - - "executor-computation/**" - - "common/**" - pull_request: - branches: [main, dev] - paths: - - "executor-base/**" - - "executor-computation/**" - - "common/**" - - workflow_dispatch: -jobs: - build: - name: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - java-version: 11 - - name: Cache SonarCloud packages - uses: actions/cache@v1 - with: - path: ~/.sonar/cache - key: ${{ runner.os }}-sonar - restore-keys: ${{ runner.os }}-sonar - - name: Cache Maven packages - uses: actions/cache@v1 - with: - path: ~/.m2 - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-m2 - - name: Build common - run: mvn -f common/pom.xml -B install - - name: Build executorBase - run: mvn -f executor-base/pom.xml -B install - - name: Build and analyze - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: mvn -f executor-computation/pom.xml -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=scs-asse-fs21-group1_tapas-executor2 diff --git a/.github/workflows/ci.executor-pool.yml b/.github/workflows/ci.executor-pool.yml deleted file mode 100644 index e22a171..0000000 --- a/.github/workflows/ci.executor-pool.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: CI Executor Pool -on: - push: - branches: [main, dev] - paths: - - "executor-pool/**" - pull_request: - branches: [main, dev] - paths: - - "executor-pool/**" - - workflow_dispatch: -jobs: - build: - name: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - java-version: 11 - - name: Cache SonarCloud packages - uses: actions/cache@v1 - with: - path: ~/.sonar/cache - key: ${{ runner.os }}-sonar - restore-keys: ${{ runner.os }}-sonar - - name: Cache Maven packages - uses: actions/cache@v1 - with: - path: ~/.m2 - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-m2 - - name: Build and analyze - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: mvn -f executor-pool/pom.xml -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=scs-asse-fs21-group1_tapas-executor-pool diff --git a/.github/workflows/ci.executor-robot.yml b/.github/workflows/ci.executor-robot.yml deleted file mode 100644 index 7a216aa..0000000 --- a/.github/workflows/ci.executor-robot.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: CI executor-robot -on: - push: - branches: [main, dev] - paths: - - "executor-base/**" - - "executor-robot/**" - - "common/**" - pull_request: - branches: [main, dev] - paths: - - "executor-base/**" - - "executor-robot/**" - - "common/**" - - workflow_dispatch: -jobs: - build: - name: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - java-version: 11 - - name: Cache SonarCloud packages - uses: actions/cache@v1 - with: - path: ~/.sonar/cache - key: ${{ runner.os }}-sonar - restore-keys: ${{ runner.os }}-sonar - - name: Cache Maven packages - uses: actions/cache@v1 - with: - path: ~/.m2 - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-m2 - - name: Build executorBase - run: mvn -f common/pom.xml -B install - - name: Build executorBase - run: mvn -f executor-base/pom.xml -B install - - name: Build and analyze - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: mvn -f executor-robot/pom.xml -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=scs-asse-fs21-group1_tapas-executor1 diff --git a/.github/workflows/ci.roster.yml b/.github/workflows/ci.roster.yml deleted file mode 100644 index b38355e..0000000 --- a/.github/workflows/ci.roster.yml +++ /dev/null @@ -1,45 +0,0 @@ -name: CI Roster -on: - push: - branches: [main, dev] - paths: - - "roster/**" - - "common/**" - pull_request: - branches: [main, dev] - paths: - - "roster/**" - - "common/**" - - workflow_dispatch: -jobs: - build: - name: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - java-version: 11 - - name: Cache SonarCloud packages - uses: actions/cache@v1 - with: - path: ~/.sonar/cache - key: ${{ runner.os }}-sonar - restore-keys: ${{ runner.os }}-sonar - - name: Cache Maven packages - uses: actions/cache@v1 - with: - path: ~/.m2 - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-m2 - - name: Build common package - run: mvn -f common/pom.xml -B install - - name: Build and analyze - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: mvn -f roster/pom.xml -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=scs-asse-fs21-group1_tapas-assignment diff --git a/.github/workflows/ci.tapas-tasks.yml b/.github/workflows/ci.tapas-tasks.yml deleted file mode 100644 index 2ddd621..0000000 --- a/.github/workflows/ci.tapas-tasks.yml +++ /dev/null @@ -1,41 +0,0 @@ -name: CI Tasks -on: - push: - branches: [main, dev] - paths: - - "tapas-tasks/**" - pull_request: - branches: [main, dev] - paths: - - "tapas-tasks/**" - - workflow_dispatch: -jobs: - build: - name: Build - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - with: - fetch-depth: 0 - - name: Set up JDK 11 - uses: actions/setup-java@v1 - with: - java-version: 11 - - name: Cache SonarCloud packages - uses: actions/cache@v1 - with: - path: ~/.sonar/cache - key: ${{ runner.os }}-sonar - restore-keys: ${{ runner.os }}-sonar - - name: Cache Maven packages - uses: actions/cache@v1 - with: - path: ~/.m2 - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-m2 - - name: Build and analyze - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} - run: mvn -f tapas-tasks/pom.xml -B verify org.sonarsource.scanner.maven:sonar-maven-plugin:sonar -Dsonar.projectKey=scs-asse-fs21-group1_tapas-tasks diff --git a/.gitignore b/.gitignore index e01b495..549e00a 100644 --- a/.gitignore +++ b/.gitignore @@ -31,7 +31,3 @@ build/ ### VS Code ### .vscode/ - -### Mac ### -.DS_Store - diff --git a/README.md b/README.md index 57106c5..bcc7355 100644 --- a/README.md +++ b/README.md @@ -1,113 +1,62 @@ # TAPAS - This is the main GitHub project for your implementation of the TAPAS application. -## Run application in developent - -We use Docker & docker-compose in development to easly start all the microservices and other needed application (db's, message-broker's) at once. All microservices have hot-reloads enabled by default! - -#### Start - -``` -docker-compose up -``` - -#### Rebuild container - -``` -docker-compose up --build -``` - -#### Start detached - -``` -docker-compose up -d -``` - -#### Stop detached - -``` -docker-compose down -``` - -## Available Services - -Ports and debug ports of each service are listed below: - -| Name | Port | Debug Port | -| ------------------ | ---- | ---------- | -| Tasklist | 8081 | 5005 | -| Assignment Service | 8082 | 5006 | -| Executor Pool | 8083 | 5007 | -| Executor 1 | 8084 | 5008 | -| Executor 2 | 8085 | 5009 | - ## Project Structure - This project is structured as follows: - -- [tapas-tasks](tapas-tasks): standalone project for the Tapas-Tasks micro-service (Spring Boot project) - - [tapas-tasks/src](tapas-tasks/src): source code of the project (following the Hexagonal Architecture) - - [tapas-tasks/pom.xml](tapas-tasks\pom.xml): Maven pom-file -- [app](app): folder as placeholder for a second micro-service (Spring Boot project) -- [docker-compose.yml](docker-compose.yml): Docker Compose configuration file for all services -- [.github/workflows/build-and-deploy.yml](.github/workflows/build-and-deploy.yml): GitHub actions script (CI/CD workflow) +* [tapas-tasks](tapas-tasks): standalone project for the Tapas-Tasks micro-service (Spring Boot project) + * [tapas-tasks/src](tapas-tasks/src): source code of the project (following the Hexagonal Architecture) + * [tapas-tasks/pom.xml](tapas-tasks\pom.xml): Maven pom-file +* [app](app): folder as placeholder for a second micro-service (Spring Boot project) +* [docker-compose.yml](docker-compose.yml): Docker Compose configuration file for all services +* [.github/workflows/build-and-deploy.yml](.github/workflows/build-and-deploy.yml): GitHub actions script (CI/CD workflow) ## How to Add a New Service with Spring Boot ### Create a new Spring Boot project -- Recommended: use [Spring Initialzr](https://start.spring.io/) (Maven, Spring Boot 2.5.5, Jar, Java 11, dependencies as needed) -- Set the Spring application properties for your service (e.g., port of the web server) in `src/resources/application.properties` +* Recommended: use [Spring Initialzr](https://start.spring.io/) (Maven, Spring Boot 2.5.5, Jar, Java 11, dependencies as needed) +* Set the Spring application properties for your service (e.g., port of the web server) in `src/resources/application.properties` ### Update the Docker Compose file - Your TAPAS application is a multi-container Docker application ran with [Docker Compose](https://docs.docker.com/compose/). -To add your newly created service to the Docker Compose configuration file, you need to create a new service +To add your newly created service to the Docker Compose configuration file, you need to create a new service definition in [docker-compose.yml](docker-compose.yml): - -- copy and edit the `tapas-tasks` service definition from [lines 29-42](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/docker-compose.yml#L29-L42) -- change `command` (see [line 31](https://github.com/scs-asse/tapas/blob/main/docker-compose.yml#L31)) - to use the name of the JAR file generated by Maven for your service - - note: if you change the version of your service, you need to update this line to reflect the change -- update the Traefik label names to reflect the name of your new service (see [lines 37-42](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/docker-compose.yml#L37-L42)) - - e.g., change `traefik.http.routers.tapas-tasks.rule` to `traefik.http.routers..rule` -- update the Traefik `rule` (see [line 37](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/docker-compose.yml#L37)) with the name of your new service: `` Host(`.${PUB_IP}.nip.io`) `` -- update the Traefik `port` (see [line 39](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/docker-compose.yml#L39)) with the port configured for your new service +* copy and edit the `tapas-tasks` service definition from [lines 29-42](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/docker-compose.yml#L29-L42) +* change `command` (see [line 31](https://github.com/scs-asse/tapas/blob/main/docker-compose.yml#L31)) +to use the name of the JAR file generated by Maven for your service + * note: if you change the version of your service, you need to update this line to reflect the change +* update the Traefik label names to reflect the name of your new service (see [lines 37-42](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/docker-compose.yml#L37-L42)) + * e.g., change `traefik.http.routers.tapas-tasks.rule` to `traefik.http.routers..rule` +* update the Traefik `rule` (see [line 37](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/docker-compose.yml#L37)) with the name of your new service: ``Host(`.${PUB_IP}.nip.io`)`` +* update the Traefik `port` (see [line 39](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/docker-compose.yml#L39)) with the port configured for your new service ### Update the GitHub Actions Workflow - -This project uses GitHub Actions to build and deploy your TAPAS application whenever a new commit is -pushed on the `main` branch. You can add your new service to the GitHub Actions workflow defined in +This project uses GitHub Actions to build and deploy your TAPAS application whenever a new commit is +pushed on the `main` branch. You can add your new service to the GitHub Actions workflow defined in [.github/workflows/build-and-deploy.yml](.github/workflows/build-and-deploy.yml): - -- copy and edit the definition for `tapas-tasks` from [line 28-30](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/.github/workflows/build-and-deploy.yml#L28-L30) -- update the `mvn` command used to build your service to point to the `pom.xml` file of your new service (see [line 29](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/.github/workflows/build-and-deploy.yml#L29)) -- update the `cp` command to point to the JAR file of your new service directive (see [line 30](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/.github/workflows/build-and-deploy.yml#L30)) - - note you will need to update the complete file path (folder structure and JAR name) +* copy and edit the definition for `tapas-tasks` from [line 28-30](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/.github/workflows/build-and-deploy.yml#L28-L30) +* update the `mvn` command used to build your service to point to the `pom.xml` file of your new service (see [line 29](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/.github/workflows/build-and-deploy.yml#L29)) +* update the `cp` command to point to the JAR file of your new service directive (see [line 30](https://github.com/scs-asse/tapas/blob/424a5f5aa2d6524acfe95d93000571884ed9d66f/.github/workflows/build-and-deploy.yml#L30)) + * note you will need to update the complete file path (folder structure and JAR name) ### How to Run Your Service Locally - You can run and test your micro-service on your local machine just like a regular Maven project: - -- Run from IntelliJ: - - Reload _pom.xml_ if necessary - - Run the micro-service's main class from IntelliJ for all required projects -- Use Maven to run from the command line: - +* Run from IntelliJ: + * Reload *pom.xml* if necessary + * Run the micro-service's main class from IntelliJ for all required projects +* Use Maven to run from the command line: ```shell mvn spring-boot:run ``` ## How to Deploy on your VM - 1. Start your Ubuntu VM on Switch. - - VM shuts down automatically at 2 AM - - Group admins can do this via https://engines.switch.ch/horizon -2. Push new code to the _main_ branch - - Check the status of the workflow on the _Actions_ page of the GitHub project - - We recommend to test your project locally before pushing the code to GitHub. The GitHub Organizations - used in the course are on a free tier plan, which comes with [various limits](https://github.com/pricing). + * VM shuts down automatically at 2 AM + * Group admins can do this via https://engines.switch.ch/horizon +2. Push new code to the *main* branch + * Check the status of the workflow on the *Actions* page of the GitHub project + * We recommend to test your project locally before pushing the code to GitHub. The GitHub Organizations + used in the course are on a free tier plan, which comes with [various limits](https://github.com/pricing). 3. Open in your browser `https://app..nip.io` For the server IP address (see below), you should use dashes instead of dots, e.g.: `127.0.0.1` becomes `127-0-0-1`. @@ -115,21 +64,19 @@ For the server IP address (see below), you should use dashes instead of dots, e. ## VM Configurations Specs (we can upgrade if needed): +* 1 CPU +* 2 GB RAM +* 20 GB HD +* Ubuntu 20.04 -- 1 CPU -- 2 GB RAM -- 20 GB HD -- Ubuntu 20.04 - -| Name | Server IP | -| ------------------ | ------------- | -| SCS-ASSE-VM-Group1 | 86.119.35.40 | -| SCS-ASSE-VM-Group2 | 86.119.35.213 | -| SCS-ASSE-VM-Group3 | 86.119.34.242 | -| SCS-ASSE-VM-Group4 | 86.119.35.199 | -| SCS-ASSE-VM-Group5 | 86.119.35.72 | +| Name | Server IP | +|-------|-----------| +|SCS-ASSE-VM-Group1|86.119.35.40| +|SCS-ASSE-VM-Group2|86.119.35.213| +|SCS-ASSE-VM-Group3|86.119.34.242| +|SCS-ASSE-VM-Group4|86.119.35.199| +|SCS-ASSE-VM-Group5|86.119.35.72| ## Architecture Decision Records - -We recommend you to use [adr-tools](https://github.com/npryce/adr-tools) to manage your ADRs here in -this GitHub project in a dedicated folder. The tool works best on a Mac OS or Linux machine. +We recommend you to use [adr-tools](https://github.com/npryce/adr-tools) to manage your ADRs here in +this GitHub project in a dedicated folder. The tool works best on a Mac OS or Linux machine. \ No newline at end of file diff --git a/app/Dockerfile b/app/Dockerfile new file mode 100644 index 0000000..429a177 --- /dev/null +++ b/app/Dockerfile @@ -0,0 +1,13 @@ +# Dockerfile/Docker-Compose file based on an initial version authored by Alexander Lontke (ASSE, Fall Semester 2021) + +FROM maven as build + +COPY . /app + +RUN mvn -f app/pom.xml --batch-mode --update-snapshots verify + +FROM openjdk + +COPY --from=build /app/target/app-0.1.0.jar ./app-0.1.0.jar + +CMD java -jar app-0.1.0.jar diff --git a/app/pom.xml b/app/pom.xml new file mode 100644 index 0000000..5f4a1fe --- /dev/null +++ b/app/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + com.dockerforjavadevelopers + app + 0.1.0 + + + org.springframework.boot + spring-boot-starter-parent + 2.2.1.RELEASE + + + + + org.springframework.boot + spring-boot-starter-web + + + + junit + junit + 4.13.1 + test + + + + + + com.dockerforjavadevelopers.hello.Application + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/app/src/main/java/com/app/hello/Application.java b/app/src/main/java/com/app/hello/Application.java new file mode 100755 index 0000000..8f330a7 --- /dev/null +++ b/app/src/main/java/com/app/hello/Application.java @@ -0,0 +1,19 @@ +package com.dockerforjavadevelopers.hello; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +@Configuration +@EnableAutoConfiguration +@ComponentScan +public class Application { + + public static void main(String[] args) { + ApplicationContext ctx = SpringApplication.run(Application.class, args); + + } + +} diff --git a/app/src/main/java/com/app/hello/HelloController.java b/app/src/main/java/com/app/hello/HelloController.java new file mode 100755 index 0000000..8d69328 --- /dev/null +++ b/app/src/main/java/com/app/hello/HelloController.java @@ -0,0 +1,14 @@ +package com.dockerforjavadevelopers.hello; + +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.RequestMapping; + +@RestController +public class HelloController { + + @RequestMapping("/") + public String index() { + return "Hello World! Nice to see you :-)\n"; + } + +} diff --git a/app/src/test/java/com/app/hello/DummyTest.java b/app/src/test/java/com/app/hello/DummyTest.java new file mode 100755 index 0000000..7d25f73 --- /dev/null +++ b/app/src/test/java/com/app/hello/DummyTest.java @@ -0,0 +1,13 @@ +package com.dockerforjavadevelopers.hello; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class DummyTest { + + @Test + public void aTest() { + assertEquals(true, true); + } +} diff --git a/common/.mvn/wrapper/MavenWrapperDownloader.java b/common/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index e76d1f3..0000000 --- a/common/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed 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 - * - * https://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. - */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/common/.mvn/wrapper/maven-wrapper.jar b/common/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 2cc7d4a..0000000 Binary files a/common/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/common/.mvn/wrapper/maven-wrapper.properties b/common/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index abd303b..0000000 --- a/common/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/common/mvnw b/common/mvnw deleted file mode 100755 index a16b543..0000000 --- a/common/mvnw +++ /dev/null @@ -1,310 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - 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" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/common/mvnw.cmd b/common/mvnw.cmd deleted file mode 100644 index c8d4337..0000000 --- a/common/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@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 https://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 Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/common/pom.xml b/common/pom.xml deleted file mode 100644 index f4e8342..0000000 --- a/common/pom.xml +++ /dev/null @@ -1,72 +0,0 @@ - - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.5.5 - - - - ch.unisg - common - 0.0.1-SNAPSHOT - - common - - http://www.example.com - - - 11 - - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - org.springframework.boot - spring-boot-starter-validation - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - - javax.validation - validation-api - 1.1.0.Final - - - - javax.transaction - javax.transaction-api - 1.2 - - - - org.json - json - 20210307 - - - - - diff --git a/common/src/main/java/ch/unisg/common/exception/ErrorResponse.java b/common/src/main/java/ch/unisg/common/exception/ErrorResponse.java deleted file mode 100644 index aeef41c..0000000 --- a/common/src/main/java/ch/unisg/common/exception/ErrorResponse.java +++ /dev/null @@ -1,13 +0,0 @@ -package ch.unisg.common.exception; - -import org.springframework.http.HttpStatus; - -import lombok.Data; -import lombok.RequiredArgsConstructor; - -@Data -@RequiredArgsConstructor -public class ErrorResponse { - private final HttpStatus httpStatus; - private final String message; -} diff --git a/common/src/main/java/ch/unisg/common/exception/InvalidExecutorURIException.java b/common/src/main/java/ch/unisg/common/exception/InvalidExecutorURIException.java deleted file mode 100644 index 1d619e9..0000000 --- a/common/src/main/java/ch/unisg/common/exception/InvalidExecutorURIException.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.unisg.common.exception; - -public class InvalidExecutorURIException extends Exception { - public InvalidExecutorURIException() { - super("URI is invalid"); - } -} diff --git a/common/src/main/java/ch/unisg/common/validation/SelfValidating.java b/common/src/main/java/ch/unisg/common/validation/SelfValidating.java deleted file mode 100644 index bb2d0fe..0000000 --- a/common/src/main/java/ch/unisg/common/validation/SelfValidating.java +++ /dev/null @@ -1,31 +0,0 @@ -package ch.unisg.common.validation; - -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; -import java.util.Set; - -public abstract class SelfValidating { - - private Validator validator; - - protected SelfValidating() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - validator = factory.getValidator(); - } - - /** - * Evaluates all Bean Validations on the attributes of this - * instance. - */ - protected void validateSelf() { - @SuppressWarnings("unchecked") - Set> violations = validator.validate((T) this); - if (!violations.isEmpty()) { - throw new ConstraintViolationException(violations); - } - } -} - diff --git a/common/src/main/java/ch/unisg/common/valueobject/ExecutorURI.java b/common/src/main/java/ch/unisg/common/valueobject/ExecutorURI.java deleted file mode 100644 index 627104e..0000000 --- a/common/src/main/java/ch/unisg/common/valueobject/ExecutorURI.java +++ /dev/null @@ -1,13 +0,0 @@ -package ch.unisg.common.valueobject; - -import java.net.URI; -import lombok.Value; - -@Value -public class ExecutorURI { - private URI value; - - public ExecutorURI(String uri) { - this.value = URI.create(uri); - } -} diff --git a/doc/architecture/decisions/0001-record-architecture-decisions.md b/doc/architecture/decisions/0001-record-architecture-decisions.md deleted file mode 100644 index ed632e4..0000000 --- a/doc/architecture/decisions/0001-record-architecture-decisions.md +++ /dev/null @@ -1,19 +0,0 @@ -# 1. Record architecture decisions - -Date: 2021-10-18 - -## Status - -Accepted - -## Context - -We need to record the architectural decisions made on this project. - -## Decision - -We will use Architecture Decision Records, as [described by Michael Nygard](http://thinkrelevance.com/blog/2011/11/15/documenting-architecture-decisions). - -## Consequences - -See Michael Nygard's article, linked above. For a lightweight ADR toolset, see Nat Pryce's [adr-tools](https://github.com/npryce/adr-tools). diff --git a/doc/architecture/decisions/0002-seperate-service-for-executors.md b/doc/architecture/decisions/0002-seperate-service-for-executors.md deleted file mode 100644 index 781d9b4..0000000 --- a/doc/architecture/decisions/0002-seperate-service-for-executors.md +++ /dev/null @@ -1,21 +0,0 @@ -# 2. Seperate service for Executors - -Date: 2021-10-18 - -## Status - -Accepted - -## Context - -The users need to be able to add new executors to the executor pool. The functionality of the executor is currently unknown. - -## Decision - -We will use a separate microservice for each executor. -New executors will be added/removed during runtime. Therefore, we need a high extensibility. -Different executors can have different execution times and a different load. This means the executors scale differently. - -## Consequences - -Having executors as its own service we can deploy new executors independently and easily add new executors during runtime and guarantee high scalability as well as evolvability. diff --git a/doc/architecture/decisions/0003-seperate-service-for-assignment-domain.md b/doc/architecture/decisions/0003-seperate-service-for-assignment-domain.md deleted file mode 100644 index 309c793..0000000 --- a/doc/architecture/decisions/0003-seperate-service-for-assignment-domain.md +++ /dev/null @@ -1,21 +0,0 @@ -# 3. Seperate service for assignment domain - -Date: 2021-10-18 - -## Status - -Accepted - -## Context - -The Assignment Service handles the assignment of a task to a corresponding and available executor. It keeps track of all the connections between tasks and executors. - -## Decision - -The assignment domain will be its own service. -The assignment service will be a central point in our application. It will have most of the business logic in it and will communicate with all the different services. Therefore, other services can be kind of “dumb” and only need to focus on their simple tasks. -The code of the assignment will change more often than the code of the other services, thus having the assignment service split from the other makes it more deployable. - -## Consequences - -Having this system as its own service we reduce the Fault tolerance because the assignment service can be the single point of failure. We can mitigate this risk by implementing (server) replication and/or having an event driven communication with persisting messages. Therefore, all other services can run independently, and the assignment service can recover from a crash. diff --git a/doc/architecture/decisions/0004-seperate-service-for-executor-pool.md b/doc/architecture/decisions/0004-seperate-service-for-executor-pool.md deleted file mode 100644 index 6c8aea2..0000000 --- a/doc/architecture/decisions/0004-seperate-service-for-executor-pool.md +++ /dev/null @@ -1,21 +0,0 @@ -# 4. Seperate service for executor pool - -Date: 2021-10-18 - -## Status - -Accepted - -## Context - -The Executor pool keeps track of the connected executors and their purpose and status. - -## Decision - -We will have a separate service for the executor pool. -There are no other domains which share the same or similar functionality. -The executor pool also scales differently than other services. - -## Consequences - -Having the executor pool as a separate service will help with the deployability of this service but will make the overall structure more complex and reduces testability. diff --git a/doc/architecture/decisions/0005-event-driven-communication.md b/doc/architecture/decisions/0005-event-driven-communication.md deleted file mode 100644 index c711f62..0000000 --- a/doc/architecture/decisions/0005-event-driven-communication.md +++ /dev/null @@ -1,20 +0,0 @@ -# 5. Event driven communication - -Date: 2021-10-18 - -## Status - -Accepted - -## Context - -Services need to be able to communicate with each other. Services need to be scalable and therefore multiple services will need to get the same messages. Most of the processes are about responding to events that are happening throughout the system. - -## Decision - -We will use mainly event driven communication. - -## Consequences - -Event driven communication will help use to create a system which has high scalability and elasticity. Through persisting messages, we will also reach way higher fault tolerance and recoverability. -Having an event driven communication, we can only guarantee eventual consistency. diff --git a/doc/architecture/decisions/0006-one-global-database-or-one-database-per-service.md b/doc/architecture/decisions/0006-one-global-database-or-one-database-per-service.md deleted file mode 100644 index 5f5c70d..0000000 --- a/doc/architecture/decisions/0006-one-global-database-or-one-database-per-service.md +++ /dev/null @@ -1,20 +0,0 @@ -# 6. One global database or one database per service - -Date: 2021-10-18 - -## Status - -Accepted - -## Context - -We can have one database for all services or each Microservice can have its own database. - -## Decision - -Each Microservice will have its own database. -The different services don’t need to store a lot of similar data. Therefore, we can have every Microservice handle its own data. This also gives the advantage that every Microservice owns its own data and is also responsible for it. (Data ownership, Data responsibility). - -## Consequences - -Having one database per Microservice will lead to eventual consistency. Having an event driven communication we can use event-based synchronisation to keep the data in sync between the services, thus the individual services don’t need to know about each other. To guarantee data consistency we can also use a pattern like sagas. diff --git a/doc/workflow.bpmn b/doc/workflow.bpmn deleted file mode 100644 index 6d68a24..0000000 --- a/doc/workflow.bpmn +++ /dev/null @@ -1,337 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - Flow_1rie16h - Flow_159tlyd - Flow_01pbz6s - - - Flow_159tlyd - - - Flow_01pbz6s - - - Flow_1urp3d2 - - - Flow_1urp3d2 - Flow_1oy6e8u - Flow_1rxws1j - - - Flow_1oy6e8u - - - Flow_1rxws1j - - - - - Flow_1rie16h - - - - - - - - - - - - - - - Flow_0nuuhk7 - - - Flow_0nuuhk7 - Flow_197gie6 - Flow_0ruufha - - - Flow_197gie6 - - - - Flow_0ruufha - Flow_1duwugb - - - - Flow_19m4xhk - - - Flow_19m4xhk - Flow_0b4g73l - Flow_1duwugb - - - Flow_0b4g73l - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/doc/workflow.png b/doc/workflow.png deleted file mode 100644 index 4946693..0000000 Binary files a/doc/workflow.png and /dev/null differ diff --git a/docker-compose-local.yml b/docker-compose-local.yml new file mode 100644 index 0000000..1ddfc24 --- /dev/null +++ b/docker-compose-local.yml @@ -0,0 +1,60 @@ +# Dockerfile/Docker-Compose file based on an initial version authored by Alexander Lontke (ASSE, Fall Semester 2021) + +version: "3.7" + +services: + app: + build: + context: ./app + dockerfile: Dockerfile + # Use environment variables instead of application.properties + environment: + - KEY=VALUE + ports: #Just needed when testing from outside the docker network + - "8080:8080" + networks: + - tapas-network + + tapas-tasks: + build: + context: ./tapas-tasks + dockerfile: Dockerfile + # Use environment variables instead of application.properties + environment: + - KEY=VALUE + ports: #Just needed when testing from outside + - "8081:8081" + networks: + - tapas-network + + tapas-auction-house: + build: + context: ./tapas-auction-house + dockerfile: Dockerfile + # Use environment variables instead of application.properties + environment: + - KEY=VALUE + ports: #Just needed when testing from outside + - "8082:8082" + networks: + - tapas-network + + mongodb: + image: mongo + container_name: mongodb + restart: unless-stopped + environment: + MONGO_INITDB_ROOT_USERNAME: root + MONGO_INITDB_ROOT_PASSWORD: 8nP7s0a # Can not be changed again later on + volumes: + - database:/data/db + networks: + - tapas-network + +#Volume for mongodb. One per server. +volumes: + database: + +networks: + tapas-network: + driver: bridge diff --git a/docker-compose.yaml b/docker-compose.yaml deleted file mode 100644 index 1364b66..0000000 --- a/docker-compose.yaml +++ /dev/null @@ -1,62 +0,0 @@ -version: "3.6" -services: - tapas-tasks: - container_name: tapas-tasks - build: - context: "./tapas-tasks" - dockerfile: "Dockerfile" - target: development - ports: - - "8081:8081" - - "5005:5005" - volumes: - - ./tapas-tasks/src:/opt/app/src - - ./tapas-tasks/target:/opt/app/target - assignment: - container_name: assignment - build: - context: "./assignment" - dockerfile: "Dockerfile" - target: development - ports: - - "8082:8082" - - "5006:5005" - volumes: - - ./assignment/src:/opt/app/src - - ./assignment/target:/opt/app/target - executor-pool: - container_name: executor-pool - build: - context: "./executor-pool" - dockerfile: "Dockerfile" - target: development - ports: - - "8083:8083" - - "5007:5005" - volumes: - - ./executor-pool/src:/opt/app/src - - ./executor-pool/target:/opt/app/target - executor1: - container_name: executor1 - build: - context: "./executor1" - dockerfile: "Dockerfile" - target: development - ports: - - "8084:8084" - - "5008:5005" - volumes: - - ./executor1/src:/opt/app/src - - ./executor1/target:/opt/app/target - executor2: - container_name: executor2 - build: - context: "./executor2" - dockerfile: "Dockerfile" - target: development - ports: - - "8085:8085" - - "5009:5005" - volumes: - - ./executor2/src:/opt/app/src - - ./executor2/target:/opt/app/target diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..84b12fe --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,105 @@ +version: "3.0" + +services: + reverse-proxy: + image: traefik:v2.1.3 + command: + - --entrypoints.web.address=:80 + - --entrypoints.websecure.address=:443 + - --providers.docker=true + - --certificatesResolvers.le.acme.httpChallenge.entryPoint=web + - --certificatesresolvers.le.acme.email=martin.eigenmann@unisg.ch + - --certificatesresolvers.le.acme.storage=/acme.json + - --providers.docker.exposedByDefault=false + - --serversTransport.insecureSkipVerify=true + ports: + - "80:80" + - "443:443" + volumes: + - /var/run/docker.sock:/var/run/docker.sock + - ./acme.json:/acme.json + restart: unless-stopped + labels: + - "traefik.enable=true" + - "traefik.http.routers.http-catchall.rule=hostregexp(`{host:.+}`)" + - "traefik.http.routers.http-catchall.entrypoints=web" + - "traefik.http.routers.http-catchall.middlewares=redirect-to-https" + - "traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https" + + tapas-tasks: + image: openjdk + command: "java -jar /data/tapas-tasks-0.0.1-SNAPSHOT.jar" + restart: unless-stopped + volumes: + - ./:/data/ + labels: + - "traefik.enable=true" + - "traefik.http.routers.tapas-tasks.rule=Host(`tapas-tasks.${PUB_IP}.nip.io`)" + - "traefik.http.routers.tapas-tasks.service=tapas-tasks" + - "traefik.http.services.tapas-tasks.loadbalancer.server.port=8081" + - "traefik.http.routers.tapas-tasks.tls=true" + - "traefik.http.routers.tapas-tasks.entryPoints=web,websecure" + - "traefik.http.routers.tapas-tasks.tls.certresolver=le" + + tapas-auction-house: + image: openjdk + command: "java -jar /data/tapas-auction-house-0.0.1-SNAPSHOT.jar" + restart: unless-stopped + volumes: + - ./:/data/ + labels: + - "traefik.enable=true" + - "traefik.http.routers.tapas-auction-house.rule=Host(`tapas-auction-house.${PUB_IP}.nip.io`)" + - "traefik.http.routers.tapas-auction-house.service=tapas-auction-house" + - "traefik.http.services.tapas-auction-house.loadbalancer.server.port=8082" + - "traefik.http.routers.tapas-auction-house.tls=true" + - "traefik.http.routers.tapas-auction-house.entryPoints=web,websecure" + - "traefik.http.routers.tapas-auction-house.tls.certresolver=le" + + app: + image: openjdk + command: "java -jar /data/app-0.1.0.jar" + restart: unless-stopped + volumes: + - ./:/data/ + labels: + - "traefik.enable=true" + - "traefik.http.routers.app.rule=Host(`app.${PUB_IP}.nip.io`)" + - "traefik.http.routers.app.service=app" + - "traefik.http.services.app.loadbalancer.server.port=8080" + - "traefik.http.routers.app.tls=true" + - "traefik.http.routers.app.entryPoints=web,websecure" + - "traefik.http.routers.app.tls.certresolver=le" + + mongodb: + image: mongo + container_name: mongodb + restart: unless-stopped + environment: + MONGO_INITDB_ROOT_USERNAME: root + MONGO_INITDB_ROOT_PASSWORD: 8nP7s0a # Can not be changed again later on + volumes: + - database:/data/db + + dbadmin: + image: mongo-express + container_name: dbadmin + restart: unless-stopped + environment: + ME_CONFIG_BASICAUTH_USERNAME: student # Access to web interface: username + ME_CONFIG_BASICAUTH_PASSWORD: studious # Access to web interface: password + ME_CONFIG_MONGODB_ADMINUSERNAME: root + ME_CONFIG_MONGODB_ADMINPASSWORD: 8nP7s0a # must correspond to the db + ME_CONFIG_MONGODB_PORT: 27017 # Default 27017 + ME_CONFIG_MONGODB_SERVER: mongodb + labels: + - "traefik.enable=true" + - "traefik.http.routers.dbadmin.rule=Host(`dbadmin.${PUB_IP}.nip.io`)" + - "traefik.http.routers.dbadmin.service=dbadmin" + - "traefik.http.services.dbadmin.loadbalancer.server.port=8081" + - "traefik.http.routers.dbadmin.tls=true" + - "traefik.http.routers.dbadmin.entryPoints=web,websecure" + - "traefik.http.routers.dbadmin.tls.certresolver=le" + +volumes: + database: diff --git a/executor-base/.gitignore b/executor-base/.gitignore deleted file mode 100644 index 549e00a..0000000 --- a/executor-base/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -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/executor-base/.mvn/wrapper/MavenWrapperDownloader.java b/executor-base/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index e76d1f3..0000000 --- a/executor-base/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed 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 - * - * https://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. - */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/executor-base/.mvn/wrapper/maven-wrapper.jar b/executor-base/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 2cc7d4a..0000000 Binary files a/executor-base/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/executor-base/.mvn/wrapper/maven-wrapper.properties b/executor-base/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index abd303b..0000000 --- a/executor-base/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/executor-base/Dockerfile b/executor-base/Dockerfile deleted file mode 100644 index db90fb6..0000000 --- a/executor-base/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM openjdk:11 AS development - -WORKDIR /opt/app - -# ENV SPRING_DATASOURCE_URL=jdbc:mysql://backend-db:3306/db - -COPY .mvn/ .mvn -COPY mvnw pom.xml mvnw.cmd ./ - -RUN apt-get clean && apt-get update && apt-get install dos2unix -RUN dos2unix mvnw - -RUN ./mvnw dependency:go-offline - -COPY src /opt/app/src -COPY *target /opt/app/target - -CMD ["./mvnw", "spring-boot:run", "-Dspring-boot.run.jvmArguments=\"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005\"", "-Dspring.devtools.restart.enabled=true"] diff --git a/executor-base/mvnw b/executor-base/mvnw deleted file mode 100755 index a16b543..0000000 --- a/executor-base/mvnw +++ /dev/null @@ -1,310 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - 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" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/executor-base/mvnw.cmd b/executor-base/mvnw.cmd deleted file mode 100644 index c8d4337..0000000 --- a/executor-base/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@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 https://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 Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/executor-base/pom.xml b/executor-base/pom.xml deleted file mode 100644 index 4ea8d2a..0000000 --- a/executor-base/pom.xml +++ /dev/null @@ -1,71 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.5.5 - - - ch.unisg - executor-base - 0.0.1-SNAPSHOT - executor-base - Demo project for Spring Boot - - 11 - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - org.springframework.boot - spring-boot-starter-validation - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - - javax.validation - validation-api - 1.1.0.Final - - - - javax.transaction - javax.transaction-api - 1.2 - - - - org.json - json - 20210307 - - - - ch.unisg - common - 0.0.1-SNAPSHOT - - - - diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/in/web/TaskAvailableController.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/in/web/TaskAvailableController.java deleted file mode 100644 index 66ef496..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/in/web/TaskAvailableController.java +++ /dev/null @@ -1,46 +0,0 @@ -package ch.unisg.executorbase.executor.adapter.in.web; - -import java.util.logging.Logger; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; - -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableCommand; -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableUseCase; -import ch.unisg.executorbase.executor.domain.ExecutorType; - -@RestController -public class TaskAvailableController { - private final TaskAvailableUseCase taskAvailableUseCase; - - public TaskAvailableController(TaskAvailableUseCase taskAvailableUseCase) { - this.taskAvailableUseCase = taskAvailableUseCase; - } - - Logger logger = Logger.getLogger(TaskAvailableController.class.getName()); - - /** - * Controller for notification about new events. - * @return 200 OK - **/ - @GetMapping(path = "/newtask/{taskType}", consumes = { "application/json" }) - public ResponseEntity retrieveTaskFromTaskList(@PathVariable("taskType") String taskType) { - - logger.info("New " + taskType + " available"); - - if (ExecutorType.contains(taskType.toUpperCase())) { - TaskAvailableCommand command = new TaskAvailableCommand( - ExecutorType.valueOf(taskType.toUpperCase())); - taskAvailableUseCase.newTaskAvailable(command); - } - - // Add the content type as a response header - HttpHeaders responseHeaders = new HttpHeaders(); - - return new ResponseEntity<>("OK", responseHeaders, HttpStatus.OK); - } -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/out/web/ExecutionFinishedEventAdapter.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/out/web/ExecutionFinishedEventAdapter.java deleted file mode 100644 index 4321f72..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/out/web/ExecutionFinishedEventAdapter.java +++ /dev/null @@ -1,58 +0,0 @@ -package ch.unisg.executorbase.executor.adapter.out.web; - -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.json.JSONObject; - -import ch.unisg.executorbase.executor.application.port.out.ExecutionFinishedEventPort; -import ch.unisg.executorbase.executor.domain.ExecutionFinishedEvent; - -public class ExecutionFinishedEventAdapter implements ExecutionFinishedEventPort { - - String server = System.getenv("roster_uri") == null ? - "http://localhost:8082" : System.getenv("roster_uri"); - - - Logger logger = Logger.getLogger(ExecutionFinishedEventAdapter.class.getName()); - - /** - * Publishes the execution finished event - * @return void - **/ - @Override - public void publishExecutionFinishedEvent(ExecutionFinishedEvent event) { - - String body = new JSONObject() - .put("taskID", event.getTaskID()) - .put("outputData", event.getOutputData()) - .put("status", event.getStatus()) - .toString(); - - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(server+"/task/completed")) - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofString(body)) - .build(); - - - try { - client.send(request, HttpResponse.BodyHandlers.ofString()); - } catch (InterruptedException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - } - - logger.log(Level.INFO, "Finish execution event sent with result: {0}", event.getOutputData()); - - } - -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/out/web/GetAssignmentAdapter.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/out/web/GetAssignmentAdapter.java deleted file mode 100644 index 9d8013b..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/out/web/GetAssignmentAdapter.java +++ /dev/null @@ -1,73 +0,0 @@ -package ch.unisg.executorbase.executor.adapter.out.web; - -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; - -import ch.unisg.common.valueobject.ExecutorURI; -import ch.unisg.executorbase.executor.application.port.out.GetAssignmentPort; -import ch.unisg.executorbase.executor.domain.ExecutorType; -import ch.unisg.executorbase.executor.domain.Task; - -import org.json.JSONObject; - -@Component -@Primary -public class GetAssignmentAdapter implements GetAssignmentPort { - - String server = System.getenv("roster_uri") == null ? - "http://localhost:8082" : System.getenv("roster_uri"); - - Logger logger = Logger.getLogger(GetAssignmentAdapter.class.getName()); - - /** - * Requests a new task assignment - * @return the assigned task - * @see Task - **/ - @Override - public Task getAssignment(ExecutorType executorType, ExecutorURI executorURI) { - - String body = new JSONObject() - .put("executorType", executorType) - .put("executorURI", executorURI.getValue()) - .toString(); - - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(server+"/task/apply")) - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofString(body)) - .build(); - - try { - logger.info("Sending getAssignment Request"); - HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); - logger.log(Level.INFO, "getAssignment request result:\n {0}", response.body()); - if (response.body().equals("")) { - return null; - } - JSONObject responseBody = new JSONObject(response.body()); - - String inputData = responseBody.getString("inputData"); - return new Task(responseBody.getString("taskID"), inputData); - - } catch (InterruptedException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - } - - return null; - } - -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/out/web/NotifyExecutorPoolAdapter.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/out/web/NotifyExecutorPoolAdapter.java deleted file mode 100644 index bb38e66..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/adapter/out/web/NotifyExecutorPoolAdapter.java +++ /dev/null @@ -1,64 +0,0 @@ -package ch.unisg.executorbase.executor.adapter.out.web; - -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Primary; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Component; - -import ch.unisg.common.valueobject.ExecutorURI; -import ch.unisg.executorbase.executor.application.port.out.NotifyExecutorPoolPort; -import ch.unisg.executorbase.executor.domain.ExecutorType; - -@Component -@Primary -public class NotifyExecutorPoolAdapter implements NotifyExecutorPoolPort { - - String server = System.getenv("executor_pool_uri") == null ? - "http://localhost:8083" : System.getenv("executor_pool_uri"); - - Logger logger = Logger.getLogger(NotifyExecutorPoolAdapter.class.getName()); - - /** - * Notifies the executor-pool about the startup of this executor - * @return if the notification was successful - **/ - @Override - public boolean notifyExecutorPool(ExecutorURI executorURI, ExecutorType executorType) { - - String body = new JSONObject() - .put("executorTaskType", executorType) - .put("executorUri", executorURI.getValue()) - .toString(); - - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(server+"/executor-pool/AddExecutor")) - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofString(body)) - .build(); - - try { - HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); - if (response.statusCode() == HttpStatus.CREATED.value()) { - return true; - } - } catch (InterruptedException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - } - - return false; - } - -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/in/TaskAvailableCommand.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/in/TaskAvailableCommand.java deleted file mode 100644 index 57bee60..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/in/TaskAvailableCommand.java +++ /dev/null @@ -1,19 +0,0 @@ -package ch.unisg.executorbase.executor.application.port.in; - -import javax.validation.constraints.NotNull; - -import ch.unisg.common.validation.SelfValidating; -import ch.unisg.executorbase.executor.domain.ExecutorType; -import lombok.Value; - -@Value -public class TaskAvailableCommand extends SelfValidating { - - @NotNull - private final ExecutorType taskType; - - public TaskAvailableCommand(ExecutorType taskType) { - this.taskType = taskType; - this.validateSelf(); - } -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/in/TaskAvailableUseCase.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/in/TaskAvailableUseCase.java deleted file mode 100644 index 5e000da..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/in/TaskAvailableUseCase.java +++ /dev/null @@ -1,5 +0,0 @@ -package ch.unisg.executorbase.executor.application.port.in; - -public interface TaskAvailableUseCase { - void newTaskAvailable(TaskAvailableCommand command); -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/out/ExecutionFinishedEventPort.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/out/ExecutionFinishedEventPort.java deleted file mode 100644 index ef65922..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/out/ExecutionFinishedEventPort.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.unisg.executorbase.executor.application.port.out; - -import ch.unisg.executorbase.executor.domain.ExecutionFinishedEvent; - -public interface ExecutionFinishedEventPort { - void publishExecutionFinishedEvent(ExecutionFinishedEvent event); -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/out/GetAssignmentPort.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/out/GetAssignmentPort.java deleted file mode 100644 index 95dc15d..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/out/GetAssignmentPort.java +++ /dev/null @@ -1,9 +0,0 @@ -package ch.unisg.executorbase.executor.application.port.out; - -import ch.unisg.common.valueobject.ExecutorURI; -import ch.unisg.executorbase.executor.domain.ExecutorType; -import ch.unisg.executorbase.executor.domain.Task; - -public interface GetAssignmentPort { - Task getAssignment(ExecutorType executorType, ExecutorURI executorURI); -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/out/NotifyExecutorPoolPort.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/out/NotifyExecutorPoolPort.java deleted file mode 100644 index 1d4d3d3..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/port/out/NotifyExecutorPoolPort.java +++ /dev/null @@ -1,8 +0,0 @@ -package ch.unisg.executorbase.executor.application.port.out; - -import ch.unisg.common.valueobject.ExecutorURI; -import ch.unisg.executorbase.executor.domain.ExecutorType; - -public interface NotifyExecutorPoolPort { - boolean notifyExecutorPool(ExecutorURI executorURI, ExecutorType executorType); -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/service/NotifyExecutorPoolService.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/application/service/NotifyExecutorPoolService.java deleted file mode 100644 index aee3142..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/service/NotifyExecutorPoolService.java +++ /dev/null @@ -1,16 +0,0 @@ -package ch.unisg.executorbase.executor.application.service; - -import ch.unisg.common.valueobject.ExecutorURI; -import ch.unisg.executorbase.executor.application.port.out.NotifyExecutorPoolPort; -import ch.unisg.executorbase.executor.domain.ExecutorType; -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -public class NotifyExecutorPoolService { - - private final NotifyExecutorPoolPort notifyExecutorPoolPort; - - public boolean notifyExecutorPool(ExecutorURI executorURI, ExecutorType executorType) { - return notifyExecutorPoolPort.notifyExecutorPool(executorURI, executorType); - } -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/service/TaskAvailableService.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/application/service/TaskAvailableService.java deleted file mode 100644 index 050a807..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/application/service/TaskAvailableService.java +++ /dev/null @@ -1,20 +0,0 @@ -package ch.unisg.executorbase.executor.application.service; - -import org.springframework.stereotype.Component; - -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableCommand; -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableUseCase; -import lombok.RequiredArgsConstructor; - -import javax.transaction.Transactional; - -@RequiredArgsConstructor -@Component -@Transactional -public class TaskAvailableService implements TaskAvailableUseCase { - - @Override - public void newTaskAvailable(TaskAvailableCommand command) { - // Placeholder so spring can create a bean, implementation of this function is inside the executors - } -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutionFinishedEvent.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutionFinishedEvent.java deleted file mode 100644 index 56637c4..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutionFinishedEvent.java +++ /dev/null @@ -1,21 +0,0 @@ -package ch.unisg.executorbase.executor.domain; - -import lombok.Getter; - -public class ExecutionFinishedEvent { - - @Getter - private String taskID; - - @Getter - private String outputData; - - @Getter - private String status; - - public ExecutionFinishedEvent(String taskID, String outputData, String status) { - this.taskID = taskID; - this.outputData = outputData; - this.status = status; - } -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutorBase.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutorBase.java deleted file mode 100644 index 09ded48..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutorBase.java +++ /dev/null @@ -1,93 +0,0 @@ -package ch.unisg.executorbase.executor.domain; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import ch.unisg.common.valueobject.ExecutorURI; -import ch.unisg.executorbase.executor.adapter.out.web.ExecutionFinishedEventAdapter; -import ch.unisg.executorbase.executor.adapter.out.web.GetAssignmentAdapter; -import ch.unisg.executorbase.executor.adapter.out.web.NotifyExecutorPoolAdapter; -import ch.unisg.executorbase.executor.application.port.out.ExecutionFinishedEventPort; -import ch.unisg.executorbase.executor.application.port.out.GetAssignmentPort; -import ch.unisg.executorbase.executor.application.port.out.NotifyExecutorPoolPort; -import ch.unisg.executorbase.executor.application.service.NotifyExecutorPoolService; -import lombok.Getter; - -public abstract class ExecutorBase { - - @Getter - private ExecutorURI executorURI; - - @Getter - private ExecutorType executorType; - - @Getter - private ExecutorStatus status; - - // TODO Violation of the Dependency Inversion Principle?, - // TODO do this with only services - private final NotifyExecutorPoolPort notifyExecutorPoolPort = new NotifyExecutorPoolAdapter(); - private final NotifyExecutorPoolService notifyExecutorPoolService = new NotifyExecutorPoolService(notifyExecutorPoolPort); - private final GetAssignmentPort getAssignmentPort = new GetAssignmentAdapter(); - private final ExecutionFinishedEventPort executionFinishedEventPort = new ExecutionFinishedEventAdapter(); - - Logger logger = Logger.getLogger(ExecutorBase.class.getName()); - - protected ExecutorBase(ExecutorType executorType) { - logger.info("Starting Executor"); - this.status = ExecutorStatus.STARTING_UP; - this.executorType = executorType; - // TODO set this automaticly - this.executorURI = new ExecutorURI("http://localhost:8084"); - // TODO do this in main - // Notify executor-pool about existence. If executor-pools response is successfull start with getting an assignment, else shut down executor. - if(!notifyExecutorPoolService.notifyExecutorPool(this.executorURI, this.executorType)) { - logger.log(Level.WARNING, "Executor could not connect to executor pool! Shuting down!"); - System.exit(0); - } else { - logger.info("Executor conntected to executor pool"); - this.status = ExecutorStatus.IDLING; - getAssignment(); - } - } - - /** - * Requests a new task from the task queue - * @return void - **/ - public void getAssignment() { - Task newTask = getAssignmentPort.getAssignment(this.getExecutorType(), this.getExecutorURI()); - if (newTask != null) { - logger.info("Executor got a new task"); - this.executeTask(newTask); - } else { - logger.info("Executor got no new task"); - this.status = ExecutorStatus.IDLING; - } - } - - /** - * Start the execution of a task - * @return void - **/ - private void executeTask(Task task) { - logger.info("Starting execution"); - this.status = ExecutorStatus.EXECUTING; - - task.setOutputData(execution(task.getInputData())); - - // TODO implement logic if execution was not successful - executionFinishedEventPort.publishExecutionFinishedEvent( - new ExecutionFinishedEvent(task.getTaskID(), task.getOutputData(), "SUCCESS")); - - logger.info("Finish execution"); - getAssignment(); - } - - /** - * Implementation of the actual execution method of an executor - * @return the execution result - **/ - protected abstract String execution(String input); - -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutorStatus.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutorStatus.java deleted file mode 100644 index 1fcf7de..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutorStatus.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.unisg.executorbase.executor.domain; - -public enum ExecutorStatus { - STARTING_UP, // Executor is starting - EXECUTING, // Executor is currently executing a task - IDLING, // Executor has no tasks left and is waiting for new instructions -} diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutorType.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutorType.java deleted file mode 100644 index ca9533a..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/ExecutorType.java +++ /dev/null @@ -1,22 +0,0 @@ -package ch.unisg.executorbase.executor.domain; - -public enum ExecutorType { - ADDITION, ROBOT; - - /** - * Checks if the give executor type exists. - * @return Wheter the given executor type exists - **/ - public static boolean contains(String test) { - - for (ExecutorType x : ExecutorType.values()) { - if (x.name().equals(test)) { - return true; - } - } - return false; - } -} - - - diff --git a/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/Task.java b/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/Task.java deleted file mode 100644 index 44595e1..0000000 --- a/executor-base/src/main/java/ch/unisg/executorBase/executor/domain/Task.java +++ /dev/null @@ -1,25 +0,0 @@ -package ch.unisg.executorbase.executor.domain; - -import lombok.Getter; -import lombok.Setter; - -public class Task { - - @Getter - private String taskID; - - @Getter - @Setter - private String outputData; - - // TODO maybe create a value object for inputData so we can make sure it is in the right - // format. - @Getter - private String inputData; - - public Task(String taskID, String inputData) { - this.taskID = taskID; - this.inputData= inputData; - } - -} diff --git a/executor-base/src/main/resources/application.properties b/executor-base/src/main/resources/application.properties deleted file mode 100644 index 5056e10..0000000 --- a/executor-base/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -server.port=8081 -roster.url=http://127.0.0.1:8082 -executor.pool.url=http://127.0.0.1:8083 diff --git a/executor-computation/.gitignore b/executor-computation/.gitignore deleted file mode 100644 index 549e00a..0000000 --- a/executor-computation/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -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/executor-computation/.mvn/wrapper/MavenWrapperDownloader.java b/executor-computation/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index e76d1f3..0000000 --- a/executor-computation/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed 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 - * - * https://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. - */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/executor-computation/.mvn/wrapper/maven-wrapper.jar b/executor-computation/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 2cc7d4a..0000000 Binary files a/executor-computation/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/executor-computation/.mvn/wrapper/maven-wrapper.properties b/executor-computation/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index abd303b..0000000 --- a/executor-computation/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/executor-computation/Dockerfile b/executor-computation/Dockerfile deleted file mode 100644 index db90fb6..0000000 --- a/executor-computation/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM openjdk:11 AS development - -WORKDIR /opt/app - -# ENV SPRING_DATASOURCE_URL=jdbc:mysql://backend-db:3306/db - -COPY .mvn/ .mvn -COPY mvnw pom.xml mvnw.cmd ./ - -RUN apt-get clean && apt-get update && apt-get install dos2unix -RUN dos2unix mvnw - -RUN ./mvnw dependency:go-offline - -COPY src /opt/app/src -COPY *target /opt/app/target - -CMD ["./mvnw", "spring-boot:run", "-Dspring-boot.run.jvmArguments=\"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005\"", "-Dspring.devtools.restart.enabled=true"] diff --git a/executor-computation/mvnw b/executor-computation/mvnw deleted file mode 100755 index a16b543..0000000 --- a/executor-computation/mvnw +++ /dev/null @@ -1,310 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - 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" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/executor-computation/mvnw.cmd b/executor-computation/mvnw.cmd deleted file mode 100644 index c8d4337..0000000 --- a/executor-computation/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@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 https://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 Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/executor-computation/pom.xml b/executor-computation/pom.xml deleted file mode 100644 index c319081..0000000 --- a/executor-computation/pom.xml +++ /dev/null @@ -1,74 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.5.5 - - - ch.unisg - executor-computation - 0.0.1-SNAPSHOT - executor-computation - Demo project for Spring Boot - - 11 - scs-asse-fs21-group1 - https://sonarcloud.io - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - ch.unisg - executor-base - 0.0.1-SNAPSHOT - compile - - - - org.json - json - 20210307 - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - - - - - - diff --git a/executor-computation/src/main/java/ch/unisg/executorcomputation/ExecutorcomputationApplication.java b/executor-computation/src/main/java/ch/unisg/executorcomputation/ExecutorcomputationApplication.java deleted file mode 100644 index 81975ba..0000000 --- a/executor-computation/src/main/java/ch/unisg/executorcomputation/ExecutorcomputationApplication.java +++ /dev/null @@ -1,16 +0,0 @@ -package ch.unisg.executorcomputation; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -import ch.unisg.executorcomputation.executor.domain.Executor; - -@SpringBootApplication -public class ExecutorcomputationApplication { - - public static void main(String[] args) { - SpringApplication.run(ExecutorcomputationApplication.class, args); - Executor.getExecutor(); - } - -} diff --git a/executor-computation/src/main/java/ch/unisg/executorcomputation/executor/adapter/in/web/TaskAvailableController.java b/executor-computation/src/main/java/ch/unisg/executorcomputation/executor/adapter/in/web/TaskAvailableController.java deleted file mode 100644 index a421924..0000000 --- a/executor-computation/src/main/java/ch/unisg/executorcomputation/executor/adapter/in/web/TaskAvailableController.java +++ /dev/null @@ -1,35 +0,0 @@ -package ch.unisg.executorcomputation.executor.adapter.in.web; - -import java.util.concurrent.CompletableFuture; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; - -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableCommand; -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableUseCase; -import ch.unisg.executorbase.executor.domain.ExecutorType; - -@RestController -public class TaskAvailableController { - private final TaskAvailableUseCase taskAvailableUseCase; - - public TaskAvailableController(TaskAvailableUseCase taskAvailableUseCase) { - this.taskAvailableUseCase = taskAvailableUseCase; - } - - @GetMapping(path = "/newtask/{taskType}") - public ResponseEntity retrieveTaskFromTaskList(@PathVariable("taskType") String taskType) { - - if (ExecutorType.contains(taskType.toUpperCase())) { - TaskAvailableCommand command = new TaskAvailableCommand( - ExecutorType.valueOf(taskType.toUpperCase())); - CompletableFuture.runAsync(() -> taskAvailableUseCase.newTaskAvailable(command)); - } - - return new ResponseEntity<>("OK", new HttpHeaders(), HttpStatus.OK); - } -} diff --git a/executor-computation/src/main/java/ch/unisg/executorcomputation/executor/application/service/TaskAvailableService.java b/executor-computation/src/main/java/ch/unisg/executorcomputation/executor/application/service/TaskAvailableService.java deleted file mode 100644 index 6a94577..0000000 --- a/executor-computation/src/main/java/ch/unisg/executorcomputation/executor/application/service/TaskAvailableService.java +++ /dev/null @@ -1,28 +0,0 @@ -package ch.unisg.executorcomputation.executor.application.service; - -import org.springframework.stereotype.Component; - -import ch.unisg.executorcomputation.executor.domain.Executor; -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableCommand; -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableUseCase; -import ch.unisg.executorbase.executor.domain.ExecutorStatus; -import lombok.RequiredArgsConstructor; - -import javax.transaction.Transactional; - -@RequiredArgsConstructor -@Component -@Transactional -public class TaskAvailableService implements TaskAvailableUseCase { - - @Override - public void newTaskAvailable(TaskAvailableCommand command) { - - Executor executor = Executor.getExecutor(); - - if (executor.getExecutorType() == command.getTaskType() && - executor.getStatus() == ExecutorStatus.IDLING) { - executor.getAssignment(); - } - } -} diff --git a/executor-computation/src/main/java/ch/unisg/executorcomputation/executor/domain/Executor.java b/executor-computation/src/main/java/ch/unisg/executorcomputation/executor/domain/Executor.java deleted file mode 100644 index f281b4f..0000000 --- a/executor-computation/src/main/java/ch/unisg/executorcomputation/executor/domain/Executor.java +++ /dev/null @@ -1,63 +0,0 @@ -package ch.unisg.executorcomputation.executor.domain; - -import java.util.concurrent.TimeUnit; - -import ch.unisg.executorbase.executor.domain.ExecutorBase; -import ch.unisg.executorbase.executor.domain.ExecutorType; - -public class Executor extends ExecutorBase { - - private static final Executor executor = new Executor(ExecutorType.ADDITION); - - public static Executor getExecutor() { - return executor; - } - - private Executor(ExecutorType executorType) { - super(executorType); - } - - @Override - protected - String execution(String inputData) { - - String operator = ""; - if (inputData.contains("+")) { - operator = "+"; - } else if (inputData.contains("-")) { - operator = "-"; - } else if (inputData.contains("*")) { - operator = "*"; - } else { - return "invalid data"; - } - - double result = Double.NaN; - - // try { - // TimeUnit.SECONDS.sleep(5); - // } catch (InterruptedException e) { - // e.printStackTrace(); - // } - - if (operator.equalsIgnoreCase("+")) { - String[] parts = inputData.split("\\+"); - double a = Double.parseDouble(parts[0]); - double b = Double.parseDouble(parts[1]); - result = a + b; - } else if (operator.equalsIgnoreCase("*")) { - String[] parts = inputData.split("\\*"); - double a = Double.parseDouble(parts[0]); - double b = Double.parseDouble(parts[1]); - result = a * b; - } else if (operator.equalsIgnoreCase("-")) { - String[] parts = inputData.split("-"); - double a = Double.parseDouble(parts[0]); - double b = Double.parseDouble(parts[1]); - result = a - b; - } - - return Double.toString(result); - } - -} diff --git a/executor-computation/src/main/resources/application.properties b/executor-computation/src/main/resources/application.properties deleted file mode 100644 index cd2d02b..0000000 --- a/executor-computation/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -server.port=8085 diff --git a/executor-computation/src/test/java/ch/unisg/executorcomputation/ExecutorcomputationApplicationTests.java b/executor-computation/src/test/java/ch/unisg/executorcomputation/ExecutorcomputationApplicationTests.java deleted file mode 100644 index f17d100..0000000 --- a/executor-computation/src/test/java/ch/unisg/executorcomputation/ExecutorcomputationApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package ch.unisg.executorcomputation; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class ExecutorcomputationApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/executor-pool/.gitignore b/executor-pool/.gitignore deleted file mode 100644 index 549e00a..0000000 --- a/executor-pool/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -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/executor-pool/.mvn/wrapper/MavenWrapperDownloader.java b/executor-pool/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index e76d1f3..0000000 --- a/executor-pool/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed 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 - * - * https://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. - */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/executor-pool/.mvn/wrapper/maven-wrapper.jar b/executor-pool/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 2cc7d4a..0000000 Binary files a/executor-pool/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/executor-pool/.mvn/wrapper/maven-wrapper.properties b/executor-pool/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index abd303b..0000000 --- a/executor-pool/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/executor-pool/Dockerfile b/executor-pool/Dockerfile deleted file mode 100644 index db90fb6..0000000 --- a/executor-pool/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM openjdk:11 AS development - -WORKDIR /opt/app - -# ENV SPRING_DATASOURCE_URL=jdbc:mysql://backend-db:3306/db - -COPY .mvn/ .mvn -COPY mvnw pom.xml mvnw.cmd ./ - -RUN apt-get clean && apt-get update && apt-get install dos2unix -RUN dos2unix mvnw - -RUN ./mvnw dependency:go-offline - -COPY src /opt/app/src -COPY *target /opt/app/target - -CMD ["./mvnw", "spring-boot:run", "-Dspring-boot.run.jvmArguments=\"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005\"", "-Dspring.devtools.restart.enabled=true"] diff --git a/executor-pool/mvnw b/executor-pool/mvnw deleted file mode 100755 index a16b543..0000000 --- a/executor-pool/mvnw +++ /dev/null @@ -1,310 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - 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" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/executor-pool/mvnw.cmd b/executor-pool/mvnw.cmd deleted file mode 100644 index c8d4337..0000000 --- a/executor-pool/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@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 https://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 Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/executor-pool/pom.xml b/executor-pool/pom.xml deleted file mode 100644 index 512235d..0000000 --- a/executor-pool/pom.xml +++ /dev/null @@ -1,91 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.5.5 - - - ch.unisg - executor-pool - 0.0.1-SNAPSHOT - executor-pool - Executor Pool - - 11 - scs-asse-fs21-group1 - https://sonarcloud.io - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - org.springframework.boot - spring-boot-starter-validation - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - org.json - json - 20210307 - - - javax.validation - validation-api - compile - - - jakarta.validation - jakarta.validation-api - - - javax.transaction - javax.transaction-api - compile - - - org.eclipse.paho - org.eclipse.paho.client.mqttv3 - 1.2.5 - compile - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - - - - - - diff --git a/executor-pool/src/main/java/ch/unisg/common/ConfigProperties.java b/executor-pool/src/main/java/ch/unisg/common/ConfigProperties.java deleted file mode 100644 index 253922c..0000000 --- a/executor-pool/src/main/java/ch/unisg/common/ConfigProperties.java +++ /dev/null @@ -1,22 +0,0 @@ -package ch.unisg.common; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -import java.net.URI; - -@Component -public class ConfigProperties { - @Autowired - private Environment environment; - - /** - * Retrieves the URI of the MQTT broker. - * - * @return the URI of the MQTT broker - */ - public URI getMqttBrokerUri() { - return URI.create(environment.getProperty("mqtt.broker.uri")); - } -} diff --git a/executor-pool/src/main/java/ch/unisg/common/SelfValidating.java b/executor-pool/src/main/java/ch/unisg/common/SelfValidating.java deleted file mode 100644 index cacf16e..0000000 --- a/executor-pool/src/main/java/ch/unisg/common/SelfValidating.java +++ /dev/null @@ -1,30 +0,0 @@ -package ch.unisg.common; - -import javax.validation.ConstraintViolation; -import javax.validation.ConstraintViolationException; -import javax.validation.Validation; -import javax.validation.Validator; -import javax.validation.ValidatorFactory; -import java.util.Set; - -public class SelfValidating { - - private Validator validator; - - public SelfValidating() { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - validator = factory.getValidator(); - } - - /** - * Evaluates all Bean Validations on the attributes of this - * instance. - */ - protected void validateSelf() { - @SuppressWarnings("unchecked") - Set> violations = validator.validate((T) this); - if (!violations.isEmpty()) { - throw new ConstraintViolationException(violations); - } - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/ExecutorPoolApplication.java b/executor-pool/src/main/java/ch/unisg/executorpool/ExecutorPoolApplication.java deleted file mode 100644 index 5cd0108..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/ExecutorPoolApplication.java +++ /dev/null @@ -1,13 +0,0 @@ -package ch.unisg.executorpool; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -@SpringBootApplication -public class ExecutorPoolApplication { - - public static void main(String[] args) { - SpringApplication.run(ExecutorPoolApplication.class, args); - } - -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/common/clients/TapasMqttClient.java b/executor-pool/src/main/java/ch/unisg/executorpool/adapter/common/clients/TapasMqttClient.java deleted file mode 100644 index 0b24b81..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/common/clients/TapasMqttClient.java +++ /dev/null @@ -1,41 +0,0 @@ -package ch.unisg.executorpool.adapter.common.clients; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.paho.client.mqttv3.*; -import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; - -import java.nio.charset.StandardCharsets; -import java.util.UUID; - -public class TapasMqttClient { - private static final Logger LOGGER = LogManager.getLogger(TapasMqttClient.class); - - private static TapasMqttClient tapasClient = null; - - private MqttClient mqttClient; - private final String mqttClientId; - private final String brokerAddress; - - private TapasMqttClient(String brokerAddress) { - this.mqttClientId = UUID.randomUUID().toString(); - this.brokerAddress = brokerAddress; - } - - public static synchronized TapasMqttClient getInstance(String brokerAddress) { - - if (tapasClient == null) { - tapasClient = new TapasMqttClient(brokerAddress); - } - - return tapasClient; - } - - public void publishMessage(String topic, String payload) throws MqttException { - mqttClient = new org.eclipse.paho.client.mqttv3.MqttClient(brokerAddress, mqttClientId, new MemoryPersistence()); - mqttClient.connect(); - MqttMessage message = new MqttMessage(payload.getBytes(StandardCharsets.UTF_8)); - mqttClient.publish(topic, message); - mqttClient.disconnect(); - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/common/formats/ExecutorJsonRepresentation.java b/executor-pool/src/main/java/ch/unisg/executorpool/adapter/common/formats/ExecutorJsonRepresentation.java deleted file mode 100644 index 3c8f6e4..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/common/formats/ExecutorJsonRepresentation.java +++ /dev/null @@ -1,51 +0,0 @@ -package ch.unisg.executorpool.adapter.common.formats; - -import ch.unisg.executorpool.domain.ExecutorClass; -import lombok.Getter; -import lombok.Setter; -import org.json.JSONArray; -import org.json.JSONObject; - -import java.util.List; - -public class ExecutorJsonRepresentation { - public static final String EXECUTOR_MEDIA_TYPE = "application/json"; - - @Getter @Setter - private String executorUri; - - @Getter @Setter - private String executorTaskType; - - // TODO Check if this need Setters. Also applies to AuctionJsonRepresentation - public ExecutorJsonRepresentation(String executorUri, String executorTaskType){ - this.executorUri = executorUri; - this.executorTaskType = executorTaskType; - } - - public static String serialize(ExecutorClass executorClass) { - JSONObject payload = new JSONObject(); - - payload.put("executorUri", executorClass.getExecutorUri().getValue()); - payload.put("executorTaskType", executorClass.getExecutorTaskType().getValue()); - - return payload.toString(); - } - - public static String serialize(List listOfExecutors) { - JSONArray jsonArray = new JSONArray(); - - for (ExecutorClass executor: listOfExecutors) { - JSONObject jsonObject = new JSONObject(); - - jsonObject.put("executorUri", executor.getExecutorUri().getValue()); - jsonObject.put("executorTaskType", executor.getExecutorTaskType().getValue()); - - jsonArray.put(jsonObject); - } - - return jsonArray.toString(); - } - - private ExecutorJsonRepresentation() { } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/AddNewExecutorToExecutorPoolWebController.java b/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/AddNewExecutorToExecutorPoolWebController.java deleted file mode 100644 index ff464d3..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/AddNewExecutorToExecutorPoolWebController.java +++ /dev/null @@ -1,49 +0,0 @@ -package ch.unisg.executorpool.adapter.in.web; - -import ch.unisg.executorpool.adapter.common.clients.TapasMqttClient; -import ch.unisg.executorpool.adapter.common.formats.ExecutorJsonRepresentation; -import ch.unisg.executorpool.application.port.in.AddNewExecutorToExecutorPoolUseCase; -import ch.unisg.executorpool.application.port.in.AddNewExecutorToExecutorPoolCommand; -import ch.unisg.executorpool.domain.ExecutorClass; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; -import javax.validation.ConstraintViolationException; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.util.UUID; - -import org.eclipse.paho.client.mqttv3.*; - -@RestController -public class AddNewExecutorToExecutorPoolWebController { - private final AddNewExecutorToExecutorPoolUseCase addNewExecutorToExecutorPoolUseCase; - - public AddNewExecutorToExecutorPoolWebController(AddNewExecutorToExecutorPoolUseCase addNewExecutorToExecutorPoolUseCase){ - this.addNewExecutorToExecutorPoolUseCase = addNewExecutorToExecutorPoolUseCase; - } - - @PostMapping(path = "/executor-pool/AddExecutor", consumes = {ExecutorJsonRepresentation.EXECUTOR_MEDIA_TYPE}) - public ResponseEntity addNewExecutorToExecutorPool(@RequestBody ExecutorJsonRepresentation payload){ - try { - AddNewExecutorToExecutorPoolCommand command = new AddNewExecutorToExecutorPoolCommand( - new ExecutorClass.ExecutorUri(URI.create(payload.getExecutorUri())), - new ExecutorClass.ExecutorTaskType(payload.getExecutorTaskType()) - ); - - ExecutorClass newExecutor = addNewExecutorToExecutorPoolUseCase.addNewExecutorToExecutorPool(command); - - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.add(HttpHeaders.CONTENT_TYPE, ExecutorJsonRepresentation.EXECUTOR_MEDIA_TYPE); - - return new ResponseEntity<>(ExecutorJsonRepresentation.serialize(newExecutor), responseHeaders, HttpStatus.CREATED); - - } catch (ConstraintViolationException e){ - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage()); - } - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/GetAllExecutorsInExecutorPoolByTypeWebController.java b/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/GetAllExecutorsInExecutorPoolByTypeWebController.java deleted file mode 100644 index 8c7ce3d..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/GetAllExecutorsInExecutorPoolByTypeWebController.java +++ /dev/null @@ -1,36 +0,0 @@ -package ch.unisg.executorpool.adapter.in.web; - -import ch.unisg.executorpool.adapter.common.formats.ExecutorJsonRepresentation; -import ch.unisg.executorpool.application.port.in.GetAllExecutorsInExecutorPoolByTypeQuery; -import ch.unisg.executorpool.application.port.in.GetAllExecutorsInExecutorPoolByTypeUseCase; -import ch.unisg.executorpool.domain.ExecutorClass; -import ch.unisg.executorpool.domain.ExecutorClass.ExecutorTaskType; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; - -@RestController -public class GetAllExecutorsInExecutorPoolByTypeWebController { - private final GetAllExecutorsInExecutorPoolByTypeUseCase getAllExecutorsInExecutorPoolByTypeUseCase; - - public GetAllExecutorsInExecutorPoolByTypeWebController(GetAllExecutorsInExecutorPoolByTypeUseCase getAllExecutorInExecutorPoolByTypeUseCase){ - this.getAllExecutorsInExecutorPoolByTypeUseCase = getAllExecutorInExecutorPoolByTypeUseCase; - } - - @GetMapping(path = "/executor-pool/GetAllExecutorsInExecutorPoolByType/{taskType}") - public ResponseEntity getAllExecutorInExecutorPoolByType(@PathVariable("taskType") String taskType){ - GetAllExecutorsInExecutorPoolByTypeQuery query = new GetAllExecutorsInExecutorPoolByTypeQuery(new ExecutorTaskType(taskType)); - List matchedExecutors = getAllExecutorsInExecutorPoolByTypeUseCase.getAllExecutorsInExecutorPoolByType(query); - - // Add the content type as a response header - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.add(HttpHeaders.CONTENT_TYPE, ExecutorJsonRepresentation.EXECUTOR_MEDIA_TYPE); - - return new ResponseEntity<>(ExecutorJsonRepresentation.serialize(matchedExecutors), responseHeaders, HttpStatus.OK); - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/GetAllExecutorsInExecutorPoolWebController.java b/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/GetAllExecutorsInExecutorPoolWebController.java deleted file mode 100644 index 13a631a..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/GetAllExecutorsInExecutorPoolWebController.java +++ /dev/null @@ -1,32 +0,0 @@ -package ch.unisg.executorpool.adapter.in.web; - -import ch.unisg.executorpool.adapter.common.formats.ExecutorJsonRepresentation; -import ch.unisg.executorpool.application.port.in.GetAllExecutorsInExecutorPoolUseCase; -import ch.unisg.executorpool.domain.ExecutorClass; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; - -@RestController -public class GetAllExecutorsInExecutorPoolWebController { - private final GetAllExecutorsInExecutorPoolUseCase getAllExecutorsInExecutorPoolUseCase; - - public GetAllExecutorsInExecutorPoolWebController(GetAllExecutorsInExecutorPoolUseCase getAllExecutorsInExecutorPoolUseCase){ - this.getAllExecutorsInExecutorPoolUseCase = getAllExecutorsInExecutorPoolUseCase; - } - - @GetMapping(path = "executor-pool/GetAllExecutorsinExecutorPool") - public ResponseEntity getAllExecutorsInExecutorPool(){ - List executorClassList = getAllExecutorsInExecutorPoolUseCase.getAllExecutorsInExecutorPool(); - - // Add the content type as a response header - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.add(HttpHeaders.CONTENT_TYPE, ExecutorJsonRepresentation.EXECUTOR_MEDIA_TYPE); - - return new ResponseEntity<>(ExecutorJsonRepresentation.serialize(executorClassList), responseHeaders, HttpStatus.OK); - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/RemoveExecutorFromExecutorPoolWebController.java b/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/RemoveExecutorFromExecutorPoolWebController.java deleted file mode 100644 index 28c3511..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/in/web/RemoveExecutorFromExecutorPoolWebController.java +++ /dev/null @@ -1,43 +0,0 @@ -package ch.unisg.executorpool.adapter.in.web; - -import ch.unisg.executorpool.adapter.common.formats.ExecutorJsonRepresentation; -import ch.unisg.executorpool.application.port.in.RemoveExecutorFromExecutorPoolCommand; -import ch.unisg.executorpool.application.port.in.RemoveExecutorFromExecutorPoolUseCase; -import ch.unisg.executorpool.domain.ExecutorClass; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; - -import java.net.URI; -import java.util.Optional; - -@RestController -public class RemoveExecutorFromExecutorPoolWebController { - private final RemoveExecutorFromExecutorPoolUseCase removeExecutorFromExecutorPoolUseCase; - - public RemoveExecutorFromExecutorPoolWebController(RemoveExecutorFromExecutorPoolUseCase removeExecutorFromExecutorPoolUseCase){ - this.removeExecutorFromExecutorPoolUseCase = removeExecutorFromExecutorPoolUseCase; - } - - @PostMapping(path = "/executor-pool/RemoveExecutor", consumes = {ExecutorJsonRepresentation.EXECUTOR_MEDIA_TYPE}) - public ResponseEntity removeExecutorFromExecutorPool(@RequestBody ExecutorJsonRepresentation executorJsonRepresentation){ - RemoveExecutorFromExecutorPoolCommand command = new RemoveExecutorFromExecutorPoolCommand( - new ExecutorClass.ExecutorUri(URI.create(executorJsonRepresentation.getExecutorUri())) - ); - Optional removedExecutor = removeExecutorFromExecutorPoolUseCase.removeExecutorFromExecutorPool(command); - - if(removedExecutor.isEmpty()){ - throw new ResponseStatusException(HttpStatus.NOT_FOUND); - } - - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.add(HttpHeaders.CONTENT_TYPE, ExecutorJsonRepresentation.EXECUTOR_MEDIA_TYPE); - - return new ResponseEntity<>(ExecutorJsonRepresentation.serialize(removedExecutor.get()), responseHeaders, - HttpStatus.OK); - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/out/messaging/PublishExecutorAddedEventAdapter.java b/executor-pool/src/main/java/ch/unisg/executorpool/adapter/out/messaging/PublishExecutorAddedEventAdapter.java deleted file mode 100644 index 323bcbb..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/out/messaging/PublishExecutorAddedEventAdapter.java +++ /dev/null @@ -1,43 +0,0 @@ -package ch.unisg.executorpool.adapter.out.messaging; - -import ch.unisg.common.ConfigProperties; -import ch.unisg.executorpool.adapter.common.clients.TapasMqttClient; -import ch.unisg.executorpool.adapter.common.formats.ExecutorJsonRepresentation; -import ch.unisg.executorpool.application.port.out.ExecutorAddedEventPort; -import ch.unisg.executorpool.domain.ExecutorAddedEvent; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.paho.client.mqttv3.MqttException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Primary; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -import java.net.URI; - -@Component -@Primary -public class PublishExecutorAddedEventAdapter implements ExecutorAddedEventPort { - - private static final Logger LOGGER = LogManager.getLogger(PublishExecutorAddedEventAdapter.class); - - // TODO Can't autowire. Find fix - /* - @Autowired - private ConfigProperties config; - */ - - @Autowired - private Environment environment; - - @Override - public void publishExecutorAddedEvent(ExecutorAddedEvent event){ - try{ - var mqttClient = TapasMqttClient.getInstance(environment.getProperty("mqtt.broker.uri")); - mqttClient.publishMessage("ch/unisg/tapas/executors/added", ExecutorJsonRepresentation.serialize(event.getExecutorClass())); - } - catch (MqttException e){ - LOGGER.error(e.getMessage(), e); - } - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/out/messaging/PublishExecutorRemovedEventAdapter.java b/executor-pool/src/main/java/ch/unisg/executorpool/adapter/out/messaging/PublishExecutorRemovedEventAdapter.java deleted file mode 100644 index aa01165..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/adapter/out/messaging/PublishExecutorRemovedEventAdapter.java +++ /dev/null @@ -1,41 +0,0 @@ -package ch.unisg.executorpool.adapter.out.messaging; - -import ch.unisg.executorpool.adapter.common.clients.TapasMqttClient; -import ch.unisg.executorpool.adapter.common.formats.ExecutorJsonRepresentation; -import ch.unisg.executorpool.application.port.out.ExecutorRemovedEventPort; -import ch.unisg.executorpool.domain.ExecutorAddedEvent; -import ch.unisg.executorpool.domain.ExecutorRemovedEvent; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.paho.client.mqttv3.MqttException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Primary; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -@Primary -public class PublishExecutorRemovedEventAdapter implements ExecutorRemovedEventPort { - - private static final Logger LOGGER = LogManager.getLogger(PublishExecutorAddedEventAdapter.class); - - // TODO Can't autowire. Find fix - /* - @Autowired - private ConfigProperties config; - */ - - @Autowired - private Environment environment; - - @Override - public void publishExecutorRemovedEvent(ExecutorRemovedEvent event){ - try{ - var mqttClient = TapasMqttClient.getInstance(environment.getProperty("mqtt.broker.uri")); - mqttClient.publishMessage("ch/unisg/tapas/executors/removed", ExecutorJsonRepresentation.serialize(event.getExecutorClass())); - } - catch (MqttException e){ - LOGGER.error(e.getMessage(), e); - } - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/AddNewExecutorToExecutorPoolCommand.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/AddNewExecutorToExecutorPoolCommand.java deleted file mode 100644 index ddd7da9..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/AddNewExecutorToExecutorPoolCommand.java +++ /dev/null @@ -1,23 +0,0 @@ -package ch.unisg.executorpool.application.port.in; - -import ch.unisg.common.SelfValidating; -import ch.unisg.executorpool.domain.ExecutorPool; -import ch.unisg.executorpool.domain.ExecutorClass.ExecutorUri; -import ch.unisg.executorpool.domain.ExecutorClass.ExecutorTaskType; -import lombok.Value; -import javax.validation.constraints.NotNull; - -@Value -public class AddNewExecutorToExecutorPoolCommand extends SelfValidating { - @NotNull - private final ExecutorUri executorUri; - - @NotNull - private final ExecutorTaskType executorTaskType; - - public AddNewExecutorToExecutorPoolCommand(ExecutorUri executorUri, ExecutorTaskType executorTaskType){ - this.executorUri = executorUri; - this.executorTaskType = executorTaskType; - this.validateSelf(); - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/AddNewExecutorToExecutorPoolUseCase.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/AddNewExecutorToExecutorPoolUseCase.java deleted file mode 100644 index 51b28ba..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/AddNewExecutorToExecutorPoolUseCase.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.unisg.executorpool.application.port.in; - -import ch.unisg.executorpool.domain.ExecutorClass; - -public interface AddNewExecutorToExecutorPoolUseCase { - ExecutorClass addNewExecutorToExecutorPool(AddNewExecutorToExecutorPoolCommand command); -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/GetAllExecutorsInExecutorPoolByTypeQuery.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/GetAllExecutorsInExecutorPoolByTypeQuery.java deleted file mode 100644 index 079e7e1..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/GetAllExecutorsInExecutorPoolByTypeQuery.java +++ /dev/null @@ -1,18 +0,0 @@ -package ch.unisg.executorpool.application.port.in; - -import ch.unisg.executorpool.domain.ExecutorClass.ExecutorTaskType; -import ch.unisg.common.SelfValidating; -import lombok.Value; - -import javax.validation.constraints.NotNull; - -@Value -public class GetAllExecutorsInExecutorPoolByTypeQuery extends SelfValidating { - @NotNull - private final ExecutorTaskType executorTaskType; - - public GetAllExecutorsInExecutorPoolByTypeQuery(ExecutorTaskType executorTaskType){ - this.executorTaskType = executorTaskType; - this.validateSelf(); - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/GetAllExecutorsInExecutorPoolByTypeUseCase.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/GetAllExecutorsInExecutorPoolByTypeUseCase.java deleted file mode 100644 index 4821284..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/GetAllExecutorsInExecutorPoolByTypeUseCase.java +++ /dev/null @@ -1,9 +0,0 @@ -package ch.unisg.executorpool.application.port.in; - -import ch.unisg.executorpool.domain.ExecutorClass; - -import java.util.List; - -public interface GetAllExecutorsInExecutorPoolByTypeUseCase { - List getAllExecutorsInExecutorPoolByType(GetAllExecutorsInExecutorPoolByTypeQuery query); -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/GetAllExecutorsInExecutorPoolUseCase.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/GetAllExecutorsInExecutorPoolUseCase.java deleted file mode 100644 index b7f2eb7..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/GetAllExecutorsInExecutorPoolUseCase.java +++ /dev/null @@ -1,10 +0,0 @@ -package ch.unisg.executorpool.application.port.in; - -import ch.unisg.executorpool.domain.ExecutorClass; -import ch.unisg.executorpool.domain.ExecutorPool; - -import java.util.List; - -public interface GetAllExecutorsInExecutorPoolUseCase { - List getAllExecutorsInExecutorPool(); -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/RemoveExecutorFromExecutorPoolCommand.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/RemoveExecutorFromExecutorPoolCommand.java deleted file mode 100644 index 162426c..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/RemoveExecutorFromExecutorPoolCommand.java +++ /dev/null @@ -1,18 +0,0 @@ -package ch.unisg.executorpool.application.port.in; - -import ch.unisg.common.SelfValidating; -import ch.unisg.executorpool.domain.ExecutorClass.ExecutorUri; -import lombok.Value; - -import javax.validation.constraints.NotNull; - -@Value -public class RemoveExecutorFromExecutorPoolCommand extends SelfValidating { - @NotNull - private final ExecutorUri executorUri; - - public RemoveExecutorFromExecutorPoolCommand(ExecutorUri executorUri){ - this.executorUri = executorUri; - this.validateSelf(); - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/RemoveExecutorFromExecutorPoolUseCase.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/RemoveExecutorFromExecutorPoolUseCase.java deleted file mode 100644 index 8b899e7..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/in/RemoveExecutorFromExecutorPoolUseCase.java +++ /dev/null @@ -1,9 +0,0 @@ -package ch.unisg.executorpool.application.port.in; - -import ch.unisg.executorpool.domain.ExecutorClass; - -import java.util.Optional; - -public interface RemoveExecutorFromExecutorPoolUseCase { - Optional removeExecutorFromExecutorPool(RemoveExecutorFromExecutorPoolCommand command); -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/out/ExecutorAddedEventPort.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/port/out/ExecutorAddedEventPort.java deleted file mode 100644 index ad75c75..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/out/ExecutorAddedEventPort.java +++ /dev/null @@ -1,8 +0,0 @@ -package ch.unisg.executorpool.application.port.out; - -import ch.unisg.executorpool.domain.ExecutorAddedEvent; -import org.eclipse.paho.client.mqttv3.MqttException; - -public interface ExecutorAddedEventPort { - void publishExecutorAddedEvent(ExecutorAddedEvent event); -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/out/ExecutorRemovedEventPort.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/port/out/ExecutorRemovedEventPort.java deleted file mode 100644 index b905858..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/port/out/ExecutorRemovedEventPort.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.unisg.executorpool.application.port.out; - -import ch.unisg.executorpool.domain.ExecutorRemovedEvent; - -public interface ExecutorRemovedEventPort { - void publishExecutorRemovedEvent(ExecutorRemovedEvent event); -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/service/AddNewExecutorToExecutorPoolService.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/service/AddNewExecutorToExecutorPoolService.java deleted file mode 100644 index 393024a..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/service/AddNewExecutorToExecutorPoolService.java +++ /dev/null @@ -1,34 +0,0 @@ -package ch.unisg.executorpool.application.service; - -import ch.unisg.executorpool.application.port.in.AddNewExecutorToExecutorPoolUseCase; -import ch.unisg.executorpool.application.port.in.AddNewExecutorToExecutorPoolCommand; -import ch.unisg.executorpool.application.port.out.ExecutorAddedEventPort; -import ch.unisg.executorpool.domain.ExecutorAddedEvent; -import ch.unisg.executorpool.domain.ExecutorClass; -import ch.unisg.executorpool.domain.ExecutorPool; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import javax.transaction.Transactional; - -@Component -@Transactional -public class AddNewExecutorToExecutorPoolService implements AddNewExecutorToExecutorPoolUseCase { - - private final ExecutorAddedEventPort executorAddedEventPort; - - public AddNewExecutorToExecutorPoolService(ExecutorAddedEventPort executorAddedEventPort){ - this.executorAddedEventPort = executorAddedEventPort; - } - - @Override - public ExecutorClass addNewExecutorToExecutorPool(AddNewExecutorToExecutorPoolCommand command){ - ExecutorPool executorPool = ExecutorPool.getExecutorPool(); - var newExecutor = executorPool.addNewExecutor(command.getExecutorUri(), command.getExecutorTaskType()); - - var executorAddedEvent = new ExecutorAddedEvent(newExecutor); - executorAddedEventPort.publishExecutorAddedEvent(executorAddedEvent); - - return newExecutor; - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/service/GetAllExecutorsInExecutorPoolByTypeService.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/service/GetAllExecutorsInExecutorPoolByTypeService.java deleted file mode 100644 index 00d1636..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/service/GetAllExecutorsInExecutorPoolByTypeService.java +++ /dev/null @@ -1,24 +0,0 @@ -package ch.unisg.executorpool.application.service; - -import ch.unisg.executorpool.application.port.in.GetAllExecutorsInExecutorPoolByTypeQuery; -import ch.unisg.executorpool.application.port.in.GetAllExecutorsInExecutorPoolByTypeUseCase; -import ch.unisg.executorpool.domain.ExecutorClass; -import ch.unisg.executorpool.domain.ExecutorPool; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import javax.transaction.Transactional; -import java.util.List; - -@RequiredArgsConstructor -@Component -@Transactional -public class GetAllExecutorsInExecutorPoolByTypeService implements GetAllExecutorsInExecutorPoolByTypeUseCase { - - @Override - public List getAllExecutorsInExecutorPoolByType(GetAllExecutorsInExecutorPoolByTypeQuery query){ - ExecutorPool executorPool = ExecutorPool.getExecutorPool(); - return executorPool.getAllExecutorsByType(query.getExecutorTaskType()); - } - -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/service/GetAllExecutorsInExecutorPoolService.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/service/GetAllExecutorsInExecutorPoolService.java deleted file mode 100644 index 589cf46..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/service/GetAllExecutorsInExecutorPoolService.java +++ /dev/null @@ -1,22 +0,0 @@ -package ch.unisg.executorpool.application.service; - -import ch.unisg.executorpool.application.port.in.GetAllExecutorsInExecutorPoolUseCase; -import ch.unisg.executorpool.domain.ExecutorClass; -import ch.unisg.executorpool.domain.ExecutorPool; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import javax.transaction.Transactional; -import java.util.List; - -@RequiredArgsConstructor -@Component -@Transactional -public class GetAllExecutorsInExecutorPoolService implements GetAllExecutorsInExecutorPoolUseCase { - - @Override - public List getAllExecutorsInExecutorPool(){ - ExecutorPool executorPool = ExecutorPool.getExecutorPool(); - return executorPool.getListOfExecutors().getValue(); - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/application/service/RemoveExecutorFromExecutorPoolService.java b/executor-pool/src/main/java/ch/unisg/executorpool/application/service/RemoveExecutorFromExecutorPoolService.java deleted file mode 100644 index 4d2457d..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/application/service/RemoveExecutorFromExecutorPoolService.java +++ /dev/null @@ -1,37 +0,0 @@ -package ch.unisg.executorpool.application.service; - -import ch.unisg.executorpool.application.port.in.RemoveExecutorFromExecutorPoolCommand; -import ch.unisg.executorpool.application.port.in.RemoveExecutorFromExecutorPoolUseCase; -import ch.unisg.executorpool.application.port.out.ExecutorRemovedEventPort; -import ch.unisg.executorpool.domain.ExecutorClass; -import ch.unisg.executorpool.domain.ExecutorPool; -import ch.unisg.executorpool.domain.ExecutorRemovedEvent; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import javax.transaction.Transactional; -import java.util.Optional; - -@Component -@Transactional -public class RemoveExecutorFromExecutorPoolService implements RemoveExecutorFromExecutorPoolUseCase { - - private final ExecutorRemovedEventPort executorRemovedEventPort; - - public RemoveExecutorFromExecutorPoolService(ExecutorRemovedEventPort executorRemovedEventPort){ - this.executorRemovedEventPort = executorRemovedEventPort; - } - - @Override - public Optional removeExecutorFromExecutorPool(RemoveExecutorFromExecutorPoolCommand command){ - ExecutorPool executorPool = ExecutorPool.getExecutorPool(); - var removedExecutor = executorPool.removeExecutorByIpAndPort(command.getExecutorUri()); - - if(removedExecutor.isPresent()){ - var executorRemovedEvent = new ExecutorRemovedEvent(removedExecutor.get()); - executorRemovedEventPort.publishExecutorRemovedEvent(executorRemovedEvent); - } - - return removedExecutor; - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorAddedEvent.java b/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorAddedEvent.java deleted file mode 100644 index 6ec291e..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorAddedEvent.java +++ /dev/null @@ -1,10 +0,0 @@ -package ch.unisg.executorpool.domain; - -import lombok.Getter; - -public class ExecutorAddedEvent { - @Getter - private ExecutorClass executorClass; - - public ExecutorAddedEvent(ExecutorClass executorClass) { this.executorClass = executorClass; } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorClass.java b/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorClass.java deleted file mode 100644 index 5da6fe7..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorClass.java +++ /dev/null @@ -1,35 +0,0 @@ -package ch.unisg.executorpool.domain; - -import lombok.Getter; -import lombok.Value; - -import java.net.URI; - -public class ExecutorClass { - - @Getter - private final ExecutorUri executorUri; - - @Getter - private final ExecutorTaskType executorTaskType; - - public ExecutorClass(ExecutorUri executorUri, ExecutorTaskType executorTaskType){ - this.executorUri = executorUri; - this.executorTaskType = executorTaskType; - } - - protected static ExecutorClass createExecutorClass(ExecutorUri executorUri, ExecutorTaskType executorTaskType){ - System.out.println("New Executor: " + executorUri.value.toString() + " " + executorTaskType.getValue()); - return new ExecutorClass(executorUri, executorTaskType); - } - - @Value - public static class ExecutorUri { - private URI value; - } - - @Value - public static class ExecutorTaskType { - private String value; - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorPool.java b/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorPool.java deleted file mode 100644 index 0ca0d5e..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorPool.java +++ /dev/null @@ -1,74 +0,0 @@ -package ch.unisg.executorpool.domain; - -import ch.unisg.executorpool.domain.ExecutorClass.ExecutorUri; -import ch.unisg.executorpool.domain.ExecutorClass.ExecutorTaskType; - -import lombok.Getter; -import lombok.Value; - -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; - -public class ExecutorPool { - - @Getter - private final ListOfExecutors listOfExecutors; - - private static final ExecutorPool executorPool = new ExecutorPool(); - - private ExecutorPool(){ - this.listOfExecutors = new ListOfExecutors(new LinkedList()); - } - - public static ExecutorPool getExecutorPool() { return executorPool; } - - public ExecutorClass addNewExecutor(ExecutorUri executorUri, ExecutorTaskType executorTaskType){ - ExecutorClass newExecutor = ExecutorClass.createExecutorClass(executorUri, executorTaskType); - listOfExecutors.value.add(newExecutor); - System.out.println("Number of executors: " + listOfExecutors.value.size()); - return newExecutor; - } - - public Optional getExecutorByUri(ExecutorUri executorUri){ - - for (ExecutorClass executor : listOfExecutors.value ) { - if(executor.getExecutorUri().getValue().equals(executorUri)){ - return Optional.of(executor); - } - } - - return Optional.empty(); - } - - public List getAllExecutorsByType(ExecutorClass.ExecutorTaskType executorTaskType){ - - List matchedExecutors = new LinkedList(); - - for (ExecutorClass executor : listOfExecutors.value ) { - // TODO can this be simplified by overwriting equals()? - if(executor.getExecutorTaskType().getValue().equalsIgnoreCase(executorTaskType.getValue())){ - matchedExecutors.add(executor); - } - } - - return matchedExecutors; - } - - public Optional removeExecutorByIpAndPort(ExecutorUri executorUri){ - for (ExecutorClass executor : listOfExecutors.value ) { - // TODO can this be simplified by overwriting equals()? - if(executor.getExecutorUri().getValue().equals(executorUri.getValue())){ - listOfExecutors.value.remove(executor); - return Optional.of(executor); - } - } - - return Optional.empty(); - } - - @Value - public static class ListOfExecutors { - private List value; - } -} diff --git a/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorRemovedEvent.java b/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorRemovedEvent.java deleted file mode 100644 index a038928..0000000 --- a/executor-pool/src/main/java/ch/unisg/executorpool/domain/ExecutorRemovedEvent.java +++ /dev/null @@ -1,11 +0,0 @@ -package ch.unisg.executorpool.domain; - -import ch.unisg.executorpool.domain.ExecutorClass; -import lombok.Getter; - -public class ExecutorRemovedEvent { - @Getter - private ExecutorClass executorClass; - - public ExecutorRemovedEvent(ExecutorClass executorClass) { this.executorClass = executorClass; } -} diff --git a/executor-pool/src/main/resources/application.properties b/executor-pool/src/main/resources/application.properties deleted file mode 100644 index 0c9ba7e..0000000 --- a/executor-pool/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -server.port=8083 - -mqtt.broker.uri=tcp://localhost:1883 diff --git a/executor-pool/src/test/java/ch/unisg/executorpool/ExecutorPoolApplicationTests.java b/executor-pool/src/test/java/ch/unisg/executorpool/ExecutorPoolApplicationTests.java deleted file mode 100644 index 77e1032..0000000 --- a/executor-pool/src/test/java/ch/unisg/executorpool/ExecutorPoolApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package ch.unisg.executorpool; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class ExecutorPoolApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/executor-robot/.gitignore b/executor-robot/.gitignore deleted file mode 100644 index 549e00a..0000000 --- a/executor-robot/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -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/executor-robot/.mvn/wrapper/MavenWrapperDownloader.java b/executor-robot/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index e76d1f3..0000000 --- a/executor-robot/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed 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 - * - * https://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. - */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/executor-robot/.mvn/wrapper/maven-wrapper.jar b/executor-robot/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 2cc7d4a..0000000 Binary files a/executor-robot/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/executor-robot/.mvn/wrapper/maven-wrapper.properties b/executor-robot/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index abd303b..0000000 --- a/executor-robot/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/executor-robot/Dockerfile b/executor-robot/Dockerfile deleted file mode 100644 index db90fb6..0000000 --- a/executor-robot/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM openjdk:11 AS development - -WORKDIR /opt/app - -# ENV SPRING_DATASOURCE_URL=jdbc:mysql://backend-db:3306/db - -COPY .mvn/ .mvn -COPY mvnw pom.xml mvnw.cmd ./ - -RUN apt-get clean && apt-get update && apt-get install dos2unix -RUN dos2unix mvnw - -RUN ./mvnw dependency:go-offline - -COPY src /opt/app/src -COPY *target /opt/app/target - -CMD ["./mvnw", "spring-boot:run", "-Dspring-boot.run.jvmArguments=\"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005\"", "-Dspring.devtools.restart.enabled=true"] diff --git a/executor-robot/mvnw b/executor-robot/mvnw deleted file mode 100755 index a16b543..0000000 --- a/executor-robot/mvnw +++ /dev/null @@ -1,310 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - 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" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/executor-robot/mvnw.cmd b/executor-robot/mvnw.cmd deleted file mode 100644 index c8d4337..0000000 --- a/executor-robot/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@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 https://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 Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/executor-robot/pom.xml b/executor-robot/pom.xml deleted file mode 100644 index ca95edf..0000000 --- a/executor-robot/pom.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.5.5 - - - ch.unisg - executor-robot - 0.0.1-SNAPSHOT - executor-robot - Demo project for Spring Boot - - 11 - scs-asse-fs21-group1 - https://sonarcloud.io - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - ch.unisg - executor-base - 0.0.1-SNAPSHOT - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - - - - - - diff --git a/executor-robot/src/main/java/ch/unisg/executorrobot/ExecutorrobotApplication.java b/executor-robot/src/main/java/ch/unisg/executorrobot/ExecutorrobotApplication.java deleted file mode 100644 index fcee5ee..0000000 --- a/executor-robot/src/main/java/ch/unisg/executorrobot/ExecutorrobotApplication.java +++ /dev/null @@ -1,16 +0,0 @@ -package ch.unisg.executorrobot; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; - -import ch.unisg.executorrobot.executor.domain.Executor; - -@SpringBootApplication -public class ExecutorrobotApplication { - - public static void main(String[] args) { - SpringApplication.run(ExecutorrobotApplication.class, args); - Executor.getExecutor(); - } - -} diff --git a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/in/web/TaskAvailableController.java b/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/in/web/TaskAvailableController.java deleted file mode 100644 index 7f256df..0000000 --- a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/in/web/TaskAvailableController.java +++ /dev/null @@ -1,38 +0,0 @@ -package ch.unisg.executorrobot.executor.adapter.in.web; - -import java.util.concurrent.CompletableFuture; - -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RestController; - -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableCommand; -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableUseCase; -import ch.unisg.executorbase.executor.domain.ExecutorType; - -@RestController -public class TaskAvailableController { - private final TaskAvailableUseCase taskAvailableUseCase; - - public TaskAvailableController(TaskAvailableUseCase taskAvailableUseCase) { - this.taskAvailableUseCase = taskAvailableUseCase; - } - - @GetMapping(path = "/newtask/{taskType}") - public ResponseEntity retrieveTaskFromTaskList(@PathVariable("taskType") String taskType) { - - if (ExecutorType.contains(taskType.toUpperCase())) { - TaskAvailableCommand command = new TaskAvailableCommand( - ExecutorType.valueOf(taskType.toUpperCase())); - CompletableFuture.runAsync(() -> taskAvailableUseCase.newTaskAvailable(command)); - } - - // Add the content type as a response header - HttpHeaders responseHeaders = new HttpHeaders(); - - return new ResponseEntity<>("OK", responseHeaders, HttpStatus.OK); - } -} diff --git a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/out/DeleteUserFromRobotAdapter.java b/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/out/DeleteUserFromRobotAdapter.java deleted file mode 100644 index 157bc3e..0000000 --- a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/out/DeleteUserFromRobotAdapter.java +++ /dev/null @@ -1,42 +0,0 @@ -package ch.unisg.executorrobot.executor.adapter.out; -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; - -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; - -import ch.unisg.executorrobot.executor.application.port.out.DeleteUserFromRobotPort; - -@Component -@Primary -public class DeleteUserFromRobotAdapter implements DeleteUserFromRobotPort { - - @Override - public boolean deleteUserFromRobot(String key) { - - String url = "https://api.interactions.ics.unisg.ch/leubot1/v1.3.0/user/" + key; - - var request = HttpRequest.newBuilder() - .uri(URI.create(url)) - .header("Content-Type", "application/json") - .DELETE() - .build(); - - var client = HttpClient.newHttpClient(); - - try { - var response = client.send(request, HttpResponse.BodyHandlers.ofString()); - System.out.println(response.statusCode()); - return true; - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return false; - } - -} diff --git a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/out/InstructionToRobotAdapter.java b/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/out/InstructionToRobotAdapter.java deleted file mode 100644 index c7507e4..0000000 --- a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/out/InstructionToRobotAdapter.java +++ /dev/null @@ -1,46 +0,0 @@ -package ch.unisg.executorrobot.executor.adapter.out; -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; - -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; - -import ch.unisg.executorrobot.executor.application.port.out.InstructionToRobotPort; - -@Component -@Primary -public class InstructionToRobotAdapter implements InstructionToRobotPort { - - @Override - public boolean instructionToRobot(String key) { - - String putEndpoint = "https://api.interactions.ics.unisg.ch/leubot1/v1.3.0/elbow"; - - String inputJson = "{ \"value\": 400}"; - var request = HttpRequest.newBuilder() - .uri(URI.create(putEndpoint)) - .header("Content-Type", "application/json") - .header("X-API-KEY", key) - .PUT(HttpRequest.BodyPublishers.ofString(inputJson)) - .build(); - - var client = HttpClient.newHttpClient(); - - try { - var response = client.send(request, HttpResponse.BodyHandlers.ofString()); - System.out.println(response.statusCode()); - System.out.println(response.headers()); - return true; - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return false; - - } - -} diff --git a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/out/UserToRobotAdapter.java b/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/out/UserToRobotAdapter.java deleted file mode 100644 index 92ca8c1..0000000 --- a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/adapter/out/UserToRobotAdapter.java +++ /dev/null @@ -1,46 +0,0 @@ -package ch.unisg.executorrobot.executor.adapter.out; -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; - -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; - -import ch.unisg.executorrobot.executor.application.port.out.UserToRobotPort; - -@Component -@Primary -public class UserToRobotAdapter implements UserToRobotPort { - - @Override - public String userToRobot() { - String postEndpoint = "https://api.interactions.ics.unisg.ch/leubot1/v1.3.0/user"; - - String inputJson = "{ \"name\":\"keanu rahimian\", \"email\":\"keanu.rahimian@student.unisg.ch\"}"; - var request = HttpRequest.newBuilder() - .uri(URI.create(postEndpoint)) - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofString(inputJson)) - .build(); - - var client = HttpClient.newHttpClient(); - - try { - var response = client.send(request, HttpResponse.BodyHandlers.ofString()); - System.out.println(response.statusCode()); - System.out.println(response.headers()); - String url = response.headers().map().get("location").toString(); - String key = url.split("/")[url.split("/").length-1].split("]")[0]; - return key; - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - return null; - - } - -} diff --git a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/port/out/DeleteUserFromRobotPort.java b/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/port/out/DeleteUserFromRobotPort.java deleted file mode 100644 index 2411353..0000000 --- a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/port/out/DeleteUserFromRobotPort.java +++ /dev/null @@ -1,5 +0,0 @@ -package ch.unisg.executorrobot.executor.application.port.out; - -public interface DeleteUserFromRobotPort { - boolean deleteUserFromRobot(String key); -} diff --git a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/port/out/InstructionToRobotPort.java b/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/port/out/InstructionToRobotPort.java deleted file mode 100644 index 97985b0..0000000 --- a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/port/out/InstructionToRobotPort.java +++ /dev/null @@ -1,5 +0,0 @@ -package ch.unisg.executorrobot.executor.application.port.out; - -public interface InstructionToRobotPort { - boolean instructionToRobot(String key); -} diff --git a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/port/out/UserToRobotPort.java b/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/port/out/UserToRobotPort.java deleted file mode 100644 index 3da8ded..0000000 --- a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/port/out/UserToRobotPort.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.unisg.executorrobot.executor.application.port.out; - -import ch.unisg.executorbase.executor.domain.ExecutorType; - -public interface UserToRobotPort { - String userToRobot(); -} diff --git a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/service/TaskAvailableService.java b/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/service/TaskAvailableService.java deleted file mode 100644 index 5d26502..0000000 --- a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/application/service/TaskAvailableService.java +++ /dev/null @@ -1,28 +0,0 @@ -package ch.unisg.executorrobot.executor.application.service; - -import org.springframework.stereotype.Component; - -import ch.unisg.executorrobot.executor.domain.Executor; -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableCommand; -import ch.unisg.executorbase.executor.application.port.in.TaskAvailableUseCase; -import ch.unisg.executorbase.executor.domain.ExecutorStatus; -import lombok.RequiredArgsConstructor; - -import javax.transaction.Transactional; - -@RequiredArgsConstructor -@Component -@Transactional -public class TaskAvailableService implements TaskAvailableUseCase { - - @Override - public void newTaskAvailable(TaskAvailableCommand command) { - - Executor executor = Executor.getExecutor(); - - if (executor.getExecutorType() == command.getTaskType() && - executor.getStatus() == ExecutorStatus.IDLING) { - executor.getAssignment(); - } - } -} diff --git a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/domain/Executor.java b/executor-robot/src/main/java/ch/unisg/executorrobot/executor/domain/Executor.java deleted file mode 100644 index e83579c..0000000 --- a/executor-robot/src/main/java/ch/unisg/executorrobot/executor/domain/Executor.java +++ /dev/null @@ -1,52 +0,0 @@ -package ch.unisg.executorrobot.executor.domain; - -import java.util.concurrent.TimeUnit; - -import ch.unisg.executorrobot.executor.adapter.out.DeleteUserFromRobotAdapter; -import ch.unisg.executorrobot.executor.adapter.out.InstructionToRobotAdapter; -import ch.unisg.executorrobot.executor.adapter.out.UserToRobotAdapter; -import ch.unisg.executorrobot.executor.application.port.out.DeleteUserFromRobotPort; -import ch.unisg.executorrobot.executor.application.port.out.InstructionToRobotPort; -import ch.unisg.executorrobot.executor.application.port.out.UserToRobotPort; -import ch.unisg.executorbase.executor.domain.ExecutorBase; -import ch.unisg.executorbase.executor.domain.ExecutorType; - -public class Executor extends ExecutorBase { - - private static final Executor executor = new Executor(ExecutorType.ROBOT); - private final UserToRobotPort userToRobotPort = new UserToRobotAdapter(); - private final InstructionToRobotPort instructionToRobotPort = new InstructionToRobotAdapter(); - private final DeleteUserFromRobotPort deleteUserFromRobotPort = new DeleteUserFromRobotAdapter(); - - public static Executor getExecutor() { - return executor; - } - - private Executor(ExecutorType executorType) { - super(executorType); - } - - @Override - protected - String execution(String input) { - - String key = userToRobotPort.userToRobot(); - try { - TimeUnit.MILLISECONDS.sleep(1500); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - boolean result1 = instructionToRobotPort.instructionToRobot(key); - try { - TimeUnit.MILLISECONDS.sleep(10000); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - deleteUserFromRobotPort.deleteUserFromRobot(key); - - return Boolean.toString(result1); - } - -} diff --git a/executor-robot/src/main/resources/application.properties b/executor-robot/src/main/resources/application.properties deleted file mode 100644 index 5e3bb81..0000000 --- a/executor-robot/src/main/resources/application.properties +++ /dev/null @@ -1 +0,0 @@ -server.port=8084 diff --git a/executor-robot/src/test/java/ch/unisg/executorrobot/ExecutorrobotApplicationTests.java b/executor-robot/src/test/java/ch/unisg/executorrobot/ExecutorrobotApplicationTests.java deleted file mode 100644 index 82f67a8..0000000 --- a/executor-robot/src/test/java/ch/unisg/executorrobot/ExecutorrobotApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package ch.unisg.executorrobot; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class ExecutorrobotApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/mocks/README.md b/mocks/README.md deleted file mode 100644 index 7135682..0000000 --- a/mocks/README.md +++ /dev/null @@ -1,29 +0,0 @@ -In this directory are some files to mock an auction house to test WebSub local. - -To run a local WebSubHub instance - -1. Start a mongodb in docker: - -- docker run -d -p 27017:27017 -p 28017:28017 -e AUTH=no tutum/mongodb - -2. Install a local hub - -- yarn global add websub-hub - -3. Run the hub localy - -- websub-hub -l info -m mongodb://localhost:27017/hub - -Create an example subscription - -- node auction-house/subscriber.js - -Create an example auctionhouse - -- node auction-house/auctions.js - -Publish to the hub - -- node auction-house/publisher.js - -Mostly inspired by: https://github.com/hemerajs/websub-hub diff --git a/mocks/auction-house/auctions.js b/mocks/auction-house/auctions.js deleted file mode 100644 index 68a6aa5..0000000 --- a/mocks/auction-house/auctions.js +++ /dev/null @@ -1,39 +0,0 @@ -// Require the framework and instantiate it -const fastify = require('fastify')({ logger: true }) - -// Declare a route -fastify.get('/auctions', async (request, reply) => { - console.log('content provided') - - return [ - { - id: '2', - content_text: 'This is a second item.', - url: 'https://example.org/second-item' - }, - { - id: '1', - content_html: '

Hello, world!

', - url: 'https://example.org/initial-post' - } - ] -}) - -fastify.get('/websub', async (request, reply) => { - console.log('content provided') - - return { - topic: 'http://localhost:3100/auctions' - } -}) - -// Run the server! -const start = async () => { - try { - await fastify.listen(3100) - } catch (err) { - fastify.log.error(err) - process.exit(1) - } -} -start() diff --git a/mocks/auction-house/publisher.js b/mocks/auction-house/publisher.js deleted file mode 100644 index c760820..0000000 --- a/mocks/auction-house/publisher.js +++ /dev/null @@ -1,17 +0,0 @@ -const axios = require('axios').default - -// Run the server! -const start = async () => { - await axios - .post('http://localhost:3000/publish', { - 'hub.mode': 'publish', - 'hub.url': 'http://localhost:3100/auctions' - }) - .then(response => { - console.log(response.data) - }) - .catch(error => { - console.log(error) - }) -} -start() diff --git a/mocks/auction-house/subscriber.js b/mocks/auction-house/subscriber.js deleted file mode 100644 index ce27197..0000000 --- a/mocks/auction-house/subscriber.js +++ /dev/null @@ -1,42 +0,0 @@ -// Require the framework and instantiate it -const fastify = require('fastify')({ logger: true }) -const axios = require('axios').default - -// Declare a route -fastify.get('/auction-created', async (request, reply) => { - console.log('subscription verified', request.query) - console.log(request.query) - return request.query -}) - -fastify.post('/auction-created', async (request, reply) => { - console.log('received blog content', request.body) - reply.send() -}) - -// Run the server! -const start = async () => { - // subscribe to the feed - - try { - await fastify.listen(3200) - } catch (err) { - fastify.log.error(err) - process.exit(1) - } - - await axios - .post('http://localhost:3000', { - 'hub.callback': 'http://localhost:3200/auction-created', - 'hub.mode': 'subscribe', - 'hub.topic': 'http://localhost:3100/auctions', - 'hub.ws': false - }) - .then(response => { - console.log(response.data) - }) - .catch(error => { - console.log(error) - }) -} -start() diff --git a/roster/.gitignore b/roster/.gitignore deleted file mode 100644 index 549e00a..0000000 --- a/roster/.gitignore +++ /dev/null @@ -1,33 +0,0 @@ -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/roster/.mvn/wrapper/MavenWrapperDownloader.java b/roster/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index e76d1f3..0000000 --- a/roster/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed 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 - * - * https://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. - */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. - */ - private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; - - /** - * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to - * use instead of the default one. - */ - private static final String MAVEN_WRAPPER_PROPERTIES_PATH = - ".mvn/wrapper/maven-wrapper.properties"; - - /** - * Path where the maven-wrapper.jar will be saved to. - */ - private static final String MAVEN_WRAPPER_JAR_PATH = - ".mvn/wrapper/maven-wrapper.jar"; - - /** - * Name of the property which should be used to override the default download url for the wrapper. - */ - private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; - - public static void main(String args[]) { - System.out.println("- Downloader started"); - File baseDirectory = new File(args[0]); - System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); - - // If the maven-wrapper.properties exists, read it and check if it contains a custom - // wrapperUrl parameter. - File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); - String url = DEFAULT_DOWNLOAD_URL; - if(mavenWrapperPropertyFile.exists()) { - FileInputStream mavenWrapperPropertyFileInputStream = null; - try { - mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); - Properties mavenWrapperProperties = new Properties(); - mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); - url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); - } catch (IOException e) { - System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); - } finally { - try { - if(mavenWrapperPropertyFileInputStream != null) { - mavenWrapperPropertyFileInputStream.close(); - } - } catch (IOException e) { - // Ignore ... - } - } - } - System.out.println("- Downloading from: " + url); - - File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); - if(!outputFile.getParentFile().exists()) { - if(!outputFile.getParentFile().mkdirs()) { - System.out.println( - "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); - } - } - System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); - try { - downloadFileFromURL(url, outputFile); - System.out.println("Done"); - System.exit(0); - } catch (Throwable e) { - System.out.println("- Error downloading"); - e.printStackTrace(); - System.exit(1); - } - } - - private static void downloadFileFromURL(String urlString, File destination) throws Exception { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - URL website = new URL(urlString); - ReadableByteChannel rbc; - rbc = Channels.newChannel(website.openStream()); - FileOutputStream fos = new FileOutputStream(destination); - fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); - fos.close(); - rbc.close(); - } - -} diff --git a/roster/.mvn/wrapper/maven-wrapper.jar b/roster/.mvn/wrapper/maven-wrapper.jar deleted file mode 100644 index 2cc7d4a..0000000 Binary files a/roster/.mvn/wrapper/maven-wrapper.jar and /dev/null differ diff --git a/roster/.mvn/wrapper/maven-wrapper.properties b/roster/.mvn/wrapper/maven-wrapper.properties deleted file mode 100644 index abd303b..0000000 --- a/roster/.mvn/wrapper/maven-wrapper.properties +++ /dev/null @@ -1,2 +0,0 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar diff --git a/roster/Dockerfile b/roster/Dockerfile deleted file mode 100644 index db90fb6..0000000 --- a/roster/Dockerfile +++ /dev/null @@ -1,18 +0,0 @@ -FROM openjdk:11 AS development - -WORKDIR /opt/app - -# ENV SPRING_DATASOURCE_URL=jdbc:mysql://backend-db:3306/db - -COPY .mvn/ .mvn -COPY mvnw pom.xml mvnw.cmd ./ - -RUN apt-get clean && apt-get update && apt-get install dos2unix -RUN dos2unix mvnw - -RUN ./mvnw dependency:go-offline - -COPY src /opt/app/src -COPY *target /opt/app/target - -CMD ["./mvnw", "spring-boot:run", "-Dspring-boot.run.jvmArguments=\"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005\"", "-Dspring.devtools.restart.enabled=true"] diff --git a/roster/mvnw b/roster/mvnw deleted file mode 100755 index a16b543..0000000 --- a/roster/mvnw +++ /dev/null @@ -1,310 +0,0 @@ -#!/bin/sh -# ---------------------------------------------------------------------------- -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# https://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. -# ---------------------------------------------------------------------------- - -# ---------------------------------------------------------------------------- -# Maven Start Up Batch script -# -# Required ENV vars: -# ------------------ -# JAVA_HOME - location of a JDK home dir -# -# Optional ENV vars -# ----------------- -# M2_HOME - location of maven2's installed home dir -# MAVEN_OPTS - parameters passed to the Java VM when running Maven -# e.g. to debug Maven itself, use -# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -# MAVEN_SKIP_RC - flag to disable loading of mavenrc files -# ---------------------------------------------------------------------------- - -if [ -z "$MAVEN_SKIP_RC" ] ; then - - if [ -f /etc/mavenrc ] ; then - . /etc/mavenrc - fi - - if [ -f "$HOME/.mavenrc" ] ; then - . "$HOME/.mavenrc" - fi - -fi - -# OS specific support. $var _must_ be set to either true or false. -cygwin=false; -darwin=false; -mingw=false -case "`uname`" in - CYGWIN*) cygwin=true ;; - MINGW*) mingw=true;; - Darwin*) darwin=true - # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home - # See https://developer.apple.com/library/mac/qa/qa1170/_index.html - if [ -z "$JAVA_HOME" ]; then - if [ -x "/usr/libexec/java_home" ]; then - export JAVA_HOME="`/usr/libexec/java_home`" - else - export JAVA_HOME="/Library/Java/Home" - fi - fi - ;; -esac - -if [ -z "$JAVA_HOME" ] ; then - if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` - fi -fi - -if [ -z "$M2_HOME" ] ; then - ## resolve links - $0 may be a link to maven's home - PRG="$0" - - # need this for relative symlinks - while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG="`dirname "$PRG"`/$link" - fi - done - - saveddir=`pwd` - - M2_HOME=`dirname "$PRG"`/.. - - # make it fully qualified - M2_HOME=`cd "$M2_HOME" && pwd` - - cd "$saveddir" - # echo Using m2 at $M2_HOME -fi - -# For Cygwin, ensure paths are in UNIX format before anything is touched -if $cygwin ; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --unix "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --unix "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$CLASSPATH"` -fi - -# For Mingw, ensure paths are in UNIX format before anything is touched -if $mingw ; then - [ -n "$M2_HOME" ] && - M2_HOME="`(cd "$M2_HOME"; pwd)`" - [ -n "$JAVA_HOME" ] && - JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" -fi - -if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then - # readlink(1) is not available as standard on Solaris 10. - readLink=`which readlink` - if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then - if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" - else - javaExecutable="`readlink -f \"$javaExecutable\"`" - fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` - JAVA_HOME="$javaHome" - export JAVA_HOME - fi - fi -fi - -if [ -z "$JAVACMD" ] ; then - 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" - else - JAVACMD="$JAVA_HOME/bin/java" - fi - else - JAVACMD="`which java`" - fi -fi - -if [ ! -x "$JAVACMD" ] ; then - echo "Error: JAVA_HOME is not defined correctly." >&2 - echo " We cannot execute $JAVACMD" >&2 - exit 1 -fi - -if [ -z "$JAVA_HOME" ] ; then - echo "Warning: JAVA_HOME environment variable is not set." -fi - -CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher - -# traverses directory structure from process work directory to filesystem root -# first directory with .mvn subdirectory is considered project base directory -find_maven_basedir() { - - if [ -z "$1" ] - then - echo "Path not specified to find_maven_basedir" - return 1 - fi - - basedir="$1" - wdir="$1" - while [ "$wdir" != '/' ] ; do - if [ -d "$wdir"/.mvn ] ; then - basedir=$wdir - break - fi - # workaround for JBEAP-8937 (on Solaris 10/Sparc) - if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` - fi - # end of workaround - done - echo "${basedir}" -} - -# concatenates all lines of a file -concat_lines() { - if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" - fi -} - -BASE_DIR=`find_maven_basedir "$(pwd)"` -if [ -z "$BASE_DIR" ]; then - exit 1; -fi - -########################################################################################## -# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -# This allows using the maven wrapper in projects that prohibit checking in binary data. -########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi -else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi - if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; - esac - done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" - if [ "$MVNW_VERBOSE" = true ]; then - echo "Downloading from: $jarUrl" - fi - wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" - if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` - fi - - if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" - else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" - fi - elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi - if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f - else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f - fi - - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" - # For Cygwin, switch paths to Windows format before running javac - if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` - fi - if [ -e "$javaClass" ]; then - if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Compiling MavenWrapperDownloader.java ..." - fi - # Compiling the Java class - ("$JAVA_HOME/bin/javac" "$javaClass") - fi - if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then - # Running the downloader - if [ "$MVNW_VERBOSE" = true ]; then - echo " - Running MavenWrapperDownloader.java ..." - fi - ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") - fi - fi - fi -fi -########################################################################################## -# End of extension -########################################################################################## - -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR -fi -MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" - -# For Cygwin, switch paths to Windows format before running java -if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` - [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` - [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` - [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` -fi - -# Provide a "standardized" way to retrieve the CLI args that will -# work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" -export MAVEN_CMD_LINE_ARGS - -WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -exec "$JAVACMD" \ - $MAVEN_OPTS \ - -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ - ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/roster/mvnw.cmd b/roster/mvnw.cmd deleted file mode 100644 index c8d4337..0000000 --- a/roster/mvnw.cmd +++ /dev/null @@ -1,182 +0,0 @@ -@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 https://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 Maven Start Up Batch script -@REM -@REM Required ENV vars: -@REM JAVA_HOME - location of a JDK home dir -@REM -@REM Optional ENV vars -@REM M2_HOME - location of maven2's installed home dir -@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands -@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending -@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven -@REM e.g. to debug Maven itself, use -@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 -@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files -@REM ---------------------------------------------------------------------------- - -@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' -@echo off -@REM set title of command window -title %0 -@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' -@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% - -@REM set %HOME% to equivalent of $HOME -if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") - -@REM Execute a user defined script before this one -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre -@REM check for pre script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" -if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" -:skipRcPre - -@setlocal - -set ERROR_CODE=0 - -@REM To isolate internal variables from possible post scripts, we use another setlocal -@setlocal - -@REM ==== START VALIDATION ==== -if not "%JAVA_HOME%" == "" goto OkJHome - -echo. -echo Error: JAVA_HOME not found in your environment. >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -:OkJHome -if exist "%JAVA_HOME%\bin\java.exe" goto init - -echo. -echo Error: JAVA_HOME is set to an invalid directory. >&2 -echo JAVA_HOME = "%JAVA_HOME%" >&2 -echo Please set the JAVA_HOME variable in your environment to match the >&2 -echo location of your Java installation. >&2 -echo. -goto error - -@REM ==== END VALIDATION ==== - -:init - -@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". -@REM Fallback to current working directory if not found. - -set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% -IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir - -set EXEC_DIR=%CD% -set WDIR=%EXEC_DIR% -:findBaseDir -IF EXIST "%WDIR%"\.mvn goto baseDirFound -cd .. -IF "%WDIR%"=="%CD%" goto baseDirNotFound -set WDIR=%CD% -goto findBaseDir - -:baseDirFound -set MAVEN_PROJECTBASEDIR=%WDIR% -cd "%EXEC_DIR%" -goto endDetectBaseDir - -:baseDirNotFound -set MAVEN_PROJECTBASEDIR=%EXEC_DIR% -cd "%EXEC_DIR%" - -:endDetectBaseDir - -IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig - -@setlocal EnableExtensions EnableDelayedExpansion -for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a -@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% - -:endReadAdditionalConfig - -SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" -set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" -set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain - -set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B -) - -@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central -@REM This allows using the maven wrapper in projects that prohibit checking in binary data. -if exist %WRAPPER_JAR% ( - if "%MVNW_VERBOSE%" == "true" ( - echo Found %WRAPPER_JAR% - ) -) else ( - if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" - ) - if "%MVNW_VERBOSE%" == "true" ( - echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% - ) - - powershell -Command "&{"^ - "$webclient = new-object System.Net.WebClient;"^ - "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ - "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ - "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ - "}" - if "%MVNW_VERBOSE%" == "true" ( - echo Finished downloading %WRAPPER_JAR% - ) -) -@REM End of extension - -@REM Provide a "standardized" way to retrieve the CLI args that will -@REM work with both Windows and non-Windows executions. -set MAVEN_CMD_LINE_ARGS=%* - -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* -if ERRORLEVEL 1 goto error -goto end - -:error -set ERROR_CODE=1 - -:end -@endlocal & set ERROR_CODE=%ERROR_CODE% - -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost -@REM check for post script, once with legacy .bat ending and once with .cmd ending -if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" -if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" -:skipRcPost - -@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause - -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% - -exit /B %ERROR_CODE% diff --git a/roster/pom.xml b/roster/pom.xml deleted file mode 100644 index 791e0d0..0000000 --- a/roster/pom.xml +++ /dev/null @@ -1,97 +0,0 @@ - - - 4.0.0 - - org.springframework.boot - spring-boot-starter-parent - 2.5.5 - - - ch.unisg - roster - 0.0.1-SNAPSHOT - roster - Demo project for Spring Boot - - 11 - scs-asse-fs21-group1 - https://sonarcloud.io - - - - org.springframework.boot - spring-boot-starter-web - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - - org.springframework.boot - spring-boot-starter-validation - - - org.projectlombok - lombok - true - - - org.springframework.boot - spring-boot-starter-test - test - - - javax.validation - validation-api - 1.1.0.Final - - - javax.transaction - javax.transaction-api - 1.2 - - - - org.eclipse.paho - org.eclipse.paho.client.mqttv3 - 1.2.5 - - - - org.json - json - 20210307 - - - - ch.unisg - common - 0.0.1-SNAPSHOT - - - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - org.projectlombok - lombok - - - - - - - - diff --git a/roster/src/main/java/ch/unisg/roster/RosterApplication.java b/roster/src/main/java/ch/unisg/roster/RosterApplication.java deleted file mode 100644 index 1b12ca3..0000000 --- a/roster/src/main/java/ch/unisg/roster/RosterApplication.java +++ /dev/null @@ -1,45 +0,0 @@ -package ch.unisg.roster; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.eclipse.paho.client.mqttv3.MqttException; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.core.env.ConfigurableEnvironment; - -import ch.unisg.roster.roster.adapter.common.clients.TapasMqttClient; -import ch.unisg.roster.roster.adapter.in.messaging.mqtt.ExecutorEventMqttListener; -import ch.unisg.roster.roster.adapter.in.messaging.mqtt.ExecutorEventsMqttDispatcher; - -@SpringBootApplication -public class RosterApplication { - - static Logger logger = Logger.getLogger(RosterApplication.class.getName()); - - private static ConfigurableEnvironment ENVIRONMENT; - - public static void main(String[] args) { - - SpringApplication rosterApp = new SpringApplication(RosterApplication.class); - ENVIRONMENT = rosterApp.run(args).getEnvironment(); - bootstrapMarketplaceWithMqtt(); - } - - /** - * Connects to an MQTT broker, presumably the one used by all TAPAS groups to communicate with - * one another - */ - private static void bootstrapMarketplaceWithMqtt() { - String broker = ENVIRONMENT.getProperty("mqtt.broker.uri"); - - try { - ExecutorEventsMqttDispatcher dispatcher = new ExecutorEventsMqttDispatcher(); - TapasMqttClient client = TapasMqttClient.getInstance(broker, dispatcher); - client.startReceivingMessages(); - } catch (MqttException e) { - logger.log(Level.SEVERE, e.getMessage(), e); - } - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/common/clients/TapasMqttClient.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/common/clients/TapasMqttClient.java deleted file mode 100644 index 78f2d0c..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/common/clients/TapasMqttClient.java +++ /dev/null @@ -1,94 +0,0 @@ -package ch.unisg.roster.roster.adapter.common.clients; - -import ch.unisg.roster.roster.adapter.in.messaging.mqtt.ExecutorEventsMqttDispatcher; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.paho.client.mqttv3.*; -import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; - -import java.nio.charset.StandardCharsets; -import java.util.UUID; - -/** - * MQTT client for your TAPAS application. This class is defined as a singleton, but it does not have - * to be this way. This class is only provided as an example to help you bootstrap your project. - * You are welcomed to change this class as you see fit. - */ -public class TapasMqttClient { - private static final Logger LOGGER = LogManager.getLogger(TapasMqttClient.class); - - private static TapasMqttClient tapasClient = null; - - private MqttClient mqttClient; - private final String mqttClientId; - private final String brokerAddress; - - private final MessageReceivedCallback messageReceivedCallback; - - private final ExecutorEventsMqttDispatcher dispatcher; - - private TapasMqttClient(String brokerAddress, ExecutorEventsMqttDispatcher dispatcher) { - this.mqttClientId = UUID.randomUUID().toString(); - this.brokerAddress = brokerAddress; - - this.messageReceivedCallback = new MessageReceivedCallback(); - - this.dispatcher = dispatcher; - } - - public static synchronized TapasMqttClient getInstance(String brokerAddress, - ExecutorEventsMqttDispatcher dispatcher) { - - if (tapasClient == null) { - tapasClient = new TapasMqttClient(brokerAddress, dispatcher); - } - - return tapasClient; - } - - public void startReceivingMessages() throws MqttException { - mqttClient = new org.eclipse.paho.client.mqttv3.MqttClient(brokerAddress, mqttClientId, new MemoryPersistence()); - mqttClient.connect(); - mqttClient.setCallback(messageReceivedCallback); - - subscribeToAllTopics(); - } - - public void stopReceivingMessages() throws MqttException { - mqttClient.disconnect(); - } - - private void subscribeToAllTopics() throws MqttException { - for (String topic : dispatcher.getAllTopics()) { - subscribeToTopic(topic); - } - } - - private void subscribeToTopic(String topic) throws MqttException { - mqttClient.subscribe(topic); - } - - private void publishMessage(String topic, String payload) throws MqttException { - MqttMessage message = new MqttMessage(payload.getBytes(StandardCharsets.UTF_8)); - mqttClient.publish(topic, message); - } - - private class MessageReceivedCallback implements MqttCallback { - - @Override - public void connectionLost(Throwable cause) { } - - @Override - public void messageArrived(String topic, MqttMessage message) { - LOGGER.info("Received new MQTT message for topic " + topic + ": " - + new String(message.getPayload())); - - if (topic != null && !topic.isEmpty()) { - dispatcher.dispatchEvent(topic, message); - } - } - - @Override - public void deliveryComplete(IMqttDeliveryToken token) { } - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorAddedEventListenerMqttAdapter.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorAddedEventListenerMqttAdapter.java deleted file mode 100644 index 10e907e..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorAddedEventListenerMqttAdapter.java +++ /dev/null @@ -1,47 +0,0 @@ -package ch.unisg.roster.roster.adapter.in.messaging.mqtt; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.paho.client.mqttv3.MqttMessage; - -import ch.unisg.common.valueobject.ExecutorURI; -import ch.unisg.roster.roster.application.handler.ExecutorAddedHandler; -import ch.unisg.roster.roster.application.port.in.ExecutorAddedEvent; -import ch.unisg.roster.roster.domain.valueobject.ExecutorType; - -public class ExecutorAddedEventListenerMqttAdapter extends ExecutorEventMqttListener { - private static final Logger LOGGER = LogManager.getLogger(ExecutorAddedEventListenerMqttAdapter.class); - - @Override - public boolean handleEvent(MqttMessage message) { - - System.out.println("New Executor added!"); - - String payload = new String(message.getPayload()); - - try { - // Note: this messge representation is provided only as an example. You should use a - // representation that makes sense in the context of your application. - JsonNode data = new ObjectMapper().readTree(payload); - - String taskType = data.get("executorTaskType").asText(); - String executorId = data.get("executorUri").asText(); - - ExecutorAddedEvent executorAddedEvent = new ExecutorAddedEvent( - new ExecutorURI(executorId), - new ExecutorType(taskType) - ); - - ExecutorAddedHandler newExecutorHandler = new ExecutorAddedHandler(); - newExecutorHandler.handleNewExecutorEvent(executorAddedEvent); - } catch (JsonProcessingException | NullPointerException e) { - LOGGER.error(e.getMessage(), e); - return false; - } - - return true; - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorEventMqttListener.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorEventMqttListener.java deleted file mode 100644 index df46b00..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorEventMqttListener.java +++ /dev/null @@ -1,11 +0,0 @@ -package ch.unisg.roster.roster.adapter.in.messaging.mqtt; - -import org.eclipse.paho.client.mqttv3.MqttMessage; - -/** - * Abstract MQTT listener for auction-related events - */ -public abstract class ExecutorEventMqttListener { - - public abstract boolean handleEvent(MqttMessage message); -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorEventsMqttDispatcher.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorEventsMqttDispatcher.java deleted file mode 100644 index c1b7649..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorEventsMqttDispatcher.java +++ /dev/null @@ -1,42 +0,0 @@ -package ch.unisg.roster.roster.adapter.in.messaging.mqtt; - -import org.eclipse.paho.client.mqttv3.*; - -import java.util.Hashtable; -import java.util.Map; -import java.util.Set; - -public class ExecutorEventsMqttDispatcher { - private final Map router; - - public ExecutorEventsMqttDispatcher() { - this.router = new Hashtable<>(); - initRouter(); - } - - // TODO: Register here your topics and event listener adapters - private void initRouter() { - router.put("ch/unisg/tapas/executors/added", new ExecutorAddedEventListenerMqttAdapter()); - router.put("ch/unisg/tapas/executors/removed", new ExecutorRemovedEventListenerMqttAdapter()); - } - - /** - * Returns all topics registered with this dispatcher. - * - * @return the set of registered topics - */ - public Set getAllTopics() { - return router.keySet(); - } - - /** - * Dispatches an event received via MQTT for a given topic. - * - * @param topic the topic for which the MQTT message was received - * @param message the received MQTT message - */ - public void dispatchEvent(String topic, MqttMessage message) { - ExecutorEventMqttListener listener = router.get(topic); - listener.handleEvent(message); - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorRemovedEventListenerMqttAdapter.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorRemovedEventListenerMqttAdapter.java deleted file mode 100644 index 0d0923a..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/messaging/mqtt/ExecutorRemovedEventListenerMqttAdapter.java +++ /dev/null @@ -1,41 +0,0 @@ -package ch.unisg.roster.roster.adapter.in.messaging.mqtt; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.paho.client.mqttv3.MqttMessage; - -import ch.unisg.common.valueobject.ExecutorURI; -import ch.unisg.roster.roster.application.handler.ExecutorRemovedHandler; -import ch.unisg.roster.roster.application.port.in.ExecutorRemovedEvent; - -public class ExecutorRemovedEventListenerMqttAdapter extends ExecutorEventMqttListener { - private static final Logger LOGGER = LogManager.getLogger(ExecutorRemovedEventListenerMqttAdapter.class); - - @Override - public boolean handleEvent(MqttMessage message) { - String payload = new String(message.getPayload()); - - try { - // Note: this messge representation is provided only as an example. You should use a - // representation that makes sense in the context of your application. - JsonNode data = new ObjectMapper().readTree(payload); - - String executorId = data.get("executorUri").asText(); - - ExecutorRemovedEvent executorRemovedEvent = new ExecutorRemovedEvent( - new ExecutorURI(executorId)); - - ExecutorRemovedHandler executorRemovedHandler = new ExecutorRemovedHandler(); - executorRemovedHandler.handleExecutorRemovedEvent(executorRemovedEvent); - - } catch (JsonProcessingException | NullPointerException e) { - LOGGER.error(e.getMessage(), e); - return false; - } - - return true; - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/ApplyForTaskController.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/ApplyForTaskController.java deleted file mode 100644 index 28170f0..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/ApplyForTaskController.java +++ /dev/null @@ -1,32 +0,0 @@ -package ch.unisg.roster.roster.adapter.in.web; - -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import ch.unisg.roster.roster.application.port.in.ApplyForTaskCommand; -import ch.unisg.roster.roster.application.port.in.ApplyForTaskUseCase; -import ch.unisg.roster.roster.domain.ExecutorInfo; -import ch.unisg.roster.roster.domain.Task; - -@RestController -public class ApplyForTaskController { - private final ApplyForTaskUseCase applyForTaskUseCase; - - public ApplyForTaskController(ApplyForTaskUseCase applyForTaskUseCase) { - this.applyForTaskUseCase = applyForTaskUseCase; - } - - /** - * Checks if task is available for the requesting executor. - * @return a task or null if no task found - **/ - @PostMapping(path = "/task/apply", consumes = {"application/json"}) - public Task applyForTask(@RequestBody ExecutorInfo executorInfo) { - - ApplyForTaskCommand command = new ApplyForTaskCommand(executorInfo.getExecutorType(), - executorInfo.getExecutorURI()); - - return applyForTaskUseCase.applyForTask(command); - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/DeleteTaskController.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/DeleteTaskController.java deleted file mode 100644 index eef8b71..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/DeleteTaskController.java +++ /dev/null @@ -1,35 +0,0 @@ -package ch.unisg.roster.roster.adapter.in.web; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import ch.unisg.roster.roster.application.port.in.DeleteTaskCommand; -import ch.unisg.roster.roster.application.port.in.DeleteTaskUseCase; -import ch.unisg.roster.roster.domain.Task; - -@RestController -public class DeleteTaskController { - private final DeleteTaskUseCase deleteTaskUseCase; - - public DeleteTaskController(DeleteTaskUseCase deleteTaskUseCase) { - this.deleteTaskUseCase = deleteTaskUseCase; - } - - /** - * Controller to delete a task - * @return 200 OK, 409 Conflict - **/ - @DeleteMapping(path = "/task", consumes = {"application/task+json"}) - public ResponseEntity applyForTask(@RequestBody Task task) { - - DeleteTaskCommand command = new DeleteTaskCommand(task.getTaskID(), task.getTaskType()); - - if (deleteTaskUseCase.deleteTask(command)) { - return new ResponseEntity<>(HttpStatus.OK); - } - return new ResponseEntity<>(HttpStatus.CONFLICT); - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/NewTaskController.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/NewTaskController.java deleted file mode 100644 index 7ff5349..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/NewTaskController.java +++ /dev/null @@ -1,47 +0,0 @@ -package ch.unisg.roster.roster.adapter.in.web; - -import java.util.logging.Logger; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import ch.unisg.roster.roster.application.port.in.NewTaskCommand; -import ch.unisg.roster.roster.application.port.in.NewTaskUseCase; -import ch.unisg.roster.roster.domain.Task; - -@RestController -public class NewTaskController { - private final NewTaskUseCase newTaskUseCase; - - public NewTaskController(NewTaskUseCase newTaskUseCase) { - this.newTaskUseCase = newTaskUseCase; - } - - Logger logger = Logger.getLogger(NewTaskController.class.getName()); - - /** - * Controller which handles the new task event from the tasklist - * @return 201 Create or 409 Conflict - **/ - @PostMapping(path = "/task", consumes = {"application/task+json"}) - public ResponseEntity newTaskController(@RequestBody Task task) { - - logger.info("New task with id:" + task.getTaskID()); - - NewTaskCommand command = new NewTaskCommand(task.getTaskID(), task.getTaskType(), - task.getInputData()); - - boolean success = newTaskUseCase.addNewTaskToQueue(command); - - logger.info("Could create task: " + success); - - if (success) { - return new ResponseEntity<>(HttpStatus.CREATED); - } - return new ResponseEntity<>(HttpStatus.CONFLICT); - - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/TaskCompletedController.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/TaskCompletedController.java deleted file mode 100644 index a910ee2..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/TaskCompletedController.java +++ /dev/null @@ -1,37 +0,0 @@ -package ch.unisg.roster.roster.adapter.in.web; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import ch.unisg.roster.roster.application.port.in.TaskCompletedCommand; -import ch.unisg.roster.roster.application.port.in.TaskCompletedUseCase; -import ch.unisg.roster.roster.domain.Task; - -@RestController -public class TaskCompletedController { - - private final TaskCompletedUseCase taskCompletedUseCase; - - public TaskCompletedController(TaskCompletedUseCase taskCompletedUseCase) { - this.taskCompletedUseCase = taskCompletedUseCase; - } - - /** - * Controller which handles the task completed event from executors - * @return 200 OK - **/ - @PostMapping(path = "/task/completed", consumes = {"application/json"}) - public ResponseEntity addNewTaskTaskToTaskList(@RequestBody Task task) { - TaskCompletedCommand command = new TaskCompletedCommand(task.getTaskID(), - task.getStatus(), task.getOutputData()); - - taskCompletedUseCase.taskCompleted(command); - - return new ResponseEntity<>(HttpStatus.OK); - - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/WebControllerExceptionHandler.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/WebControllerExceptionHandler.java deleted file mode 100644 index f0a4974..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/in/web/WebControllerExceptionHandler.java +++ /dev/null @@ -1,25 +0,0 @@ -package ch.unisg.roster.roster.adapter.in.web; - -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.ControllerAdvice; -import org.springframework.web.bind.annotation.ExceptionHandler; - -import ch.unisg.common.exception.ErrorResponse; -import ch.unisg.common.exception.InvalidExecutorURIException; - -@ControllerAdvice -public class WebControllerExceptionHandler { - - /** - * Handles error of type InvalidExecutorURIException - * @return 404 Bad Request - **/ - @ExceptionHandler(InvalidExecutorURIException.class) - public ResponseEntity handleException(InvalidExecutorURIException e){ - - ErrorResponse error = new ErrorResponse(HttpStatus.BAD_REQUEST, e.getLocalizedMessage()); - return new ResponseEntity<>(error, error.getHttpStatus()); - - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/out/web/PublishNewTaskEventAdapter.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/out/web/PublishNewTaskEventAdapter.java deleted file mode 100644 index c16961f..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/out/web/PublishNewTaskEventAdapter.java +++ /dev/null @@ -1,70 +0,0 @@ -package ch.unisg.roster.roster.adapter.out.web; - -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; - -import ch.unisg.roster.roster.application.port.out.NewTaskEventPort; -import ch.unisg.roster.roster.domain.event.NewTaskEvent; - -@Component -@Primary -public class PublishNewTaskEventAdapter implements NewTaskEventPort { - - @Value("${executor-robot.uri}") - private String server; - - @Value("${executor-computation.uri}") - private String server2; - - Logger logger = Logger.getLogger(PublishNewTaskEventAdapter.class.getName()); - - /** - * Informs executors about the availability of a new task. - * @return void - **/ - @Override - public void publishNewTaskEvent(NewTaskEvent event) { - - // HttpClient client = HttpClient.newHttpClient(); - // HttpRequest request = HttpRequest.newBuilder() - // .uri(URI.create(server + "/newtask/" + event.taskType.getValue())) - // .GET() - // .build(); - - - // try { - // client.send(request, HttpResponse.BodyHandlers.ofString()); - // } catch (InterruptedException e) { - // logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - // Thread.currentThread().interrupt(); - // } catch (IOException e) { - // logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - // } - - HttpClient client2 = HttpClient.newHttpClient(); - HttpRequest request2 = HttpRequest.newBuilder() - .uri(URI.create(server2 + "/newtask/" + event.taskType.getValue())) - .GET() - .build(); - - - try { - client2.send(request2, HttpResponse.BodyHandlers.ofString()); - } catch (InterruptedException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - } - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/out/web/PublishTaskAssignedEventAdapter.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/out/web/PublishTaskAssignedEventAdapter.java deleted file mode 100644 index 105d464..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/out/web/PublishTaskAssignedEventAdapter.java +++ /dev/null @@ -1,57 +0,0 @@ -package ch.unisg.roster.roster.adapter.out.web; - -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; - -import ch.unisg.roster.roster.application.port.out.TaskAssignedEventPort; -import ch.unisg.roster.roster.domain.event.TaskAssignedEvent; - -@Component -@Primary -public class PublishTaskAssignedEventAdapter implements TaskAssignedEventPort { - - @Value("${task-list.uri}") - private String server; - - Logger logger = Logger.getLogger(PublishTaskAssignedEventAdapter.class.getName()); - - /** - * Informs the task service about the assignment of the task. - * @return void - **/ - @Override - public void publishTaskAssignedEvent(TaskAssignedEvent event) { - - String body = new JSONObject() - .put("taskId", event.taskID) - .toString(); - - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(server + "/tasks/assignTask")) - .header("Content-Type", "application/task+json") - .POST(HttpRequest.BodyPublishers.ofString(body)) - .build(); - - - try { - client.send(request, HttpResponse.BodyHandlers.ofString()); - } catch (InterruptedException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - } - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/adapter/out/web/PublishTaskCompletedEventAdapter.java b/roster/src/main/java/ch/unisg/roster/roster/adapter/out/web/PublishTaskCompletedEventAdapter.java deleted file mode 100644 index 50d72ae..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/adapter/out/web/PublishTaskCompletedEventAdapter.java +++ /dev/null @@ -1,60 +0,0 @@ -package ch.unisg.roster.roster.adapter.out.web; - -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; - -import ch.unisg.roster.roster.application.port.out.TaskCompletedEventPort; -import ch.unisg.roster.roster.domain.event.TaskCompletedEvent; - -@Component -@Primary -public class PublishTaskCompletedEventAdapter implements TaskCompletedEventPort { - - @Value("${task-list.uri}") - private String server; - - Logger logger = Logger.getLogger(PublishTaskCompletedEventAdapter.class.getName()); - - /** - * Informs the task service about the completion of the task. - * @return void - **/ - @Override - public void publishTaskCompleted(TaskCompletedEvent event) { - - String body = new JSONObject() - .put("taskId", event.taskID) - .put("status", event.status) - .put("outputData", event.result) - .toString(); - - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(server + "/tasks/completeTask/")) - .header("Content-Type", "application/task+json") - .POST(HttpRequest.BodyPublishers.ofString(body)) - .build(); - - - try { - client.send(request, HttpResponse.BodyHandlers.ofString()); - } catch (InterruptedException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - } - - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/handler/ExecutorAddedHandler.java b/roster/src/main/java/ch/unisg/roster/roster/application/handler/ExecutorAddedHandler.java deleted file mode 100644 index 9545c07..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/handler/ExecutorAddedHandler.java +++ /dev/null @@ -1,16 +0,0 @@ -package ch.unisg.roster.roster.application.handler; - -import ch.unisg.roster.roster.application.port.in.ExecutorAddedEvent; -import ch.unisg.roster.roster.application.port.in.ExecutorAddedEventHandler; -import ch.unisg.roster.roster.domain.ExecutorRegistry; -import org.springframework.stereotype.Component; - -@Component -public class ExecutorAddedHandler implements ExecutorAddedEventHandler { - - @Override - public boolean handleNewExecutorEvent(ExecutorAddedEvent executorAddedEvent) { - return ExecutorRegistry.getInstance().addExecutor(executorAddedEvent.getExecutorType(), - executorAddedEvent.getExecutorURI()); - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/handler/ExecutorRemovedHandler.java b/roster/src/main/java/ch/unisg/roster/roster/application/handler/ExecutorRemovedHandler.java deleted file mode 100644 index c6e3f68..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/handler/ExecutorRemovedHandler.java +++ /dev/null @@ -1,19 +0,0 @@ -package ch.unisg.roster.roster.application.handler; - -import ch.unisg.roster.roster.application.port.in.ExecutorRemovedEvent; -import ch.unisg.roster.roster.application.port.in.ExecutorRemovedEventHandler; -import ch.unisg.roster.roster.domain.ExecutorRegistry; -import org.springframework.stereotype.Component; - -/** - * Handler for executor removed events. It removes the executor from this roster's executor - * registry. - */ -@Component -public class ExecutorRemovedHandler implements ExecutorRemovedEventHandler { - - @Override - public boolean handleExecutorRemovedEvent(ExecutorRemovedEvent executorRemovedEvent) { - return ExecutorRegistry.getInstance().removeExecutor(executorRemovedEvent.getExecutorURI()); - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ApplyForTaskCommand.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ApplyForTaskCommand.java deleted file mode 100644 index f03ef5f..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ApplyForTaskCommand.java +++ /dev/null @@ -1,26 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -import javax.validation.constraints.NotNull; - -import ch.unisg.roster.roster.domain.valueobject.ExecutorType; -import ch.unisg.common.validation.SelfValidating; -import ch.unisg.common.valueobject.ExecutorURI; -import lombok.EqualsAndHashCode; -import lombok.Value; - -@Value -@EqualsAndHashCode(callSuper=false) -public class ApplyForTaskCommand extends SelfValidating{ - - @NotNull - private final ExecutorType taskType; - - @NotNull - private final ExecutorURI executorURI; - - public ApplyForTaskCommand(ExecutorType taskType, ExecutorURI executorURI) { - this.taskType = taskType; - this.executorURI = executorURI; - this.validateSelf(); - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ApplyForTaskUseCase.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ApplyForTaskUseCase.java deleted file mode 100644 index 61b7bd4..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ApplyForTaskUseCase.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -import ch.unisg.roster.roster.domain.Task; - -public interface ApplyForTaskUseCase { - Task applyForTask(ApplyForTaskCommand applyForTaskCommand); -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/DeleteTaskCommand.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/DeleteTaskCommand.java deleted file mode 100644 index 9f59dc3..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/DeleteTaskCommand.java +++ /dev/null @@ -1,24 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -import javax.validation.constraints.NotNull; - -import ch.unisg.roster.roster.domain.valueobject.ExecutorType; -import ch.unisg.common.validation.SelfValidating; -import lombok.EqualsAndHashCode; -import lombok.Value; - -@Value -@EqualsAndHashCode(callSuper=false) -public class DeleteTaskCommand extends SelfValidating { - @NotNull - private final String taskId; - - @NotNull - private final ExecutorType taskType; - - public DeleteTaskCommand(String taskId, ExecutorType taskType) { - this.taskId = taskId; - this.taskType = taskType; - this.validateSelf(); - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/DeleteTaskUseCase.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/DeleteTaskUseCase.java deleted file mode 100644 index 2acfc63..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/DeleteTaskUseCase.java +++ /dev/null @@ -1,5 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -public interface DeleteTaskUseCase { - boolean deleteTask(DeleteTaskCommand deleteTaskCommand); -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorAddedEvent.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorAddedEvent.java deleted file mode 100644 index 0e10b8e..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorAddedEvent.java +++ /dev/null @@ -1,33 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -import lombok.Value; - -import javax.validation.constraints.NotNull; - -import ch.unisg.common.validation.SelfValidating; -import ch.unisg.common.valueobject.ExecutorURI; -import ch.unisg.roster.roster.domain.valueobject.ExecutorType; - -/** - * Event that notifies the auction house that an executor has been added to this TAPAS application. - */ -@Value -public class ExecutorAddedEvent extends SelfValidating { - @NotNull - private final ExecutorURI executorURI; - - @NotNull - private final ExecutorType executorType; - - /** - * Constructs an executor added event. - * - * @param executorURI the identifier of the executor that was added to this TAPAS application - */ - public ExecutorAddedEvent(ExecutorURI executorURI, ExecutorType executorType) { - this.executorURI = executorURI; - this.executorType = executorType; - - this.validateSelf(); - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorAddedEventHandler.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorAddedEventHandler.java deleted file mode 100644 index c7a9076..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorAddedEventHandler.java +++ /dev/null @@ -1,6 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -public interface ExecutorAddedEventHandler { - - boolean handleNewExecutorEvent(ExecutorAddedEvent executorAddedEvent); -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorRemovedEvent.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorRemovedEvent.java deleted file mode 100644 index 8753683..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorRemovedEvent.java +++ /dev/null @@ -1,27 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -import lombok.Value; - -import javax.validation.constraints.NotNull; - -import ch.unisg.common.validation.SelfValidating; -import ch.unisg.common.valueobject.ExecutorURI; - -/** - * Event that notifies the auction house that an executor has been removed from this TAPAS application. - */ -@Value -public class ExecutorRemovedEvent extends SelfValidating { - @NotNull - private final ExecutorURI executorURI; - - /** - * Constructs an executor removed event. - * - * @param executorURI the identifier of the executor that was removed from this TAPAS application - */ - public ExecutorRemovedEvent(ExecutorURI executorURI) { - this.executorURI = executorURI; - this.validateSelf(); - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorRemovedEventHandler.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorRemovedEventHandler.java deleted file mode 100644 index 79ee6a7..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/ExecutorRemovedEventHandler.java +++ /dev/null @@ -1,6 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -public interface ExecutorRemovedEventHandler { - - boolean handleExecutorRemovedEvent(ExecutorRemovedEvent executorRemovedEvent); -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/NewTaskCommand.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/NewTaskCommand.java deleted file mode 100644 index 5db2b9f..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/NewTaskCommand.java +++ /dev/null @@ -1,29 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -import javax.validation.constraints.NotNull; - -import ch.unisg.roster.roster.domain.valueobject.ExecutorType; -import ch.unisg.common.validation.SelfValidating; -import lombok.EqualsAndHashCode; -import lombok.Value; - -@Value -@EqualsAndHashCode(callSuper=false) -public class NewTaskCommand extends SelfValidating { - - @NotNull - private final String taskID; - - @NotNull - private final ExecutorType taskType; - - @NotNull - private final String inputData; - - public NewTaskCommand(String taskID, ExecutorType taskType, String inputData) { - this.taskID = taskID; - this.taskType = taskType; - this.inputData = inputData; - this.validateSelf(); - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/NewTaskUseCase.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/NewTaskUseCase.java deleted file mode 100644 index f1bd733..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/NewTaskUseCase.java +++ /dev/null @@ -1,5 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -public interface NewTaskUseCase { - boolean addNewTaskToQueue(NewTaskCommand newTaskCommand); -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/TaskCompletedCommand.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/TaskCompletedCommand.java deleted file mode 100644 index b7438c0..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/TaskCompletedCommand.java +++ /dev/null @@ -1,29 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -import javax.validation.constraints.NotNull; - -import ch.unisg.common.validation.SelfValidating; -import lombok.EqualsAndHashCode; -import lombok.Value; - -@Value -@EqualsAndHashCode(callSuper=false) -public class TaskCompletedCommand extends SelfValidating{ - - @NotNull - private final String taskID; - - @NotNull - private final String taskStatus; - - @NotNull - private final String taskResult; - - public TaskCompletedCommand(String taskID, String taskStatus, String taskResult) { - this.taskID = taskID; - this.taskStatus = taskStatus; - this.taskResult = taskResult; - this.validateSelf(); - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/TaskCompletedUseCase.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/in/TaskCompletedUseCase.java deleted file mode 100644 index 51b305a..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/in/TaskCompletedUseCase.java +++ /dev/null @@ -1,5 +0,0 @@ -package ch.unisg.roster.roster.application.port.in; - -public interface TaskCompletedUseCase { - void taskCompleted(TaskCompletedCommand taskCompletedCommand); -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/out/NewTaskEventPort.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/out/NewTaskEventPort.java deleted file mode 100644 index 75fda6d..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/out/NewTaskEventPort.java +++ /dev/null @@ -1,11 +0,0 @@ -package ch.unisg.roster.roster.application.port.out; - -import ch.unisg.roster.roster.domain.event.NewTaskEvent; - -public interface NewTaskEventPort { - /** - * Publishes the new task event. - * @return void - **/ - void publishNewTaskEvent(NewTaskEvent event); -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/out/TaskAssignedEventPort.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/out/TaskAssignedEventPort.java deleted file mode 100644 index 2bcb2ae..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/out/TaskAssignedEventPort.java +++ /dev/null @@ -1,11 +0,0 @@ -package ch.unisg.roster.roster.application.port.out; - -import ch.unisg.roster.roster.domain.event.TaskAssignedEvent; - -public interface TaskAssignedEventPort { - /** - * Publishes the task assigned event. - * @return void - **/ - void publishTaskAssignedEvent(TaskAssignedEvent taskAssignedEvent); -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/port/out/TaskCompletedEventPort.java b/roster/src/main/java/ch/unisg/roster/roster/application/port/out/TaskCompletedEventPort.java deleted file mode 100644 index a8c11ef..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/port/out/TaskCompletedEventPort.java +++ /dev/null @@ -1,11 +0,0 @@ -package ch.unisg.roster.roster.application.port.out; - -import ch.unisg.roster.roster.domain.event.TaskCompletedEvent; - -public interface TaskCompletedEventPort { - /** - * Publishes the task completed event. - * @return void - **/ - void publishTaskCompleted(TaskCompletedEvent event); -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/service/ApplyForTaskService.java b/roster/src/main/java/ch/unisg/roster/roster/application/service/ApplyForTaskService.java deleted file mode 100644 index 26b75aa..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/service/ApplyForTaskService.java +++ /dev/null @@ -1,39 +0,0 @@ -package ch.unisg.roster.roster.application.service; - -import javax.transaction.Transactional; - -import org.springframework.stereotype.Component; - -import ch.unisg.roster.roster.application.port.in.ApplyForTaskCommand; -import ch.unisg.roster.roster.application.port.in.ApplyForTaskUseCase; -import ch.unisg.roster.roster.application.port.out.TaskAssignedEventPort; -import ch.unisg.roster.roster.domain.Roster; -import ch.unisg.roster.roster.domain.Task; -import ch.unisg.roster.roster.domain.event.TaskAssignedEvent; -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -@Component -@Transactional -public class ApplyForTaskService implements ApplyForTaskUseCase { - - private final TaskAssignedEventPort taskAssignedEventPort; - - /** - * Checks if a task is available and assignes it to the executor. If task got assigned a task - * assigned event gets published. - * @return assigned task or null if no task is found - **/ - @Override - public Task applyForTask(ApplyForTaskCommand command) { - Task task = Roster.getInstance().assignTaskToExecutor(command.getTaskType(), - command.getExecutorURI()); - - if (task != null) { - taskAssignedEventPort.publishTaskAssignedEvent(new TaskAssignedEvent(task.getTaskID())); - } - - return task; - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/service/DeleteTaskService.java b/roster/src/main/java/ch/unisg/roster/roster/application/service/DeleteTaskService.java deleted file mode 100644 index a6b4841..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/service/DeleteTaskService.java +++ /dev/null @@ -1,27 +0,0 @@ -package ch.unisg.roster.roster.application.service; - -import javax.transaction.Transactional; - -import org.springframework.stereotype.Component; - -import ch.unisg.roster.roster.application.port.in.DeleteTaskCommand; -import ch.unisg.roster.roster.application.port.in.DeleteTaskUseCase; -import ch.unisg.roster.roster.domain.Roster; -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -@Component -@Transactional -public class DeleteTaskService implements DeleteTaskUseCase { - - /** - * Check if task can get deleted - * @return if task can get deleted - **/ - @Override - public boolean deleteTask(DeleteTaskCommand command) { - Roster roster = Roster.getInstance(); - return roster.deleteTask(command.getTaskId(), command.getTaskType()); - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/service/NewTaskService.java b/roster/src/main/java/ch/unisg/roster/roster/application/service/NewTaskService.java deleted file mode 100644 index c1aab5c..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/service/NewTaskService.java +++ /dev/null @@ -1,47 +0,0 @@ -package ch.unisg.roster.roster.application.service; - -import javax.transaction.Transactional; - -import org.springframework.stereotype.Component; - -import ch.unisg.roster.roster.application.port.in.NewTaskCommand; -import ch.unisg.roster.roster.application.port.in.NewTaskUseCase; -import ch.unisg.roster.roster.application.port.out.NewTaskEventPort; -import ch.unisg.roster.roster.domain.ExecutorRegistry; -import ch.unisg.roster.roster.domain.Roster; -import ch.unisg.roster.roster.domain.Task; -import ch.unisg.roster.roster.domain.event.NewTaskEvent; -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -@Component -@Transactional -public class NewTaskService implements NewTaskUseCase { - - private final NewTaskEventPort newTaskEventPort; - - /** - * Checks if we can execute the give task, if yes the task gets added to the task queue and return true. - * If the task can not be executed by an internal or auction house executor, the method return false. - * @return boolean - **/ - @Override - public boolean addNewTaskToQueue(NewTaskCommand command) { - - ExecutorRegistry executorRegistry = ExecutorRegistry.getInstance(); - - if (!executorRegistry.containsTaskType(command.getTaskType())) { - return false; - } - - Task task = new Task(command.getTaskID(), command.getTaskType(), command.getInputData()); - - Roster.getInstance().addTaskToQueue(task); - - NewTaskEvent newTaskEvent = new NewTaskEvent(task.getTaskType()); - newTaskEventPort.publishNewTaskEvent(newTaskEvent); - - return true; - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/application/service/TaskCompletedService.java b/roster/src/main/java/ch/unisg/roster/roster/application/service/TaskCompletedService.java deleted file mode 100644 index 69b65d1..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/application/service/TaskCompletedService.java +++ /dev/null @@ -1,35 +0,0 @@ -package ch.unisg.roster.roster.application.service; - -import javax.transaction.Transactional; - -import org.springframework.stereotype.Component; - -import ch.unisg.roster.roster.application.port.in.TaskCompletedCommand; -import ch.unisg.roster.roster.application.port.in.TaskCompletedUseCase; -import ch.unisg.roster.roster.application.port.out.TaskCompletedEventPort; -import ch.unisg.roster.roster.domain.Roster; -import ch.unisg.roster.roster.domain.event.TaskCompletedEvent; -import lombok.RequiredArgsConstructor; - -@RequiredArgsConstructor -@Component -@Transactional -public class TaskCompletedService implements TaskCompletedUseCase { - - private final TaskCompletedEventPort taskCompletedEventPort; - - /** - * Completes the task in the roster and publishes a task completed event. - * @return void - **/ - @Override - public void taskCompleted(TaskCompletedCommand command) { - - Roster.getInstance().taskCompleted(command.getTaskID()); - - taskCompletedEventPort.publishTaskCompleted(new TaskCompletedEvent(command.getTaskID(), - command.getTaskStatus(), command.getTaskResult())); - - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/domain/ExecutorInfo.java b/roster/src/main/java/ch/unisg/roster/roster/domain/ExecutorInfo.java deleted file mode 100644 index eb32ec0..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/domain/ExecutorInfo.java +++ /dev/null @@ -1,16 +0,0 @@ -package ch.unisg.roster.roster.domain; - -import ch.unisg.roster.roster.domain.valueobject.ExecutorType; -import ch.unisg.common.valueobject.ExecutorURI; -import lombok.Getter; -import lombok.Setter; - -public class ExecutorInfo { - @Getter - @Setter - private ExecutorURI executorURI; - - @Getter - @Setter - private ExecutorType executorType; -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/domain/ExecutorRegistry.java b/roster/src/main/java/ch/unisg/roster/roster/domain/ExecutorRegistry.java deleted file mode 100644 index 4ddba0f..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/domain/ExecutorRegistry.java +++ /dev/null @@ -1,92 +0,0 @@ -package ch.unisg.roster.roster.domain; - -import java.util.*; - -import ch.unisg.common.valueobject.ExecutorURI; -import ch.unisg.roster.roster.domain.valueobject.ExecutorType; - -/** - * Registry that keeps a track of executors internal to the TAPAS application and the types of tasks - * they can achieve. One executor may correspond to multiple task types. - * This class is a singleton. - */ -public class ExecutorRegistry { - private static ExecutorRegistry registry; - - private final Map> executors; - - private ExecutorRegistry() { - this.executors = new Hashtable<>(); - } - - public static synchronized ExecutorRegistry getInstance() { - if (registry == null) { - registry = new ExecutorRegistry(); - } - - return registry; - } - - /** - * Adds an executor to the registry for a given task type. - * - * @param taskType the type of the task - * @param executorIdentifier the identifier of the executor (can be any string) - * @return true unless a runtime exception occurs - */ - public boolean addExecutor(ExecutorType executorType, ExecutorURI executorURI) { - Set taskTypeExecs = executors.getOrDefault(executorType, - Collections.synchronizedSet(new HashSet<>())); - - taskTypeExecs.add(executorURI); - executors.put(executorType, taskTypeExecs); - - return true; - } - - /** - * Removes an executor from the registry. The executor is disassociated from all known task types. - * - * @param executorURI the identifier of the executor - * @return true unless a runtime exception occurs - */ - public boolean removeExecutor(ExecutorURI executorURI) { - Iterator iterator = executors.keySet().iterator(); - - while (iterator.hasNext()) { - ExecutorType executorType = iterator.next(); - Set set = executors.get(executorType); - - set.remove(executorURI); - - if (set.isEmpty()) { - iterator.remove(); - } - } - - return true; - } - - /** - * Checks if the registry contains an executor for a given task type. Used during task creation - * to decide if a task can be executed. - * - * @param taskType the task type being auctioned - * @return - */ - public boolean containsTaskType(ExecutorType taskType) { - return executors.containsKey(taskType); - } - - /** - * Adds a list of executors to current executor list. Should only be used on startup to - * add all available executors from the executor pool to the registry. - * - * @param executors the initial executors - * @return - */ - public void init(Map> executors) { - this.executors.putAll(executors); - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/domain/Roster.java b/roster/src/main/java/ch/unisg/roster/roster/domain/Roster.java deleted file mode 100644 index cc9a0a6..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/domain/Roster.java +++ /dev/null @@ -1,86 +0,0 @@ -package ch.unisg.roster.roster.domain; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.logging.Level; -import java.util.logging.Logger; - -import ch.unisg.roster.roster.domain.valueobject.ExecutorType; -import ch.unisg.common.valueobject.ExecutorURI; - -public class Roster { - - private static final Roster roster = new Roster(); - - // Queues which hold all the tasks which need to be assigned | Will be replaced by message queue later - private HashMap> queues = new HashMap<>(); - - // Roster witch holds information about which executor is assigned to a task - private HashMap rosterMap = new HashMap<>(); - - Logger logger = Logger.getLogger(Roster.class.getName()); - - public static Roster getInstance() { - return roster; - } - - private Roster() {} - - /** - * Adds a task to the task queue. - * @return void - * @see Task - **/ - public void addTaskToQueue(Task task) { - if (queues.containsKey(task.getTaskType().getValue())) { - queues.get(task.getTaskType().getValue()).add(task); - } else { - queues.put(task.getTaskType().getValue(), new ArrayList<>(Arrays.asList(task))); - } - logger.log(Level.INFO, "Added task with id {0} to queue", task.getTaskID()); - } - - /** - * Checks if a task of this type is in a queue and if so assignes it to the executor. - * @return assigned task or null if no task is found - * @see Task - **/ - public Task assignTaskToExecutor(ExecutorType taskType, ExecutorURI executorURI) { - // TODO I don't think we need this if - if (!queues.containsKey(taskType.getValue())) { - return null; - } - if (queues.get(taskType.getValue()).isEmpty()) { - return null; - } - - Task task = queues.get(taskType.getValue()).remove(0); - - rosterMap.put(task.getTaskID(), new RosterItem(task.getTaskID(), - task.getTaskType().getValue(), executorURI)); - - return task; - } - - /** - * Removed a task from the roster after if got completed - * @return void - * @see Task - * @see Roster - **/ - public void taskCompleted(String taskID) { - rosterMap.remove(taskID); - logger.log(Level.INFO, "Task {0} completed", taskID); - } - - /** - * Deletes a task if it is still in the queue. - * @return Whether the task got deleted or not - **/ - public boolean deleteTask(String taskID, ExecutorType taskType) { - logger.log(Level.INFO, "Try to delete task with id {0}", taskID); - return queues.get(taskType.getValue()).removeIf(task -> task.getTaskID().equalsIgnoreCase(taskID)); - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/domain/RosterItem.java b/roster/src/main/java/ch/unisg/roster/roster/domain/RosterItem.java deleted file mode 100644 index cc39c6c..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/domain/RosterItem.java +++ /dev/null @@ -1,23 +0,0 @@ -package ch.unisg.roster.roster.domain; - -import ch.unisg.common.valueobject.ExecutorURI; -import lombok.Getter; - -public class RosterItem { - - @Getter - private String taskID; - - @Getter - private String taskType; - - @Getter - private ExecutorURI executorURI; - - public RosterItem(String taskID, String taskType, ExecutorURI executorURI) { - this.taskID = taskID; - this.taskType = taskType; - this.executorURI = executorURI; - } - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/domain/Task.java b/roster/src/main/java/ch/unisg/roster/roster/domain/Task.java deleted file mode 100644 index ee30763..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/domain/Task.java +++ /dev/null @@ -1,45 +0,0 @@ -package ch.unisg.roster.roster.domain; - -import ch.unisg.roster.roster.domain.valueobject.ExecutorType; -import lombok.Getter; -import lombok.Setter; - -public class Task { - - @Getter - private String taskID; - - @Getter - private ExecutorType taskType; - - @Getter - @Setter - private String inputData; - - @Getter - @Setter - private String outputData; - - @Getter - @Setter - private String status; - - public Task(String taskID, String taskType) { - this.taskID = taskID; - this.taskType = new ExecutorType(taskType); - } - - public Task(String taskID, ExecutorType taskType) { - this.taskID = taskID; - this.taskType = taskType; - } - - public Task(String taskID, ExecutorType taskType, String inputData) { - this.taskID = taskID; - this.taskType = taskType; - this.inputData = inputData; - } - - public Task() {} - -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/domain/event/NewTaskEvent.java b/roster/src/main/java/ch/unisg/roster/roster/domain/event/NewTaskEvent.java deleted file mode 100644 index 1457f1d..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/domain/event/NewTaskEvent.java +++ /dev/null @@ -1,11 +0,0 @@ -package ch.unisg.roster.roster.domain.event; - -import ch.unisg.roster.roster.domain.valueobject.ExecutorType; - -public class NewTaskEvent { - public final ExecutorType taskType; - - public NewTaskEvent(ExecutorType taskType) { - this.taskType = taskType; - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/domain/event/TaskAssignedEvent.java b/roster/src/main/java/ch/unisg/roster/roster/domain/event/TaskAssignedEvent.java deleted file mode 100644 index 9c57270..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/domain/event/TaskAssignedEvent.java +++ /dev/null @@ -1,9 +0,0 @@ -package ch.unisg.roster.roster.domain.event; - -public class TaskAssignedEvent { - public final String taskID; - - public TaskAssignedEvent(String taskID) { - this.taskID = taskID; - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/domain/event/TaskCompletedEvent.java b/roster/src/main/java/ch/unisg/roster/roster/domain/event/TaskCompletedEvent.java deleted file mode 100644 index 926f601..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/domain/event/TaskCompletedEvent.java +++ /dev/null @@ -1,15 +0,0 @@ -package ch.unisg.roster.roster.domain.event; - -public class TaskCompletedEvent { - public final String taskID; - - public final String status; - - public final String result; - - public TaskCompletedEvent(String taskID, String status, String result) { - this.taskID = taskID; - this.status = status; - this.result = result; - } -} diff --git a/roster/src/main/java/ch/unisg/roster/roster/domain/valueobject/ExecutorType.java b/roster/src/main/java/ch/unisg/roster/roster/domain/valueobject/ExecutorType.java deleted file mode 100644 index 72368e3..0000000 --- a/roster/src/main/java/ch/unisg/roster/roster/domain/valueobject/ExecutorType.java +++ /dev/null @@ -1,12 +0,0 @@ -package ch.unisg.roster.roster.domain.valueobject; - -import lombok.Value; - -@Value -public class ExecutorType { - private String value; - - public ExecutorType(String type) { - this.value = type.toUpperCase(); - } -} diff --git a/roster/src/main/resources/application.properties b/roster/src/main/resources/application.properties deleted file mode 100644 index b7233ff..0000000 --- a/roster/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -server.port=8082 -executor-robot.uri=http://127.0.0.1:8084 -executor-computation.uri=http://127.0.0.1:8085 -task-list.uri=http://127.0.0.1:8081 -mqtt.broker.uri=tcp://localhost:1883 diff --git a/roster/src/test/java/ch/unisg/roster/RosterApplicationTests.java b/roster/src/test/java/ch/unisg/roster/RosterApplicationTests.java deleted file mode 100644 index 5ee712b..0000000 --- a/roster/src/test/java/ch/unisg/roster/RosterApplicationTests.java +++ /dev/null @@ -1,13 +0,0 @@ -package ch.unisg.roster; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - -@SpringBootTest -class RosterApplicationTests { - - @Test - void contextLoads() { - } - -} diff --git a/tapas-auction-house/BROKERS.md b/tapas-auction-house/BROKERS.md index 7e0d37a..80eed02 100644 --- a/tapas-auction-house/BROKERS.md +++ b/tapas-auction-house/BROKERS.md @@ -14,10 +14,8 @@ Running this WebSub Hub implementation requires Docker, Node.js, and npm: ### How to run ```shell -git clone https://github.com/hemerajs/websub-hub.git -cd websub-hub -docker run -d -p 27017:27017 -p 28017:28017 -e AUTH=no tutum/mongodb -npm i -g websub-hub-cli +docker run -d -p 27017:27017 -p 28017:28017 -e AUTH=no mongo:latest +npm i -g websub-hub websub-hub -l info -m mongodb://localhost:27017/hub ``` diff --git a/tapas-auction-house/Dockerfile b/tapas-auction-house/Dockerfile new file mode 100644 index 0000000..fcc6d83 --- /dev/null +++ b/tapas-auction-house/Dockerfile @@ -0,0 +1,13 @@ +# Dockerfile/Docker-Compose file based on an initial version authored by Alexander Lontke (ASSE, Fall Semester 2021) + +FROM maven as build + +COPY . /app + +RUN mvn -f app/pom.xml --batch-mode --update-snapshots verify + +FROM openjdk + +COPY --from=build /app/target/tapas-auction-house-0.0.1-SNAPSHOT.jar ./tapas-auction-house-0.0.1-SNAPSHOT.jar + +CMD java -jar tapas-auction-house-0.0.1-SNAPSHOT.jar diff --git a/tapas-auction-house/pom.xml b/tapas-auction-house/pom.xml index dd29302..4b9cbb6 100644 --- a/tapas-auction-house/pom.xml +++ b/tapas-auction-house/pom.xml @@ -46,7 +46,7 @@ org.eclipse.paho org.eclipse.paho.client.mqttv3 - 1.2.5 + 1.2.0 javax.transaction @@ -58,17 +58,6 @@ validation-api 1.1.0.Final - - org.json - json - 20210307 - - - org.springframework.boot - spring-boot-devtools - runtime - true - diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/TapasAuctionHouseApplication.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/TapasAuctionHouseApplication.java index 476c7d0..e21e82d 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/TapasAuctionHouseApplication.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/TapasAuctionHouseApplication.java @@ -4,14 +4,12 @@ import ch.unisg.tapas.auctionhouse.adapter.common.clients.TapasMqttClient; import ch.unisg.tapas.auctionhouse.adapter.in.messaging.mqtt.AuctionEventsMqttDispatcher; import ch.unisg.tapas.auctionhouse.adapter.common.clients.WebSubSubscriber; import ch.unisg.tapas.common.AuctionHouseResourceDirectory; -import ch.unisg.tapas.common.ConfigProperties; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.paho.client.mqttv3.MqttException; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; import java.net.URI; @@ -25,7 +23,7 @@ public class TapasAuctionHouseApplication { private static final Logger LOGGER = LogManager.getLogger(TapasAuctionHouseApplication.class); public static String RESOURCE_DIRECTORY = "https://api.interactions.ics.unisg.ch/auction-houses/"; - public static String DEFAULT_MQTT_BROKER = "tcp://broker.hivemq.com:1883"; + public static String MQTT_BROKER = "tcp://broker.hivemq.com:1883"; private static ConfigurableEnvironment ENVIRONMENT; @@ -33,16 +31,17 @@ public class TapasAuctionHouseApplication { SpringApplication tapasAuctioneerApp = new SpringApplication(TapasAuctionHouseApplication.class); ENVIRONMENT = tapasAuctioneerApp.run(args).getEnvironment(); - // TODO Set start up of message services with config // We will use these bootstrap methods in Week 6: // bootstrapMarketplaceWithWebSub(); - bootstrapMarketplaceWithMqtt(); + // bootstrapMarketplaceWithMqtt(); } + /** * Discovers auction houses and subscribes to WebSub notifications */ private static void bootstrapMarketplaceWithWebSub() { List auctionHouseEndpoints = discoverAuctionHouseEndpoints(); + LOGGER.info("Found auction house endpoints: " + auctionHouseEndpoints); WebSubSubscriber subscriber = new WebSubSubscriber(); @@ -57,12 +56,12 @@ public class TapasAuctionHouseApplication { */ private static void bootstrapMarketplaceWithMqtt() { try { - String broker = ENVIRONMENT.getProperty("mqtt.broker.uri"); - LOGGER.info("Bootstrapping Mqtt"); + String broker = ENVIRONMENT.getProperty("broker.mqtt"); + if (broker == null) { - broker = DEFAULT_MQTT_BROKER; + broker = MQTT_BROKER; LOGGER.info("No MQTT broker was set in application.propreties, going with default: " - + DEFAULT_MQTT_BROKER); + + MQTT_BROKER); } AuctionEventsMqttDispatcher dispatcher = new AuctionEventsMqttDispatcher(); diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/clients/TapasMqttClient.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/clients/TapasMqttClient.java index 1a30bc4..708d512 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/clients/TapasMqttClient.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/clients/TapasMqttClient.java @@ -68,10 +68,7 @@ public class TapasMqttClient { mqttClient.subscribe(topic); } - public void publishMessage(String topic, String payload) throws MqttException { - mqttClient = new org.eclipse.paho.client.mqttv3.MqttClient(brokerAddress, mqttClientId, new MemoryPersistence()); - mqttClient.connect(); - + private void publishMessage(String topic, String payload) throws MqttException { MqttMessage message = new MqttMessage(payload.getBytes(StandardCharsets.UTF_8)); mqttClient.publish(topic, message); } diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/clients/WebSubSubscriber.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/clients/WebSubSubscriber.java index 5b3fc32..da2b096 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/clients/WebSubSubscriber.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/clients/WebSubSubscriber.java @@ -1,15 +1,6 @@ package ch.unisg.tapas.auctionhouse.adapter.common.clients; -import java.io.IOException; import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.json.JSONObject; -import org.springframework.http.HttpStatus; /** * Subscribes to the WebSub hubs of auction houses discovered at run time. This class is instantiated @@ -18,24 +9,7 @@ import org.springframework.http.HttpStatus; */ public class WebSubSubscriber { - // TODO get this somehow from properties file. But on clue how to do this with static variables - static String WEBSUB_HUB_ENDPOINT = "http://localhost:3000"; - static String AUCTION_HOUSE_ENDPOINT = "http://localhost:8086"; - - Logger logger = Logger.getLogger(WebSubSubscriber.class.getName()); - public void subscribeToAuctionHouseEndpoint(URI endpoint) { - // TODO decide with other groups about auction house endpoint uri to discover websub topics - // and replace the hardcoded one with it - String topic = discoverWebSubTopic("http://localhost:3100/websub"); - - if (topic == null) { - return; - } - - subscribeToWebSub(topic); - - // Shoudl be done :D // TODO Subscribe to the auction house endpoint via WebSub: // 1. Send a request to the auction house in order to discover the WebSub hub to subscribe to. // The request URI should depend on the design of the Auction House HTTP API. @@ -51,61 +25,4 @@ public class WebSubSubscriber { // - W3C WebSub Recommendation: https://www.w3.org/TR/websub/ // - the implementation notes of the WebSub hub you are using to distribute events } - - private String discoverWebSubTopic(String endpoint) { - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(endpoint)) - .header("Content-Type", "application/json") - .GET() - .build(); - - - try { - HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); - if (response.statusCode() == HttpStatus.OK.value()) { - // TODO decide with other groups about response structure and replace the hardcoded - // uri with response uri - JSONObject jsonObject = new JSONObject(response.body()); - System.out.println(jsonObject); - return jsonObject.getString("topic"); - } else { - logger.log(Level.SEVERE, "Could not find a websub uri"); - } - } catch (InterruptedException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - } - return null; - } - - private void subscribeToWebSub(String topic) { - HttpClient client = HttpClient.newHttpClient(); - - String body = new JSONObject() - .put("hub.callback", AUCTION_HOUSE_ENDPOINT + "/auction-started") - .put("hub.mode", "subscribe") - .put("hub.topic", topic) - .put("hub.ws", false) - .toString(); - - - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(WEBSUB_HUB_ENDPOINT)) - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofString(body)) - .build(); - - - try { - client.send(request, HttpResponse.BodyHandlers.ofString()); - } catch (InterruptedException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - } - } } diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/formats/AuctionJsonRepresentation.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/formats/AuctionJsonRepresentation.java index 757c8c8..4500423 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/formats/AuctionJsonRepresentation.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/formats/AuctionJsonRepresentation.java @@ -7,16 +7,13 @@ import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Getter; import lombok.Setter; -import java.sql.Timestamp; -import java.text.SimpleDateFormat; - /** * Used to expose a representation of the state of an auction through an interface. This class is * only meant as a starting point when defining a uniform HTTP API for the Auction House: feel free * to modify this class as you see fit! */ public class AuctionJsonRepresentation { - public static final String MEDIA_TYPE = "application/auction+json"; + public static final String MEDIA_TYPE = "application/json"; @Getter @Setter private String auctionId; @@ -31,12 +28,12 @@ public class AuctionJsonRepresentation { private String taskType; @Getter @Setter - private Timestamp deadline; + private Integer deadline; public AuctionJsonRepresentation() { } public AuctionJsonRepresentation(String auctionId, String auctionHouseUri, String taskUri, - String taskType, Timestamp deadline) { + String taskType, Integer deadline) { this.auctionId = auctionId; this.auctionHouseUri = auctionHouseUri; this.taskUri = taskUri; @@ -57,7 +54,7 @@ public class AuctionJsonRepresentation { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); + return mapper.writeValueAsString(representation); } } diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/formats/BidJsonRepresentation.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/formats/BidJsonRepresentation.java deleted file mode 100644 index 7ae3dda..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/formats/BidJsonRepresentation.java +++ /dev/null @@ -1,43 +0,0 @@ -package ch.unisg.tapas.auctionhouse.adapter.common.formats; - -import ch.unisg.tapas.auctionhouse.domain.Bid; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.Getter; -import lombok.Setter; - -import java.text.SimpleDateFormat; - -public class BidJsonRepresentation { - public static final String MEDIA_TYPE = "application/bid+json"; - - @Getter @Setter - private String auctionId; - - @Getter @Setter - private String bidderName; - - @Getter @Setter - private String bidderAuctionHouseUri; - - @Getter @Setter - private String bidderTaskListUri; - - public BidJsonRepresentation() {} - - public BidJsonRepresentation(Bid bid){ - this.auctionId = bid.getAuctionId().getValue(); - this.bidderName = bid.getBidderName().getValue(); - this.bidderAuctionHouseUri = bid.getBidderAuctionHouseUri().getValue().toString(); - this.bidderTaskListUri = bid.getBidderTaskListUri().getValue().toString(); - } - - public static String serialize(Bid bid) throws JsonProcessingException { - BidJsonRepresentation representation = new BidJsonRepresentation(bid); - - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - return mapper.writeValueAsString(representation); - } -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/formats/TaskJsonRepresentation.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/formats/TaskJsonRepresentation.java deleted file mode 100644 index 782978c..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/common/formats/TaskJsonRepresentation.java +++ /dev/null @@ -1,124 +0,0 @@ -package ch.unisg.tapas.auctionhouse.adapter.common.formats; - -import ch.unisg.tapas.auctionhouse.domain.Task; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import lombok.Getter; -import lombok.Setter; - -/** - * This class is used to expose and consume representations of tasks through the HTTP interface. The - * representations conform to the custom JSON-based media type "application/task+json". The media type - * is just an identifier and can be registered with - * IANA to promote interoperability. - */ -final public class TaskJsonRepresentation { - // The media type used for this task representation format - public static final String MEDIA_TYPE = "application/task+json"; - - // A task identifier specific to our implementation (e.g., a UUID). This identifier is then used - // to generate the task's URI. URIs are standard uniform identifiers and use a universal syntax - // that can be referenced (and dereferenced) independent of context. In our uniform HTTP API, - // we identify tasks via URIs and not implementation-specific identifiers. - @Getter @Setter - private String taskId; - - // A string that represents the task's name - @Getter - private final String taskName; - - // A string that identifies the task's type. This string could also be a URI (e.g., defined in some - // Web ontology, as we shall see later in the course), but it's not constrained to be a URI. - // The task's type can be used to assign executors to tasks, to decide what tasks to bid for, etc. - @Getter - private final String taskType; - - // The task's status: OPEN, ASSIGNED, RUNNING, or EXECUTED (see Task.Status) - @Getter @Setter - private String taskStatus; - - // If this task is a delegated task (i.e., a shadow of another task), this URI points to the - // original task. Because URIs are standard and uniform, we can just dereference this URI to - // retrieve a representation of the original task. - @Getter @Setter - private String originalTaskUri; - - // The service provider who executes this task. The service provider is a any string that identifies - // a TAPAS group (e.g., tapas-group1). This identifier could also be a URI (if we have a good reason - // for it), but it's not constrained to be a URI. - @Getter @Setter - private String serviceProvider; - - // A string that provides domain-specific input data for this task. In the context of this project, - // we can parse and interpret the input data based on the task's type. - @Getter @Setter - private String inputData; - - // A string that provides domain-specific output data for this task. In the context of this project, - // we can parse and interpret the output data based on the task's type. - @Getter @Setter - private String outputData; - - /** - * Instantiate a task representation with a task name and type. - * - * @param taskName string that represents the task's name - * @param taskType string that represents the task's type - */ - public TaskJsonRepresentation(String taskName, String taskType) { - this.taskName = taskName; - this.taskType = taskType; - - this.taskStatus = null; - this.originalTaskUri = null; - this.serviceProvider = null; - this.inputData = null; - this.outputData = null; - } - - /** - * Instantiate a task representation from a domain concept. - * - * @param task the task - */ - public TaskJsonRepresentation(Task task) { - this(task.getTaskName().getValue(), task.getTaskType().getValue()); - - this.taskId = task.getTaskId().getValue(); - this.taskStatus = task.getTaskStatus().getValue().name(); - - this.originalTaskUri = (task.getOriginalTaskUri() == null) ? - null : task.getOriginalTaskUri().getValue(); - - this.serviceProvider = (task.getProvider() == null) ? null : task.getProvider().getValue(); - this.inputData = (task.getInputData() == null) ? null : task.getInputData().getValue(); - this.outputData = (task.getOutputData() == null) ? null : task.getOutputData().getValue(); - } - - /** - * Convenience method used to serialize a task provided as a domain concept in the format exposed - * through the uniform HTTP API. - * - * @param task the task as defined in the domain - * @return a string serialization using the JSON-based representation format defined for tasks - * @throws JsonProcessingException if a runtime exception occurs during object serialization - */ - public static String serialize(Task task) throws JsonProcessingException { - TaskJsonRepresentation representation = new TaskJsonRepresentation(task); - - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - - return mapper.writeValueAsString(representation); - } - - public String serialize() throws JsonProcessingException { - TaskJsonRepresentation representation = this; - - ObjectMapper mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - - return mapper.writeValueAsString(representation); - } -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/http/ExecutorAddedEventListenerHttpAdapter.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/http/ExecutorAddedEventListenerHttpAdapter.java new file mode 100644 index 0000000..3511b7d --- /dev/null +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/http/ExecutorAddedEventListenerHttpAdapter.java @@ -0,0 +1,34 @@ +package ch.unisg.tapas.auctionhouse.adapter.in.messaging.http; + +import ch.unisg.tapas.auctionhouse.application.handler.ExecutorAddedHandler; +import ch.unisg.tapas.auctionhouse.application.port.in.ExecutorAddedEvent; +import ch.unisg.tapas.auctionhouse.domain.Auction; +import ch.unisg.tapas.auctionhouse.domain.ExecutorRegistry; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Template for receiving an executor added event via HTTP + */ +@RestController +public class ExecutorAddedEventListenerHttpAdapter { + + @PostMapping(path = "/executors/{taskType}/{executorId}") + public ResponseEntity handleExecutorAddedEvent(@PathVariable("taskType") String taskType, + @PathVariable("executorId") String executorId) { + + ExecutorAddedEvent executorAddedEvent = new ExecutorAddedEvent( + new ExecutorRegistry.ExecutorIdentifier(executorId), + new Auction.AuctionedTaskType(taskType) + ); + + ExecutorAddedHandler newExecutorHandler = new ExecutorAddedHandler(); + newExecutorHandler.handleNewExecutorEvent(executorAddedEvent); + + return new ResponseEntity<>(HttpStatus.NO_CONTENT); + } +} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/http/ExecutorRemovedEventListenerHttpAdapter.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/http/ExecutorRemovedEventListenerHttpAdapter.java new file mode 100644 index 0000000..53811f9 --- /dev/null +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/http/ExecutorRemovedEventListenerHttpAdapter.java @@ -0,0 +1,16 @@ +package ch.unisg.tapas.auctionhouse.adapter.in.messaging.http; + +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; + +/** + * Template for handling an executor removed event received via an HTTP request + */ +@RestController +public class ExecutorRemovedEventListenerHttpAdapter { + + // TODO: add annotations for request method, request URI, etc. + public void handleExecutorRemovedEvent(@PathVariable("executorId") String executorId) { + // TODO: implement logic + } +} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/AuctionEventsMqttDispatcher.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/AuctionEventsMqttDispatcher.java index 91872f2..e5eaf12 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/AuctionEventsMqttDispatcher.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/AuctionEventsMqttDispatcher.java @@ -26,9 +26,7 @@ public class AuctionEventsMqttDispatcher { // TODO: Register here your topics and event listener adapters private void initRouter() { - router.put("ch/unisg/tapas/executors/added", new ExecutorAddedEventListenerMqttAdapter()); - router.put("ch/unisg/tapas/executors/removed", new ExecutorRemovedEventListenerMqttAdapter()); - router.put("ch/unisg/tapas/auctions", new ExternalAuctionStartedEventListenerMqttAdapter()); + router.put("ch/unisg/tapas-group-tutors/executors", new ExecutorAddedEventListenerMqttAdapter()); } /** diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/BidReceivedEventListenerMqttAdapter.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/BidReceivedEventListenerMqttAdapter.java deleted file mode 100644 index 29f45da..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/BidReceivedEventListenerMqttAdapter.java +++ /dev/null @@ -1,52 +0,0 @@ -package ch.unisg.tapas.auctionhouse.adapter.in.messaging.mqtt; - -import ch.unisg.tapas.auctionhouse.application.handler.BidReceivedHandler; -import ch.unisg.tapas.auctionhouse.application.handler.ExecutorAddedHandler; -import ch.unisg.tapas.auctionhouse.application.port.in.ExecutorAddedEvent; -import ch.unisg.tapas.auctionhouse.domain.Auction; -import ch.unisg.tapas.auctionhouse.domain.Bid; -import ch.unisg.tapas.auctionhouse.application.port.in.BidReceivedEvent; -import ch.unisg.tapas.auctionhouse.domain.ExecutorRegistry; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.paho.client.mqttv3.MqttMessage; - -import java.net.URI; - -public class BidReceivedEventListenerMqttAdapter extends AuctionEventMqttListener { - private static final Logger LOGGER = LogManager.getLogger(BidReceivedEventListenerMqttAdapter.class); - - @Override - public boolean handleEvent(MqttMessage message){ - String payload = new String(message.getPayload()); - - try { - // Note: this message representation is provided only as an example. You should use a - // representation that makes sense in the context of your application. - JsonNode data = new ObjectMapper().readTree(payload); - - String auctionId = data.get("auctionId").asText(); - String bidderName = data.get("bidderName").asText(); - String bidderAuctionHouseUri = data.get("bidderAuctionHouseUri").asText(); - String bidderTaskListUri = data.get("bidderTaskListUri").asText(); - - BidReceivedEvent bidReceivedEvent = new BidReceivedEvent( new Bid( - new Auction.AuctionId(auctionId), - new Bid.BidderName(bidderName), - new Bid.BidderAuctionHouseUri(URI.create(bidderAuctionHouseUri)), - new Bid.BidderTaskListUri(URI.create(bidderTaskListUri)) - )); - - BidReceivedHandler bidReceivedHandler = new BidReceivedHandler(); - bidReceivedHandler.handleNewBidReceivedEvent(bidReceivedEvent); - } catch (JsonProcessingException | NullPointerException e) { - LOGGER.error(e.getMessage(), e); - return false; - } - - return true; - } -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/ExecutorAddedEventListenerMqttAdapter.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/ExecutorAddedEventListenerMqttAdapter.java index dd2d120..2f661d1 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/ExecutorAddedEventListenerMqttAdapter.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/ExecutorAddedEventListenerMqttAdapter.java @@ -11,8 +11,6 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.eclipse.paho.client.mqttv3.MqttMessage; -import java.net.URI; - /** * Listener that handles events when an executor was added to this TAPAS application. * @@ -26,16 +24,16 @@ public class ExecutorAddedEventListenerMqttAdapter extends AuctionEventMqttListe String payload = new String(message.getPayload()); try { - // Note: this message representation is provided only as an example. You should use a + // Note: this messge representation is provided only as an example. You should use a // representation that makes sense in the context of your application. JsonNode data = new ObjectMapper().readTree(payload); - String executorUri = data.get("executorUri").asText(); - String executorTaskType = data.get("executorTaskType").asText(); + String taskType = data.get("taskType").asText(); + String executorId = data.get("executorId").asText(); ExecutorAddedEvent executorAddedEvent = new ExecutorAddedEvent( - new ExecutorRegistry.ExecutorUri(URI.create(executorUri)), - new Auction.AuctionedTaskType(executorTaskType) + new ExecutorRegistry.ExecutorIdentifier(executorId), + new Auction.AuctionedTaskType(taskType) ); ExecutorAddedHandler newExecutorHandler = new ExecutorAddedHandler(); diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/ExecutorRemovedEventListenerMqttAdapter.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/ExecutorRemovedEventListenerMqttAdapter.java deleted file mode 100644 index 4f4db7a..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/ExecutorRemovedEventListenerMqttAdapter.java +++ /dev/null @@ -1,48 +0,0 @@ -package ch.unisg.tapas.auctionhouse.adapter.in.messaging.mqtt; - -import ch.unisg.tapas.auctionhouse.application.handler.ExecutorRemovedHandler; -import ch.unisg.tapas.auctionhouse.application.port.in.ExecutorRemovedEvent; -import ch.unisg.tapas.auctionhouse.domain.Auction; -import ch.unisg.tapas.auctionhouse.domain.ExecutorRegistry; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.paho.client.mqttv3.MqttMessage; - -import java.net.URI; - -/** - * Listener that handles events when an executor was removed to this TAPAS application. - * - * This class is only provided as an example to help you bootstrap the project. - */ -public class ExecutorRemovedEventListenerMqttAdapter extends AuctionEventMqttListener { - private static final Logger LOGGER = LogManager.getLogger(ExecutorRemovedEventListenerMqttAdapter.class); - - @Override - public boolean handleEvent(MqttMessage message) { - String payload = new String(message.getPayload()); - - try { - // Note: this messge representation is provided only as an example. You should use a - // representation that makes sense in the context of your application. - JsonNode data = new ObjectMapper().readTree(payload); - - String executorUri = data.get("executorUri").asText(); - - ExecutorRemovedEvent executorRemovedEvent = new ExecutorRemovedEvent( - new ExecutorRegistry.ExecutorUri(URI.create(executorUri)) - ); - - ExecutorRemovedHandler newExecutorHandler = new ExecutorRemovedHandler(); - newExecutorHandler.handleExecutorRemovedEvent(executorRemovedEvent); - } catch (JsonProcessingException | NullPointerException e) { - LOGGER.error(e.getMessage(), e); - return false; - } - - return true; - } -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/ExternalAuctionStartedEventListenerMqttAdapter.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/ExternalAuctionStartedEventListenerMqttAdapter.java deleted file mode 100644 index 746d0ba..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/mqtt/ExternalAuctionStartedEventListenerMqttAdapter.java +++ /dev/null @@ -1,89 +0,0 @@ -package ch.unisg.tapas.auctionhouse.adapter.in.messaging.mqtt; - -import ch.unisg.tapas.auctionhouse.adapter.common.formats.BidJsonRepresentation; -import ch.unisg.tapas.auctionhouse.adapter.common.formats.TaskJsonRepresentation; -import ch.unisg.tapas.auctionhouse.application.handler.BidReceivedHandler; -import ch.unisg.tapas.auctionhouse.application.port.in.BidReceivedEvent; -import ch.unisg.tapas.auctionhouse.domain.Auction; -import ch.unisg.tapas.auctionhouse.domain.Bid; -import ch.unisg.tapas.auctionhouse.domain.ExecutorRegistry; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.paho.client.mqttv3.MqttMessage; -import org.springframework.beans.factory.annotation.Value; - -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.sql.Timestamp; - -public class ExternalAuctionStartedEventListenerMqttAdapter extends AuctionEventMqttListener{ - private static final Logger LOGGER = LogManager.getLogger(ExternalAuctionStartedEventListenerMqttAdapter.class); - - String auctionHouseURI = "https://tapas-auction-house.86-119-35-40.nip.io/"; - - String taskListURI = "https://tapas-tasks.86-119-35-40.nip.io"; - - @Override - public boolean handleEvent(MqttMessage message){ - String payload = new String(message.getPayload()); - - try { - // Note: this message representation is provided only as an example. You should use a - // representation that makes sense in the context of your application. - JsonNode data = new ObjectMapper().readTree(payload); - - // TODO Sanitize URIs - String auctionId = data.get("auctionId").asText(); - String auctionHouseUri = data.get("auctionHouseUri").asText(); - String taskUri = data.get("taskUri").asText(); - String taskType = data.get("taskType").asText(); - String deadline = data.get("deadline").asText(); - - var capable = ExecutorRegistry.getInstance().containsTaskType(new Auction.AuctionedTaskType(taskType)); - // TODO check deadline - if(capable){ - var bid = new Bid( - new Auction.AuctionId(auctionId), - new Bid.BidderName("Group-1"), - new Bid.BidderAuctionHouseUri(URI.create(auctionHouseURI)), - new Bid.BidderTaskListUri(URI.create(taskListURI)) - ); - - String body = BidJsonRepresentation.serialize(bid); - LOGGER.info(body); - var postURI = URI.create(auctionHouseUri + "/bid"); - HttpRequest postRequest = HttpRequest.newBuilder() - .uri(postURI) - .header("Content-Type", BidJsonRepresentation.MEDIA_TYPE) - .POST(HttpRequest.BodyPublishers.ofString(body)) - .build(); - - HttpClient client = HttpClient.newHttpClient(); - var postResponse = client.send(postRequest, HttpResponse.BodyHandlers.ofString()); - - LOGGER.info(postResponse.statusCode()); - } - } catch (JsonProcessingException | NullPointerException e) { - LOGGER.error(e.getMessage(), e); - return false; - } catch (IOException e) { - - LOGGER.error(e.getMessage(), e); - e.printStackTrace(); - } catch (InterruptedException e) { - - LOGGER.error(e.getMessage(), e); - e.printStackTrace(); - } catch (Exception e){ - LOGGER.error(e.getMessage(), e); - } - - return true; - } -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/websub/AuctionStartedEventListenerWebSubAdapter.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/websub/AuctionStartedEventListenerWebSubAdapter.java index 4f67dad..d156452 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/websub/AuctionStartedEventListenerWebSubAdapter.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/websub/AuctionStartedEventListenerWebSubAdapter.java @@ -1,22 +1,6 @@ package ch.unisg.tapas.auctionhouse.adapter.in.messaging.websub; -import ch.unisg.tapas.auctionhouse.adapter.common.formats.AuctionJsonRepresentation; import ch.unisg.tapas.auctionhouse.application.handler.AuctionStartedHandler; -import ch.unisg.tapas.auctionhouse.application.port.in.AuctionStartedEvent; -import ch.unisg.tapas.auctionhouse.domain.Auction; -import ch.unisg.tapas.auctionhouse.domain.Auction.AuctionDeadline; -import ch.unisg.tapas.auctionhouse.domain.Auction.AuctionHouseUri; -import ch.unisg.tapas.auctionhouse.domain.Auction.AuctionId; -import ch.unisg.tapas.auctionhouse.domain.Auction.AuctionedTaskType; -import ch.unisg.tapas.auctionhouse.domain.Auction.AuctionedTaskUri; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Collection; - -import org.json.JSONArray; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; /** @@ -29,25 +13,6 @@ public class AuctionStartedEventListenerWebSubAdapter { public AuctionStartedEventListenerWebSubAdapter(AuctionStartedHandler auctionStartedHandler) { this.auctionStartedHandler = auctionStartedHandler; } - /** - * Controller which listens to auction-started callbacks - * @return 200 OK - * @throws URISyntaxException - **/ - @PostMapping(path = "/auction-started") - public ResponseEntity handleExecutorAddedEvent(@RequestBody Collection payload) throws URISyntaxException { - for (AuctionJsonRepresentation auction : payload) { - auctionStartedHandler.handleAuctionStartedEvent( - new AuctionStartedEvent( - new Auction(new AuctionId(auction.getAuctionId()), - new AuctionHouseUri(new URI(auction.getAuctionHouseUri())), - new AuctionedTaskUri(new URI(auction.getTaskUri())), - new AuctionedTaskType(auction.getTaskType()), - new AuctionDeadline(auction.getDeadline())) - )); - } - - return new ResponseEntity<>(HttpStatus.OK); - } + //TODO } diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/websub/ValidateIntentWebSubAdapter.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/websub/ValidateIntentWebSubAdapter.java deleted file mode 100644 index 7bfb450..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/messaging/websub/ValidateIntentWebSubAdapter.java +++ /dev/null @@ -1,33 +0,0 @@ -package ch.unisg.tapas.auctionhouse.adapter.in.messaging.websub; - -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -/** - * This class validates the subscription intent from the websub hub - */ -@RestController -public class ValidateIntentWebSubAdapter { - - @Value("${application.environment}") - private String environment; - - @GetMapping(path = "/auction-started") - public ResponseEntity validateIntent(@RequestParam("hub.challenge") String challenge) { - // Different implementation depending on local development or production - if (environment.equalsIgnoreCase("development")) { - HttpHeaders headers = new HttpHeaders(); - headers.add("Content-Type", "application/json"); - String body = new JSONObject() - .put("hub.challenge", challenge) - .toString(); - return new ResponseEntity<>(body, headers, HttpStatus.OK); - } else { - return new ResponseEntity<>(challenge, HttpStatus.OK); - } - } -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/web/AddBidWebController.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/web/AddBidWebController.java deleted file mode 100644 index e95419e..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/web/AddBidWebController.java +++ /dev/null @@ -1,45 +0,0 @@ -package ch.unisg.tapas.auctionhouse.adapter.in.web; - -import ch.unisg.tapas.auctionhouse.adapter.common.formats.AuctionJsonRepresentation; -import ch.unisg.tapas.auctionhouse.adapter.common.formats.BidJsonRepresentation; -import ch.unisg.tapas.auctionhouse.adapter.in.messaging.mqtt.BidReceivedEventListenerMqttAdapter; -import ch.unisg.tapas.auctionhouse.application.handler.BidReceivedHandler; -import ch.unisg.tapas.auctionhouse.application.port.in.BidReceivedEvent; -import ch.unisg.tapas.auctionhouse.domain.Auction; -import ch.unisg.tapas.auctionhouse.domain.Bid; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import java.net.URI; - -// TODO Fix structure due to MQTT -@RestController -public class AddBidWebController { - private static final Logger LOGGER = LogManager.getLogger(AddBidWebController.class); - - @PostMapping(path = "/bid", consumes = BidJsonRepresentation.MEDIA_TYPE) - public ResponseEntity addBid(@RequestBody BidJsonRepresentation payload) { - BidReceivedEvent bidReceivedEvent = new BidReceivedEvent(new Bid( - new Auction.AuctionId(payload.getAuctionId()), - new Bid.BidderName(payload.getBidderName()), - new Bid.BidderAuctionHouseUri(URI.create(payload.getBidderAuctionHouseUri())), - new Bid.BidderTaskListUri(URI.create(payload.getBidderTaskListUri())) - )); - - LOGGER.info("Bid received:" + payload); - - BidReceivedHandler bidReceivedHandler = new BidReceivedHandler(); - bidReceivedHandler.handleNewBidReceivedEvent(bidReceivedEvent); - - HttpHeaders responseHeaders = new HttpHeaders(); - - return new ResponseEntity<>(responseHeaders, HttpStatus.NO_CONTENT); - } - -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/web/WinningBidWebController.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/web/WinningBidWebController.java deleted file mode 100644 index e4c5aa1..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/in/web/WinningBidWebController.java +++ /dev/null @@ -1,59 +0,0 @@ -package ch.unisg.tapas.auctionhouse.adapter.in.web; - -import ch.unisg.tapas.auctionhouse.adapter.common.formats.AuctionJsonRepresentation; -import ch.unisg.tapas.auctionhouse.adapter.common.formats.BidJsonRepresentation; -import ch.unisg.tapas.auctionhouse.adapter.common.formats.TaskJsonRepresentation; -import ch.unisg.tapas.auctionhouse.adapter.in.messaging.mqtt.ExternalAuctionStartedEventListenerMqttAdapter; -import ch.unisg.tapas.auctionhouse.domain.Task; -import com.fasterxml.jackson.core.JsonProcessingException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; - -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; - -@RestController -public class WinningBidWebController { - private static final Logger LOGGER = LogManager.getLogger(WinningBidWebController.class); - - @Value("${tasks.list.uri}") - String taskListURI; - - @PostMapping(path = "/taskwinner", consumes = TaskJsonRepresentation.MEDIA_TYPE) - public ResponseEntity winningBid(@RequestBody TaskJsonRepresentation payload){ - try { - var body = payload.serialize(); - LOGGER.info(body); - var postURI = URI.create("https://tapas-tasks.86-119-35-40.nip.io/tasks/"); - HttpRequest postRequest = HttpRequest.newBuilder() - .uri(postURI) - .header("Content-Type", TaskJsonRepresentation.MEDIA_TYPE) - .POST(HttpRequest.BodyPublishers.ofString(body)) - .build(); - - HttpClient client = HttpClient.newHttpClient(); - var postResponse = client.send(postRequest, HttpResponse.BodyHandlers.ofString()); - - LOGGER.info(postResponse.statusCode()); - - - HttpHeaders responseHeaders = new HttpHeaders(); - return new ResponseEntity<>(responseHeaders, HttpStatus.NO_CONTENT); - } - catch ( - IOException | InterruptedException e) { - throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } - } -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/out/messaging/mqtt/PublishAuctionStartedEventMqttAdapter.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/out/messaging/mqtt/PublishAuctionStartedEventMqttAdapter.java deleted file mode 100644 index a041b4f..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/out/messaging/mqtt/PublishAuctionStartedEventMqttAdapter.java +++ /dev/null @@ -1,36 +0,0 @@ -package ch.unisg.tapas.auctionhouse.adapter.out.messaging.mqtt; - -import ch.unisg.tapas.auctionhouse.adapter.common.clients.TapasMqttClient; -import ch.unisg.tapas.auctionhouse.adapter.common.formats.AuctionJsonRepresentation; -import ch.unisg.tapas.auctionhouse.adapter.in.messaging.mqtt.AuctionEventsMqttDispatcher; -import ch.unisg.tapas.auctionhouse.application.port.out.AuctionStartedEventPort; -import ch.unisg.tapas.auctionhouse.domain.AuctionStartedEvent; -import ch.unisg.tapas.common.ConfigProperties; -import com.fasterxml.jackson.core.JsonProcessingException; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.eclipse.paho.client.mqttv3.MqttException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; - -@Component -@Primary -public class PublishAuctionStartedEventMqttAdapter implements AuctionStartedEventPort { - - private static final Logger LOGGER = LogManager.getLogger(PublishAuctionStartedEventMqttAdapter.class); - - @Autowired - private ConfigProperties config; - - @Override - public void publishAuctionStartedEvent(AuctionStartedEvent event) { - try{ - var mqttClient = TapasMqttClient.getInstance(config.getMqttBrokerUri().toString(), new AuctionEventsMqttDispatcher()); - mqttClient.publishMessage("ch/unisg/tapas/auctions", AuctionJsonRepresentation.serialize(event.getAuction())); - } - catch (MqttException | JsonProcessingException e){ - LOGGER.error(e.getMessage(), e); - } - } -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/out/messaging/websub/PublishAuctionStartedEventWebSubAdapter.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/out/messaging/websub/PublishAuctionStartedEventWebSubAdapter.java index 228f43b..9e6ec67 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/out/messaging/websub/PublishAuctionStartedEventWebSubAdapter.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/out/messaging/websub/PublishAuctionStartedEventWebSubAdapter.java @@ -4,16 +4,12 @@ import ch.unisg.tapas.auctionhouse.application.port.out.AuctionStartedEventPort; import ch.unisg.tapas.auctionhouse.domain.Auction; import ch.unisg.tapas.auctionhouse.domain.AuctionStartedEvent; import ch.unisg.tapas.common.ConfigProperties; - -import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Primary; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import java.io.IOException; -import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; @@ -21,52 +17,21 @@ import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; import java.util.stream.Collectors; /** * This class is a template for publishing auction started events via WebSub. */ @Component +@Primary public class PublishAuctionStartedEventWebSubAdapter implements AuctionStartedEventPort { // You can use this object to retrieve properties from application.properties, e.g. the // WebSub hub publish endpoint, etc. @Autowired private ConfigProperties config; - @Value("${auctionhouse.uri}") - private String auctionHouseUri; - - @Value("${websub.hub.uri}") - private String webSubHubUri; - - Logger logger = Logger.getLogger(PublishAuctionStartedEventWebSubAdapter.class.getName()); - @Override public void publishAuctionStartedEvent(AuctionStartedEvent event) { - HttpClient client = HttpClient.newHttpClient(); - - String body = new JSONObject() - .put("hub.url", auctionHouseUri + "/auctions") - .put("hub.mode", "publish") - .toString(); - - - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(webSubHubUri)) - .header("Content-Type", "application/json") - .POST(HttpRequest.BodyPublishers.ofString(body)) - .build(); - - - try { - client.send(request, HttpResponse.BodyHandlers.ofString()); - } catch (InterruptedException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - } + // TODO } } diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/out/web/AuctionWonEventHttpAdapter.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/out/web/AuctionWonEventHttpAdapter.java index ec04b2b..26949f2 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/out/web/AuctionWonEventHttpAdapter.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/adapter/out/web/AuctionWonEventHttpAdapter.java @@ -1,24 +1,10 @@ package ch.unisg.tapas.auctionhouse.adapter.out.web; -import ch.unisg.tapas.auctionhouse.adapter.common.formats.TaskJsonRepresentation; -import ch.unisg.tapas.auctionhouse.application.handler.AuctionStartedHandler; import ch.unisg.tapas.auctionhouse.application.port.out.AuctionWonEventPort; -import ch.unisg.tapas.auctionhouse.domain.AuctionRegistry; import ch.unisg.tapas.auctionhouse.domain.AuctionWonEvent; -import ch.unisg.tapas.auctionhouse.domain.Task; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.json.JSONObject; -import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; - /** * This class is a template for sending auction won events via HTTP. This class was created here only * as a placeholder, it is up to you to decide how such events should be sent (e.g., via HTTP, @@ -27,56 +13,8 @@ import java.net.http.HttpResponse; @Component @Primary public class AuctionWonEventHttpAdapter implements AuctionWonEventPort { - private static final Logger LOGGER = LogManager.getLogger(AuctionWonEventHttpAdapter.class); - - @Value("${tasks.list.uri}") - String server; - @Override public void publishAuctionWonEvent(AuctionWonEvent event) { - try{ - var auction = AuctionRegistry.getInstance().getAuctionById(event.getWinningBid().getAuctionId()); - - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(auction.get().getTaskUri().getValue()) - .GET() - .build(); - var response = client.send(request, HttpResponse.BodyHandlers.ofString()); - LOGGER.info(response.body()); - JSONObject responseBody = new JSONObject(response.body()); - - var task = new Task( - new Task.TaskName(responseBody.getString("taskName")), - new Task.TaskType(responseBody.getString("taskType")), - new Task.OriginalTaskUri(auction.get().getTaskUri().getValue().toString()), - new Task.TaskStatus(ch.unisg.tapas.auctionhouse.domain.Task.Status.ASSIGNED), - new Task.TaskId(responseBody.getString("taskId")), - new Task.InputData(responseBody.getString("inputData")), - new Task.ServiceProvider("TODO") - ); - - var bidderAuctionHouseUri = event.getWinningBid().getBidderAuctionHouseUri().getValue().toString(); - String body = TaskJsonRepresentation.serialize(task); - LOGGER.info(body); - var postURI = URI.create(bidderAuctionHouseUri + "/taskwinner"); - LOGGER.info(postURI); - HttpRequest postRequest = HttpRequest.newBuilder() - .uri(postURI) - .header("Content-Type", TaskJsonRepresentation.MEDIA_TYPE) - .POST(HttpRequest.BodyPublishers.ofString(body)) - .build(); - - var postResponse = client.send(postRequest, HttpResponse.BodyHandlers.ofString()); - - LOGGER.info(postResponse.statusCode()); - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (Exception e){ - LOGGER.error(e.getMessage(), e); - } } } diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/handler/BidReceivedHandler.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/handler/BidReceivedHandler.java deleted file mode 100644 index dc992ac..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/handler/BidReceivedHandler.java +++ /dev/null @@ -1,17 +0,0 @@ -package ch.unisg.tapas.auctionhouse.application.handler; - -import ch.unisg.tapas.auctionhouse.application.port.in.BidReceivedEvent; -import ch.unisg.tapas.auctionhouse.application.port.in.BidReceivedEventHandler; -import ch.unisg.tapas.auctionhouse.domain.AuctionRegistry; -import org.springframework.stereotype.Component; - -@Component -public class BidReceivedHandler implements BidReceivedEventHandler { - @Override - public boolean handleNewBidReceivedEvent(BidReceivedEvent bidReceivedEvent){ - var auction = AuctionRegistry.getInstance().getAuctionById(bidReceivedEvent.bid.getAuctionId()); - // TODO Handle if auction not there - auction.get().addBid(bidReceivedEvent.bid); - return true; - } -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/handler/ExecutorAddedHandler.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/handler/ExecutorAddedHandler.java index fc30e11..624e669 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/handler/ExecutorAddedHandler.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/handler/ExecutorAddedHandler.java @@ -11,6 +11,6 @@ public class ExecutorAddedHandler implements ExecutorAddedEventHandler { @Override public boolean handleNewExecutorEvent(ExecutorAddedEvent executorAddedEvent) { return ExecutorRegistry.getInstance().addExecutor(executorAddedEvent.getTaskType(), - executorAddedEvent.getExecutorUri()); + executorAddedEvent.getExecutorId()); } } diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/handler/ExecutorRemovedHandler.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/handler/ExecutorRemovedHandler.java index 9a68da1..c3bfed8 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/handler/ExecutorRemovedHandler.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/handler/ExecutorRemovedHandler.java @@ -14,6 +14,6 @@ public class ExecutorRemovedHandler implements ExecutorRemovedEventHandler { @Override public boolean handleExecutorRemovedEvent(ExecutorRemovedEvent executorRemovedEvent) { - return ExecutorRegistry.getInstance().removeExecutor(executorRemovedEvent.getExecutorUri()); + return ExecutorRegistry.getInstance().removeExecutor(executorRemovedEvent.getExecutorId()); } } diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/BidReceivedEvent.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/BidReceivedEvent.java deleted file mode 100644 index 560f50b..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/BidReceivedEvent.java +++ /dev/null @@ -1,17 +0,0 @@ -package ch.unisg.tapas.auctionhouse.application.port.in; - -import ch.unisg.tapas.auctionhouse.domain.Bid; -import ch.unisg.tapas.common.SelfValidating; -import lombok.Getter; - -import javax.validation.constraints.NotNull; - -public class BidReceivedEvent extends SelfValidating { - @NotNull - public Bid bid; - - public BidReceivedEvent(Bid bid){ - this.bid = bid; - validateSelf(); - } -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/BidReceivedEventHandler.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/BidReceivedEventHandler.java deleted file mode 100644 index b17ac6b..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/BidReceivedEventHandler.java +++ /dev/null @@ -1,5 +0,0 @@ -package ch.unisg.tapas.auctionhouse.application.port.in; - -public interface BidReceivedEventHandler { - boolean handleNewBidReceivedEvent(BidReceivedEvent bidReceivedEvent); -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/ExecutorAddedEvent.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/ExecutorAddedEvent.java index 7d647e1..5a53b94 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/ExecutorAddedEvent.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/ExecutorAddedEvent.java @@ -1,8 +1,7 @@ package ch.unisg.tapas.auctionhouse.application.port.in; import ch.unisg.tapas.auctionhouse.domain.Auction.AuctionedTaskType; -import ch.unisg.tapas.auctionhouse.domain.ExecutorRegistry; -import ch.unisg.tapas.auctionhouse.domain.ExecutorRegistry.ExecutorUri; +import ch.unisg.tapas.auctionhouse.domain.ExecutorRegistry.ExecutorIdentifier; import ch.unisg.tapas.common.SelfValidating; import lombok.Value; @@ -14,7 +13,7 @@ import javax.validation.constraints.NotNull; @Value public class ExecutorAddedEvent extends SelfValidating { @NotNull - private final ExecutorRegistry.ExecutorUri executorUri; + private final ExecutorIdentifier executorId; @NotNull private final AuctionedTaskType taskType; @@ -22,10 +21,10 @@ public class ExecutorAddedEvent extends SelfValidating { /** * Constructs an executor added event. * - * @param executorUri the identifier of the executor that was added to this TAPAS application + * @param executorId the identifier of the executor that was added to this TAPAS application */ - public ExecutorAddedEvent(ExecutorUri executorUri, AuctionedTaskType taskType) { - this.executorUri = executorUri; + public ExecutorAddedEvent(ExecutorIdentifier executorId, AuctionedTaskType taskType) { + this.executorId = executorId; this.taskType = taskType; this.validateSelf(); diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/ExecutorRemovedEvent.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/ExecutorRemovedEvent.java index a1633fe..4d5c910 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/ExecutorRemovedEvent.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/port/in/ExecutorRemovedEvent.java @@ -1,7 +1,6 @@ package ch.unisg.tapas.auctionhouse.application.port.in; -import ch.unisg.tapas.auctionhouse.domain.ExecutorRegistry; -import ch.unisg.tapas.auctionhouse.domain.ExecutorRegistry.ExecutorUri; +import ch.unisg.tapas.auctionhouse.domain.ExecutorRegistry.ExecutorIdentifier; import ch.unisg.tapas.common.SelfValidating; import lombok.Value; @@ -13,15 +12,15 @@ import javax.validation.constraints.NotNull; @Value public class ExecutorRemovedEvent extends SelfValidating { @NotNull - private final ExecutorUri executorUri; + private final ExecutorIdentifier executorId; /** * Constructs an executor removed event. * - * @param executorUri + * @param executorId the identifier of the executor that was removed from this TAPAS application */ - public ExecutorRemovedEvent(ExecutorUri executorUri) { - this.executorUri = executorUri; + public ExecutorRemovedEvent(ExecutorIdentifier executorId) { + this.executorId = executorId; this.validateSelf(); } } diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/service/StartAuctionService.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/service/StartAuctionService.java index 60c5f24..42c6e37 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/service/StartAuctionService.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/application/service/StartAuctionService.java @@ -2,7 +2,6 @@ package ch.unisg.tapas.auctionhouse.application.service; import ch.unisg.tapas.auctionhouse.application.port.in.LaunchAuctionCommand; import ch.unisg.tapas.auctionhouse.application.port.in.LaunchAuctionUseCase; -import ch.unisg.tapas.auctionhouse.application.port.in.LaunchAuctionUseCase; import ch.unisg.tapas.auctionhouse.application.port.out.AuctionWonEventPort; import ch.unisg.tapas.auctionhouse.application.port.out.AuctionStartedEventPort; import ch.unisg.tapas.auctionhouse.domain.*; @@ -12,7 +11,6 @@ import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.sql.Timestamp; import java.util.Optional; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; @@ -27,7 +25,7 @@ import java.util.concurrent.TimeUnit; public class StartAuctionService implements LaunchAuctionUseCase { private static final Logger LOGGER = LogManager.getLogger(StartAuctionService.class); - private final Timestamp DEFAULT_AUCTION_DEADLINE_MILLIS = Timestamp.valueOf("1970-01-01 00:00:01"); + private final static int DEFAULT_AUCTION_DEADLINE_MILLIS = 10000; // Event port used to publish an auction started event private final AuctionStartedEventPort auctionStartedEventPort; @@ -65,7 +63,7 @@ public class StartAuctionService implements LaunchAuctionUseCase { auctions.addAuction(auction); // Schedule the closing of the auction at the deadline - service.schedule(new CloseAuctionTask(auction.getAuctionId()), deadline.getValue().getTime() - System.currentTimeMillis(), + service.schedule(new CloseAuctionTask(auction.getAuctionId()), deadline.getValue(), TimeUnit.MILLISECONDS); // Publish an auction started event diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/domain/Auction.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/domain/Auction.java index c6d9333..3e51ef7 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/domain/Auction.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/domain/Auction.java @@ -4,7 +4,6 @@ import lombok.Getter; import lombok.Value; import java.net.URI; -import java.sql.Timestamp; import java.util.*; /** @@ -167,6 +166,6 @@ public class Auction { @Value public static class AuctionDeadline { - Timestamp value; + int value; } } diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/domain/ExecutorRegistry.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/domain/ExecutorRegistry.java index 1aedc80..9da3756 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/domain/ExecutorRegistry.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/domain/ExecutorRegistry.java @@ -2,7 +2,6 @@ package ch.unisg.tapas.auctionhouse.domain; import lombok.Value; -import java.net.URI; import java.util.*; /** @@ -14,7 +13,7 @@ import java.util.*; public class ExecutorRegistry { private static ExecutorRegistry registry; - private final Map> executors; + private final Map> executors; private ExecutorRegistry() { this.executors = new Hashtable<>(); @@ -32,14 +31,14 @@ public class ExecutorRegistry { * Adds an executor to the registry for a given task type. * * @param taskType the type of the task - * @param executorUri the executor's URI + * @param executorIdentifier the identifier of the executor (can be any string) * @return true unless a runtime exception occurs */ - public boolean addExecutor(Auction.AuctionedTaskType taskType, ExecutorUri executorUri) { - Set taskTypeExecs = executors.getOrDefault(taskType, + public boolean addExecutor(Auction.AuctionedTaskType taskType, ExecutorIdentifier executorIdentifier) { + Set taskTypeExecs = executors.getOrDefault(taskType, Collections.synchronizedSet(new HashSet<>())); - taskTypeExecs.add(executorUri); + taskTypeExecs.add(executorIdentifier); executors.put(taskType, taskTypeExecs); return true; @@ -48,17 +47,17 @@ public class ExecutorRegistry { /** * Removes an executor from the registry. The executor is disassociated from all known task types. * - * @param executorUri the executor's URI + * @param executorIdentifier the identifier of the executor (can be any string) * @return true unless a runtime exception occurs */ - public boolean removeExecutor(ExecutorUri executorUri) { + public boolean removeExecutor(ExecutorIdentifier executorIdentifier) { Iterator iterator = executors.keySet().iterator(); while (iterator.hasNext()) { Auction.AuctionedTaskType taskType = iterator.next(); - Set set = executors.get(taskType); + Set set = executors.get(taskType); - set.remove(executorUri); + set.remove(executorIdentifier); if (set.isEmpty()) { iterator.remove(); @@ -81,7 +80,7 @@ public class ExecutorRegistry { // Value Object for the executor identifier @Value - public static class ExecutorUri { - URI value; + public static class ExecutorIdentifier { + String value; } } diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/domain/Task.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/domain/Task.java deleted file mode 100644 index 3fd0d89..0000000 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/auctionhouse/domain/Task.java +++ /dev/null @@ -1,122 +0,0 @@ -package ch.unisg.tapas.auctionhouse.domain; - -import lombok.Getter; -import lombok.Setter; -import lombok.Value; - -import java.util.UUID; - -/**This is a domain entity**/ -public class Task { - public enum Status { - OPEN, ASSIGNED, RUNNING, EXECUTED - } - - @Getter - private final TaskId taskId; - - @Getter - private final TaskName taskName; - - @Getter - private final TaskType taskType; - - @Getter @Setter - public TaskStatus taskStatus; // had to make public for CompleteTaskService - - @Getter - public TaskResult taskResult; // same as above - - @Getter - private final OriginalTaskUri originalTaskUri; - - @Getter @Setter - private ServiceProvider provider; - - @Getter @Setter - private InputData inputData; - - @Getter @Setter - private OutputData outputData; - - public Task(TaskName taskName, TaskType taskType, OriginalTaskUri taskUri) { - this.taskName = taskName; - this.taskType = taskType; - this.taskStatus = new TaskStatus(Status.OPEN); - this.taskId = new TaskId(UUID.randomUUID().toString()); - this.taskResult = new TaskResult(""); - this.originalTaskUri = taskUri; - - this.inputData = null; - this.outputData = null; - } - - public Task(TaskName taskName, TaskType taskType, OriginalTaskUri taskUri, TaskStatus taskStatus, TaskId taskId, InputData inputData, ServiceProvider serviceProvider) { - this.taskName = taskName; - this.taskType = taskType; - this.taskStatus = taskStatus; - this.taskId = taskId; - this.taskResult = new TaskResult(""); - this.originalTaskUri = taskUri; - this.provider = serviceProvider; - - this.inputData = inputData; - this.outputData = new OutputData(""); - } - - protected static Task createTaskWithNameAndType(TaskName name, TaskType type) { - //This is a simple debug message to see that the request has reached the right method in the core - System.out.println("New Task: " + name.getValue() + " " + type.getValue()); - return new Task(name, type, null); - } - - protected static Task createTaskWithNameAndTypeAndOriginalTaskUri(TaskName name, TaskType type, - OriginalTaskUri originalTaskUri) { - return new Task(name, type, originalTaskUri); - } - - @Value - public static class TaskId { - String value; - } - - @Value - public static class TaskName { - String value; - } - - @Value - public static class TaskType { - String value; - } - - @Value - public static class OriginalTaskUri { - String value; - } - - @Value - public static class TaskStatus { - Status value; - } - - @Value - public static class ServiceProvider { - String value; - } - - @Value - public static class InputData { - String value; - } - - @Value - public static class OutputData { - String value; - } - - @Value - public static class TaskResult{ - private String value; - } -} diff --git a/tapas-auction-house/src/main/java/ch/unisg/tapas/common/ConfigProperties.java b/tapas-auction-house/src/main/java/ch/unisg/tapas/common/ConfigProperties.java index 2933465..748afda 100644 --- a/tapas-auction-house/src/main/java/ch/unisg/tapas/common/ConfigProperties.java +++ b/tapas-auction-house/src/main/java/ch/unisg/tapas/common/ConfigProperties.java @@ -61,14 +61,4 @@ public class ConfigProperties { public URI getTaskListUri() { return URI.create(environment.getProperty("tasks.list.uri")); } - - - /** - * Retrieves the URI of the MQTT broker. - * - * @return the URI of the MQTT broker - */ - public URI getMqttBrokerUri() { - return URI.create(environment.getProperty("mqtt.broker.uri")); - } } diff --git a/tapas-auction-house/src/main/resources/application.properties b/tapas-auction-house/src/main/resources/application.properties index 78bda13..f69e5dd 100644 --- a/tapas-auction-house/src/main/resources/application.properties +++ b/tapas-auction-house/src/main/resources/application.properties @@ -1,13 +1,10 @@ -server.port=8086 +server.port=8082 + +broker.mqtt=tcp://broker.hivemq.com websub.hub=https://websub.appspot.com/ websub.hub.publish=https://websub.appspot.com/ group=tapas-group-tutors -auction.house.uri=https://tapas-auction-house.86-119-35-40.nip.io -tasks.list.uri=http://localhost:8081 - -application.environment=development -auctionhouse.uri=http://localhost:8086 -websub.hub.uri=http://localhost:3000 -mqtt.broker.uri=tcp://localhost:1883 +auction.house.uri=https://tapas-auction-house.86-119-34-23.nip.io/ +tasks.list.uri=https://tapas-tasks.86-119-34-23.nip.io/ diff --git a/tapas-tasks/Dockerfile b/tapas-tasks/Dockerfile index db90fb6..b05be85 100644 --- a/tapas-tasks/Dockerfile +++ b/tapas-tasks/Dockerfile @@ -1,18 +1,13 @@ -FROM openjdk:11 AS development - -WORKDIR /opt/app - -# ENV SPRING_DATASOURCE_URL=jdbc:mysql://backend-db:3306/db - -COPY .mvn/ .mvn -COPY mvnw pom.xml mvnw.cmd ./ - -RUN apt-get clean && apt-get update && apt-get install dos2unix -RUN dos2unix mvnw - -RUN ./mvnw dependency:go-offline - -COPY src /opt/app/src -COPY *target /opt/app/target - -CMD ["./mvnw", "spring-boot:run", "-Dspring-boot.run.jvmArguments=\"-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=*:5005\"", "-Dspring.devtools.restart.enabled=true"] +# Dockerfile/Docker-Compose file based on an initial version authored by Alexander Lontke (ASSE, Fall Semester 2021) + +FROM maven as build + +COPY . /app + +RUN mvn -f app/pom.xml --batch-mode --update-snapshots verify + +FROM openjdk + +COPY --from=build /app/target/tapas-tasks-0.0.1-SNAPSHOT.jar ./tapas-tasks-0.0.1-SNAPSHOT.jar + +CMD java -jar tapas-tasks-0.0.1-SNAPSHOT.jar diff --git a/tapas-tasks/README.md b/tapas-tasks/README.md index 90016c3..55f120f 100644 --- a/tapas-tasks/README.md +++ b/tapas-tasks/README.md @@ -167,3 +167,25 @@ Date: Sun, 17 Oct 2021 21:32:25 GMT Internally, this request is mapped to a [TaskExecutedEvent](src/main/java/ch/unisg/tapastasks/tasks/application/port/in/TaskExecutedEvent.java). The HTTP response returns a `200 OK` status code together with the updated representation of the task. + +## Working with MongoDB +The provided TAPAS Tasks service is connected to a MongoDB as a repository for persisting data. + +Here are some pointers to start integrating the MongoDB with the other microservices: +* [application.properties](src/main/resources/application.properties) defines the + * URI of the DB server that Spring will connect to (`mongodb`service running in Docker container). Username and password for the server can be found in [docker-compose.yml](../docker-compose.yml). + * Name of the database for the microservice (`tapas-tasks`) +* [docker-compose.yml](../docker-compose.yml) defines + * in lines 74-82: the configuration of the mongodb service based on the mongodb container including the root username and password (once deployed this cannot be changed anymore!) + * in lines 84-102: the configuration of a web application called `mongo-express` to manage the MongoDB server. The web app can be reached via the URI: [http://dbadmin.${PUB_IP}.nip.io]([http://dbadmin.${PUB_IP}.nip.io]). Login credentials for mongo-express can be found in lines 89 and 90. + * in lines 104-105: the volume to be used by the mongodb service for writing and storing data (do not forget!). +* The [pom.xml](./pom.xml) needs to have `spring-boot-starter-data-mongodb` and `spring-data-mongodb` as new dependencies. +* The [TapasTasksApplication.java](/src/main/java/ch/unisg/tapastasks/TapasTasksApplication.java) specifies in line 9 the location of the MongoRepository classes for the microservice. +* The [persistence.mongodb](/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb) package has the relevant classes to work with MongoDB: + * The [MongoTaskDocument.java](/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/MongoTaskDocument.java) class defines the attributes of a Document for storing a task in the collection `tasks`. + * The [TaskRepository.java](/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskRepository.java) class specifies the MongoRepository. + * The [TaskPersistenceAdapter.java](/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskPersistenceAdapter.java) implements the two ports to add a new task ([AddTaskPort](/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/AddTaskPort.java)) and retrieve a task ([LoadTaskPort](/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/LoadTaskPort.java)). These ports are used in the classes [AddNewTaskToTaskListService.java](/src/main/java/ch/unisg/tapastasks/tasks/application/service/AddNewTaskToTaskListService.java) and [RetrieveTaskFromTaskListService.java](/src/main/java/ch/unisg/tapastasks/tasks/application/service/RetrieveTaskFromTaskListService.java). + +#### General hints: +* To not overload the VMs we recommend to use only one MongoDB server that all microservices connect to. Per microservice you could use one database or one collection (discuss in your ADRs!). To use more than one MongoDB server you have to extend the [docker-compose.yml](../docker-compose.yml) file by basically replicating lines 74-105 and changing the names of the services and volumes to be unique (ask your tutors!). +* For local testing you have to install the MongoDB server locally on your computers and change the `spring.data.mongodb.uri` String in [application.properties](./src/main/resources/application.properties). diff --git a/tapas-tasks/pom.xml b/tapas-tasks/pom.xml index 715b947..25ef1f2 100644 --- a/tapas-tasks/pom.xml +++ b/tapas-tasks/pom.xml @@ -15,8 +15,6 @@ TAPAS Tasks 11 - scs-asse-fs21-group1 - https://sonarcloud.io @@ -29,6 +27,25 @@ org.springframework.boot spring-boot-starter-web + + org.springframework.data + spring-data-mongodb + 3.2.6 + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + + org.springframework.boot + spring-boot-starter-actuator + + + de.codecentric + chaos-monkey-spring-boot + 2.5.4 + org.projectlombok @@ -40,6 +57,17 @@ spring-boot-starter-test test + + org.mockito + mockito-core + 2.21.0 + + + com.tngtech.archunit + archunit-junit4 + 0.22.0 + test + org.springframework.boot @@ -62,29 +90,15 @@ json-patch 1.13 - - - - org.springframework.boot - spring-boot-devtools - runtime - true - - - org.eclipse.paho org.eclipse.paho.client.mqttv3 - 1.2.5 + 1.2.0 - - com.vaadin.external.google - android-json - 0.0.20131108.vaadin1 - compile + org.springframework.boot + spring-boot-test - diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/TapasTasksApplication.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/TapasTasksApplication.java index 2675391..78a6145 100644 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/TapasTasksApplication.java +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/TapasTasksApplication.java @@ -1,14 +1,20 @@ package ch.unisg.tapastasks; +import ch.unisg.tapastasks.tasks.adapter.out.persistence.mongodb.TaskRepository; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @SpringBootApplication +@EnableMongoRepositories(basePackageClasses = TaskRepository.class) public class TapasTasksApplication { public static void main(String[] args) { SpringApplication tapasTasksApp = new SpringApplication(TapasTasksApplication.class); tapasTasksApp.run(args); + + + } } diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/AddNewTaskToTaskListWebController.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/AddNewTaskToTaskListWebController.java index 679b1e3..234dcde 100644 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/AddNewTaskToTaskListWebController.java +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/AddNewTaskToTaskListWebController.java @@ -55,15 +55,16 @@ public class AddNewTaskToTaskListWebController { (payload.getOriginalTaskUri() == null) ? Optional.empty() : Optional.of(new Task.OriginalTaskUri(payload.getOriginalTaskUri())); - Optional inputData = - (payload.getInputData() == null) ? Optional.empty() - : Optional.of(new Task.InputData(payload.getInputData())); - AddNewTaskToTaskListCommand command = new AddNewTaskToTaskListCommand(taskName, taskType, - originalTaskUriOptional, inputData); + originalTaskUriOptional); Task createdTask = addNewTaskToTaskListUseCase.addNewTaskToTaskList(command); + // When creating a task, the task's representation may include optional input data + if (payload.getInputData() != null) { + createdTask.setInputData(new Task.InputData(payload.getInputData())); + } + // Add the content type as a response header HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.add(HttpHeaders.CONTENT_TYPE, TaskJsonRepresentation.MEDIA_TYPE); @@ -78,8 +79,6 @@ public class AddNewTaskToTaskListWebController { throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); } catch (ConstraintViolationException e) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage()); - } catch (NullPointerException e) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage()); } } } diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/CompleteTaskWebController.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/CompleteTaskWebController.java deleted file mode 100644 index 02bdec3..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/CompleteTaskWebController.java +++ /dev/null @@ -1,53 +0,0 @@ -package ch.unisg.tapastasks.tasks.adapter.in.web; - -import ch.unisg.tapastasks.tasks.adapter.in.formats.TaskJsonRepresentation; -import ch.unisg.tapastasks.tasks.application.port.in.CompleteTaskCommand; -import ch.unisg.tapastasks.tasks.application.port.in.CompleteTaskUseCase; -import ch.unisg.tapastasks.tasks.domain.Task; -import com.fasterxml.jackson.core.JsonProcessingException; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -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.RequestBody; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; - -import javax.validation.ConstraintViolationException; - -@RestController -public class CompleteTaskWebController { - private final CompleteTaskUseCase completeTaskUseCase; - - public CompleteTaskWebController(CompleteTaskUseCase completeTaskUseCase){ - this.completeTaskUseCase = completeTaskUseCase; - } - - @PostMapping(path = "/tasks/completeTask") - public ResponseEntity completeTask (@RequestBody TaskJsonRepresentation payload) { - - System.out.println("completeTask"); - System.out.println(payload.getTaskId()); - - - try { - CompleteTaskCommand command = new CompleteTaskCommand( - new Task.TaskId(payload.getTaskId()), new Task.OutputData(payload.getOutputData()) - ); - - Task updateATask = completeTaskUseCase.completeTask(command); - - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.add(HttpHeaders.CONTENT_TYPE, TaskJsonRepresentation.MEDIA_TYPE); - - return new ResponseEntity<>(TaskJsonRepresentation.serialize(updateATask), responseHeaders, HttpStatus.ACCEPTED); - } catch (JsonProcessingException e) { - throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } catch (ConstraintViolationException e) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage()); - } - } -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/DeleteTaskWebController.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/DeleteTaskWebController.java deleted file mode 100644 index ef79e6a..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/DeleteTaskWebController.java +++ /dev/null @@ -1,52 +0,0 @@ -package ch.unisg.tapastasks.tasks.adapter.in.web; - - -import ch.unisg.tapastasks.tasks.adapter.in.formats.TaskJsonRepresentation; -import ch.unisg.tapastasks.tasks.application.port.in.DeleteTaskCommand; -import ch.unisg.tapastasks.tasks.application.port.in.DeleteTaskUseCase; -import ch.unisg.tapastasks.tasks.domain.Task; -import com.fasterxml.jackson.core.JsonProcessingException; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; - -import javax.validation.ConstraintViolationException; -import java.util.Optional; - -@RestController -public class DeleteTaskWebController { - private final DeleteTaskUseCase deleteClassUseCase; - - public DeleteTaskWebController(DeleteTaskUseCase deleteClassUseCase){ - this.deleteClassUseCase = deleteClassUseCase; - } - - @PostMapping(path="/tasks/deleteTask", consumes = {TaskJsonRepresentation.MEDIA_TYPE}) - public ResponseEntity deleteTask (@RequestBody Task task){ - try { - DeleteTaskCommand command = new DeleteTaskCommand(task.getTaskId(), task.getOriginalTaskUri()); - - Optional deleteATask = deleteClassUseCase.deleteTask(command); - - // Check if the task with the given identifier exists - if (deleteATask.isEmpty()) { - // If not, through a 404 Not Found status code - throw new ResponseStatusException(HttpStatus.NOT_FOUND); - } - - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.add(HttpHeaders.CONTENT_TYPE, TaskJsonRepresentation.MEDIA_TYPE); - - - return new ResponseEntity<>(TaskJsonRepresentation.serialize(deleteATask.get()), responseHeaders, HttpStatus.ACCEPTED); - } catch (JsonProcessingException e) { - throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } catch (ConstraintViolationException e) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage()); - } - } -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/TaskAssignedWebController.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/TaskAssignedWebController.java deleted file mode 100644 index 1bec71a..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/in/web/TaskAssignedWebController.java +++ /dev/null @@ -1,46 +0,0 @@ -package ch.unisg.tapastasks.tasks.adapter.in.web; - -import ch.unisg.tapastasks.tasks.adapter.in.formats.TaskJsonRepresentation; -import ch.unisg.tapastasks.tasks.application.port.in.TaskAssignedCommand; -import ch.unisg.tapastasks.tasks.application.port.in.TaskAssignedUseCase; -import ch.unisg.tapastasks.tasks.domain.Task; -import com.fasterxml.jackson.core.JsonProcessingException; -import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.server.ResponseStatusException; - -import javax.validation.ConstraintViolationException; - -@RestController -public class TaskAssignedWebController { - private final TaskAssignedUseCase taskAssignedUseCase; - - public TaskAssignedWebController(TaskAssignedUseCase taskAssignedUseCase){ - this.taskAssignedUseCase = taskAssignedUseCase; - } - - @PostMapping(path="/tasks/assignTask", consumes= {TaskJsonRepresentation.MEDIA_TYPE}) - public ResponseEntity assignTask(@RequestBody TaskJsonRepresentation payload) { - try{ - TaskAssignedCommand command = new TaskAssignedCommand( - new Task.TaskId(payload.getTaskId()) - ); - - Task updateATask = taskAssignedUseCase.assignTask(command); - - HttpHeaders responseHeaders = new HttpHeaders(); - responseHeaders.add(HttpHeaders.CONTENT_TYPE, TaskJsonRepresentation.MEDIA_TYPE); - - return new ResponseEntity<>(TaskJsonRepresentation.serialize(updateATask), responseHeaders, HttpStatus.ACCEPTED); - } catch (JsonProcessingException e) { - throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - } catch (ConstraintViolationException e) { - throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage()); - } - } - -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/MongoTaskDocument.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/MongoTaskDocument.java new file mode 100644 index 0000000..442e01e --- /dev/null +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/MongoTaskDocument.java @@ -0,0 +1,32 @@ +package ch.unisg.tapastasks.tasks.adapter.out.persistence.mongodb; + +import lombok.Data; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Data +@Document(collection = "tasks") +public class MongoTaskDocument { + + @Id + public String taskId; + + public String taskName; + public String taskType; + public String originalTaskUri; + public String taskStatus; + public String taskListName; + + + public MongoTaskDocument(String taskId, String taskName, String taskType, + String originalTaskUri, + String taskStatus, String taskListName) { + + this.taskId = taskId; + this.taskName = taskName; + this.taskType = taskType; + this.originalTaskUri = originalTaskUri; + this.taskStatus = taskStatus; + this.taskListName = taskListName; + } +} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskMapper.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskMapper.java new file mode 100644 index 0000000..0af73b6 --- /dev/null +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskMapper.java @@ -0,0 +1,30 @@ +package ch.unisg.tapastasks.tasks.adapter.out.persistence.mongodb; + +import ch.unisg.tapastasks.tasks.domain.Task; +import ch.unisg.tapastasks.tasks.domain.TaskList; +import org.springframework.stereotype.Component; + +@Component +class TaskMapper { + + Task mapToDomainEntity(MongoTaskDocument task) { + return Task.withIdNameTypeOriginaluriStatus( + new Task.TaskId(task.taskId), + new Task.TaskName(task.taskName), + new Task.TaskType(task.taskType), + new Task.OriginalTaskUri(task.originalTaskUri), + new Task.TaskStatus(Task.Status.valueOf(task.taskStatus)) + ); + } + + MongoTaskDocument mapToMongoDocument(Task task) { + return new MongoTaskDocument( + task.getTaskId().getValue(), + task.getTaskName().getValue(), + task.getTaskType().getValue(), + task.getOriginalTaskUri().getValue(), + task.getTaskStatus().getValue().toString(), + TaskList.getTapasTaskList().getTaskListName().getValue() + ); + } +} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskPersistenceAdapter.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskPersistenceAdapter.java new file mode 100644 index 0000000..beabf63 --- /dev/null +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskPersistenceAdapter.java @@ -0,0 +1,34 @@ +package ch.unisg.tapastasks.tasks.adapter.out.persistence.mongodb; + +import ch.unisg.tapastasks.tasks.application.port.out.AddTaskPort; +import ch.unisg.tapastasks.tasks.application.port.out.LoadTaskPort; +import ch.unisg.tapastasks.tasks.domain.Task; +import ch.unisg.tapastasks.tasks.domain.TaskList; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +@RequiredArgsConstructor +public class TaskPersistenceAdapter implements + AddTaskPort, + LoadTaskPort { + + @Autowired + private final TaskRepository taskRepository; + + private final TaskMapper taskMapper; + + @Override + public void addTask(Task task) { + MongoTaskDocument mongoTaskDocument = taskMapper.mapToMongoDocument(task); + taskRepository.save(mongoTaskDocument); + } + + @Override + public Task loadTask(Task.TaskId taskId, TaskList.TaskListName taskListName) { + MongoTaskDocument mongoTaskDocument = taskRepository.findByTaskId(taskId.getValue(),taskListName.getValue()); + Task task = taskMapper.mapToDomainEntity(mongoTaskDocument); + return task; + } +} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskRepository.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskRepository.java new file mode 100644 index 0000000..867671c --- /dev/null +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskRepository.java @@ -0,0 +1,14 @@ +package ch.unisg.tapastasks.tasks.adapter.out.persistence.mongodb; + +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public interface TaskRepository extends MongoRepository { + + public MongoTaskDocument findByTaskId(String taskId, String taskListName); + + public List findByTaskListName(String taskListName); +} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/web/CanTaskBeDeletedWebAdapter.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/web/CanTaskBeDeletedWebAdapter.java deleted file mode 100644 index a69f2e5..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/web/CanTaskBeDeletedWebAdapter.java +++ /dev/null @@ -1,60 +0,0 @@ -package ch.unisg.tapastasks.tasks.adapter.out.web; - - -import ch.unisg.tapastasks.tasks.application.port.out.CanTaskBeDeletedPort; -import ch.unisg.tapastasks.tasks.domain.DeleteTaskEvent; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; - -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.HashMap; - -@Component -@Primary -public class CanTaskBeDeletedWebAdapter implements CanTaskBeDeletedPort { - - @Value("${roster.uri}") - String server; - - @Override - public void canTaskBeDeletedEvent(DeleteTaskEvent event){ - - var values = new HashMap<> () {{ - put("taskId", event.taskId); - put("taskUri", event.taskUri); - }}; - - var objectMapper = new ObjectMapper(); - String requestBody = null; - try { - requestBody = objectMapper.writeValueAsString(values); - } catch (JsonProcessingException e){ - e.printStackTrace(); - } - - //Todo: Question: How do we include the URI from the DeleteTaskEvent? Do we even need it? - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(server+"task")) - .header("Content-Type", "application/task+json") - .POST(HttpRequest.BodyPublishers.ofString(requestBody)) - .build(); - - //Todo: The following parameters probably need to be changed to get the right error code - try { - HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); - } catch (IOException e){ - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/web/ExternalTaskExecutedWebAdapter.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/web/ExternalTaskExecutedWebAdapter.java deleted file mode 100644 index 4e18349..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/web/ExternalTaskExecutedWebAdapter.java +++ /dev/null @@ -1,74 +0,0 @@ -package ch.unisg.tapastasks.tasks.adapter.out.web; - -import java.io.IOException; -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.util.logging.Level; -import java.util.logging.Logger; - -import com.github.fge.jsonpatch.JsonPatch; -import com.github.fge.jsonpatch.JsonPatchOperation; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.springframework.context.annotation.Primary; -import org.springframework.stereotype.Component; - -import ch.unisg.tapastasks.tasks.adapter.in.formats.TaskJsonPatchRepresentation; -import ch.unisg.tapastasks.tasks.application.port.out.ExternalTaskExecutedEvent; -import ch.unisg.tapastasks.tasks.application.port.out.ExternalTaskExecutedEventHandler; - -@Component -@Primary -public class ExternalTaskExecutedWebAdapter implements ExternalTaskExecutedEventHandler { - - Logger logger = Logger.getLogger(ExternalTaskExecutedWebAdapter.class.getName()); - - /** - * Updates an external task which got executed in our system. - **/ - @Override - public void handleEvent(ExternalTaskExecutedEvent externalTaskExecutedEvent) { - - JSONObject op1; - JSONObject op2; - try { - op1 = new JSONObject() - .put("op", "replace") - .put("path", "/taskStatus") - .put("value", "EXECUTED"); - - op2 = new JSONObject() - .put("op", "add") - .put("path", "/outputData") - .put("value", "0"); - } catch (JSONException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - return; - } - - String body = new JSONArray().put(op1).put(op2).toString(); - - HttpClient client = HttpClient.newHttpClient(); - HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(externalTaskExecutedEvent.getOriginalTaskUri().getValue())) - .header("Content-Type", TaskJsonPatchRepresentation.MEDIA_TYPE) - .method("PATCH", HttpRequest.BodyPublishers.ofString(body)) - .build(); - - - try { - client.send(request, HttpResponse.BodyHandlers.ofString()); - } catch (InterruptedException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - Thread.currentThread().interrupt(); - } catch (IOException e) { - logger.log(Level.SEVERE, e.getLocalizedMessage(), e); - } - - } - -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/web/PublishNewTaskAddedEventWebAdapter.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/web/PublishNewTaskAddedEventWebAdapter.java index 53435d0..db02f2a 100644 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/web/PublishNewTaskAddedEventWebAdapter.java +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/adapter/out/web/PublishNewTaskAddedEventWebAdapter.java @@ -4,8 +4,6 @@ import ch.unisg.tapastasks.tasks.application.port.out.NewTaskAddedEventPort; import ch.unisg.tapastasks.tasks.domain.NewTaskAddedEvent; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; - -import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @@ -20,8 +18,8 @@ import java.util.HashMap; @Primary public class PublishNewTaskAddedEventWebAdapter implements NewTaskAddedEventPort { - @Value("${roster.uri}") - String server; + //This is the base URI of the service interested in this event (in my setup, running locally as separate Spring Boot application) + String server = "http://127.0.0.1:8082"; @Override public void publishNewTaskAddedEvent(NewTaskAddedEvent event) { @@ -29,9 +27,8 @@ public class PublishNewTaskAddedEventWebAdapter implements NewTaskAddedEventPort //Here we would need to work with DTOs in case the payload of calls becomes more complex var values = new HashMap() {{ - put("taskID", event.taskId); - put("taskType", event.taskType); - put("inputData", event.inputData); + put("taskname",event.taskName); + put("tasklist",event.taskListName); }}; var objectMapper = new ObjectMapper(); @@ -44,11 +41,11 @@ public class PublishNewTaskAddedEventWebAdapter implements NewTaskAddedEventPort HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(server+"/task")) - .header("Content-Type", "application/task+json") + .uri(URI.create(server+"/roster/newtask/")) .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .build(); + /** Needs the other service running try { HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); } catch (IOException e) { @@ -56,5 +53,6 @@ public class PublishNewTaskAddedEventWebAdapter implements NewTaskAddedEventPort } catch (InterruptedException e) { e.printStackTrace(); } + **/ } } diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/AddNewTaskToTaskListCommand.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/AddNewTaskToTaskListCommand.java index d307a1f..fbb66ed 100644 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/AddNewTaskToTaskListCommand.java +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/AddNewTaskToTaskListCommand.java @@ -19,19 +19,11 @@ public class AddNewTaskToTaskListCommand extends SelfValidating originalTaskUri; - @Getter - private final Optional inputData; - - public AddNewTaskToTaskListCommand( - Task.TaskName taskName, - Task.TaskType taskType, - Optional originalTaskUri, - Optional inputData - ) { + public AddNewTaskToTaskListCommand(Task.TaskName taskName, Task.TaskType taskType, + Optional originalTaskUri) { this.taskName = taskName; this.taskType = taskType; this.originalTaskUri = originalTaskUri; - this.inputData = inputData; this.validateSelf(); } diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/CompleteTaskCommand.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/CompleteTaskCommand.java deleted file mode 100644 index 238abd2..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/CompleteTaskCommand.java +++ /dev/null @@ -1,24 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.port.in; - -import ch.unisg.tapastasks.common.SelfValidating; -import ch.unisg.tapastasks.tasks.domain.Task.OutputData; -import ch.unisg.tapastasks.tasks.domain.Task.TaskId; -import ch.unisg.tapastasks.tasks.domain.Task.TaskResult; -import lombok.Value; - -import javax.validation.constraints.NotNull; - -@Value -public class CompleteTaskCommand extends SelfValidating { - @NotNull - private final TaskId taskId; - - @NotNull - private final OutputData outputData; - - public CompleteTaskCommand(TaskId taskId, OutputData outputData){ - this.taskId = taskId; - this.outputData = outputData; - this.validateSelf(); - } -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/CompleteTaskUseCase.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/CompleteTaskUseCase.java deleted file mode 100644 index 6fba7e6..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/CompleteTaskUseCase.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.port.in; - -import ch.unisg.tapastasks.tasks.domain.Task; - -public interface CompleteTaskUseCase { - Task completeTask(CompleteTaskCommand command); -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/DeleteTaskCommand.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/DeleteTaskCommand.java deleted file mode 100644 index b57c719..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/DeleteTaskCommand.java +++ /dev/null @@ -1,23 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.port.in; - -import ch.unisg.tapastasks.common.SelfValidating; -import ch.unisg.tapastasks.tasks.domain.Task.TaskId; -import ch.unisg.tapastasks.tasks.domain.Task.OriginalTaskUri; -import lombok.Value; - -import javax.validation.constraints.NotNull; - -@Value -public class DeleteTaskCommand extends SelfValidating { - @NotNull - private final TaskId taskId; - - @NotNull - private final OriginalTaskUri taskUri; - - public DeleteTaskCommand(TaskId taskId, OriginalTaskUri taskUri){ - this.taskId=taskId; - this.taskUri = taskUri; - this.validateSelf(); - } -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/DeleteTaskUseCase.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/DeleteTaskUseCase.java deleted file mode 100644 index 8ba206f..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/DeleteTaskUseCase.java +++ /dev/null @@ -1,9 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.port.in; - -import ch.unisg.tapastasks.tasks.domain.Task; - -import java.util.Optional; - -public interface DeleteTaskUseCase { - Optional deleteTask(DeleteTaskCommand command); -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/TaskAssignedCommand.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/TaskAssignedCommand.java deleted file mode 100644 index 7a5e383..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/TaskAssignedCommand.java +++ /dev/null @@ -1,18 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.port.in; - -import ch.unisg.tapastasks.common.SelfValidating; -import ch.unisg.tapastasks.tasks.domain.Task.TaskId; -import lombok.Value; - -import javax.validation.constraints.NotNull; - -@Value -public class TaskAssignedCommand extends SelfValidating { - @NotNull - private final TaskId taskId; - - public TaskAssignedCommand(TaskId taskId){ - this.taskId=taskId; - this.validateSelf(); - } -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/TaskAssignedUseCase.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/TaskAssignedUseCase.java deleted file mode 100644 index 3a84587..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/in/TaskAssignedUseCase.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.port.in; - -import ch.unisg.tapastasks.tasks.domain.Task; - -public interface TaskAssignedUseCase { - Task assignTask(TaskAssignedCommand command); -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/AddTaskPort.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/AddTaskPort.java new file mode 100644 index 0000000..b87795d --- /dev/null +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/AddTaskPort.java @@ -0,0 +1,9 @@ +package ch.unisg.tapastasks.tasks.application.port.out; + +import ch.unisg.tapastasks.tasks.domain.Task; + +public interface AddTaskPort { + + void addTask(Task task); + +} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/CanTaskBeDeletedPort.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/CanTaskBeDeletedPort.java deleted file mode 100644 index 67bde16..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/CanTaskBeDeletedPort.java +++ /dev/null @@ -1,7 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.port.out; - -import ch.unisg.tapastasks.tasks.domain.DeleteTaskEvent; - -public interface CanTaskBeDeletedPort { - void canTaskBeDeletedEvent(DeleteTaskEvent event); -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/ExternalTaskExecutedEvent.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/ExternalTaskExecutedEvent.java deleted file mode 100644 index 43bad47..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/ExternalTaskExecutedEvent.java +++ /dev/null @@ -1,28 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.port.out; - -import javax.validation.constraints.NotNull; - -import ch.unisg.tapastasks.common.SelfValidating; -import ch.unisg.tapastasks.tasks.domain.Task; -import lombok.Getter; -import lombok.Value; - -@Value -public class ExternalTaskExecutedEvent extends SelfValidating { - @NotNull - private final Task.TaskId taskId; - - @Getter - private final Task.OriginalTaskUri originalTaskUri; - - @Getter - private final Task.OutputData outputData; - - public ExternalTaskExecutedEvent(Task.TaskId taskId, Task.OriginalTaskUri originalTaskUri, Task.OutputData outputData) { - this.taskId = taskId; - this.originalTaskUri = originalTaskUri; - this.outputData = outputData; - - this.validateSelf(); - } -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/ExternalTaskExecutedEventHandler.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/ExternalTaskExecutedEventHandler.java deleted file mode 100644 index 90bff49..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/ExternalTaskExecutedEventHandler.java +++ /dev/null @@ -1,5 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.port.out; - -public interface ExternalTaskExecutedEventHandler { - void handleEvent(ExternalTaskExecutedEvent externalTaskExecutedEvent); -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/LoadTaskPort.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/LoadTaskPort.java new file mode 100644 index 0000000..acca3c0 --- /dev/null +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/LoadTaskPort.java @@ -0,0 +1,10 @@ +package ch.unisg.tapastasks.tasks.application.port.out; + +import ch.unisg.tapastasks.tasks.domain.Task; +import ch.unisg.tapastasks.tasks.domain.TaskList; + +public interface LoadTaskPort { + + Task loadTask(Task.TaskId taskId, TaskList.TaskListName taskListName); + +} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/TaskListLock.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/TaskListLock.java new file mode 100644 index 0000000..802abba --- /dev/null +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/port/out/TaskListLock.java @@ -0,0 +1,11 @@ +package ch.unisg.tapastasks.tasks.application.port.out; + +import ch.unisg.tapastasks.tasks.domain.TaskList; + +public interface TaskListLock { + + void lockTaskList(TaskList.TaskListName taskListName); + + void releaseTaskList(TaskList.TaskListName taskListName); + +} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/AddNewTaskToTaskListService.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/AddNewTaskToTaskListService.java index d7b9740..9776064 100644 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/AddNewTaskToTaskListService.java +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/AddNewTaskToTaskListService.java @@ -2,40 +2,43 @@ package ch.unisg.tapastasks.tasks.application.service; import ch.unisg.tapastasks.tasks.application.port.in.AddNewTaskToTaskListCommand; import ch.unisg.tapastasks.tasks.application.port.in.AddNewTaskToTaskListUseCase; +import ch.unisg.tapastasks.tasks.application.port.out.AddTaskPort; import ch.unisg.tapastasks.tasks.application.port.out.NewTaskAddedEventPort; +import ch.unisg.tapastasks.tasks.application.port.out.TaskListLock; import ch.unisg.tapastasks.tasks.domain.Task; import ch.unisg.tapastasks.tasks.domain.NewTaskAddedEvent; import ch.unisg.tapastasks.tasks.domain.TaskList; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; + import javax.transaction.Transactional; @RequiredArgsConstructor @Component @Transactional +@Service("AddNewTaskToTaskList") public class AddNewTaskToTaskListService implements AddNewTaskToTaskListUseCase { private final NewTaskAddedEventPort newTaskAddedEventPort; + private final AddTaskPort addTaskToRepositoryPort; + private final TaskListLock taskListLock; @Override public Task addNewTaskToTaskList(AddNewTaskToTaskListCommand command) { TaskList taskList = TaskList.getTapasTaskList(); - Task newTask; + taskListLock.lockTaskList(taskList.getTaskListName()); + Task newTask = (command.getOriginalTaskUri().isPresent()) ? + // Create a delegated task that points back to the original task + taskList.addNewTaskWithNameAndTypeAndOriginalTaskUri(command.getTaskName(), + command.getTaskType(), command.getOriginalTaskUri().get()) + // Create an original task + : taskList.addNewTaskWithNameAndType(command.getTaskName(), command.getTaskType()); - if (command.getOriginalTaskUri().isPresent() && command.getInputData().isPresent()) { - newTask = taskList.addNewTaskWithNameAndTypeAndOriginalTaskUriAndInputData(command.getTaskName(), - command.getTaskType(), command.getOriginalTaskUri().get(), command.getInputData().get()); - } else if (command.getOriginalTaskUri().isPresent()) { - newTask = taskList.addNewTaskWithNameAndTypeAndOriginalTaskUri(command.getTaskName(), - command.getTaskType(), command.getOriginalTaskUri().get()); - } else if (command.getInputData().isPresent()) { - newTask = taskList.addNewTaskWithNameAndTypeAndInputData(command.getTaskName(), - command.getTaskType(), command.getInputData().get()); - } else { - newTask = taskList.addNewTaskWithNameAndType(command.getTaskName(), command.getTaskType()); - } + addTaskToRepositoryPort.addTask(newTask); + taskListLock.releaseTaskList(taskList.getTaskListName()); //Here we are using the application service to emit the domain event to the outside of the bounded context. //This event should be considered as a light-weight "integration event" to communicate with other services. @@ -43,13 +46,8 @@ public class AddNewTaskToTaskListService implements AddNewTaskToTaskListUseCase //not recommended to emit a domain event via an application service! You should first emit the domain event in //the core and then the integration event in the application layer. if (newTask != null) { - NewTaskAddedEvent newTaskAdded = new NewTaskAddedEvent( - newTask.getTaskName().getValue(), - taskList.getTaskListName().getValue(), - newTask.getTaskId().getValue(), - newTask.getTaskType().getValue(), - newTask.getInputData().getValue() - ); + NewTaskAddedEvent newTaskAdded = new NewTaskAddedEvent(newTask.getTaskName().getValue(), + taskList.getTaskListName().getValue()); newTaskAddedEventPort.publishNewTaskAddedEvent(newTaskAdded); } diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/CompleteTaskService.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/CompleteTaskService.java deleted file mode 100644 index 8ded0ea..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/CompleteTaskService.java +++ /dev/null @@ -1,43 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.service; - -import ch.unisg.tapastasks.tasks.application.port.in.CompleteTaskCommand; -import ch.unisg.tapastasks.tasks.application.port.in.CompleteTaskUseCase; -import ch.unisg.tapastasks.tasks.application.port.out.ExternalTaskExecutedEvent; -import ch.unisg.tapastasks.tasks.application.port.out.ExternalTaskExecutedEventHandler; -import ch.unisg.tapastasks.tasks.domain.Task; -import ch.unisg.tapastasks.tasks.domain.Task.*; -import ch.unisg.tapastasks.tasks.domain.TaskList; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import javax.transaction.Transactional; -import java.util.Optional; - -@RequiredArgsConstructor -@Component -@Transactional -public class CompleteTaskService implements CompleteTaskUseCase { - - private final ExternalTaskExecutedEventHandler externalTaskExecutedEventHandler; - - @Override - public Task completeTask(CompleteTaskCommand command){ - TaskList taskList = TaskList.getTapasTaskList(); - Optional updatedTask = taskList.retrieveTaskById(command.getTaskId()); - - Task newTask = updatedTask.get(); - newTask.setOutputData(command.getOutputData()); - newTask.setTaskStatus(new TaskStatus(Task.Status.EXECUTED)); - - if (newTask.getOriginalTaskUri() != null) { - ExternalTaskExecutedEvent event = new ExternalTaskExecutedEvent( - newTask.getTaskId(), - newTask.getOriginalTaskUri(), - newTask.getOutputData() - ); - externalTaskExecutedEventHandler.handleEvent(event); - } - - return newTask; - } -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/DeleteTaskService.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/DeleteTaskService.java deleted file mode 100644 index 35685a3..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/DeleteTaskService.java +++ /dev/null @@ -1,33 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.service; - - -import ch.unisg.tapastasks.tasks.application.port.in.DeleteTaskCommand; -import ch.unisg.tapastasks.tasks.application.port.in.DeleteTaskUseCase; -import ch.unisg.tapastasks.tasks.domain.Task; -import ch.unisg.tapastasks.tasks.domain.TaskList; -import jdk.jshell.spi.ExecutionControl; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import javax.transaction.Transactional; -import java.util.Optional; - -@RequiredArgsConstructor -@Component -@Transactional -public class DeleteTaskService implements DeleteTaskUseCase { - - @Override - public Optional deleteTask(DeleteTaskCommand command){ - - TaskList taskList = TaskList.getTapasTaskList(); - Optional updatedTask = taskList.retrieveTaskById(command.getTaskId()); - Task newTask = updatedTask.get(); - // TODO: Fill in the right condition into the if-statement and the else-statement - if (true){ - return taskList.deleteTaskById(command.getTaskId()); - } - // TODO Handle with a return message - return Optional.empty(); - } -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/NoOpTaskListLock.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/NoOpTaskListLock.java new file mode 100644 index 0000000..783dca1 --- /dev/null +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/NoOpTaskListLock.java @@ -0,0 +1,18 @@ +package ch.unisg.tapastasks.tasks.application.service; + +import ch.unisg.tapastasks.tasks.application.port.out.TaskListLock; +import ch.unisg.tapastasks.tasks.domain.TaskList; +import org.springframework.stereotype.Component; + +@Component +public class NoOpTaskListLock implements TaskListLock { + @Override + public void lockTaskList(TaskList.TaskListName taskListName) { + //do nothing + } + + @Override + public void releaseTaskList(TaskList.TaskListName taskListName) { + //do nothing + } +} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/RetrieveTaskFromTaskListService.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/RetrieveTaskFromTaskListService.java index fd6aea5..39026f5 100644 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/RetrieveTaskFromTaskListService.java +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/RetrieveTaskFromTaskListService.java @@ -2,10 +2,12 @@ package ch.unisg.tapastasks.tasks.application.service; import ch.unisg.tapastasks.tasks.application.port.in.RetrieveTaskFromTaskListQuery; import ch.unisg.tapastasks.tasks.application.port.in.RetrieveTaskFromTaskListUseCase; +import ch.unisg.tapastasks.tasks.application.port.out.LoadTaskPort; import ch.unisg.tapastasks.tasks.domain.Task; import ch.unisg.tapastasks.tasks.domain.TaskList; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.util.Optional; @@ -13,10 +15,19 @@ import java.util.Optional; @RequiredArgsConstructor @Component @Transactional +@Service("RetrieveTaskFromTaskList") public class RetrieveTaskFromTaskListService implements RetrieveTaskFromTaskListUseCase { + + private final LoadTaskPort loadTaskFromRepositoryPort; + @Override public Optional retrieveTaskFromTaskList(RetrieveTaskFromTaskListQuery query) { TaskList taskList = TaskList.getTapasTaskList(); - return taskList.retrieveTaskById(query.getTaskId()); + + Optional task = taskList.retrieveTaskById(query.getTaskId()); + + Optional taskFromRepo = Optional.ofNullable(loadTaskFromRepositoryPort.loadTask(query.getTaskId(), taskList.getTaskListName())); + + return taskFromRepo; } } diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/TaskAssignedService.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/TaskAssignedService.java deleted file mode 100644 index fc13db3..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/application/service/TaskAssignedService.java +++ /dev/null @@ -1,31 +0,0 @@ -package ch.unisg.tapastasks.tasks.application.service; - -import ch.unisg.tapastasks.tasks.application.port.in.TaskAssignedCommand; -import ch.unisg.tapastasks.tasks.application.port.in.TaskAssignedUseCase; -import ch.unisg.tapastasks.tasks.domain.Task; -import ch.unisg.tapastasks.tasks.domain.Task.*; -import ch.unisg.tapastasks.tasks.domain.TaskList; -import lombok.RequiredArgsConstructor; -import org.springframework.stereotype.Component; - -import javax.transaction.Transactional; -import java.util.Optional; - -@RequiredArgsConstructor -@Component -@Transactional -public class TaskAssignedService implements TaskAssignedUseCase { - - @Override - public Task assignTask(TaskAssignedCommand command) { - // retrieve the task based on ID - TaskList taskList = TaskList.getTapasTaskList(); - Optional task = taskList.retrieveTaskById(command.getTaskId()); - - // update the status to assigned - Task updatedTask = task.get(); - updatedTask.setTaskStatus(new TaskStatus(Status.ASSIGNED)); - - return updatedTask; - } -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/DeleteTaskEvent.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/DeleteTaskEvent.java deleted file mode 100644 index 16e803b..0000000 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/DeleteTaskEvent.java +++ /dev/null @@ -1,11 +0,0 @@ -package ch.unisg.tapastasks.tasks.domain; - -public class DeleteTaskEvent { - public String taskId; - public String taskUri; - - public DeleteTaskEvent(String taskId, String taskUri){ - this.taskId = taskId; - this.taskUri = taskUri; - } -} diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/NewTaskAddedEvent.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/NewTaskAddedEvent.java index 049c2fb..32f5966 100644 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/NewTaskAddedEvent.java +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/NewTaskAddedEvent.java @@ -4,16 +4,9 @@ package ch.unisg.tapastasks.tasks.domain; public class NewTaskAddedEvent { public String taskName; public String taskListName; - public String taskId; - public String taskType; - public String inputData; - public NewTaskAddedEvent(String taskName, String taskListName, String taskId, String taskType, String inputData) { + public NewTaskAddedEvent(String taskName, String taskListName) { this.taskName = taskName; this.taskListName = taskListName; - this.taskId = taskId; - this.taskType = taskType; - this.inputData = inputData; } - } diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/Task.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/Task.java index aca71dd..7a02976 100644 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/Task.java +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/Task.java @@ -21,12 +21,12 @@ public class Task { @Getter private final TaskType taskType; - @Getter @Setter - private TaskStatus taskStatus; - @Getter private final OriginalTaskUri originalTaskUri; + @Getter @Setter + private TaskStatus taskStatus; + @Getter @Setter private ServiceProvider provider; @@ -36,68 +36,51 @@ public class Task { @Getter @Setter private OutputData outputData; - public Task(TaskName taskName, TaskType taskType) { - this.taskName = taskName; - this.taskType = taskType; - this.taskStatus = new TaskStatus(Status.OPEN); - this.taskId = new TaskId(UUID.randomUUID().toString()); - this.originalTaskUri = null; - - this.inputData = null; - this.outputData = null; - } - public Task(TaskName taskName, TaskType taskType, OriginalTaskUri taskUri) { + this.taskId = new TaskId(UUID.randomUUID().toString()); + this.taskName = taskName; this.taskType = taskType; - this.taskStatus = new TaskStatus(Status.OPEN); - this.taskId = new TaskId(UUID.randomUUID().toString()); this.originalTaskUri = taskUri; + this.taskStatus = new TaskStatus(Status.OPEN); + this.inputData = null; this.outputData = null; } - public Task(TaskName taskName, TaskType taskType, InputData inputData) { + //Constructor from repo + public Task(TaskId taskId, TaskName taskName, TaskType taskType, OriginalTaskUri taskUri, + TaskStatus taskStatus) { + this.taskId = taskId; this.taskName = taskName; this.taskType = taskType; - this.taskStatus = new TaskStatus(Status.OPEN); - this.taskId = new TaskId(UUID.randomUUID().toString()); - this.originalTaskUri = null; - - this.inputData = inputData; - this.outputData = null; - } - - public Task(TaskName taskName, TaskType taskType, OriginalTaskUri taskUri, InputData inputData) { - this.taskName = taskName; - this.taskType = taskType; - this.taskStatus = new TaskStatus(Status.OPEN); - this.taskId = new TaskId(UUID.randomUUID().toString()); this.originalTaskUri = taskUri; - - this.inputData = inputData; + this.taskStatus = taskStatus; + this.inputData = null; this.outputData = null; } - protected static Task createTaskWithNameAndType(TaskName name, TaskType type) { - return new Task(name, type); + + public static Task createTaskWithNameAndType(TaskName name, TaskType type) { + //This is a simple debug message to see that the request has reached the right method in the core + System.out.println("New Task: " + name.getValue() + " " + type.getValue()); + return new Task(name, type, null); } - protected static Task createTaskWithNameAndTypeAndOriginalTaskUri(TaskName name, TaskType type, + public static Task createTaskWithNameAndTypeAndOriginalTaskUri(TaskName name, TaskType type, OriginalTaskUri originalTaskUri) { return new Task(name, type, originalTaskUri); } - protected static Task createTaskWithNameAndTypeAndInputData(TaskName name, TaskType type, - InputData inputData) { - return new Task(name, type, inputData); + //This is for recreating a task from a repository. + public static Task withIdNameTypeOriginaluriStatus(TaskId taskId, TaskName taskName, + TaskType taskType, + OriginalTaskUri originalTaskUri, + TaskStatus taskStatus) { + return new Task(taskId, taskName, taskType, originalTaskUri, taskStatus); } - protected static Task createTaskWithNameAndTypeAndOriginalTaskUriAndInputData(TaskName name, TaskType type, - OriginalTaskUri originalTaskUri, InputData inputData) { - return new Task(name, type, originalTaskUri, inputData); - } @Value public static class TaskId { @@ -138,9 +121,4 @@ public class Task { public static class OutputData { String value; } - - @Value - public static class TaskResult{ - private String value; - } } diff --git a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/TaskList.java b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/TaskList.java index 5c2913d..4a52c62 100644 --- a/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/TaskList.java +++ b/tapas-tasks/src/main/java/ch/unisg/tapastasks/tasks/domain/TaskList.java @@ -6,15 +6,11 @@ import lombok.Value; import java.util.LinkedList; import java.util.List; import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; /**This is our aggregate root**/ public class TaskList { - Logger logger = Logger.getLogger(TaskList.class.getName()); - @Getter private final TaskListName taskListName; @@ -23,8 +19,8 @@ public class TaskList { //Note: We do not care about the management of task lists, there is only one within this service //--> using the Singleton pattern here to make lives easy; we will later load it from a repo - - private static final TaskList taskList = new TaskList(new TaskListName("tapas-tasks-group1")); + //TODO: change "tutors" to your group name ("groupx") + private static final TaskList taskList = new TaskList(new TaskListName("tapas-tasks-tutors")); private TaskList(TaskListName taskListName) { this.taskListName = taskListName; @@ -52,32 +48,13 @@ public class TaskList { return newTask; } - public Task addNewTaskWithNameAndTypeAndInputData(Task.TaskName name, Task.TaskType type, - Task.InputData inputData) { - Task newTask = Task.createTaskWithNameAndTypeAndInputData(name, type, inputData); - this.addNewTaskToList(newTask); - - return newTask; - } - - public Task addNewTaskWithNameAndTypeAndOriginalTaskUriAndInputData(Task.TaskName name, Task.TaskType type, - Task.OriginalTaskUri originalTaskUri, Task.InputData inputData) { - Task newTask = Task.createTaskWithNameAndTypeAndOriginalTaskUriAndInputData(name, type, originalTaskUri, inputData); - this.addNewTaskToList(newTask); - - return newTask; - } - - private void addNewTaskToList(Task newTask) { //Here we would also publish a domain event to other entities in the core interested in this event. //However, we skip this here as it makes the core even more complex (e.g., we have to implement a light-weight //domain event publisher and subscribers (see "Implementing Domain-Driven Design by V. Vernon, pp. 296ff). listOfTasks.value.add(newTask); - logger.log(Level.INFO, "New task created! Id: " + newTask.getTaskId().getValue() + - " | Name: " + newTask.getTaskName().getValue() + - " | InputData: " + newTask.getInputData().getValue()); - logger.log(Level.INFO, "Number of tasks: {0}", listOfTasks.value.size()); + //This is a simple debug message to see that the task list is growing with each new request + System.out.println("Number of tasks: " + listOfTasks.value.size()); } public Optional retrieveTaskById(Task.TaskId id) { @@ -90,52 +67,42 @@ public class TaskList { return Optional.empty(); } - public Optional deleteTaskById(Task.TaskId id) { - for (Task task : listOfTasks.value) { - if (task.getTaskId().getValue().equalsIgnoreCase(id.getValue())) { - listOfTasks.value.remove(task); - return Optional.of(task); - } + public Task changeTaskStatusToAssigned(Task.TaskId id, Optional serviceProvider) + throws TaskNotFoundException { + return changeTaskStatus(id, new Task.TaskStatus(Task.Status.ASSIGNED), serviceProvider, Optional.empty()); + } + + public Task changeTaskStatusToRunning(Task.TaskId id, Optional serviceProvider) + throws TaskNotFoundException { + return changeTaskStatus(id, new Task.TaskStatus(Task.Status.RUNNING), serviceProvider, Optional.empty()); + } + + public Task changeTaskStatusToExecuted(Task.TaskId id, Optional serviceProvider, + Optional outputData) throws TaskNotFoundException { + return changeTaskStatus(id, new Task.TaskStatus(Task.Status.EXECUTED), serviceProvider, outputData); + } + + private Task changeTaskStatus(Task.TaskId id, Task.TaskStatus status, Optional serviceProvider, + Optional outputData) { + Optional taskOpt = retrieveTaskById(id); + + if (taskOpt.isEmpty()) { + throw new TaskNotFoundException(); } - return Optional.empty(); + Task task = taskOpt.get(); + task.setTaskStatus(status); + + if (serviceProvider.isPresent()) { + task.setProvider(serviceProvider.get()); + } + + if (outputData.isPresent()) { + task.setOutputData(outputData.get()); + } + + return task; } - public Task changeTaskStatusToAssigned(Task.TaskId id, Optional serviceProvider) - throws TaskNotFoundException { - return changeTaskStatus(id, new Task.TaskStatus(Task.Status.ASSIGNED), serviceProvider, Optional.empty()); - } - - public Task changeTaskStatusToRunning(Task.TaskId id, Optional serviceProvider) - throws TaskNotFoundException { - return changeTaskStatus(id, new Task.TaskStatus(Task.Status.RUNNING), serviceProvider, Optional.empty()); - } - - public Task changeTaskStatusToExecuted(Task.TaskId id, Optional serviceProvider, - Optional outputData) throws TaskNotFoundException { - return changeTaskStatus(id, new Task.TaskStatus(Task.Status.EXECUTED), serviceProvider, outputData); - } - - private Task changeTaskStatus(Task.TaskId id, Task.TaskStatus status, Optional serviceProvider, - Optional outputData) { - Optional taskOpt = retrieveTaskById(id); - - if (taskOpt.isEmpty()) { - throw new TaskNotFoundException(); - } - - Task task = taskOpt.get(); - task.setTaskStatus(status); - - if (serviceProvider.isPresent()) { - task.setProvider(serviceProvider.get()); - } - - if (outputData.isPresent()) { - task.setOutputData(outputData.get()); - } - - return task; - } @Value public static class TaskListName { diff --git a/tapas-tasks/src/main/resources/application.properties b/tapas-tasks/src/main/resources/application.properties index 485e4e7..7588f89 100644 --- a/tapas-tasks/src/main/resources/application.properties +++ b/tapas-tasks/src/main/resources/application.properties @@ -1,3 +1,38 @@ server.port=8081 +spring.data.mongodb.uri=mongodb://127.0.0.1:27017 +#spring.data.mongodb.uri=mongodb://root:8nP7s0a@mongodb:27017/ +spring.data.mongodb.database=tapas-tasks baseuri=https://tapas-tasks.86-119-34-23.nip.io/ -roster.uri=http://127.0.0.1:8082 + +spring.profiles.active=chaos-monkey +chaos.monkey.enabled=true +management.endpoint.chaosmonkey.enabled=true +management.endpoint.chaosmonkeyjmx.enabled=true +# include specific endpoints +management.endpoints.web.exposure.include=health,info,chaosmonkey +chaos.monkey.watcher.controller=true +chaos.monkey.watcher.restController=true +chaos.monkey.watcher.service=true +chaos.monkey.watcher.repository=true +chaos.monkey.watcher.component=true + +#Chaos Monkey configs taken from here: https://www.baeldung.com/spring-boot-chaos-monkey + +#Latency Assault +#chaos.monkey.assaults.latencyActive=true +#chaos.monkey.assaults.latencyRangeStart=3000 +#chaos.monkey.assaults.latencyRangeEnd=15000 + +#Exception Assault +#chaos.monkey.assaults.latencyActive=false +#chaos.monkey.assaults.exceptionsActive=true +#chaos.monkey.assaults.killApplicationActive=false + +#AppKiller Assault +#chaos.monkey.assaults.latencyActive=false +#chaos.monkey.assaults.exceptionsActive=false +#chaos.monkey.assaults.killApplicationActive=true + +#Chaos Monkey assaults via REST to endpoint /actuator/chaosmonkey/assaults/ +#https://softwarehut.com/blog/tech/chaos-monkey +#https://codecentric.github.io/chaos-monkey-spring-boot/latest/ diff --git a/tapas-tasks/src/test/java/ch/unisg/tapastasks/AddNewTaskToTaskListSystemTest.java b/tapas-tasks/src/test/java/ch/unisg/tapastasks/AddNewTaskToTaskListSystemTest.java new file mode 100644 index 0000000..e17c2e2 --- /dev/null +++ b/tapas-tasks/src/test/java/ch/unisg/tapastasks/AddNewTaskToTaskListSystemTest.java @@ -0,0 +1,76 @@ +package ch.unisg.tapastasks; + +import ch.unisg.tapastasks.tasks.adapter.in.formats.TaskJsonRepresentation; +import ch.unisg.tapastasks.tasks.application.port.out.AddTaskPort; +import ch.unisg.tapastasks.tasks.domain.Task; +import ch.unisg.tapastasks.tasks.domain.TaskList; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.http.*; + +import static org.assertj.core.api.BDDAssertions.*; + + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class AddNewTaskToTaskListSystemTest { + + @Autowired + private TestRestTemplate restTemplate; + + @Autowired + private AddTaskPort addTaskPort; + + @Test + void addNewTaskToTaskList() throws JSONException { + + Task.TaskName taskName = new Task.TaskName("system-integration-test-task"); + Task.TaskType taskType = new Task.TaskType("system-integration-test-type"); + Task.OriginalTaskUri originalTaskUri = new Task.OriginalTaskUri("example.org"); + + ResponseEntity response = whenAddNewTaskToEmptyList(taskName, taskType, originalTaskUri); + + JSONObject responseJson = new JSONObject(response.getBody().toString()); + String respTaskId = responseJson.getString("taskId"); + String respTaskName = responseJson.getString("taskName"); + String respTaskType = responseJson.getString("taskType"); + + then(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); + then(respTaskId).isNotEmpty(); + then(respTaskName).isEqualTo(taskName.getValue()); + then(respTaskType).isEqualTo(taskType.getValue()); + then(TaskList.getTapasTaskList().getListOfTasks().getValue()).hasSize(1); + + } + + private ResponseEntity whenAddNewTaskToEmptyList( + Task.TaskName taskName, + Task.TaskType taskType, + Task.OriginalTaskUri originalTaskUri) throws JSONException { + + TaskList.getTapasTaskList().getListOfTasks().getValue().clear(); + + HttpHeaders headers = new HttpHeaders(); + headers.add("Content-Type", TaskJsonRepresentation.MEDIA_TYPE); + + String jsonPayLoad = new JSONObject() + .put("taskName", taskName.getValue() ) + .put("taskType", taskType.getValue()) + .put("originalTaskUri",originalTaskUri.getValue()) + .toString(); + + HttpEntity request = new HttpEntity<>(jsonPayLoad,headers); + + return restTemplate.exchange( + "/tasks/", + HttpMethod.POST, + request, + Object.class + ); + + } + +} diff --git a/tapas-tasks/src/test/java/ch/unisg/tapastasks/DependencyRuleTests.java b/tapas-tasks/src/test/java/ch/unisg/tapastasks/DependencyRuleTests.java new file mode 100644 index 0000000..0d26f37 --- /dev/null +++ b/tapas-tasks/src/test/java/ch/unisg/tapastasks/DependencyRuleTests.java @@ -0,0 +1,24 @@ +package ch.unisg.tapastasks; + +import ch.unisg.tapastasks.archunit.HexagonalArchitecture; +import com.tngtech.archunit.core.importer.ClassFileImporter; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; + +class DependencyRuleTests { + + @Test + void testPackageDependencies() { + noClasses() + .that() + .resideInAPackage("ch.unisg.tapastasks.tasks.domain..") + .should() + .dependOnClassesThat() + .resideInAnyPackage("ch.unisg.tapastasks.tasks.application..") + .check(new ClassFileImporter() + .importPackages("ch.unisg.tapastasks.tasks..")); + } + +} diff --git a/tapas-tasks/src/test/java/ch/unisg/tapastasks/TapasTasksApplicationTests.java b/tapas-tasks/src/test/java/ch/unisg/tapastasks/TapasTasksApplicationTests.java index b96cb8b..a343151 100644 --- a/tapas-tasks/src/test/java/ch/unisg/tapastasks/TapasTasksApplicationTests.java +++ b/tapas-tasks/src/test/java/ch/unisg/tapastasks/TapasTasksApplicationTests.java @@ -1,13 +1,18 @@ package ch.unisg.tapastasks; +import ch.unisg.tapastasks.tasks.application.port.out.AddTaskPort; +import ch.unisg.tapastasks.tasks.application.port.out.NewTaskAddedEventPort; +import ch.unisg.tapastasks.tasks.application.port.out.TaskListLock; +import ch.unisg.tapastasks.tasks.application.service.AddNewTaskToTaskListService; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class TapasTasksApplicationTests { - @Test + @Test void contextLoads() { + } } diff --git a/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/Adapters.java b/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/Adapters.java new file mode 100644 index 0000000..92a764b --- /dev/null +++ b/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/Adapters.java @@ -0,0 +1,62 @@ +package ch.unisg.tapastasks.archunit; + +import com.tngtech.archunit.core.domain.JavaClasses; + +import java.util.ArrayList; +import java.util.List; + +public class Adapters extends ArchitectureElement { + + private final HexagonalArchitecture parentContext; + private List incomingAdapterPackages = new ArrayList<>(); + private List outgoingAdapterPackages = new ArrayList<>(); + + Adapters(HexagonalArchitecture parentContext, String basePackage) { + super(basePackage); + this.parentContext = parentContext; + } + + public Adapters outgoing(String packageName) { + this.incomingAdapterPackages.add(fullQualifiedPackage(packageName)); + return this; + } + + public Adapters incoming(String packageName) { + this.outgoingAdapterPackages.add(fullQualifiedPackage(packageName)); + return this; + } + + List allAdapterPackages() { + List allAdapters = new ArrayList<>(); + allAdapters.addAll(incomingAdapterPackages); + allAdapters.addAll(outgoingAdapterPackages); + return allAdapters; + } + + public HexagonalArchitecture and() { + return parentContext; + } + + String getBasePackage() { + return basePackage; + } + + void dontDependOnEachOther(JavaClasses classes) { + List allAdapters = allAdapterPackages(); + for (String adapter1 : allAdapters) { + for (String adapter2 : allAdapters) { + if (!adapter1.equals(adapter2)) { + denyDependency(adapter1, adapter2, classes); + } + } + } + } + + void doesNotDependOn(String packageName, JavaClasses classes) { + denyDependency(this.basePackage, packageName, classes); + } + + void doesNotContainEmptyPackages() { + denyEmptyPackages(allAdapterPackages()); + } +} diff --git a/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/ApplicationLayer.java b/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/ApplicationLayer.java new file mode 100644 index 0000000..e8e00a5 --- /dev/null +++ b/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/ApplicationLayer.java @@ -0,0 +1,59 @@ +package ch.unisg.tapastasks.archunit; + +import com.tngtech.archunit.core.domain.JavaClasses; + +import java.util.ArrayList; +import java.util.List; + +public class ApplicationLayer extends ArchitectureElement { + + private final HexagonalArchitecture parentContext; + private List incomingPortsPackages = new ArrayList<>(); + private List outgoingPortsPackages = new ArrayList<>(); + private List servicePackages = new ArrayList<>(); + + public ApplicationLayer(String basePackage, HexagonalArchitecture parentContext) { + super(basePackage); + this.parentContext = parentContext; + } + + public ApplicationLayer incomingPorts(String packageName) { + this.incomingPortsPackages.add(fullQualifiedPackage(packageName)); + return this; + } + + public ApplicationLayer outgoingPorts(String packageName) { + this.outgoingPortsPackages.add(fullQualifiedPackage(packageName)); + return this; + } + + public ApplicationLayer services(String packageName) { + this.servicePackages.add(fullQualifiedPackage(packageName)); + return this; + } + + public HexagonalArchitecture and() { + return parentContext; + } + + public void doesNotDependOn(String packageName, JavaClasses classes) { + denyDependency(this.basePackage, packageName, classes); + } + + public void incomingAndOutgoingPortsDoNotDependOnEachOther(JavaClasses classes) { + denyAnyDependency(this.incomingPortsPackages, this.outgoingPortsPackages, classes); + denyAnyDependency(this.outgoingPortsPackages, this.incomingPortsPackages, classes); + } + + private List allPackages() { + List allPackages = new ArrayList<>(); + allPackages.addAll(incomingPortsPackages); + allPackages.addAll(outgoingPortsPackages); + allPackages.addAll(servicePackages); + return allPackages; + } + + void doesNotContainEmptyPackages() { + denyEmptyPackages(allPackages()); + } +} diff --git a/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/ArchitectureElement.java b/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/ArchitectureElement.java new file mode 100644 index 0000000..465f441 --- /dev/null +++ b/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/ArchitectureElement.java @@ -0,0 +1,74 @@ +package ch.unisg.tapastasks.archunit; + +import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.importer.ClassFileImporter; + +import java.util.List; + +import static com.tngtech.archunit.base.DescribedPredicate.*; +import static com.tngtech.archunit.base.DescribedPredicate.greaterThanOrEqualTo; +import static com.tngtech.archunit.lang.conditions.ArchConditions.*; +import static com.tngtech.archunit.lang.conditions.ArchConditions.containNumberOfElements; +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.*; +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes; +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; + +abstract class ArchitectureElement { + + final String basePackage; + + public ArchitectureElement(String basePackage) { + this.basePackage = basePackage; + } + + String fullQualifiedPackage(String relativePackage) { + return this.basePackage + "." + relativePackage; + } + + static void denyDependency(String fromPackageName, String toPackageName, JavaClasses classes) { + noClasses() + .that() + .resideInAPackage("ch.unisg.tapastasks.tasks.domain..") + .should() + .dependOnClassesThat() + .resideInAnyPackage("ch.unisg.tapastasks.tasks.application..") + .check(classes); + } + + static void denyAnyDependency( + List fromPackages, List toPackages, JavaClasses classes) { + for (String fromPackage : fromPackages) { + for (String toPackage : toPackages) { + noClasses() + .that() + .resideInAPackage(matchAllClassesInPackage(fromPackage)) + .should() + .dependOnClassesThat() + .resideInAnyPackage(matchAllClassesInPackage(toPackage)) + .check(classes); + } + } + } + + static String matchAllClassesInPackage(String packageName) { + return packageName + ".."; + } + + void denyEmptyPackage(String packageName) { + classes() + .that() + .resideInAPackage(matchAllClassesInPackage(packageName)) + .should(containNumberOfElements(greaterThanOrEqualTo(1))) + .check(classesInPackage(packageName)); + } + + private JavaClasses classesInPackage(String packageName) { + return new ClassFileImporter().importPackages(packageName); + } + + void denyEmptyPackages(List packages) { + for (String packageName : packages) { + denyEmptyPackage(packageName); + } + } +} diff --git a/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/HexagonalArchitecture.java b/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/HexagonalArchitecture.java new file mode 100644 index 0000000..1445968 --- /dev/null +++ b/tapas-tasks/src/test/java/ch/unisg/tapastasks/archunit/HexagonalArchitecture.java @@ -0,0 +1,61 @@ +package ch.unisg.tapastasks.archunit; + +import com.tngtech.archunit.core.domain.JavaClasses; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class HexagonalArchitecture extends ArchitectureElement { + + private Adapters adapters; + private ApplicationLayer applicationLayer; + private String configurationPackage; + private List domainPackages = new ArrayList<>(); + + public static HexagonalArchitecture boundedContext(String basePackage) { + return new HexagonalArchitecture(basePackage); + } + + public HexagonalArchitecture(String basePackage) { + super(basePackage); + } + + public Adapters withAdaptersLayer(String adaptersPackage) { + this.adapters = new Adapters(this, fullQualifiedPackage(adaptersPackage)); + return this.adapters; + } + + public HexagonalArchitecture withDomainLayer(String domainPackage) { + this.domainPackages.add(fullQualifiedPackage(domainPackage)); + return this; + } + + public ApplicationLayer withApplicationLayer(String applicationPackage) { + this.applicationLayer = new ApplicationLayer(fullQualifiedPackage(applicationPackage), this); + return this.applicationLayer; + } + + public HexagonalArchitecture withConfiguration(String packageName) { + this.configurationPackage = fullQualifiedPackage(packageName); + return this; + } + + private void domainDoesNotDependOnOtherPackages(JavaClasses classes) { + denyAnyDependency( + this.domainPackages, Collections.singletonList(adapters.basePackage), classes); + denyAnyDependency( + this.domainPackages, Collections.singletonList(applicationLayer.basePackage), classes); + } + + public void check(JavaClasses classes) { + this.adapters.doesNotContainEmptyPackages(); + this.adapters.dontDependOnEachOther(classes); + this.adapters.doesNotDependOn(this.configurationPackage, classes); + this.applicationLayer.doesNotContainEmptyPackages(); + this.applicationLayer.doesNotDependOn(this.adapters.getBasePackage(), classes); + this.applicationLayer.doesNotDependOn(this.configurationPackage, classes); + this.applicationLayer.incomingAndOutgoingPortsDoNotDependOnEachOther(classes); + this.domainDoesNotDependOnOtherPackages(classes); + } +} diff --git a/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/adapter/in/web/AddNewTaskToTaskListWebControllerTest.java b/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/adapter/in/web/AddNewTaskToTaskListWebControllerTest.java new file mode 100644 index 0000000..d397908 --- /dev/null +++ b/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/adapter/in/web/AddNewTaskToTaskListWebControllerTest.java @@ -0,0 +1,68 @@ +package ch.unisg.tapastasks.tasks.adapter.in.web; + +import ch.unisg.tapastasks.tasks.adapter.in.formats.TaskJsonRepresentation; +import ch.unisg.tapastasks.tasks.adapter.in.web.AddNewTaskToTaskListWebController; +import ch.unisg.tapastasks.tasks.adapter.out.persistence.mongodb.TaskRepository; +import ch.unisg.tapastasks.tasks.application.port.in.AddNewTaskToTaskListCommand; +import ch.unisg.tapastasks.tasks.application.port.in.AddNewTaskToTaskListUseCase; +import ch.unisg.tapastasks.tasks.domain.Task; +import org.json.JSONObject; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.test.web.servlet.MockMvc; + +import java.util.Optional; + +import static org.mockito.BDDMockito.eq; +import static org.mockito.BDDMockito.then; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@WebMvcTest(controllers = AddNewTaskToTaskListWebController.class) +public class AddNewTaskToTaskListWebControllerTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private AddNewTaskToTaskListUseCase addNewTaskToTaskListUseCase; + + @MockBean + TaskRepository taskRepository; + + @Disabled + @Test + void testAddNewTaskToTaskList() throws Exception { + + String taskName = "test-request"; + String taskType = "test-request-type"; + String originalTaskUri = "example.org"; + + String jsonPayLoad = new JSONObject() + .put("taskName", taskName ) + .put("taskType", taskType) + .put("originalTaskUri",originalTaskUri) + .toString(); + + //This raises a NullPointerException since it tries to build the HTTP response with attributes from + //the domain object (created task), which is mocked --> we need System Tests here! + //See the buckpal example from the lecture for a working integration test for testing the web controller + mockMvc.perform(post("/tasks/") + .contentType(TaskJsonRepresentation.MEDIA_TYPE) + .content(jsonPayLoad)) + .andExpect(status().isCreated()); + + then(addNewTaskToTaskListUseCase).should() + .addNewTaskToTaskList(eq(new AddNewTaskToTaskListCommand( + new Task.TaskName(taskName), new Task.TaskType(taskType), + Optional.of(new Task.OriginalTaskUri(originalTaskUri)) + ))); + + } + + +} diff --git a/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskPersistenceAdapterTest.java b/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskPersistenceAdapterTest.java new file mode 100644 index 0000000..ef1fa99 --- /dev/null +++ b/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/adapter/out/persistence/mongodb/TaskPersistenceAdapterTest.java @@ -0,0 +1,77 @@ +package ch.unisg.tapastasks.tasks.adapter.out.persistence.mongodb; + +import ch.unisg.tapastasks.tasks.domain.Task; +import ch.unisg.tapastasks.tasks.domain.TaskList; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.data.mongo.AutoConfigureDataMongo; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Import; + +import java.util.UUID; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) +@AutoConfigureDataMongo +@Import({TaskPersistenceAdapter.class, TaskMapper.class}) +public class TaskPersistenceAdapterTest { + + @Autowired + private TaskRepository taskRepository; + + @Autowired + private TaskPersistenceAdapter adapterUnderTest; + + @Test + void addsNewTask() { + + String testTaskId = UUID.randomUUID().toString(); + String testTaskName = "adds-persistence-task-name"; + String testTaskType = "adds-persistence-task-type"; + String testTaskOuri = "adds-persistence-test-task-ouri"; + String testTaskStatus = Task.Status.OPEN.toString(); + String testTaskListName = "tapas-tasks-tutors"; + + + Task testTask = new Task( + new Task.TaskId(testTaskId), + new Task.TaskName(testTaskName), + new Task.TaskType(testTaskType), + new Task.OriginalTaskUri(testTaskOuri), + new Task.TaskStatus(Task.Status.valueOf(testTaskStatus)) + ); + adapterUnderTest.addTask(testTask); + + MongoTaskDocument retrievedDoc = taskRepository.findByTaskId(testTaskId,testTaskListName); + + assertThat(retrievedDoc.taskId).isEqualTo(testTaskId); + assertThat(retrievedDoc.taskName).isEqualTo(testTaskName); + assertThat(retrievedDoc.taskListName).isEqualTo(testTaskListName); + + } + + @Test + void retrievesTask() { + + String testTaskId = UUID.randomUUID().toString(); + String testTaskName = "reads-persistence-task-name"; + String testTaskType = "reads-persistence-task-type"; + String testTaskOuri = "reads-persistence-test-task-ouri"; + String testTaskStatus = Task.Status.OPEN.toString(); + String testTaskListName = "tapas-tasks-tutors"; + + MongoTaskDocument mongoTask = new MongoTaskDocument(testTaskId, testTaskName, testTaskType, testTaskOuri, + testTaskStatus, testTaskListName); + taskRepository.insert(mongoTask); + + Task retrievedTask = adapterUnderTest.loadTask(new Task.TaskId(testTaskId), + new TaskList.TaskListName(testTaskListName)); + + assertThat(retrievedTask.getTaskName().getValue()).isEqualTo(testTaskName); + assertThat(retrievedTask.getTaskId().getValue()).isEqualTo(testTaskId); + assertThat(retrievedTask.getTaskStatus().getValue()).isEqualTo(Task.Status.valueOf(testTaskStatus)); + + } + +} diff --git a/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/application/service/AddNewTaskToTaskListServiceTest.java b/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/application/service/AddNewTaskToTaskListServiceTest.java new file mode 100644 index 0000000..10d21fd --- /dev/null +++ b/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/application/service/AddNewTaskToTaskListServiceTest.java @@ -0,0 +1,63 @@ +package ch.unisg.tapastasks.tasks.application.service; + +import ch.unisg.tapastasks.tasks.application.port.in.AddNewTaskToTaskListCommand; +import ch.unisg.tapastasks.tasks.application.port.out.AddTaskPort; +import ch.unisg.tapastasks.tasks.application.port.out.NewTaskAddedEventPort; +import ch.unisg.tapastasks.tasks.application.port.out.TaskListLock; +import ch.unisg.tapastasks.tasks.domain.NewTaskAddedEvent; +import ch.unisg.tapastasks.tasks.domain.Task; +import ch.unisg.tapastasks.tasks.domain.TaskList; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import java.util.Optional; + +import static org.mockito.BDDMockito.*; +import static org.assertj.core.api.Assertions.*; + + +public class AddNewTaskToTaskListServiceTest { + + private final AddTaskPort addTaskPort = Mockito.mock(AddTaskPort.class); + private final TaskListLock taskListLock = Mockito.mock(TaskListLock.class); + private final NewTaskAddedEventPort newTaskAddedEventPort = Mockito.mock(NewTaskAddedEventPort.class); + private final AddNewTaskToTaskListService addNewTaskToTaskListService = new AddNewTaskToTaskListService( + newTaskAddedEventPort, addTaskPort, taskListLock); + + @Test + void addingSucceeds() { + + Task newTask = givenATaskWithNameAndTypeAndURI(new Task.TaskName("test-task"), + new Task.TaskType("test-type"), Optional.of(new Task.OriginalTaskUri("example.org"))); + + TaskList taskList = givenAnEmptyTaskList(TaskList.getTapasTaskList()); + + AddNewTaskToTaskListCommand addNewTaskToTaskListCommand = new AddNewTaskToTaskListCommand(newTask.getTaskName(), + newTask.getTaskType(), Optional.ofNullable(newTask.getOriginalTaskUri())); + + Task addedTask = addNewTaskToTaskListService.addNewTaskToTaskList(addNewTaskToTaskListCommand); + + assertThat(addedTask).isNotNull(); + assertThat(taskList.getListOfTasks().getValue()).hasSize(1); + + then(taskListLock).should().lockTaskList(eq(TaskList.getTapasTaskList().getTaskListName())); + then(newTaskAddedEventPort).should(times(1)) + .publishNewTaskAddedEvent(any(NewTaskAddedEvent.class)); + + } + + private TaskList givenAnEmptyTaskList(TaskList taskList) { + taskList.getListOfTasks().getValue().clear(); + return taskList; + } + + private Task givenATaskWithNameAndTypeAndURI(Task.TaskName taskName, Task.TaskType taskType, + Optional originalTaskUri) { + Task task = Mockito.mock(Task.class); + given(task.getTaskName()).willReturn(taskName); + given(task.getTaskType()).willReturn(taskType); + given(task.getOriginalTaskUri()).willReturn(originalTaskUri.get()); + return task; + } + +} diff --git a/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/domain/TaskListTest.java b/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/domain/TaskListTest.java new file mode 100644 index 0000000..05dc664 --- /dev/null +++ b/tapas-tasks/src/test/java/ch/unisg/tapastasks/tasks/domain/TaskListTest.java @@ -0,0 +1,49 @@ +package ch.unisg.tapastasks.tasks.domain; + +import org.junit.jupiter.api.Test; + +import java.util.Optional; + +import static org.assertj.core.api.Assertions.*; + + +public class TaskListTest { + + @Test + void addNewTaskToTaskListSuccess() { + TaskList taskList = TaskList.getTapasTaskList(); + taskList.getListOfTasks().getValue().clear(); + Task newTask = taskList.addNewTaskWithNameAndType(new Task.TaskName("My-Test-Task"), + new Task.TaskType("My-Test-Type")); + + assertThat(newTask.getTaskName().getValue()).isEqualTo("My-Test-Task"); + assertThat(taskList.getListOfTasks().getValue()).hasSize(1); + assertThat(taskList.getListOfTasks().getValue().get(0)).isEqualTo(newTask); + + } + + @Test + void retrieveTaskSuccess() { + TaskList taskList = TaskList.getTapasTaskList(); + Task newTask = taskList.addNewTaskWithNameAndType(new Task.TaskName("My-Test-Task2"), + new Task.TaskType("My-Test-Type2")); + + Task retrievedTask = taskList.retrieveTaskById(newTask.getTaskId()).get(); + + assertThat(retrievedTask).isEqualTo(newTask); + + } + + @Test + void retrieveTaskFailure() { + TaskList taskList = TaskList.getTapasTaskList(); + Task newTask = taskList.addNewTaskWithNameAndType(new Task.TaskName("My-Test-Task3"), + new Task.TaskType("My-Test-Type3")); + + Task.TaskId fakeId = new Task.TaskId("fake-id"); + + Optional retrievedTask = taskList.retrieveTaskById(fakeId); + + assertThat(retrievedTask.isPresent()).isFalse(); + } +} diff --git a/tapas-tasks/src/test/resources/application-test.properties b/tapas-tasks/src/test/resources/application-test.properties new file mode 100644 index 0000000..e45b53d --- /dev/null +++ b/tapas-tasks/src/test/resources/application-test.properties @@ -0,0 +1,2 @@ +spring.data.mongodb.uri=mongodb://127.0.0.1:27017 +spring.data.mongodb.database=tapas-tasks