diff --git a/.classpath b/.classpath deleted file mode 100755 index 1641ef18..00000000 --- a/.classpath +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..00a51aff --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# These are explicitly windows files and should use crlf +*.bat text eol=crlf + diff --git a/.github/workflows/build_container.yaml b/.github/workflows/build_container.yaml new file mode 100644 index 00000000..8eb03d1e --- /dev/null +++ b/.github/workflows/build_container.yaml @@ -0,0 +1,76 @@ +on: [ push ] + +name: Build Container + +jobs: + build: + runs-on: ubuntu-latest + + services: + postgres: + image: postgres:13 + ports: + - 5432:5432 + env: + POSTGRES_USER: reqbaz + POSTGRES_PASSWORD: reqbaz + POSTGRES_DB: reqbaz + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 14 + uses: actions/setup-java@v1 + with: + java-version: 14 + - name: Build release bundle with Gradle + run: ./gradlew export -x test #-Pservice.version=${{ steps.get_version.outputs.version-without-v }} + - name: Docker metadata setup + id: meta + uses: docker/metadata-action@v3 + with: + # list of Docker images to use as base name for tags + images: | + ghcr.io/rwth-acis/requirementsbazaar + # generate Docker tags based on the following events/attributes + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + type=sha + - name: Docker metadata setup for init container + id: meta-init + uses: docker/metadata-action@v3 + with: + # list of Docker images to use as base name for tags + images: | + ghcr.io/rwth-acis/requirementsbazaar-init + # generate Docker tags based on the following events/attributes + tags: | + type=ref,event=branch + type=semver,pattern={{version}} + type=sha + - name: Login to Packages Container registry + uses: docker/login-action@v1 + with: + registry: ghcr.io + username: ${{ github.repository_owner }} + password: ${{ secrets.GITHUB_TOKEN }} + - name: Build and push + uses: docker/build-push-action@v2 + with: + context: . + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + - name: Build and push init container + uses: docker/build-push-action@v2 + with: + context: . + file: DockerfileInit + push: true + tags: ${{ steps.meta-init.outputs.tags }} + labels: ${{ steps.meta-init.outputs.labels }} diff --git a/.github/workflows/gradle.yml b/.github/workflows/gradle.yml new file mode 100644 index 00000000..0b54c9d5 --- /dev/null +++ b/.github/workflows/gradle.yml @@ -0,0 +1,36 @@ +name: Gradle Build & Test +on: [ pull_request, push ] + +jobs: + build: + runs-on: ubuntu-latest + + services: + postgres: + image: postgres:13 + ports: + - 5432:5432 + env: + POSTGRES_USER: reqbaz + POSTGRES_PASSWORD: reqbaz + POSTGRES_DB: reqbaz + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 14 + uses: actions/setup-java@v1 + with: + java-version: 14 + - name: Build with Gradle + run: ./gradlew clean build --info + - uses: codecov/codecov-action@v1 + with: + flags: unittests + files: ./reqbaz/build/reports/jacoco/test/jacocoTestReport.xml + fail_ci_if_error: true + verbose: true diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml new file mode 100644 index 00000000..4953d0fc --- /dev/null +++ b/.github/workflows/release.yaml @@ -0,0 +1,61 @@ +on: + push: + # Sequence of patterns matched against refs/tags + tags: + - 'v[0-9]+.[0-9]+.[0-9]+' + +name: Create Release + +jobs: + build: + name: Create Pre-Release + runs-on: ubuntu-latest + services: + postgres: + image: postgres:13 + ports: + - 5432:5432 + env: + POSTGRES_USER: reqbaz + POSTGRES_PASSWORD: reqbaz + POSTGRES_DB: reqbaz + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + steps: + - name: Checkout code + uses: actions/checkout@v2 + - name: Get Version + id: get_version + uses: battila7/get-version-action@v2 + - name: Set up JDK 14 + uses: actions/setup-java@v1 + with: + java-version: 14 + - name: Build release bundle with Gradle + run: ./gradlew packageDistribution -x test -Pservice.version=${{ steps.get_version.outputs.version-without-v }} + - name: Create Release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: Release ${{ github.ref }} + body: | + This is the ${{ steps.get_version.outputs.version }} release. For changes please check the [Changelog](https://github.com/rwth-acis/RequirementsBazaar/blob/develop/CHANGELOG.md). + draft: false + prerelease: false + - name: Upload Release Asset + id: upload-release-asset + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ./reqbaz/build/dist/BazaarService.zip + asset_name: RequirementsBazaar-${{ steps.get_version.outputs.version }}.zip + asset_content_type: application/zip diff --git a/.github/workflows/release_rc.yaml b/.github/workflows/release_rc.yaml new file mode 100644 index 00000000..4e7baaec --- /dev/null +++ b/.github/workflows/release_rc.yaml @@ -0,0 +1,61 @@ +on: + push: + # Sequence of patterns matched against refs/tags + tags: + - 'v[0-9]+.[0-9]+.[0-9]+-rc\.[0-9]+' + +name: Create Pre-Release + +jobs: + build: + name: Create Pre-Release + runs-on: ubuntu-latest + services: + postgres: + image: postgres:13 + ports: + - 5432:5432 + env: + POSTGRES_USER: reqbaz + POSTGRES_PASSWORD: reqbaz + POSTGRES_DB: reqbaz + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + + steps: + - name: Checkout code + uses: actions/checkout@v2 + - name: Get Version + id: get_version + uses: battila7/get-version-action@v2 + - name: Set up JDK 14 + uses: actions/setup-java@v1 + with: + java-version: 14 + - name: Build release bundle with Gradle + run: ./gradlew packageDistribution -x test -Pservice.version=${{ steps.get_version.outputs.version-without-v }} + - name: Create Release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: Release ${{ github.ref }} + body: | + This is a pre-release. For changes please check the [Changelog](https://github.com/rwth-acis/RequirementsBazaar/blob/develop/CHANGELOG.md). + draft: false + prerelease: true + - name: Upload Release Asset + id: upload-release-asset + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} + asset_path: ./reqbaz/build/dist/BazaarService.zip + asset_name: RequirementsBazaar-${{ steps.get_version.outputs.version }}.zip + asset_content_type: application/zip diff --git a/.gitignore b/.gitignore index 9278c1d8..5538276d 100644 --- a/.gitignore +++ b/.gitignore @@ -11,7 +11,7 @@ /.las2peer /node-storage /startup -/log +log/ /lib etc/ivy/ivy.jar /service @@ -21,6 +21,7 @@ etc/ivy/ivy.jar restMapping.xml /out /output/ +/servicebundle # IntelliJ .idea/ @@ -62,3 +63,10 @@ Temporary Items .apdisk # End of https://www.gitignore.io/api/macos +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build + +.db_data diff --git a/.project b/.project deleted file mode 100755 index 762f646b..00000000 --- a/.project +++ /dev/null @@ -1,15 +0,0 @@ - - - Requirement Bazaar - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.jdt.core.javanature - - diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..5433387b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,90 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres +to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +Releases prior to v0.7.2 are only documented on +the [GitHub Release Page](https://github.com/rwth-acis/RequirementsBazaar/releases) + +## [Unreleased] + +## [0.9.0] - 2021-09-08 + +### Added + +- Added new testcases [#73](https://github.com/rwth-acis/RequirementsBazaar/pull/73) +- Added endpoints to provide anonymous feedback which can be read by project + admins [#85](https://github.com/rwth-acis/RequirementsBazaar/pull/85) +- Added endpoint to search for users by name or email [#90](https://github.com/rwth-acis/RequirementsBazaar/pull/90) +- Categories, projects and requirements now have a `lastActivity` + attribute [#91](https://github.com/rwth-acis/RequirementsBazaar/pull/91). +- Categories, projects and requirements now have a `userContext` encapsuling the dynamic user related information ( + permissions, votes, contribution) [#94](https://github.com/rwth-acis/RequirementsBazaar/pull/94). +- If a user is a member of a project the respective role is now returned in the`usertRole` attribute of the + new `userContext` + attribute [#94](https://github.com/rwth-acis/RequirementsBazaar/pull/94) [#96](https://github.com/rwth-acis/RequirementsBazaar/pull/96) + . +- Add a delete projects endpoint [#100](https://github.com/rwth-acis/RequirementsBazaar/pull/100). +- Add an update comment endpoint [#100](https://github.com/rwth-acis/RequirementsBazaar/pull/100). +- Redacted comments now have a deleted flag [#103](https://github.com/rwth-acis/RequirementsBazaar/pull/103). +- Added a user dashboard listing the last 10 most recent active followed projects, categories and + requirements [#106](https://github.com/rwth-acis/RequirementsBazaar/pull/106). +- Requirements can now have arbitrary tags next to the categories. Tags are a project scoped + entity [#108](https://github.com/rwth-acis/RequirementsBazaar/pull/108). +- Projects, categories and requirements now have an `additionalProperties` object which allows storing and providing + additional context as plain json [#109](https://github.com/rwth-acis/RequirementsBazaar/pull/109). +- The projects endpoint now has a recursive flag which includes projects with requirements matching the search term into the results [#116](https://github.com/rwth-acis/RequirementsBazaar/pull/116) + +### Changed + +- Updated all dependencies, most notably las2peer 1.0.0 [#68](https://github.com/rwth-acis/RequirementsBazaar/pull/68) +- Updated las2peer to 1.1.0 and thereby requiring Java 14 [#73](https://github.com/rwth-acis/RequirementsBazaar/pull/73) +- Updated las2peer to 1.1.2 [#115](https://github.com/rwth-acis/RequirementsBazaar/pull/115) +- Changed buildsystem to use gradle [#73](https://github.com/rwth-acis/RequirementsBazaar/pull/73) +- Automatically generate jooq code from migration files at build + time [#73](https://github.com/rwth-acis/RequirementsBazaar/pull/73) +- Replaced vtor with Java Bean Validation (this implies changes to the API documentation as these annotations included) + [#73](https://github.com/rwth-acis/RequirementsBazaar/pull/73) +- Fixed a bug in the swagger documentation where `GET /categories/{categoryId/requirements` was incorrectly annotated to + return a list of categories instead of a list of + requirements [#78](https://github.com/rwth-acis/RequirementsBazaar/pull/78) +- Revised and automated release process [#78](https://github.com/rwth-acis/RequirementsBazaar/pull/78) +- Split leading `+`/`-`from sort parameter in favour of a `sortDirection` (ASC/DESC) parameter. + [#82](https://github.com/rwth-acis/RequirementsBazaar/pull/82) +- Order by name now implies natural sorting [#82](https://github.com/rwth-acis/RequirementsBazaar/pull/82) +- Remove static code from data classes and generate getter/setters and builder with lombok. This renames the `category` + attribute in `EntityContext` to `categories` [#83](https://github.com/rwth-acis/RequirementsBazaar/pull/82) +- Rework permission system as lined out + in [Privileges](docs/Privileges.md) [#85](https://github.com/rwth-acis/RequirementsBazaar/pull/85) +- Category `leader` attribute has been renamed + to `creator` [#85](https://github.com/rwth-acis/RequirementsBazaar/pull/85) +- Voting now returns a 303 response with reference to the modified + object [#85](https://github.com/rwth-acis/RequirementsBazaar/pull/85) +- Restrict user attributes normally returned to id, username, profile image and + las2peerid [#90](https://github.com/rwth-acis/RequirementsBazaar/pull/90) +- Requirements no longer return the category objects in the `categories` attribute but a list of category + ids [#91](https://github.com/rwth-acis/RequirementsBazaar/pull/91). +- Vote direction can no longer be provided as a query + parameter [#94](https://github.com/rwth-acis/RequirementsBazaar/pull/94) but instead as a direction object strictly + defined by an enum [#96](https://github.com/rwth-acis/RequirementsBazaar/pull/96), +- Moved user related information in categories, requirements and projects (isFollower/Developer/Contributor, userVoted) + into the new `userContext` [#94](https://github.com/rwth-acis/RequirementsBazaar/pull/94). +- Comments with existing responses will no longer be deleted but + redacted [#103](https://github.com/rwth-acis/RequirementsBazaar/pull/103). +- Comments for a requirement are no longer paginated but instead return all + comments [#103](https://github.com/rwth-acis/RequirementsBazaar/pull/103). +- Postgres is now the backend database [#112](https://github.com/rwth-acis/RequirementsBazaar/pull/112) +- Attachments are now updated via PUT towards the requirement + endpoint [#114](https://github.com/rwth-acis/RequirementsBazaar/pull/114). +- All timestamps now contain timezone information [#115](https://github.com/rwth-acis/RequirementsBazaar/pull/115) + +### Removed + +- Personalisation endpoints [#94](https://github.com/rwth-acis/RequirementsBazaar/pull/94) +- Attachment endpoint [#114](https://github.com/rwth-acis/RequirementsBazaar/pull/114) + +## [0.7.2] - 2017-10-25 + +See GH Releases diff --git a/Dockerfile b/Dockerfile index ef4f617b..24b51e1f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,21 +1,26 @@ -FROM openjdk:8-jdk-alpine +# Build final container without build dependencies etc. +FROM openjdk:14-jdk-alpine ENV HTTP_PORT=8080 ENV HTTPS_PORT=8443 ENV LAS2PEER_PORT=9011 -RUN apk add --update bash mysql-client apache-ant && rm -f /var/cache/apk/* RUN addgroup -g 1000 -S las2peer && \ adduser -u 1000 -S las2peer -G las2peer +RUN apk add --update bash iproute2 && rm -f /var/cache/apk/* + -COPY --chown=las2peer:las2peer . /src WORKDIR /src +COPY --chown=las2peer:las2peer ./reqbaz/build/export/ . +COPY --chown=las2peer:las2peer docker-entrypoint.sh /src/docker-entrypoint.sh +COPY --chown=las2peer:las2peer gradle.properties /src/gradle.properties +RUN mkdir /src/log && chown -R las2peer:las2peer /src # run the rest as unprivileged user USER las2peer -RUN ant jar EXPOSE $HTTP_PORT EXPOSE $HTTPS_PORT EXPOSE $LAS2PEER_PORT + ENTRYPOINT ["/src/docker-entrypoint.sh"] diff --git a/DockerfileInit b/DockerfileInit new file mode 100644 index 00000000..9aa094b2 --- /dev/null +++ b/DockerfileInit @@ -0,0 +1,5 @@ +FROM liquibase/liquibase:4.4.0 + +ADD reqbaz/src/main/resources/changelog.yaml reqbaz/src/main/resources/base-permissions.sql /liquibase/changelog/ + +CMD docker-entrypoint.sh --url=jdbc:postgresql://${HOST}:5432/reqbaz --username=${USERNAME} --password=${PASSWORD} --classpath=/liquibase/changelog --changeLogFile=changelog.yaml update diff --git a/README.md b/README.md index 9b31ec71..f2fa7c00 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,7 @@ -Requirements Bazaar -=================== +# Requirements Bazaar + +## Idea -Idea -------------------- In years of research at RWTH Aachen we have developed and actually operated an **Open Innovation Platform for gathering requirements** for prototypes in large international academic projects. The last version of the current product is available under http://requirements-bazaar.org . End-users can enter their requirements by providing short descriptions including user stories, screenshots and other images. The requirements can then be shared amongst its users. On the other side of the chain, developers may take up ideas and transfer the accepted requirements to an issue system like JIRA. Over the last years it turned out that people want more lightweight and mobile-friendly tools; we found the old monolithic system to be very hard to maintain to add new features. Therefore we are currently redeveloping it from scratch integrating many ideas from our users and incorporating new research findings. We are further driven by a mobile-first approach to support a wide variety of devices. We additionally want to support various social features like sharing on social networks or blogs and allowing discussions and rating amongst end-users and developers. @@ -15,52 +14,50 @@ The service is under development. You can participate by creating pull requests More information about our microservice ecosystem is explained in our **[Requirements-Bazaar wiki on Github](https://github.com/rwth-acis/RequirementsBazaar/wiki)**. ----------- +--- + +## Service Documentation -Service Documentation -------------------- We use **[Swagger](http://swagger.io/specification/)** for documenting this microservice. You can use **[Swagger UI](http://swagger.io/swagger-ui/)** to inspect the API. Please use our deployed **[Swagger UI instance](https://requirements-bazaar.org/docs)** to inspect our API. You can authorize yourself via Oauth 2.0 by clicking at the `Authorize` button at the top. After you are authorized you can try out all the API calls directly from Swagger UI. -To try out one API call open one method, fill the parameters and click `Try it out!`. The Swagger UI instance is connected to our development environment where we test nex features. So feel free to play around. +To try out one API call open one method, fill the parameters and click `Try it out!`. The Swagger UI instance is also connected to our development environment where we test nex features. You can select this in the dropdown menu at the top. Feel free to play around there. API documentation endpoints: - `baseURL/bazaar/swagger.json` ----------- +--- + +## Technology -Technology -------------------- Requirements bazaar itself is a web application, which is separated to a client-only side and a back-end side. This GitHub repo holds the codebase of the back-end side only. If you are looking for the front-end, take a look at this GitHub project: **[Requirement Bazaar Web Frontend](https://github.com/rwth-acis/RequirementsBazaar-WebFrontend)** -The backend is built on Java technologies. As a service framework we use our in-house developed **[las2peer](https://github.com/rwth-acis/LAS2peer)** project. For persisting our data we use MySQL database and jOOQ to access it. User input validation is done using Jodd Vtor library and for serializing our data into JSON format, we use the Jackson library. +The backend is built on Java technologies. As a service framework we use our in-house developed **[las2peer](https://github.com/rwth-acis/LAS2peer)** project. For persisting our data we use a PostgreSQL database and jOOQ to access it and for serializing our data into JSON format, we use the Jackson library. + +## Dependencies -Dependencies -------------------- In order to be able to run this service project the following components should be installed on your system: - - JDK (min v1.8) + Java Cryptography Extension (JCE) - - MySQL 5.7 - - Apache Ant to build - -How to set up the database -------------------- - 1. `git clone` this repo - 2. To configure your database access look at the [Configuration](#configuration) section - 3. Compile the project with `ant` - 4. Create a new database called `reqbaz`, possibly with UTF-8 collation - 5. Run `ant migrate-db` to create your db schema or migrate to a newer version while updating your service - 6. If you need sample data run the file `\etc\add_reqbaz_demo_data.sql` or `\etc\add_reqbaz_demo_data_full.sql` - -Configuration -------------------- + - JDK 14 + - PostgreSQL 12 or newer + - Gradle to build + +## How to set up the database (non developer guide) + + 1. Download a release bundle from [GitHub](https://github.com/rwth-acis/RequirementsBazaar/releases) + 2. Create a new database called `reqbaz`, possibly with UTF-8 collation + 3. To configure your database access look at the [Configuration](#configuration) section + 4. Use liquibase to migrate the database + +## Configuration + You need to configure this service to work with your own specific environment. Here is the list of configuration variables: `\etc\de.rwth.dbis.acis.bazaar.service.BazaarService.properties`: - `dbUserName`: A database user's name, which will be used to access the database - `dbPassword`: The database user's password - `dbUrl`: JDBC Connection string to access the database. Modify it if you have changed the name of your database - - `land`: Default language setting + - `lang`: Default language setting - `country`: Default country setting - `baseURL`: Base URL this service runs on - `frontendBaseURL`: Base URL for the frontend which uses Requirements-Bazaar service @@ -71,38 +68,43 @@ You need to configure this service to work with your own specific environment. H For other configuration settings, check the **[las2peer](https://github.com/rwth-acis/LAS2peer)** project. -Build -------------------- -For build management we use Ant. To build the cloned code, please using a console/terminal navigate to the home directory, where the build.xml file is located and run the following commands: +### How to run + 1. First please make sure you have already [set up the database](#how-to-set-up-the-database). + 2. Make sure your [config settings](#configuration) are properly set. + 3. When not using a release asset, check [Building](#building). + 4. Open a console/terminal window and navigate to the project directory. + 5. Run the `bin\start_network.bat` or `bin/start_network.sh` script. - - `ant` - -You can also generate a bundled jar with all the dependencies with the command - - - `ant jar-big` +--- -How to run -------------------- - 1. First please make sure you have already [set up the database](#how-to-set-up-the-database) - 2. Make sure your [config settings](#configuration) are properly set. - 3. [Build](#build) - 4. Open a console/terminal window and navigate to the project directory - 5. Run the `bin\start_network.bat` or `bin/start_network.sh` script +## Developer guide + +### Prerequisites + +Building and testing requires a database which will be cleaned on every build. + +Set the credentials for this database in the gradle.properties and in the `reqbaz/etc` folder. +This configuration folder is relevant for any testing related settings. + +In the `etc` folder on top level you may configure a different database if you want to distinguish between local testing and automated testing. +However you'll have to apply the migrations with liquibase manually to this database. + +### Building + +The build and test process is done with gradle. A simple `gradle build` should be sufficient to build the project and run the test cases. + +You may have to adjust either your global java environment or the one in your IDE to use Java 14 or the built asset won't start. + +### Debugging + +Add the debugger parameters below to your startscript and set up your IDE to connect to a remote debugging port. - How to run using Docker - ------------------- - Docker is providing the simplest way to run the Requirement Bazaar back-end. Just follow the following steps if Docker is already installed on your system: +`-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5433`. - 1. `git clone` this repo - 2. `cd` into the cloned repo - 3. `docker build -t rwthacis/reqbaz-service .` - 4. `docker run -i -t --rm -v "$(pwd)":/build rwthacis/reqbaz-service` +Now you should be able to set breakpoints and inspect the runtime. ----------- +## Troubleshooting & FAQ -Troubleshooting & FAQ -------------------- - - I get Java encryption errors: Did you install Java Cryptography Extension? - I can not run the start script: Check if you have OS permission to run the file. - The service does not start: Check if all jars in the lib and service folder are readable. - The start script seems broken: Check if the start script has the correct encoding. If you ran the service on Unix use `dos2unix` to change the encoding. diff --git a/bin/JOOQGeneration/reqbaz_generation_info.xml b/bin/JOOQGeneration/reqbaz_generation_info.xml deleted file mode 100644 index 7c563ab3..00000000 --- a/bin/JOOQGeneration/reqbaz_generation_info.xml +++ /dev/null @@ -1,50 +0,0 @@ - - - - - com.mysql.jdbc.Driver - jdbc:mysql://localhost:3306/reqbaz - root - reqbaz - - - - - org.jooq.util.DefaultGenerator - - - - org.jooq.util.mysql.MySQLDatabase - - - reqbaz - - - .* - - - - - - BOOLEAN - .*\.admin - - - - - - - de.rwth.dbis.acis.bazaar.service.dal.jooq - - - ../../src/main - - - diff --git a/bin/JOOQGeneration/run.bat b/bin/JOOQGeneration/run.bat deleted file mode 100644 index fe58ffc6..00000000 --- a/bin/JOOQGeneration/run.bat +++ /dev/null @@ -1 +0,0 @@ -java -classpath ../../service/jooq-3.9.1.jar;../../service/jooq-meta-3.9.1.jar;../../service/jooq-codegen-3.9.1.jar;../../service/mysql-connector-java-6.0.5.jar;. org.jooq.util.GenerationTool /reqbaz_generation_info.xml diff --git a/bin/JOOQGeneration/run.sh b/bin/JOOQGeneration/run.sh deleted file mode 100755 index 01bb562d..00000000 --- a/bin/JOOQGeneration/run.sh +++ /dev/null @@ -1 +0,0 @@ -java -classpath ../../service/jooq-3.9.1.jar:../../service/jooq-meta-3.9.1.jar:../../service/jooq-codegen-3.9.1.jar:../../service/mysql-connector-java-6.0.5.jar:. org.jooq.util.GenerationTool /reqbaz_generation_info.xml diff --git a/build.xml b/build.xml deleted file mode 100755 index a33adf53..00000000 --- a/build.xml +++ /dev/null @@ -1,317 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #!/bin/bash - - # this script is autogenerated by 'ant startscripts' - # it starts a LAS2peer node providing the service '${service.name}.${service.class}' of this project - # pls execute it from the root folder of your deployment, e. g. ./bin/start_network.sh - - java -cp "lib/*" i5.las2peer.tools.L2pNodeLauncher -p 9011 uploadStartupDirectory --service-directory service startService\(\'${service.name}.${service.class}@${service.version}\',\'${service.passphrase}\'\) startWebConnector interactive - - :: this script is autogenerated by 'ant - startscripts' - :: it starts a LAS2peer node providing the service '${service.name}.${service.class}' of this project - :: pls execute it from the bin folder of your deployment by double-clicking on it - - %~d0 - cd %~p0 - cd .. - set BASE=%CD% - set CLASSPATH="%BASE%/lib/*;" - - java -cp %CLASSPATH% i5.las2peer.tools.L2pNodeLauncher -p 9011 uploadStartupDirectory --service-directory service startService('${service.name}.${service.class}@${service.version}','${service.passphrase}') startWebConnector interactive - - pause - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - agent-user-${las2peer_user.name}.xml;${las2peer_user.password} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 7716f83a..416137a2 100755 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -4,29 +4,28 @@ set -e # print all comands to console if DEBUG is set if [[ ! -z "${DEBUG}" ]]; then - set -x + set -x fi # set some helpful variables export SERVICE_PROPERTY_FILE='etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties' export WEB_CONNECTOR_PROPERTY_FILE='etc/i5.las2peer.webConnector.WebConnector.properties' -export SERVICE_VERSION=$(awk -F "=" '/service.version/ {print $2}' etc/ant_configuration/service.properties) -export SERVICE_NAME=$(awk -F "=" '/service.name/ {print $2}' etc/ant_configuration/service.properties) -export SERVICE_CLASS=$(awk -F "=" '/service.class/ {print $2}' etc/ant_configuration/service.properties) + +export SERVICE_VERSION=$(awk -F "=" '/service.version/ {print $2}' gradle.properties) +export SERVICE_NAME=$(awk -F "=" '/service.name/ {print $2}' gradle.properties) +export SERVICE_CLASS=$(awk -F "=" '/service.class/ {print $2}' gradle.properties) export SERVICE=${SERVICE_NAME}.${SERVICE_CLASS}@${SERVICE_VERSION} -export DEMO_DATA_SQL='etc/migrations/add_reqbaz_demo_data.sql' -export DEMO_DATA_SQL_FULL='etc/migrations/add_reqbaz_demo_data_full.sql' -export MYSQL_DATABASE='reqbaz' +export POSTGRES_DATABASE='reqbaz' # check mandatory variables -[[ -z "${MYSQL_USER}" ]] && \ - echo "Mandatory variable MYSQL_USER is not set. Add -e MYSQL_USER=myuser to your arguments." && exit 1 -[[ -z "${MYSQL_PASSWORD}" ]] && \ - echo "Mandatory variable MYSQL_PASSWORD is not set. Add -e MYSQL_PASSWORD=mypasswd to your arguments." && exit 1 +[[ -z "${POSTGRES_USER}" ]] && + echo "Mandatory variable POSTGRES_USER is not set. Add -e POSTGRES_USER=reqbaz to your arguments." && exit 1 +[[ -z "${POSTGRES_PASSWORD}" ]] && + echo "Mandatory variable POSTGRES_PASSWORD is not set. Add -e POSTGRES_PASSWORD=mypasswd to your arguments." && exit 1 # set defaults for optional service parameters -[[ -z "${MYSQL_HOST}" ]] && export MYSQL_HOST='mysql' -[[ -z "${MYSQL_PORT}" ]] && export MYSQL_PORT='3306' +[[ -z "${POSTGRES_HOST}" ]] && export POSTGRES_HOST='postgres' +[[ -z "${POSTGRES_PORT}" ]] && export POSTGRES_PORT='5432' [[ -z "${SERVICE_PASSPHRASE}" ]] && export SERVICE_PASSPHRASE='Passphrase' [[ -z "${BAZAAR_LANG}" ]] && export BAZAAR_LANG='en' @@ -51,12 +50,12 @@ export MYSQL_DATABASE='reqbaz' # configure service properties -function set_in_service_config { - sed -i "s?${1}[[:blank:]]*=.*?${1}=${2}?g" ${SERVICE_PROPERTY_FILE} +function set_in_service_config() { + sed -i "s?${1}[[:blank:]]*=.*?${1}=${2}?g" ${SERVICE_PROPERTY_FILE} } -set_in_service_config dbUserName ${MYSQL_USER} -set_in_service_config dbPassword ${MYSQL_PASSWORD} -set_in_service_config dbUrl "jdbc:mysql://${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DATABASE}" +set_in_service_config dbUserName ${POSTGRES_USER} +set_in_service_config dbPassword ${POSTGRES_PASSWORD} +set_in_service_config dbUrl "jdbc:postgresql://${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DATABASE}" set_in_service_config lang ${BAZAAR_LANG} set_in_service_config country ${BAZAAR_COUNTRY} set_in_service_config baseURL ${BASE_URL} @@ -67,11 +66,10 @@ set_in_service_config smtpServer ${SMTP_SERVER} set_in_service_config emailFromAddress ${EMAIL_FROM_ADDRESS} set_in_service_config emailSummaryTimePeriodInMinutes ${EMAIL_SUMMARY_TIME_PERIOD_IN_MINUTES} - # configure web connector properties -function set_in_web_config { - sed -i "s?${1}[[:blank:]]*=.*?${1}=${2}?g" ${WEB_CONNECTOR_PROPERTY_FILE} +function set_in_web_config() { + sed -i "s?${1}[[:blank:]]*=.*?${1}=${2}?g" ${WEB_CONNECTOR_PROPERTY_FILE} } set_in_web_config httpPort ${HTTP_PORT} set_in_web_config httpsPort ${HTTPS_PORT} @@ -84,50 +82,35 @@ set_in_web_config crossOriginResourceMaxAge ${CROSS_ORIGIN_RESOURCE_MAX_AGE} set_in_web_config enableCrossOriginResourceSharing ${ENABLE_CROSS_ORIGIN_RESOURCE_SHARING} set_in_web_config oidcProviders ${OIDC_PROVIDERS} -# ensure the database is ready -while ! mysqladmin ping -h${MYSQL_HOST} -P${MYSQL_PORT} -u${MYSQL_USER} -p${MYSQL_PASSWORD} --silent; do - echo "Waiting for mysql at ${MYSQL_HOST}:${MYSQL_PORT}..." - sleep 1 -done -echo "${MYSQL_HOST}:${MYSQL_PORT} is available. Continuing..." - -# run migrations (does nothing if already migrated) -ant migrate-db - -if [[ ! -z "${INSERT_DEMO_DATA}" ]]; then - echo "Inserting demo data into the database..." - mysql -h${MYSQL_HOST} -P${MYSQL_PORT} -u${MYSQL_USER} -p${MYSQL_PASSWORD} ${MYSQL_DATABASE} < ${DEMO_DATA_SQL} -fi - -if [[ ! -z "${INSERT_DEMO_DATA_FULL}" ]]; then - echo "Inserting demo data into the database..." - mysql -h${MYSQL_HOST} -P${MYSQL_PORT} -u${MYSQL_USER} -p${MYSQL_PASSWORD} ${MYSQL_DATABASE} < ${DEMO_DATA_SQL_FULL} +# set pod ip in pastry conf +if [[ ! -z "${POD_IP}" ]]; then + echo external_address = ${POD_IP}:${LAS2PEER_PORT} > etc/pastry.properties + echo socket_bindAddress = ${POD_IP} >> etc/pastry.properties fi # wait for any bootstrap host to be available if [[ ! -z "${BOOTSTRAP}" ]]; then - echo "Waiting for any bootstrap host to become available..." - for host_port in ${BOOTSTRAP//,/ }; do - arr_host_port=(${host_port//:/ }) - host=${arr_host_port[0]} - port=${arr_host_port[1]} - if { /dev/null; then - echo "${host_port} is available. Continuing..." - break - fi - done + echo "Waiting for any bootstrap host to become available..." + for host_port in ${BOOTSTRAP//,/ }; do + arr_host_port=(${host_port//:/ }) + host=${arr_host_port[0]} + port=${arr_host_port[1]} + if { /dev/null; then + echo "${host_port} is available. Continuing..." + break + fi + done fi # prevent glob expansion in lib/* set -f LAUNCH_COMMAND='java -cp lib/*:service/* i5.las2peer.tools.L2pNodeLauncher -s service -p '"${LAS2PEER_PORT} ${SERVICE_EXTRA_ARGS}" if [[ ! -z "${BOOTSTRAP}" ]]; then - LAUNCH_COMMAND="${LAUNCH_COMMAND} -b ${BOOTSTRAP}" + LAUNCH_COMMAND="${LAUNCH_COMMAND} -b ${BOOTSTRAP}" fi # start the service within a las2peer node -if [[ -z "${@}" ]] -then +if [[ -z "${@}" ]]; then exec ${LAUNCH_COMMAND} startService\("'""${SERVICE}""'", "'""${SERVICE_PASSPHRASE}""'"\) startWebConnector else exec ${LAUNCH_COMMAND} ${@} diff --git a/docs/AttachmentUpload.md b/docs/AttachmentUpload.md new file mode 100644 index 00000000..f750e873 --- /dev/null +++ b/docs/AttachmentUpload.md @@ -0,0 +1,26 @@ +# File Upload + +## Implications + +Uploads and references in the database are separate operations. This may lead to incomplete and unreferenced uploads. +This is a tradeoff made in favour of having multipart API endpoints. + +A way to resolve this is to regularly synchronize the file index with the references in database. + +## Workflows + +### Upload with requirement creation + +1. Upload the file to the file service and receive or generate an identifier. +2. Include reference to the uploaded file as a regular attachment object in the attachment array. Then send this to the + create requirement endpoint. + +### Add attachments to an existing requirement + +1. Upload the file to the file service and receive or generate an identifier. +2. Add reference to the uploaded file as a regular attachment object to the attachment array and use the requirements + update endpoint. + +### Remove attachments from an existing requirement + +1. Remove the reference in the attachments array and use the update requirement endpoint. diff --git a/docs/Privileges.md b/docs/Privileges.md new file mode 100644 index 00000000..0a309b7e --- /dev/null +++ b/docs/Privileges.md @@ -0,0 +1,52 @@ +# Privileges + +With Version 0.9 the privilege model has been extended and partially redesigned. + +## Roles +There are 6 roles, which inherit the privileges of the roles mentioned before. The `Project.*` roles are scoped to a specific project. + +1. Anonymous +2. Logged in user +3. Project Member (scoped) +4. Project Manager (scoped) +5. Project Admin (scoped) +6. System Administrator + +## Privilege Map +|name |name | +|--------------|---------------------------| +|Anonymous |Read_PUBLIC_ATTACHMENT | +|Anonymous |Read_PUBLIC_CATEGORY | +|Anonymous |Read_PUBLIC_COMMENT | +|Anonymous |Read_PUBLIC_PROJECT | +|Anonymous |Read_PUBLIC_REQUIREMENT | +|LoggedInUser |Create_ATTACHMENT | +|LoggedInUser |Create_COMMENT | +|LoggedInUser |Create_FOLLOW | +|LoggedInUser |Create_PERSONALISATION_DATA| +|LoggedInUser |Create_PROJECT | +|LoggedInUser |Create_REQUIREMENT | +|LoggedInUser |Create_VOTE | +|LoggedInUser |Delete_FOLLOW | +|LoggedInUser |Delete_VOTE | +|LoggedInUser |Read_PERSONALISATION_DATA | +|LoggedInUser |Read_USERS | +|ProjectAdmin |Modify_CATEGORY | +|ProjectAdmin |Modify_PROJECT | +|ProjectAdmin |Modify_ADMIN_MEMBERS | +|ProjectAdmin |Delete_PROJECT | +|ProjectManager|Create_CATEGORY | +|ProjectManager|Modify_ATTACHMENT | +|ProjectManager|Modify_COMMENT | +|ProjectManager|Modify_REQUIREMENT | +|ProjectManager|Promote_USER | +|ProjectManager|Read_FEEDBACK | +|ProjectManager|Modify_MEMBERS | +|ProjectMember |Create_DEVELOP | +|ProjectMember |Delete_DEVELOP | +|ProjectMember |Read_ATTACHMENT | +|ProjectMember |Read_CATEGORY | +|ProjectMember |Read_COMMENT | +|ProjectMember |Read_PROJECT | +|ProjectMember |Read_REQUIREMENT | +|ProjectMember |Realize_REQUIREMENT | diff --git a/etc/ant_configuration/service.properties b/etc/ant_configuration/service.properties deleted file mode 100755 index 9146bacc..00000000 --- a/etc/ant_configuration/service.properties +++ /dev/null @@ -1,6 +0,0 @@ -service.version=0.8.0 -service.name=de.rwth.dbis.acis.bazaar.service -service.path=de/rwth/dbis/acis/bazaar/service -service.class=BazaarService -service.passphrase=Passphrase -service.dependencies=commons-codec;version="1.9",commons-dbcp2;version="2.0",commons-io;version="2.4",commons-logging;version="1.2",commons-pool2;version="2.2",emoji-java;version="3.1.3",gson;version="2.3",httpclient;version="4.5.1",httpcore;version="4.4.3",jodd-bean;version="3.6.1",jodd-core;version="3.6.1",jodd-vtor;version="3.6.1",jooq;version="3.9.1",jooq-codegen;version="3.9.1",jooq-meta;version="3.9.1",json;version="20140107",mysql-connector-java;version="6.0.5" diff --git a/etc/ant_configuration/user.properties b/etc/ant_configuration/user.properties deleted file mode 100755 index 1ba6e2ca..00000000 --- a/etc/ant_configuration/user.properties +++ /dev/null @@ -1,3 +0,0 @@ -las2peer_user.name=anonymous -las2peer_user.password=anonymous -las2peer_user.email=anonymous@mail.com \ No newline at end of file diff --git a/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties b/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties index 67ea03e9..082404f1 100644 --- a/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties +++ b/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties @@ -1,13 +1,13 @@ -dbUserName=root +dbUserName=reqbaz dbPassword=reqbaz -dbUrl=jdbc:mysql://localhost:3306/reqbaz +dbUrl=jdbc:postgresql://localhost:5432/reqbaz lang=en country=us baseURL=http://localhost:8080/bazaar/ frontendBaseURL=http://localhost:5000/ -activityTrackerService=de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService@0.4.1 +activityTrackerService=de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService@0.8.0 activityOrigin=https://requirements-bazaar.org smtpServer= emailFromAddress= emailSummaryTimePeriodInMinutes= -monitor= \ No newline at end of file +monitor= diff --git a/etc/i5.las2peer.webConnector.WebConnector.properties b/etc/i5.las2peer.webConnector.WebConnector.properties index 8c815727..8bcbca0e 100755 --- a/etc/i5.las2peer.webConnector.WebConnector.properties +++ b/etc/i5.las2peer.webConnector.WebConnector.properties @@ -8,7 +8,8 @@ crossOriginResourceDomain = * crossOriginResourceMaxAge = 60 enableCrossOriginResourceSharing = TRUE preferLocalServices = TRUE -xmlPath = +xmlPath = defaultLoginUser=anonymous defaultLoginPassword=anonymous -oidcProviders = https://api.learning-layers.eu/o/oauth2,https://accounts.google.com \ No newline at end of file +oidcProviders = https://api.learning-layers.eu/o/oauth2,https://accounts.google.com +#oidcProviders = http://api.learning-layers.eu:8081/auth/realms/main,https://accounts.google.com diff --git a/etc/ivy/ivy.xml b/etc/ivy/ivy.xml deleted file mode 100755 index 33c81a82..00000000 --- a/etc/ivy/ivy.xml +++ /dev/null @@ -1,30 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/etc/ivy/ivysettings.xml b/etc/ivy/ivysettings.xml deleted file mode 100755 index 042d228b..00000000 --- a/etc/ivy/ivysettings.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/etc/migrations/V1__create_reqbaz_schema.sql b/etc/migrations/V1__create_reqbaz_schema.sql deleted file mode 100644 index 296fb54f..00000000 --- a/etc/migrations/V1__create_reqbaz_schema.sql +++ /dev/null @@ -1,318 +0,0 @@ -SET FOREIGN_KEY_CHECKS = 0; - --- tables --- Table attachment -CREATE TABLE IF NOT EXISTS reqbaz.attachment ( - id INT NOT NULL AUTO_INCREMENT, - creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - last_updated_date TIMESTAMP NULL, - requirement_id INT NOT NULL, - user_id INT NOT NULL, - name VARCHAR(255) NOT NULL, - description TEXT NULL, - mime_type VARCHAR(255) NOT NULL, - identifier VARCHAR(900) NOT NULL, - file_url VARCHAR(1000) NOT NULL, - CONSTRAINT attachment_pk PRIMARY KEY (id), - CONSTRAINT attachment_requirement FOREIGN KEY attachment_requirement (requirement_id) REFERENCES requirement (id) - ON DELETE CASCADE, - CONSTRAINT attachment_user FOREIGN KEY attachment_user (user_id) REFERENCES user (id) -); - --- Table comment -CREATE TABLE IF NOT EXISTS reqbaz.comment ( - id INT NOT NULL AUTO_INCREMENT, - message TEXT NOT NULL, - creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - last_updated_date TIMESTAMP NULL, - requirement_id INT NOT NULL, - user_id INT NOT NULL, - reply_to_comment_id INT, - CONSTRAINT comment_pk PRIMARY KEY (id), - CONSTRAINT comment_requirement FOREIGN KEY comment_requirement (requirement_id) REFERENCES requirement (id) - ON DELETE CASCADE, - CONSTRAINT comment_user FOREIGN KEY comment_user (user_id) REFERENCES user (id), - CONSTRAINT reply_comment FOREIGN KEY reply_comment (reply_to_comment_id) REFERENCES comment (id) -); - --- Table category -CREATE TABLE IF NOT EXISTS reqbaz.category ( - id INT NOT NULL AUTO_INCREMENT, - name VARCHAR(255) NOT NULL, - description TEXT NOT NULL, - creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - last_updated_date TIMESTAMP NULL, - project_id INT NOT NULL, - leader_id INT NOT NULL, - CONSTRAINT category_pk PRIMARY KEY (id), - CONSTRAINT category_project FOREIGN KEY category_project (project_id) REFERENCES project (id), - CONSTRAINT category_user FOREIGN KEY category_user (leader_id) REFERENCES user (id) -); - --- Table requirement_developer_map -CREATE TABLE IF NOT EXISTS reqbaz.requirement_developer_map ( - id INT NOT NULL AUTO_INCREMENT, - requirement_id INT NOT NULL, - user_id INT NOT NULL, - creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT requirement_developer_map_pk PRIMARY KEY (id), - CONSTRAINT requirement_developer_map_requirement FOREIGN KEY requirement_developer_map_requirement (requirement_id) REFERENCES requirement (id) - ON DELETE CASCADE, - CONSTRAINT requirement_developer_map_user FOREIGN KEY requirement_developer_map_user (user_id) REFERENCES user (id) -); - --- Table follower_requirement_map -CREATE TABLE IF NOT EXISTS reqbaz.requirement_follower_map ( - id INT NOT NULL AUTO_INCREMENT, - requirement_id INT NOT NULL, - user_id INT NOT NULL, - creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT requirement_follower_map_pk PRIMARY KEY (id), - CONSTRAINT requirement_follower_map_requirement FOREIGN KEY requirement_follower_map_requirement (requirement_id) REFERENCES requirement (id) - ON DELETE CASCADE, - CONSTRAINT requirement_follower_map_user FOREIGN KEY requirement_follower_user (user_id) REFERENCES user (id) -); - --- Table category_follower_map -CREATE TABLE IF NOT EXISTS reqbaz.category_follower_map ( - id INT NOT NULL AUTO_INCREMENT, - category_id INT NOT NULL, - user_id INT NOT NULL, - creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT category_follower_map_pk PRIMARY KEY (id), - CONSTRAINT category_follower_map_category FOREIGN KEY category_follower_map_category (category_id) REFERENCES category (id) - ON DELETE CASCADE, - CONSTRAINT category_follower_map_user FOREIGN KEY category_follower_map_user (user_id) REFERENCES user (id) -); - --- Table project_follower_map -CREATE TABLE IF NOT EXISTS reqbaz.project_follower_map ( - id INT NOT NULL AUTO_INCREMENT, - project_id INT NOT NULL, - user_id INT NOT NULL, - creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT project_follower_map_pk PRIMARY KEY (id), - CONSTRAINT project_follower_map_project FOREIGN KEY project_follower_map_project (project_id) REFERENCES project (id) - ON DELETE CASCADE, - CONSTRAINT project_follower_map_user FOREIGN KEY project_follower_map_user (user_id) REFERENCES user (id) -); - --- Table privilege -CREATE TABLE IF NOT EXISTS reqbaz.privilege ( - id INT NOT NULL AUTO_INCREMENT, - name VARCHAR(100) NOT NULL, - CONSTRAINT privilege_pk PRIMARY KEY (id) -); - --- Table project -CREATE TABLE IF NOT EXISTS reqbaz.project ( - id INT NOT NULL AUTO_INCREMENT, - name VARCHAR(255) NOT NULL, - description TEXT NOT NULL, - visibility BOOLEAN NOT NULL, - creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - last_updated_date TIMESTAMP NULL, - leader_id INT NOT NULL, - default_category_id INT NULL, - CONSTRAINT project_pk PRIMARY KEY (id), - CONSTRAINT project_category FOREIGN KEY project_category (default_category_id) REFERENCES category (id), - CONSTRAINT project_user FOREIGN KEY project_user (leader_id) REFERENCES user (id) -); - --- Table requirement -CREATE TABLE IF NOT EXISTS reqbaz.requirement ( - id INT NOT NULL AUTO_INCREMENT, - name VARCHAR(255) NOT NULL, - description TEXT NULL, - realized TIMESTAMP NULL DEFAULT NULL, - creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - last_updated_date TIMESTAMP NULL, - lead_developer_id INT NULL, - creator_id INT NOT NULL, - project_id INT NOT NULL, - CONSTRAINT requirement_pk PRIMARY KEY (id), - CONSTRAINT creator FOREIGN KEY creator (creator_id) REFERENCES user (id), - CONSTRAINT lead_developer FOREIGN KEY lead_developer (lead_developer_id) REFERENCES user (id), - CONSTRAINT requirement_project FOREIGN KEY requirement_project (project_id) REFERENCES project (id) -); - --- Table requirement_category_map -CREATE TABLE IF NOT EXISTS reqbaz.requirement_category_map ( - id INT NOT NULL AUTO_INCREMENT, - category_id INT NOT NULL, - requirement_id INT NOT NULL, - CONSTRAINT requirement_category_map_pk PRIMARY KEY (id), - CONSTRAINT requirement_category_map_category FOREIGN KEY requirement_category_map_category (category_id) REFERENCES category (id), - CONSTRAINT requirement_category_map_requirement FOREIGN KEY requirement_category_map_requirement (requirement_id) REFERENCES requirement (id) - ON DELETE CASCADE -); - --- Table role_privilege_map -CREATE TABLE IF NOT EXISTS reqbaz.role_privilege_map ( - id INT NOT NULL AUTO_INCREMENT, - role_id INT NOT NULL, - privilege_id INT NOT NULL, - CONSTRAINT role_privilege_map_pk PRIMARY KEY (id), - CONSTRAINT role_privilege_map_privilege FOREIGN KEY role_privilege_map_privilege (privilege_id) REFERENCES privilege (id) - ON DELETE CASCADE, - CONSTRAINT role_privilege_map_role FOREIGN KEY role_privilege_map_role (role_id) REFERENCES role (id) - ON DELETE CASCADE -); - --- Table role_role_map -CREATE TABLE IF NOT EXISTS reqbaz.role_role_map ( - id INT NOT NULL AUTO_INCREMENT, - child_id INT NOT NULL, - parent_id INT NOT NULL, - CONSTRAINT role_role_map_pk PRIMARY KEY (id), - CONSTRAINT role_role_map_child FOREIGN KEY role_role_map_child (child_id) REFERENCES role (id) - ON DELETE CASCADE, - CONSTRAINT role_role_map_parent FOREIGN KEY role_role_map_parent (parent_id) REFERENCES role (id) - ON DELETE CASCADE -); - --- Table role -CREATE TABLE IF NOT EXISTS reqbaz.role ( - id INT NOT NULL AUTO_INCREMENT, - name VARCHAR(50) NULL, - CONSTRAINT role_pk PRIMARY KEY (id), - UNIQUE KEY role_idx_1 (name) -); - --- Table user_role_map -CREATE TABLE IF NOT EXISTS reqbaz.user_role_map ( - id INT NOT NULL AUTO_INCREMENT, - role_id INT NOT NULL, - user_id INT NOT NULL, - context_info VARCHAR(255) NULL, - CONSTRAINT user_role_map_pk PRIMARY KEY (id), - CONSTRAINT user_role_map_role FOREIGN KEY user_role_map_role (role_id) REFERENCES role (id) - ON DELETE CASCADE, - CONSTRAINT user_role_map_user FOREIGN KEY user_role_map_user (user_id) REFERENCES user (id) - ON DELETE CASCADE -); - --- Table user -CREATE TABLE IF NOT EXISTS reqbaz.user ( - id INT NOT NULL AUTO_INCREMENT, - first_name VARCHAR(150) NULL, - last_name VARCHAR(150) NULL, - email VARCHAR(255) NOT NULL, - admin BOOLEAN NOT NULL, - las2peer_id BIGINT NOT NULL, - user_name VARCHAR(255) NULL, - profile_image TEXT NULL, - email_lead_subscription BOOLEAN NOT NULL DEFAULT TRUE, - email_follow_subscription BOOLEAN NOT NULL DEFAULT TRUE, - creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - last_updated_date TIMESTAMP NULL, - last_login_date TIMESTAMP NULL, - CONSTRAINT user_pk PRIMARY KEY (id), - UNIQUE KEY las2peer_idx (las2peer_id) -); - --- Table vote -CREATE TABLE IF NOT EXISTS reqbaz.vote ( - id INT NOT NULL AUTO_INCREMENT, - is_upvote BOOLEAN NOT NULL, - requirement_id INT NOT NULL, - user_id INT NOT NULL, - creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, - CONSTRAINT vote_pk PRIMARY KEY (id), - CONSTRAINT vote_requirement FOREIGN KEY vote_requirement (requirement_id) REFERENCES requirement (id) - ON DELETE CASCADE, - CONSTRAINT vote_user FOREIGN KEY vote_user (user_id) REFERENCES user (id) -); - --- Fill roles and privileges -REPLACE INTO reqbaz.role -(id, name) -VALUES - (1, 'Anonymous'), - (2, 'LoggedInUser'), - (3, 'ProjectAdmin'), - (4, 'SystemAdmin'); - -REPLACE INTO reqbaz.privilege -(id, name) -VALUES - (1, 'Create_PROJECT'), - (2, 'Read_PROJECT'), - (3, 'Read_PUBLIC_PROJECT'), - (4, 'Modify_PROJECT'), - (5, 'Create_CATEGORY'), - (6, 'Read_CATEGORY'), - (7, 'Read_PUBLIC_CATEGORY'), - (8, 'Modify_CATEGORY'), - (9, 'Create_REQUIREMENT'), - (10, 'Read_REQUIREMENT'), - (11, 'Read_PUBLIC_REQUIREMENT'), - (12, 'Modify_REQUIREMENT'), - (13, 'Create_COMMENT'), - (14, 'Read_COMMENT'), - (15, 'Read_PUBLIC_COMMENT'), - (16, 'Modify_COMMENT'), - (17, 'Create_ATTACHMENT'), - (18, 'Read_ATTACHMENT'), - (19, 'Read_PUBLIC_ATTACHMENT'), - (20, 'Modify_ATTACHMENT'), - (21, 'Create_VOTE'), - (22, 'Delete_VOTE'), - (23, 'Create_FOLLOW'), - (24, 'Delete_FOLLOW'), - (25, 'Create_DEVELOP'), - (26, 'Delete_DEVELOP'); - -REPLACE INTO reqbaz.role_privilege_map -(id, role_id, privilege_id) -VALUES - (1, 1, 3), - (2, 1, 7), - (3, 1, 11), - (4, 1, 15), - (5, 1, 19), - (6, 4, 1), - (7, 4, 2), - (8, 4, 8), - (9, 4, 7), - (10, 4, 6), - (11, 4, 5), - (12, 4, 3), - (13, 4, 4), - (14, 4, 9), - (15, 4, 10), - (16, 4, 11), - (17, 4, 12), - (18, 4, 13), - (19, 4, 14), - (20, 4, 16), - (21, 4, 17), - (22, 4, 18), - (23, 4, 19), - (24, 4, 20), - (25, 4, 21), - (26, 4, 22), - (27, 4, 23), - (28, 4, 24), - (29, 4, 25), - (30, 4, 26); - -REPLACE INTO reqbaz.role_role_map -(id, child_id, parent_id) -VALUES - (1, 2, 1), - (2, 3, 2), - (3, 4, 3); - -REPLACE INTO reqbaz.user_role_map -(id, role_id, user_id) -VALUES - (1, 1, 1); - -REPLACE INTO reqbaz.user -(id, first_name, last_name, email, admin, las2peer_id, user_name, profile_image, email_lead_subscription, email_follow_subscription) -VALUES - (1, NULL, NULL, 'anonymous@requirements-bazaar.org', 0, '-1722613621014065292', 'anonymous', - 'https://api.learning-layers.eu/profile.png', 0, 0); - -SET FOREIGN_KEY_CHECKS = 1; \ No newline at end of file diff --git a/etc/migrations/V2__user_las2peer_id_to_string.sql b/etc/migrations/V2__user_las2peer_id_to_string.sql deleted file mode 100644 index 48c5493f..00000000 --- a/etc/migrations/V2__user_las2peer_id_to_string.sql +++ /dev/null @@ -1,7 +0,0 @@ -SET FOREIGN_KEY_CHECKS = 0; - -ALTER TABLE reqbaz.user change las2peer_id las2peer_id VARCHAR(128); - -UPDATE reqbaz.user SET las2peer_id = "anonymous" where id = 1; - -SET FOREIGN_KEY_CHECKS = 1; \ No newline at end of file diff --git a/etc/migrations/add_reqbaz_demo_data.sql b/etc/sample_data/add_reqbaz_demo_data.sql similarity index 100% rename from etc/migrations/add_reqbaz_demo_data.sql rename to etc/sample_data/add_reqbaz_demo_data.sql diff --git a/etc/migrations/add_reqbaz_demo_data_full.sql b/etc/sample_data/add_reqbaz_demo_data_full.sql similarity index 100% rename from etc/migrations/add_reqbaz_demo_data_full.sql rename to etc/sample_data/add_reqbaz_demo_data_full.sql diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 00000000..06ce347d --- /dev/null +++ b/gradle.properties @@ -0,0 +1,14 @@ +org.gradle.parallel=true +java.version=14 +core.version=1.1.2 +service.version=0.9.0 +service.name=de.rwth.dbis.acis.bazaar.service +service.class=BazaarService +jooq.version=3.14.4 +postgres.version=42.2.23 +liquibase.version=4.4.3 +db.port=5432 +db.hostname=localhost +db.user=reqbaz +db.password=reqbaz +db.name=reqbaz diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..e708b1c0 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..442d9132 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..4f906e0c --- /dev/null +++ b/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 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. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +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 +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..107acd32 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem 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, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/reqbaz/build.gradle b/reqbaz/build.gradle new file mode 100644 index 00000000..fc2e72ff --- /dev/null +++ b/reqbaz/build.gradle @@ -0,0 +1,251 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * This generated file contains a sample Java application project to get you started. + * For more details take a look at the 'Building Java & JVM projects' chapter in the Gradle + * User Manual available at https://docs.gradle.org/6.7/userguide/building_java_projects.html + */ +buildscript { + configurations["classpath"].resolutionStrategy.eachDependency { + if (requested.group == "org.jooq") { + useVersion("${project.property('jooq.version')}") + } + } +} + +plugins { + // Apply the application plugin to add support for building a CLI application in Java. + id 'java' + id 'application' + id 'idea' + id "nu.studer.jooq" version "5.2.1" + id "io.freefair.lombok" version "5.3.0" + id 'com.github.ben-manes.versions' version '0.38.0' + id 'jacoco' + id 'org.liquibase.gradle' version '2.0.4' +} + +application { + // Define the main class for the application. + mainClass = "${project.property('service.name')}.${project.property('service.class')}" + + group = "${project.property('service.name')}" + archivesBaseName = group + + version = "${project.property('service.version')}" + mainClassName = "i5.las2peer.tools.L2pNodeLauncher" + sourceCompatibility = "${project.property('java.version')}" + targetCompatibility = "${project.property('java.version')}" +} + +repositories { + // Use JCenter for resolving dependencies. + jcenter() + + // DBIS Archiva + maven { + url "https://archiva.dbis.rwth-aachen.de:9911/repository/internal/" + } +} + +dependencies { + // Use JUnit test framework. + testImplementation 'junit:junit:4.13' + + liquibaseRuntime "org.liquibase:liquibase-core:${project.property('liquibase.version')}" + liquibaseRuntime 'org.yaml:snakeyaml:1.29' + liquibaseRuntime "org.postgresql:postgresql:${project.property('postgres.version')}" + liquibaseRuntime 'javax.xml.bind:jaxb-api:2.3.1' + + // las2peer bundle which is not necessary in the runtime path + // compileOnly will be moved into the lib dir afterwards + compileOnly "i5:las2peer-bundle:${project.property('core.version')}" + compileOnly "org.postgresql:postgresql:${project.property('postgres.version')}" + compileOnly 'org.hibernate:hibernate-validator:5.4.3.Final' + compileOnly 'org.glassfish:jakarta.el:3.0.3' + compileOnly 'javax.validation:validation-api:1.1.0.Final' + + // This is for the jooq generation only + jooqGenerator "org.jooq:jooq-codegen:${project.property('jooq.version')}" + + implementation 'com.google.code.gson:gson:2.8.6' + implementation 'org.apache.commons:commons-pool2:2.9.0' + implementation 'org.apache.commons:commons-dbcp2:2.8.0' + implementation "org.jooq:jooq:${project.property('jooq.version')}" + implementation "org.jooq:jooq-meta:${project.property('jooq.version')}" + implementation 'org.apache.httpcomponents:httpclient:4.5.13' + implementation 'commons-io:commons-io:2.8.0' + implementation 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.8.9' +} + +configurations { + // This ensures las2peer is available in the tests, but won't be bundled + testCompile.extendsFrom compileOnly + jooqGenerator.extendsFrom liquibaseRuntime +} + +test { + finalizedBy jacocoTestReport // report is always generated after tests run +} + +jacocoTestReport { + dependsOn test // tests are required to run before generating the report + reports { + xml.enabled true + } +} + +jar { + manifest { + attributes "Main-Class": "${project.property('service.name')}.${project.property('service.class')}" + attributes "Library-Version": "${project.property('service.version')}" + attributes "Library-SymbolicName": "${project.property('service.name')}" + } + + from { (configurations.runtimeClasspath).collect { it.isDirectory() ? it : zipTree(it) } } { + // Exclude signatures to be able to natively bundle signed jars + exclude 'META-INF/*.RSA', 'META-INF/*.SF', 'META-INF/*.DSA' + } +} + +// These two tasks restore the build and runtime environment used +// in the ant environment +task copyJar(type: Copy) { + from jar // here it automatically reads jar file produced from jar task + into '../service' +} + +// Maybe there is a more idiomatic way to separate out las2peer +task copyToLib(type: Copy) { + from configurations.compileOnly + into "../lib" +} + +task startscripts { + new File("$rootDir/bin", "start_network.sh").text = """#!/bin/bash +# this script is autogenerated by 'gradle startscripts' +# it starts a las2peer node providing the service '${project.property('service.name')}.${project.property('service.class')}' of this project +# pls execute it from the root folder of your deployment, e. g. ./bin/start_network.sh +java -cp "lib/*" i5.las2peer.tools.L2pNodeLauncher --port 9011 --service-directory service uploadStartupDirectory startService\\(\\'${project.property('service.name')}.${project.property('service.class')}@${project.property('service.version')}\\'\\) startWebConnector interactive +""" + new File("$rootDir/bin", "start_network.bat").text = """:: this script is autogenerated by 'gradle startscripts' +:: it starts a las2peer node providing the service '${project.property('service.name')}.${project.property('service.class')}' of this project +:: pls execute it from the bin folder of your deployment by double-clicking on it +%~d0 +cd %~p0 +cd .. +set BASE=%CD% +set CLASSPATH="%BASE%/lib/*;" +java -cp %CLASSPATH% i5.las2peer.tools.L2pNodeLauncher --port 9011 --service-directory service uploadStartupDirectory startService('${project.property('service.name')}.${project.property('service.class')}@${project.property('service.version')}') startWebConnector interactive +pause +""" +} + +build.dependsOn javadoc +build.dependsOn copyJar +build.dependsOn copyToLib +build.dependsOn startscripts + + +// Flyway and jooq configuration for database management +jooq { + version = "${project.property('jooq.version')}" + configurations { + main { // name of the jOOQ configuration + generationTool { + logging = org.jooq.meta.jaxb.Logging.WARN + jdbc { + driver = 'org.postgresql.Driver' + url = "jdbc:postgresql://${project.property('db.hostname')}:${project.property('db.port')}/${project.property('db.name')}" + user = "${project.property('db.user')}" + password = "${project.property('db.password')}" + } + generator { + name = 'org.jooq.codegen.DefaultGenerator' + database { + name = 'org.jooq.meta.postgres.PostgresDatabase' + inputSchema = "public" + } + generate { + deprecated = false + records = true + immutablePojos = false + fluentSetters = true + } + target { + packageName = 'de.rwth.dbis.acis.bazaar.dal.jooq' + directory = 'build/generated/jooq/main' + } + strategy.name = 'org.jooq.codegen.DefaultGeneratorStrategy' + } + } + } + } +} + +// liquibase migrations +generateJooq.dependsOn dropAll +generateJooq.dependsOn update + +liquibase { + activities { + main { + defaultSchemaName 'public' + changeLogFile "changelog.yaml" + classpath "$projectDir/src/main/resources" + url "jdbc:postgresql://${project.property('db.hostname')}:${project.property('db.port')}/${project.property('db.name')}" + username "${project.property('db.user')}" + password "${project.property('db.password')}" + } + } +} + + +// Build export directory which can be shipped on request +task export(type: Copy, dependsOn: build) { + into "$buildDir/export" + + into("service") { + from jar + } + into("lib") { + from configurations.compileOnly + } + into("bin") { + from "../bin" + } + into("etc") { + from "../etc" + } + into("javadoc") { + from "$buildDir/docs/javadoc" + } + into("sql") { + from processResources + include "*.sql" + include "changelog.yaml" + } +} + +task packageDistribution(type: Zip, dependsOn: export) { + archiveFileName = "${project.property('service.class')}.zip" + destinationDirectory = file("$buildDir/dist") + + from "$buildDir/export" +} + +// Cleanup +clean.doLast { + file("$rootDir/lib").deleteDir() + file("$rootDir/service").deleteDir() +} + +task cleanAll { + dependsOn "clean" + + doLast { + file("$rootDir/log").deleteDir() + file("$projectDir/log").deleteDir() + file("$rootDir/node-storage").deleteDir() + } +} diff --git a/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties b/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties new file mode 100644 index 00000000..194a91bb --- /dev/null +++ b/reqbaz/etc/de.rwth.dbis.acis.bazaar.service.BazaarService.properties @@ -0,0 +1,13 @@ +dbUserName=reqbaz +dbPassword=reqbaz +dbUrl=jdbc:postgresql://localhost:5432/reqbaz +lang=en +country=us +baseURL=http://localhost:8080/bazaar/ +frontendBaseURL=http://localhost:5000/ +activityTrackerService=de.rwth.dbis.acis.activitytracker.service.ActivityTrackerService@0.8.0 +activityOrigin=https://requirements-bazaar.org +smtpServer= +emailFromAddress= +emailSummaryTimePeriodInMinutes= +monitor='' diff --git a/reqbaz/lombok.config b/reqbaz/lombok.config new file mode 100644 index 00000000..189c0bef --- /dev/null +++ b/reqbaz/lombok.config @@ -0,0 +1,3 @@ +# This file is generated by the 'io.freefair.lombok' Gradle plugin +config.stopBubbling = true +lombok.addLombokGeneratedAnnotation = true diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/BazaarFunction.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarFunction.java similarity index 93% rename from src/main/de/rwth/dbis/acis/bazaar/service/BazaarFunction.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarFunction.java index 1f635169..a6fd44af 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/BazaarFunction.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarFunction.java @@ -21,7 +21,6 @@ package de.rwth.dbis.acis.bazaar.service; /** - * @author Adam Gavronek * @since 1/9/2015 */ public enum BazaarFunction { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/BazaarFunctionRegistrar.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarFunctionRegistrar.java similarity index 94% rename from src/main/de/rwth/dbis/acis/bazaar/service/BazaarFunctionRegistrar.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarFunctionRegistrar.java index 28d48358..70d7e925 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/BazaarFunctionRegistrar.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarFunctionRegistrar.java @@ -23,7 +23,6 @@ import java.util.EnumSet; /** - * @author Adam Gavronek * @since 1/9/2015 */ public interface BazaarFunctionRegistrar { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/BazaarService.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java similarity index 81% rename from src/main/de/rwth/dbis/acis/bazaar/service/BazaarService.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java index 0c4c0254..6bc9130b 100755 --- a/src/main/de/rwth/dbis/acis/bazaar/service/BazaarService.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/BazaarService.java @@ -22,11 +22,14 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.DALFacadeImpl; import de.rwth.dbis.acis.bazaar.service.dal.entities.Activity; import de.rwth.dbis.acis.bazaar.service.dal.entities.Statistic; +import de.rwth.dbis.acis.bazaar.service.dal.entities.SystemRole; import de.rwth.dbis.acis.bazaar.service.dal.entities.User; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreateValidation; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; @@ -37,6 +40,7 @@ import de.rwth.dbis.acis.bazaar.service.notification.EmailDispatcher; import de.rwth.dbis.acis.bazaar.service.notification.NotificationDispatcher; import de.rwth.dbis.acis.bazaar.service.notification.NotificationDispatcherImp; +import de.rwth.dbis.acis.bazaar.service.resources.*; import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; import i5.las2peer.api.Context; import i5.las2peer.api.ManualDeployment; @@ -49,12 +53,15 @@ import i5.las2peer.restMapper.RESTService; import i5.las2peer.restMapper.annotations.ServicePath; import io.swagger.annotations.*; -import jodd.vtor.Vtor; import org.apache.commons.dbcp2.BasicDataSource; import org.apache.http.client.utils.URIBuilder; import org.jooq.SQLDialect; import javax.sql.DataSource; +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.Validator; +import javax.validation.ValidatorFactory; import javax.ws.rs.*; import javax.ws.rs.core.Link; import javax.ws.rs.core.MediaType; @@ -62,6 +69,7 @@ import javax.xml.bind.DatatypeConverter; import java.net.HttpURLConnection; import java.net.URISyntaxException; +import java.time.OffsetDateTime; import java.util.*; @@ -76,6 +84,13 @@ @ServicePath("/bazaar") public class BazaarService extends RESTService { + private static final ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule()).setSerializationInclusion(JsonInclude.Include.NON_NULL); + private final L2pLogger logger = L2pLogger.getInstance(BazaarService.class.getName()); + private final ValidatorFactory validatorFactory; + private final List functionRegistrar; + private final NotificationDispatcher notificationDispatcher; + private final DataSource dataSource; + //CONFIG PROPERTIES protected String dbUserName; protected String dbPassword; @@ -90,34 +105,15 @@ public class BazaarService extends RESTService { protected String emailFromAddress; protected String emailSummaryTimePeriodInMinutes; - private Vtor vtor; - private List functionRegistrar; - private NotificationDispatcher notificationDispatcher; - private DataSource dataSource; - - private final L2pLogger logger = L2pLogger.getInstance(BazaarService.class.getName()); - private static ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); - - @Override - protected void initResources() { - getResourceConfig().register(Resource.class); - getResourceConfig().register(ProjectsResource.class); - getResourceConfig().register(CategoryResource.class); - getResourceConfig().register(RequirementsResource.class); - getResourceConfig().register(CommentsResource.class); - getResourceConfig().register(AttachmentsResource.class); - getResourceConfig().register(UsersResource.class); - } - public BazaarService() throws Exception { setFieldValues(); Locale locale = new Locale(lang, country); Localization.getInstance().setResourceBundle(ResourceBundle.getBundle("i18n.Translation", locale)); - Class.forName("com.mysql.jdbc.Driver").newInstance(); - dataSource = setupDataSource(dbUrl, dbUserName, dbPassword); + validatorFactory = Validation.buildDefaultValidatorFactory(); + functionRegistrar = new ArrayList<>(); functionRegistrar.add(functions -> { DALFacade dalFacade = null; @@ -133,12 +129,6 @@ public BazaarService() throws Exception { } }); - functionRegistrar.add(functions -> { - if (functions.contains(BazaarFunction.VALIDATION)) { - createValidators(); - } - }); - functionRegistrar.add(functions -> { if (functions.contains(BazaarFunction.USER_FIRST_LOGIN_HANDLING)) { registerUserAtFirstLogin(); @@ -170,11 +160,169 @@ public BazaarService() throws Exception { notificationDispatcher.setBazaarService(this); } + public static DataSource setupDataSource(String dbUrl, String dbUserName, String dbPassword) { + BasicDataSource dataSource = new BasicDataSource(); + dataSource.setUrl(dbUrl); + dataSource.setUsername(dbUserName); + dataSource.setPassword(dbPassword); + dataSource.setValidationQuery("SELECT 1;"); + dataSource.setTestOnBorrow(true); // test each connection when borrowing from the pool with the validation query + dataSource.setMaxConnLifetimeMillis(1000 * 60 * 60); // max connection life time 1h. mysql drops connection after 8h. + return dataSource; + } + + @Override + protected void initResources() { + getResourceConfig().register(Resource.class); + getResourceConfig().register(ProjectsResource.class); + getResourceConfig().register(CategoryResource.class); + getResourceConfig().register(RequirementsResource.class); + getResourceConfig().register(CommentsResource.class); + getResourceConfig().register(UsersResource.class); + //getResourceConfig().register(PersonalisationDataResource.class); + getResourceConfig().register(FeedbackResource.class); + } + + public String getBaseURL() { + return baseURL; + } + + public String notifyRegistrars(EnumSet functions) { + String resultJSON = null; + try { + for (BazaarFunctionRegistrar functionRegistrar : functionRegistrar) { + functionRegistrar.registerFunction(functions); + } + } catch (BazaarException bazaarEx) { + resultJSON = ExceptionHandler.getInstance().toJSON(bazaarEx); + } catch (Exception ex) { + BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, Localization.getInstance().getResourceBundle().getString("error.registrars")); + resultJSON = ExceptionHandler.getInstance().toJSON(bazaarException); + } + return resultJSON; + } + + public Set> validate(Object entity) { + Validator validator = validatorFactory.getValidator(); + // Take Object for generic error handling + return validator.validate(entity); + } + + public Set> validateCreate(Object entity) { + Validator validator = validatorFactory.getValidator(); + // Take Object for generic error handling + return validator.validate(entity, CreateValidation.class); + } + + public NotificationDispatcher getNotificationDispatcher() { + return notificationDispatcher; + } + + private void registerUserAtFirstLogin() throws Exception { + Agent agent = Context.getCurrent().getMainAgent(); + + String loginName = null; + String email = null; + String profileImage = "https://api.learning-layers.eu/profile.png"; + + if (agent instanceof AnonymousAgent) { + loginName = ((AnonymousAgent) agent).LOGIN_NAME; + email = "NO.EMAIL@WARNING.COM"; + } else if (agent instanceof UserAgent) { + loginName = ((UserAgent) agent).getLoginName(); + if (((UserAgent) agent).getEmail() == null) { + email = "NO.EMAIL@WARNING.COM"; + } else { + email = ((UserAgent) agent).getEmail(); + } + } + + DALFacade dalFacade = null; + try { + dalFacade = getDBConnection(); + Integer userIdByLAS2PeerId = dalFacade.getUserIdByLAS2PeerId(agent.getIdentifier()); + if (userIdByLAS2PeerId == null) { + // create user + User user = User.builder() + .eMail(email) + .las2peerId(agent.getIdentifier()) + .userName(loginName) + .profileImage(profileImage) + .emailLeadSubscription(true) + .emailFollowSubscription(true) + .personalizationEnabled(false) + .build(); + user = dalFacade.createUser(user); + int userId = user.getId(); + // this.getNotificationDispatcher().dispatchNotification(user.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_55, userId, Activity.DataType.USER, userId); + dalFacade.addUserToRole(userId, "LoggedInUser", null); + } else { + // update lastLoginDate + dalFacade.updateLastLoginDate(userIdByLAS2PeerId); + } + } catch (Exception ex) { + ExceptionHandler.getInstance().convertAndThrowException(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, Localization.getInstance().getResourceBundle().getString("error.first_login")); + logger.warning(ex.getMessage()); + } finally { + closeDBConnection(dalFacade); + } + } + + public DALFacade getDBConnection() throws Exception { // TODO: Specify Exception + return new DALFacadeImpl(dataSource, SQLDialect.POSTGRES); + } + + public void closeDBConnection(DALFacade dalFacade) { + if (dalFacade == null) { + return; + } + dalFacade.close(); + } + + public ObjectMapper getMapper() { + return mapper; + } + + public Response.ResponseBuilder paginationLinks(Response.ResponseBuilder responseBuilder, PaginationResult paginationResult, + String path, Map> httpParameter) throws URISyntaxException { + List links = new ArrayList<>(); + URIBuilder uriBuilder = new URIBuilder(baseURL + path); + for (Map.Entry> entry : httpParameter.entrySet()) { + for (String parameter : entry.getValue()) { + uriBuilder.addParameter(entry.getKey(), parameter); + } + } + if (paginationResult.getPrevPage() != -1) { + links.add(Link.fromUri(uriBuilder.setParameter("page", String.valueOf(paginationResult.getPrevPage())).build()).rel("prev").build()); + } + if (paginationResult.getNextPage() != -1) { + links.add(Link.fromUri(uriBuilder.setParameter("page", String.valueOf(paginationResult.getNextPage())).build()).rel("next").build()); + } + links.add(Link.fromUri(uriBuilder.setParameter("page", "0").build()).rel("first").build()); + links.add(Link.fromUri(uriBuilder.setParameter("page", String.valueOf(paginationResult.getTotalPages())).build()).rel("last").build()); + responseBuilder = responseBuilder.links(links.toArray(new Link[links.size()])); + return responseBuilder; + } + + public Response.ResponseBuilder xHeaderFields(Response.ResponseBuilder responseBuilder, PaginationResult paginationResult) { + responseBuilder = responseBuilder.header("X-Page", String.valueOf(paginationResult.getPageable().getPageNumber())); + responseBuilder = responseBuilder.header("X-Per-Page", String.valueOf(paginationResult.getPageable().getPageSize())); + if (paginationResult.getPrevPage() != -1) { + responseBuilder = responseBuilder.header("X-Prev-Page", String.valueOf(paginationResult.getPrevPage())); + } + if (paginationResult.getNextPage() != -1) { + responseBuilder = responseBuilder.header("X-Next-Page", String.valueOf(paginationResult.getNextPage())); + } + responseBuilder = responseBuilder.header("X-Total-Pages", String.valueOf(paginationResult.getTotalPages())); + responseBuilder = responseBuilder.header("X-Total", String.valueOf(paginationResult.getTotal())); + return responseBuilder; + } + @Api(value = "/", description = "Bazaar service") @SwaggerDefinition( info = @Info( title = "Requirements Bazaar", - version = "0.8.0", + version = "0.9.0", description = "Requirements Bazaar project", termsOfService = "http://requirements-bazaar.org", contact = @Contact( @@ -248,7 +396,7 @@ public Response getStatistics( Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Calendar sinceCal = since == null ? null : DatatypeConverter.parseDateTime(since); Statistic platformStatistics = dalFacade.getStatisticsForAllProjects(internalUserId, sinceCal); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_2, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_2, 0, Activity.DataType.STATISTIC, internalUserId); return Response.ok(platformStatistics.toJSON()).build(); } catch (BazaarException bex) { @@ -279,15 +427,35 @@ public Response getStatistics( @Path("/notifications") @ApiOperation(value = "This method sends all notifications (emails) in the waiting queue. Run this method before shutting down Requirements Bazaar.") @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Notifications send"), + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Notifications send"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") }) public Response sendNotifications() { - // TODO: Use authorization scopes to limit users who can run this method to admins + DALFacade dalFacade = null; try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, dalFacade.getRoleByName(SystemRole.SystemAdmin.name()), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.notifications")); + } bazaarService.notificationDispatcher.run(); - return Response.status(Response.Status.CREATED).build(); + return Response.status(Response.Status.OK).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Flushing notifications"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } } catch (Exception ex) { BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Send Notifications failed"); @@ -297,132 +465,4 @@ public Response sendNotifications() { } } - public String notifyRegistrars(EnumSet functions) { - String resultJSON = null; - try { - for (BazaarFunctionRegistrar functionRegistrar : functionRegistrar) { - functionRegistrar.registerFunction(functions); - } - } catch (BazaarException bazaarEx) { - resultJSON = ExceptionHandler.getInstance().toJSON(bazaarEx); - } catch (Exception ex) { - BazaarException bazaarException = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, Localization.getInstance().getResourceBundle().getString("error.registrars")); - resultJSON = ExceptionHandler.getInstance().toJSON(bazaarException); - } - return resultJSON; - } - - private void createValidators() { - vtor = new Vtor(); - } - - public Vtor getValidators() { - return vtor; - } - - public NotificationDispatcher getNotificationDispatcher() { - return notificationDispatcher; - } - - private void registerUserAtFirstLogin() throws Exception { - Agent agent = Context.getCurrent().getMainAgent(); - - String loginName = null; - String email = null; - String profileImage = "https://api.learning-layers.eu/profile.png"; - - if (agent instanceof AnonymousAgent) { - loginName = ((AnonymousAgent) agent).LOGIN_NAME; - email = "NO.EMAIL@WARNING.COM"; - } else if (agent instanceof UserAgent) { - loginName = ((UserAgent) agent).getLoginName(); - if (((UserAgent) agent).getEmail() == null) { - email = "NO.EMAIL@WARNING.COM"; - } else { - email = ((UserAgent) agent).getEmail(); - } - } - - DALFacade dalFacade = null; - try { - dalFacade = getDBConnection(); - Integer userIdByLAS2PeerId = dalFacade.getUserIdByLAS2PeerId(agent.getIdentifier()); - if (userIdByLAS2PeerId == null) { - // create user - User.Builder userBuilder = User.geBuilder(email); - User user = userBuilder.admin(false).las2peerId(agent.getIdentifier()).userName(loginName).profileImage(profileImage) - .emailLeadSubscription(true).emailFollowSubscription(true).build(); - user = dalFacade.createUser(user); - int userId = user.getId(); - this.getNotificationDispatcher().dispatchNotification(user.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_55, - userId, Activity.DataType.USER, userId); - dalFacade.addUserToRole(userId, "SystemAdmin", null); - } else { - // update lastLoginDate - dalFacade.updateLastLoginDate(userIdByLAS2PeerId); - } - } catch (Exception ex) { - ExceptionHandler.getInstance().convertAndThrowException(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, Localization.getInstance().getResourceBundle().getString("error.first_login")); - logger.warning(ex.getMessage()); - } finally { - closeDBConnection(dalFacade); - } - } - - public static DataSource setupDataSource(String dbUrl, String dbUserName, String dbPassword) { - BasicDataSource dataSource = new BasicDataSource(); - dataSource.setDriverClassName("com.mysql.jdbc.Driver"); - dataSource.setUrl(dbUrl + "?useSSL=false&serverTimezone=UTC"); - dataSource.setUsername(dbUserName); - dataSource.setPassword(dbPassword); - dataSource.setValidationQuery("SELECT 1;"); - dataSource.setTestOnBorrow(true); // test each connection when borrowing from the pool with the validation query - dataSource.setMaxConnLifetimeMillis(1000 * 60 * 60); // max connection life time 1h. mysql drops connection after 8h. - return dataSource; - } - - public DALFacade getDBConnection() throws Exception { // TODO: Specify Exception - return new DALFacadeImpl(dataSource, SQLDialect.MYSQL); - } - - public void closeDBConnection(DALFacade dalFacade) { - if (dalFacade == null) return; - dalFacade.close(); - } - - public Response.ResponseBuilder paginationLinks(Response.ResponseBuilder responseBuilder, PaginationResult paginationResult, - String path, Map> httpParameter) throws URISyntaxException { - List links = new ArrayList<>(); - URIBuilder uriBuilder = new URIBuilder(baseURL + path); - for (Map.Entry> entry : httpParameter.entrySet()) { - for (String parameter : entry.getValue()) { - uriBuilder.addParameter(entry.getKey(), parameter); - } - } - if (paginationResult.getPrevPage() != -1) { - links.add(Link.fromUri(uriBuilder.setParameter("page", String.valueOf(paginationResult.getPrevPage())).build()).rel("prev").build()); - } - if (paginationResult.getNextPage() != -1) { - links.add(Link.fromUri(uriBuilder.setParameter("page", String.valueOf(paginationResult.getNextPage())).build()).rel("next").build()); - } - links.add(Link.fromUri(uriBuilder.setParameter("page", "0").build()).rel("first").build()); - links.add(Link.fromUri(uriBuilder.setParameter("page", String.valueOf(paginationResult.getTotalPages())).build()).rel("last").build()); - responseBuilder = responseBuilder.links(links.toArray(new Link[links.size()])); - return responseBuilder; - } - - public Response.ResponseBuilder xHeaderFields(Response.ResponseBuilder responseBuilder, PaginationResult paginationResult) { - responseBuilder = responseBuilder.header("X-Page", String.valueOf(paginationResult.getPageable().getPageNumber())); - responseBuilder = responseBuilder.header("X-Per-Page", String.valueOf(paginationResult.getPageable().getPageSize())); - if (paginationResult.getPrevPage() != -1) { - responseBuilder = responseBuilder.header("X-Prev-Page", String.valueOf(paginationResult.getPrevPage())); - } - if (paginationResult.getNextPage() != -1) { - responseBuilder = responseBuilder.header("X-Next-Page", String.valueOf(paginationResult.getNextPage())); - } - responseBuilder = responseBuilder.header("X-Total-Pages", String.valueOf(paginationResult.getTotalPages())); - responseBuilder = responseBuilder.header("X-Total", String.valueOf(paginationResult.getTotal())); - return responseBuilder; - } - } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/DALFacade.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacade.java similarity index 74% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/DALFacade.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacade.java index d88dcc65..c4ba83be 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/DALFacade.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacade.java @@ -135,6 +135,15 @@ public interface DALFacade { * @return list of users to receive email notification */ List getRecipientListForRequirement(int requirementId) throws BazaarException; + + /** + * Search for users with a given search term + * + * @param pageInfo + * @return + */ + PaginationResult searchUsers(PageInfo pageInfo) throws BazaarException; + //endregion //region Project @@ -175,6 +184,14 @@ public interface DALFacade { */ Project modifyProject(Project modifiedProject) throws Exception; + /** + * Deletes a given project + * + * @param projectId id of the project to delete + * @param userId id of the user + */ + Project deleteProjectById(int projectId, Integer userId) throws Exception; + /** * Returns if a project is public or not * @@ -193,6 +210,33 @@ public interface DALFacade { Statistic getStatisticsForAllProjects(int userId, Calendar since) throws BazaarException; Statistic getStatisticsForProject(int userId, int projectId, Calendar since) throws BazaarException; + + /** + * Get the members of a project and their according role + * + * @param projectId + * @return List of projectmembers in the project + */ + PaginationResult getProjectMembers(int projectId, Pageable pageable) throws BazaarException; + + /** + * Allows to remove a role from a user + * + * @param userId + * @param context + * @throws BazaarException + */ + void removeUserFromProject(int userId, Integer context) throws BazaarException; + + /** + * Returns the count most recent active projects followed by the user + * + * @param userId id of the follower + * @param count how many should be returned + * @return Followed projects ordered by last activity + */ + List getFollowedProjects(int userId, int count) throws BazaarException; + //endregion //region ProjectFollower @@ -248,6 +292,13 @@ public interface DALFacade { */ PaginationResult listRequirementsByCategory(int categoryId, Pageable pageable, int userId) throws BazaarException; + /** + * @param pageable pagination information + * @param userId + * @return the requirements filtered by pageable + */ + PaginationResult listAllRequirements(Pageable pageable, int userId) throws BazaarException; + /** * @param requirementId the identifier of the requirement should be returned * @return the requirement identified by the given id and all of its assets: comments,attachments,followers,developers,creator @@ -324,6 +375,15 @@ public interface DALFacade { boolean isRequirementPublic(int requirementId) throws BazaarException; Statistic getStatisticsForRequirement(int userId, int requirementId, Calendar timestamp) throws BazaarException; + + /** + * Returns the count most recent active requirements followed by the user + * + * @param userId id of the follower + * @param count how many should be returned + * @return Followed requirements ordered by last activity + */ + List getFollowedRequirements(int userId, int count) throws BazaarException; //endregion //region Category @@ -337,10 +397,9 @@ public interface DALFacade { /** * @param requirementId the id of the requirement we are looking in - * @param pageable pagination information * @return the categories under the given project in a paginated way */ - PaginationResult listCategoriesByRequirementId(int requirementId, Pageable pageable, int userId) throws BazaarException; + List listCategoriesByRequirementId(int requirementId, int userId) throws BazaarException; /** * @param category to be added to the database. @@ -378,6 +437,15 @@ public interface DALFacade { boolean isCategoryPublic(int categoryId) throws BazaarException; Statistic getStatisticsForCategory(int userId, int categoryId, Calendar timestamp) throws BazaarException; + + /** + * Returns the count most recent active categories followed by the user + * + * @param userId id of the follower + * @param count how many should be returned + * @return Followed categories ordered by last activity + */ + List getFollowedCategories(int userId, int count) throws BazaarException; //endregion //region CategoryFollower @@ -439,10 +507,22 @@ public interface DALFacade { /** * @param requirementId the identifier of the requirement we are looking in - * @param pageable pagination information * @return the comments for a given requirement */ - PaginationResult listCommentsByRequirementId(int requirementId, Pageable pageable) throws BazaarException; + List listCommentsByRequirementId(int requirementId) throws BazaarException; + + /** + * @param pageable pagination information + * @return the set of comments + */ + PaginationResult listAllComments(Pageable pageable) throws BazaarException; + + /** + * @param userId the identifier of user we are looking at + * @param pageable pagination information + * @return the answers for a given user + */ + PaginationResult listAllAnswers(Pageable pageable, int userId) throws BazaarException; /** * @param commentId @@ -455,6 +535,15 @@ public interface DALFacade { */ Comment createComment(Comment comment) throws Exception; + /** + * Updates a comment + * + * @param comment comment to persist + * @return the updated comment + * @throws Exception + */ + Comment updateComment(Comment comment) throws Exception; + /** * @param commentId to identify the comment to be deleted */ @@ -556,12 +645,129 @@ public interface DALFacade { * @param userId the identifier of the user * @return all the roles filled up with parents and permissions */ - List getRolesByUserId(int userId, String context) throws BazaarException; + List getRolesByUserId(int userId, Integer context) throws BazaarException; List getParentsForRole(int roleId) throws BazaarException; void createPrivilegeIfNotExists(PrivilegeEnum privilege) throws BazaarException; - void addUserToRole(int userId, String roleName, String context) throws BazaarException; + void addUserToRole(int userId, String roleName, Integer context) throws BazaarException; + + Role getRoleByName(String role) throws BazaarException; //endregion + + + /** + * Receives the PersonalisationData for a given userid, key and version + * + * @param userId which owns the personalisationData. + * @param key which identifies the personalisationData. + * @param version of the key's plugin + */ + PersonalisationData getPersonalisationData(int userId, String key, int version) throws BazaarException; + + /** + * Creates a new record or alters the existing record to save a given personalisationData + * + * @param personalisationData which holds the data to be saved + */ + void setPersonalisationData(PersonalisationData personalisationData) throws BazaarException; + + /** + * Creates an Entity-Overview for a given user + * + * @param includes List of entities to include values: [projects, categories, requirements] + * @param pageable Used for search-term, filters and sorting + * @param userId userId for privilege-check + */ + EntityOverview getEntitiesForUser(List includes, Pageable pageable, int userId) throws BazaarException; + + // region feedback + + /** + * Creates a new feedback item + * + * @param feedback the feedback to create (as submitted by the api) + * @return the created feedback item + * @throws BazaarException + */ + Feedback createFeedback(Feedback feedback) throws Exception; + + /** + * Returns the feedback for a project + * + * @param projectId Project to look for + * @param pageable a pageable + * @return Pageable with the feedback for this project + * @throws BazaarException + */ + PaginationResult getFeedbackByProject(int projectId, Pageable pageable) throws BazaarException; + + /** + * Allows to retrieve a single feedback item + * + * @param feedbackId ID of the feedback item + * @return the requested feedback item + * @throws Exception + */ + Feedback getFeedbackById(int feedbackId) throws Exception; + + // endregion feedback + + /** + * Aggregates the data for the dashboard + * + * @param userId Id of the user for their individual dashboard + * @param count Number of items per group + * @return + * @throws BazaarException + */ + Dashboard getDashboardData(int userId, int count) throws BazaarException; + + // region Tags + + /** + * Allows to retrieve a tag by its id + * + * @param id + * @return + */ + Tag getTagById(int id) throws Exception; + + /** + * Returns all tags associated with a project. + * + * @param projectId + * @return + */ + List getTagsByProjectId(int projectId) throws Exception; + + /** + * Creates a new project level tag + * + * @param tag + * @return + * @throws BazaarException + */ + Tag createTag(Tag tag) throws BazaarException; + + /** + * Link a tag to a requirement + * + * @param tagId id of the tag (project scoped) + * @param requirementId id of the requirement + * @return + * @throws BazaarException + */ + CreationStatus tagRequirement(int tagId, int requirementId) throws BazaarException; + + /** + * Removes a tag from a requirement + * + * @param tagId + * @param requirementId + * @throws Exception + */ + void untagRequirement(int tagId, int requirementId) throws Exception; + // endregion tags } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java similarity index 64% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java index ba8f7346..04a8d641 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeImpl.java @@ -28,9 +28,10 @@ import de.rwth.dbis.acis.bazaar.service.dal.repositories.*; import de.rwth.dbis.acis.bazaar.service.dal.transform.PrivilegeEnumConverter; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; import i5.las2peer.api.Context; -import i5.las2peer.api.security.Agent; import i5.las2peer.security.PassphraseAgentImpl; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -38,12 +39,13 @@ import javax.sql.DataSource; import java.sql.Timestamp; +import java.time.OffsetDateTime; +import java.time.ZoneOffset; import java.util.Calendar; import java.util.HashMap; import java.util.List; /** - * @author Adam Gavronek * @since 6/14/2014 */ public class DALFacadeImpl implements DALFacade { @@ -59,11 +61,15 @@ public class DALFacadeImpl implements DALFacade { private RequirementFollowerRepository requirementFollowerRepository; private ProjectRepository projectRepository; private RequirementRepository requirementRepository; - private RequirementCategoryRepository tagRepository; + private RequirementCategoryRepository requirementCategoryRepository; private UserRepository userRepository; private VoteRepository voteRepository; private RoleRepository roleRepository; private PrivilegeRepository privilegeRepository; + private PersonalisationDataRepository personalisationDataRepository; + private FeedbackRepository feedbackRepository; + private TagRepository tagRepository; + private RequirementTagRepository requirementTagRepository; public DALFacadeImpl(DataSource dataSource, SQLDialect dialect) { dslContext = DSL.using(dataSource, dialect); @@ -86,7 +92,8 @@ public DSLContext getDslContext() { @Override public void close() { - dslContext.close(); + // No longer necessary, jooq claims gc will take care of it + // dslContext.close(); } @Override @@ -179,6 +186,13 @@ public List getRecipientListForRequirement(int requirementId) throws Bazaa return userRepository.getEmailReceiverForRequirement(requirementId); } + @Override + public PaginationResult searchUsers(PageInfo pageInfo) throws BazaarException { + userRepository = (userRepository != null) ? userRepository : new UserRepositoryImpl(dslContext); + List users = userRepository.search(pageInfo); + return new PaginationResult<>(users.size(), pageInfo, users); + } + @Override public PaginationResult listPublicProjects(Pageable pageable, int userId) throws BazaarException { projectRepository = (projectRepository != null) ? projectRepository : new ProjectRepositoryImpl(dslContext); @@ -202,15 +216,24 @@ public Project createProject(Project project, int userId) throws Exception { projectRepository = (projectRepository != null) ? projectRepository : new ProjectRepositoryImpl(dslContext); project.setDefaultCategoryId(null); Project newProject = projectRepository.add(project); - Category uncategorizedCategory = Category.getBuilder(Localization.getInstance().getResourceBundle().getString("category.uncategorized.Name")) - .description(Localization.getInstance().getResourceBundle().getString("category.uncategorized.Description")) + + String categoryName = Localization.getInstance().getResourceBundle().getString("category.uncategorized.Name"); + String categoryDescription = Localization.getInstance().getResourceBundle().getString("category.uncategorized.Description"); + Category uncategorizedCategory = Category.builder() + .name(categoryName) + .description(categoryDescription) .projectId(newProject.getId()) .build(); - uncategorizedCategory.setLeader(project.getLeader()); + uncategorizedCategory.setCreator(project.getLeader()); Category defaultCategory = createCategory(uncategorizedCategory, userId); newProject.setDefaultCategoryId(defaultCategory.getId()); - //TODO concurrency transaction -> https://www.jooq.org/doc/3.9/manual/sql-execution/transaction-management/ - return projectRepository.update(newProject); + // TODO: concurrency transaction -> https://www.jooq.org/doc/3.9/manual/sql-execution/transaction-management/ + addUserToRole(userId, "ProjectAdmin", newProject.getId()); + + // This is stupid, but the return value of update is inclomplete (dependent objects won't be resolved, since only the top level get by id method is called. + // Call repository get separately + projectRepository.update(newProject); + return projectRepository.findById(newProject.getId(), userId); } @Override @@ -219,6 +242,14 @@ public Project modifyProject(Project modifiedProject) throws Exception { return projectRepository.update(modifiedProject); } + @Override + public Project deleteProjectById(int projectId, Integer userId) throws Exception { + projectRepository = (projectRepository != null) ? projectRepository : new ProjectRepositoryImpl(dslContext); + Project project = projectRepository.findById(projectId, userId); + projectRepository.delete(projectId); + return project; + } + @Override public boolean isProjectPublic(int projectId) throws BazaarException { projectRepository = (projectRepository != null) ? projectRepository : new ProjectRepositoryImpl(dslContext); @@ -229,14 +260,14 @@ public boolean isProjectPublic(int projectId) throws BazaarException { public Statistic getStatisticsForAllProjects(int userId, Calendar since) throws BazaarException { projectRepository = (projectRepository != null) ? projectRepository : new ProjectRepositoryImpl(dslContext); Timestamp timestamp = since == null ? new java.sql.Timestamp(0) : new java.sql.Timestamp(since.getTimeInMillis()); - return projectRepository.getStatisticsForVisibleProjects(userId, timestamp); + return projectRepository.getStatisticsForVisibleProjects(userId, timestamp.toLocalDateTime().atOffset(ZoneOffset.UTC)); } @Override public Statistic getStatisticsForProject(int userId, int projectId, Calendar since) throws BazaarException { projectRepository = (projectRepository != null) ? projectRepository : new ProjectRepositoryImpl(dslContext); Timestamp timestamp = since == null ? new java.sql.Timestamp(0) : new java.sql.Timestamp(since.getTimeInMillis()); - return projectRepository.getStatisticsForProject(userId, projectId, timestamp); + return projectRepository.getStatisticsForProject(userId, projectId, timestamp.toLocalDateTime().atOffset(ZoneOffset.UTC)); } @Override @@ -245,6 +276,13 @@ public PaginationResult listFollowersForProject(int projectId, Pageable pa return userRepository.findAllByFollowing(projectId, 0, 0, pageable); } + @Override + public List getFollowedProjects(int userId, int count) throws BazaarException { + projectRepository = (projectRepository != null) ? projectRepository : new ProjectRepositoryImpl(dslContext); + return projectRepository.getFollowedProjects(userId, count); + } + + @Override public List listRequirements(Pageable pageable) throws BazaarException { requirementRepository = (requirementRepository != null) ? requirementRepository : new RequirementRepositoryImpl(dslContext); @@ -263,6 +301,12 @@ public PaginationResult listRequirementsByCategory(int categoryId, return requirementRepository.findAllByCategory(categoryId, pageable, userId); } + @Override + public PaginationResult listAllRequirements(Pageable pageable, int userId) throws BazaarException { + requirementRepository = (requirementRepository != null) ? requirementRepository : new RequirementRepositoryImpl(dslContext); + return requirementRepository.findAll(pageable, userId); + } + @Override public Requirement getRequirementById(int requirementId, int userId) throws Exception { requirementRepository = (requirementRepository != null) ? requirementRepository : new RequirementRepositoryImpl(dslContext); @@ -273,8 +317,11 @@ public Requirement getRequirementById(int requirementId, int userId) throws Exce public Requirement createRequirement(Requirement requirement, int userId) throws Exception { requirementRepository = (requirementRepository != null) ? requirementRepository : new RequirementRepositoryImpl(dslContext); Requirement newRequirement = requirementRepository.add(requirement); - for (Category category : requirement.getCategories()) { - addCategoryTag(newRequirement.getId(), category.getId()); + for (Integer category : requirement.getCategories()) { + addCategoryTag(newRequirement.getId(), category); + } + for (Tag tag : requirement.getTags()) { + tagRequirement(tag.getId(), newRequirement.getId()); } return getRequirementById(newRequirement.getId(), userId); } @@ -282,14 +329,15 @@ public Requirement createRequirement(Requirement requirement, int userId) throws @Override public Requirement modifyRequirement(Requirement modifiedRequirement, int userId) throws Exception { requirementRepository = (requirementRepository != null) ? requirementRepository : new RequirementRepositoryImpl(dslContext); + Requirement oldRequirement = getRequirementById(modifiedRequirement.getId(), userId); requirementRepository.update(modifiedRequirement); if (modifiedRequirement.getCategories() != null) { - PaginationResult oldCategories = listCategoriesByRequirementId(modifiedRequirement.getId(), new PageInfo(0, 1000, new HashMap<>()), userId); - for (Category oldCategory : oldCategories.getElements()) { + List oldCategories = listCategoriesByRequirementId(modifiedRequirement.getId(), userId); + for (Category oldCategory : oldCategories) { boolean containCategory = false; - for (Category newCategory : modifiedRequirement.getCategories()) { - if (oldCategory.getId() == newCategory.getId()) { + for (Integer newCategory : modifiedRequirement.getCategories()) { + if (oldCategory.getId() == newCategory) { containCategory = true; break; } @@ -298,19 +346,79 @@ public Requirement modifyRequirement(Requirement modifiedRequirement, int userId deleteCategoryTag(modifiedRequirement.getId(), oldCategory.getId()); } } - for (Category newCategory : modifiedRequirement.getCategories()) { + for (Integer newCategory : modifiedRequirement.getCategories()) { boolean containCategory = false; - for (Category oldCategory : oldCategories.getElements()) { - if (oldCategory.getId() == newCategory.getId()) { + for (Category oldCategory : oldCategories) { + if (oldCategory.getId() == newCategory) { containCategory = true; break; } } if (!containCategory) { - addCategoryTag(modifiedRequirement.getId(), newCategory.getId()); + addCategoryTag(modifiedRequirement.getId(), newCategory); + } + } + } + + // Synchronize tags + if (modifiedRequirement.getTags() != null) { + // Check if tags have changed + for (Tag tag : modifiedRequirement.getTags()) { + try { + Tag internalTag = getTagById(tag.getId()); + + // Check if tag exists (in project) + if (internalTag == null || modifiedRequirement.getProjectId() != internalTag.getProjectId()) { + tag.setProjectId(modifiedRequirement.getProjectId()); + tag = createTag(tag); + } + tagRequirement(tag.getId(), modifiedRequirement.getId()); + } catch (Exception e) { + e.printStackTrace(); + } + } + + // Remove tags no longer present + oldRequirement.getTags().stream().filter(tag -> modifiedRequirement.getTags().contains(tag)).forEach(tag -> { + try { + untagRequirement(tag.getId(), oldRequirement.getId()); + } catch (Exception e) { + e.printStackTrace(); + } + }); + } + + // Synchronize attachments + if (modifiedRequirement.getAttachments() != null) { + // Check if tags have changed + for (Attachment attachment : modifiedRequirement.getAttachments()) { + try { + Attachment internalAttachment = null; + if (attachment.getId() != 0) { + internalAttachment = getAttachmentById(attachment.getId()); + } + + // Check if attachment exists, otherwise create + if (internalAttachment == null) { + attachment.setRequirementId(modifiedRequirement.getId()); + attachment.setCreator(getUserById(userId)); + createAttachment(attachment); + } + } catch (Exception e) { + e.printStackTrace(); } } + + // Remove tags no longer present + oldRequirement.getAttachments().stream().filter(attachment -> modifiedRequirement.getAttachments().contains(attachment)).forEach(attachment -> { + try { + deleteAttachmentById(attachment.getId()); + } catch (Exception e) { + e.printStackTrace(); + } + }); } + return getRequirementById(modifiedRequirement.getId(), userId); } @@ -325,7 +433,7 @@ public Requirement deleteRequirementById(int requirementId, int userId) throws E @Override public Requirement setRequirementToRealized(int requirementId, int userId) throws Exception { requirementRepository = (requirementRepository != null) ? requirementRepository : new RequirementRepositoryImpl(dslContext); - requirementRepository.setRealized(requirementId, new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); + requirementRepository.setRealized(requirementId, OffsetDateTime.now()); return getRequirementById(requirementId, userId); } @@ -360,7 +468,13 @@ public boolean isRequirementPublic(int requirementId) throws BazaarException { public Statistic getStatisticsForRequirement(int userId, int requirementId, Calendar since) throws BazaarException { requirementRepository = (requirementRepository != null) ? requirementRepository : new RequirementRepositoryImpl(dslContext); Timestamp timestamp = since == null ? new java.sql.Timestamp(0) : new java.sql.Timestamp(since.getTimeInMillis()); - return requirementRepository.getStatisticsForRequirement(userId, requirementId, timestamp); + return requirementRepository.getStatisticsForRequirement(userId, requirementId, timestamp.toLocalDateTime().atOffset(ZoneOffset.UTC)); + } + + @Override + public List getFollowedRequirements(int userId, int count) throws BazaarException { + requirementRepository = (requirementRepository != null) ? requirementRepository : new RequirementRepositoryImpl(dslContext); + return requirementRepository.getFollowedRequirements(userId, count); } @Override @@ -370,9 +484,9 @@ public PaginationResult listCategoriesByProjectId(int projectId, Pagea } @Override - public PaginationResult listCategoriesByRequirementId(int requirementId, Pageable pageable, int userId) throws BazaarException { + public List listCategoriesByRequirementId(int requirementId, int userId) throws BazaarException { categoryRepository = (categoryRepository != null) ? categoryRepository : new CategoryRepositoryImpl(dslContext); - return categoryRepository.findByRequirementId(requirementId, pageable, userId); + return categoryRepository.findByRequirementId(requirementId, userId); } @Override @@ -427,7 +541,13 @@ public boolean isCategoryPublic(int categoryId) throws BazaarException { public Statistic getStatisticsForCategory(int userId, int categoryId, Calendar since) throws BazaarException { categoryRepository = (categoryRepository != null) ? categoryRepository : new CategoryRepositoryImpl(dslContext); Timestamp timestamp = since == null ? new java.sql.Timestamp(0) : new java.sql.Timestamp(since.getTimeInMillis()); - return categoryRepository.getStatisticsForCategory(userId, categoryId, timestamp); + return categoryRepository.getStatisticsForCategory(userId, categoryId, timestamp.toLocalDateTime().atOffset(ZoneOffset.UTC)); + } + + @Override + public List getFollowedCategories(int userId, int count) throws BazaarException { + categoryRepository = (categoryRepository != null) ? categoryRepository : new CategoryRepositoryImpl(dslContext); + return categoryRepository.getFollowedCategories(userId, count); } @Override @@ -464,9 +584,21 @@ public Attachment deleteAttachmentById(int attachmentId) throws Exception { } @Override - public PaginationResult listCommentsByRequirementId(int requirementId, Pageable pageable) throws BazaarException { + public List listCommentsByRequirementId(int requirementId) throws BazaarException { commentRepository = (commentRepository != null) ? commentRepository : new CommentRepositoryImpl(dslContext); - return commentRepository.findAllByRequirementId(requirementId, pageable); + return commentRepository.findAllByRequirementId(requirementId); + } + + @Override + public PaginationResult listAllComments(Pageable pageable) throws BazaarException { + commentRepository = (commentRepository != null) ? commentRepository : new CommentRepositoryImpl(dslContext); + return commentRepository.findAllComments(pageable); + } + + @Override + public PaginationResult listAllAnswers(Pageable pageable, int userId) throws BazaarException { + commentRepository = (commentRepository != null) ? commentRepository : new CommentRepositoryImpl(dslContext); + return commentRepository.findAllAnswers(pageable, userId); } @Override @@ -482,18 +614,31 @@ public Comment createComment(Comment comment) throws Exception { return commentRepository.findById(newComment.getId()); } + @Override + public Comment updateComment(Comment comment) throws Exception { + commentRepository = (commentRepository != null) ? commentRepository : new CommentRepositoryImpl(dslContext); + commentRepository.update(comment); + return commentRepository.findById(comment.getId()); + } + @Override public Comment deleteCommentById(int commentId) throws Exception { commentRepository = (commentRepository != null) ? commentRepository : new CommentRepositoryImpl(dslContext); Comment comment = commentRepository.findById(commentId); - commentRepository.delete(commentId); + if (commentRepository.hasAnswers(commentId)) { + comment.setDeleted(true); + comment.setMessage("[This message has been deleted]"); + commentRepository.update(comment); + } else { + commentRepository.delete(commentId); + } return comment; } @Override public CreationStatus followProject(int userId, int projectId) throws BazaarException { projectFollowerRepository = (projectFollowerRepository != null) ? projectFollowerRepository : new ProjectFollowerRepositoryImpl(dslContext); - return projectFollowerRepository.addOrUpdate(ProjectFollower.getBuilder() + return projectFollowerRepository.addOrUpdate(ProjectFollower.builder() .projectId(projectId) .userId(userId) .build() @@ -509,7 +654,7 @@ public void unFollowProject(int userId, int projectId) throws BazaarException { @Override public CreationStatus followCategory(int userId, int categoryId) throws BazaarException { categoryFollowerRepository = (categoryFollowerRepository != null) ? categoryFollowerRepository : new CategoryFollowerRepositoryImpl(dslContext); - return categoryFollowerRepository.addOrUpdate(CategoryFollower.getBuilder() + return categoryFollowerRepository.addOrUpdate(CategoryFollower.builder() .categoryId(categoryId) .userId(userId) .build() @@ -525,7 +670,7 @@ public void unFollowCategory(int userId, int categoryId) throws BazaarException @Override public CreationStatus followRequirement(int userId, int requirementId) throws BazaarException { requirementFollowerRepository = (requirementFollowerRepository != null) ? requirementFollowerRepository : new RequirementFollowerRepositoryImpl(dslContext); - return requirementFollowerRepository.addOrUpdate(RequirementFollower.getBuilder() + return requirementFollowerRepository.addOrUpdate(RequirementFollower.builder() .requirementId(requirementId) .userId(userId) .build() @@ -541,7 +686,7 @@ public void unFollowRequirement(int userId, int requirementId) throws BazaarExce @Override public CreationStatus wantToDevelop(int userId, int requirementId) throws BazaarException { developerRepository = (developerRepository != null) ? developerRepository : new RequirementDeveloperRepositoryImpl(dslContext); - return developerRepository.addOrUpdate(RequirementDeveloper.getBuilder() + return developerRepository.addOrUpdate(RequirementDeveloper.builder() .requirementId(requirementId) .userId(userId) .build() @@ -557,8 +702,9 @@ public void notWantToDevelop(int userId, int requirementId) throws BazaarExcepti @Override public void addCategoryTag(int requirementId, int categoryId) throws BazaarException { - tagRepository = (tagRepository != null) ? tagRepository : new RequirementCategoryRepositoryImpl(dslContext); - tagRepository.add(RequirementCategory.getBuilder(categoryId) + requirementCategoryRepository = (requirementCategoryRepository != null) ? requirementCategoryRepository : new RequirementCategoryRepositoryImpl(dslContext); + requirementCategoryRepository.add(RequirementCategory.builder() + .categoryId(categoryId) .requirementId(requirementId) .build() ); @@ -566,14 +712,14 @@ public void addCategoryTag(int requirementId, int categoryId) throws BazaarExcep @Override public void deleteCategoryTag(int requirementId, int categoryId) throws BazaarException { - tagRepository = (tagRepository != null) ? tagRepository : new RequirementCategoryRepositoryImpl(dslContext); - tagRepository.delete(requirementId, categoryId); + requirementCategoryRepository = (requirementCategoryRepository != null) ? requirementCategoryRepository : new RequirementCategoryRepositoryImpl(dslContext); + requirementCategoryRepository.delete(requirementId, categoryId); } @Override public CreationStatus vote(int userId, int requirementId, boolean isUpVote) throws BazaarException { voteRepository = (voteRepository != null) ? voteRepository : new VoteRepositoryImpl(dslContext); - return voteRepository.addOrUpdate(Vote.getBuilder() + return voteRepository.addOrUpdate(Vote.builder() .requirementId(requirementId) .userId(userId) .isUpvote(isUpVote) @@ -594,7 +740,7 @@ public boolean hasUserVotedForRequirement(int userId, int requirementId) throws } @Override - public List getRolesByUserId(int userId, String context) throws BazaarException { + public List getRolesByUserId(int userId, Integer context) throws BazaarException { roleRepository = (roleRepository != null) ? roleRepository : new RoleRepositoryImpl(dslContext); return roleRepository.listRolesOfUser(userId, context); } @@ -611,14 +757,140 @@ public void createPrivilegeIfNotExists(PrivilegeEnum privilege) throws BazaarExc Privilege privilegeDb = privilegeRepository.findByName(new PrivilegeEnumConverter().to(privilege)); if (privilegeDb == null) { - privilegeRepository.add(Privilege.getBuilder(privilege).build()); + privilegeRepository.add(Privilege.builder().name(privilege).build()); } } @Override - public void addUserToRole(int userId, String roleName, String context) throws BazaarException { + public void addUserToRole(int userId, String roleName, Integer context) throws BazaarException { roleRepository = (roleRepository != null) ? roleRepository : new RoleRepositoryImpl(dslContext); roleRepository.addUserToRole(userId, roleName, context); } + + @Override + public Role getRoleByName(String role) throws BazaarException { + roleRepository = (roleRepository != null) ? roleRepository : new RoleRepositoryImpl(dslContext); + return roleRepository.findByRoleName(role); + } + + @Override + public void removeUserFromProject(int userId, Integer context) throws BazaarException { + roleRepository = (roleRepository != null) ? roleRepository : new RoleRepositoryImpl(dslContext); + roleRepository.removeUserFromRole(userId, context); + } + + @Override + public PersonalisationData getPersonalisationData(int userId, String key, int version) throws BazaarException { + personalisationDataRepository = (personalisationDataRepository != null) ? personalisationDataRepository : new PersonalisationDataRepositoryImpl(dslContext); + return personalisationDataRepository.findByKey(userId, version, key); + } + + @Override + public void setPersonalisationData(PersonalisationData personalisationData) throws BazaarException { + personalisationDataRepository = (personalisationDataRepository != null) ? personalisationDataRepository : new PersonalisationDataRepositoryImpl(dslContext); + personalisationDataRepository.insertOrUpdate(personalisationData); + + } + + @Override + public EntityOverview getEntitiesForUser(List includes, Pageable pageable, int userId) throws BazaarException { + //categoryRepository = (categoryRepository != null) ? categoryRepository : new CategoryRepositoryImpl(dslContext); + EntityOverview.Builder result = EntityOverview.builder(); + for (String include : includes) { + switch (include) { + case "projects" -> { + projectRepository = (projectRepository != null) ? projectRepository : new ProjectRepositoryImpl(dslContext); + result.projects(projectRepository.listAllProjectIds(pageable, userId)); + } + case "requirements" -> { + requirementRepository = (requirementRepository != null) ? requirementRepository : new RequirementRepositoryImpl(dslContext); + result.requirements(requirementRepository.listAllRequirementIds(pageable, userId)); + } + case "categories" -> { + categoryRepository = (categoryRepository != null) ? categoryRepository : new CategoryRepositoryImpl(dslContext); + result.categories(categoryRepository.listAllCategoryIds(pageable, userId)); + } + } + //TODO Add Comments/Attachments + } + return result.build(); + } + + @Override + public Feedback createFeedback(Feedback feedback) throws Exception { + feedbackRepository = (feedbackRepository != null) ? feedbackRepository : new FeedbackRepositoryImpl(dslContext); + Feedback newFeedback = feedbackRepository.add(feedback); + return feedbackRepository.findById(newFeedback.getId()); + } + + @Override + public PaginationResult getFeedbackByProject(int projectId, Pageable pageable) throws BazaarException { + feedbackRepository = (feedbackRepository != null) ? feedbackRepository : new FeedbackRepositoryImpl(dslContext); + return feedbackRepository.findAllByProject(projectId, pageable); + } + + @Override + public Feedback getFeedbackById(int feedbackId) throws Exception { + feedbackRepository = (feedbackRepository != null) ? feedbackRepository : new FeedbackRepositoryImpl(dslContext); + return feedbackRepository.findById(feedbackId); + } + + @Override + public Dashboard getDashboardData(int userId, int count) throws BazaarException { + return Dashboard.builder() + .projects(getFollowedProjects(userId, count)) + .categories(getFollowedCategories(userId, count)) + .requirements(getFollowedRequirements(userId, count)) + .build(); + } + + @Override + public Tag getTagById(int id) throws Exception { + tagRepository = (tagRepository != null) ? tagRepository : new TagRepositoryImpl(dslContext); + try { + return tagRepository.findById(id); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return null; + } + ExceptionHandler.getInstance().convertAndThrowException(bex); + } + return null; + } + + @Override + public List getTagsByProjectId(int projectId) throws Exception { + tagRepository = (tagRepository != null) ? tagRepository : new TagRepositoryImpl(dslContext); + return tagRepository.findByProjectId(projectId); + } + + @Override + public Tag createTag(Tag tag) throws BazaarException { + tagRepository = (tagRepository != null) ? tagRepository : new TagRepositoryImpl(dslContext); + return tagRepository.add(tag); + } + + @Override + public CreationStatus tagRequirement(int tagId, int requirementId) throws BazaarException { + requirementTagRepository = (requirementTagRepository != null) ? requirementTagRepository : new RequirementTagRepositoryImpl(dslContext); + return requirementTagRepository.addOrUpdate(RequirementTag.builder() + .requirementId(requirementId) + .tagId(tagId) + .build() + ); + } + + @Override + public void untagRequirement(int tagId, int requirementId) throws Exception { + requirementTagRepository = (requirementTagRepository != null) ? requirementTagRepository : new RequirementTagRepositoryImpl(dslContext); + requirementTagRepository.delete(tagId, requirementId); + } + + @Override + public PaginationResult getProjectMembers(int projectId, Pageable pageable) throws + BazaarException { + roleRepository = (roleRepository != null) ? roleRepository : new RoleRepositoryImpl(dslContext); + return roleRepository.listProjectMembers(projectId, pageable); + } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Activity.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Activity.java new file mode 100644 index 00000000..3be33d10 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Activity.java @@ -0,0 +1,90 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonFilter; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.NonNull; +import lombok.extern.jackson.Jacksonized; + +import java.time.OffsetDateTime; + +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Activity extends EntityBase { + + private final transient int id; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private final OffsetDateTime creationDate; + + private final ActivityAction activityAction; + private final String dataUrl; + private final DataType dataType; + private final String dataFrontendUrl; + private final String parentDataUrl; + private final DataType parentDataType; + private final String userUrl; + private final String origin; + + private AdditionalObject additionalObject; + + @Override + @JsonIgnore + public int getId() { + return id; + } + + public enum DataType { + STATISTIC, + PROJECT, + CATEGORY, + REQUIREMENT, + COMMENT, + ATTACHMENT, + USER, + FEEDBACK, + TAG + } + + public enum ActivityAction { + RETRIEVE, + RETRIEVE_CHILD, + CREATE, + UPDATE, + DELETE, + REALIZE, + UNREALIZE, + VOTE, + UNVOTE, + DEVELOP, + UNDEVELOP, + FOLLOW, + UNFOLLOW, + LEADDEVELOP, + UNLEADDEVELOP + } + + @Data + public static class AdditionalObject { + @JsonFilter("ActivityFilter") + @NonNull + private Project project; + + @JsonFilter("ActivityFilter") + @NonNull + private Category category; + + @JsonFilter("ActivityFilter") + @NonNull + private Requirement requirement; + + @JsonFilter("ActivityFilter") + @NonNull + private User user; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Attachment.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Attachment.java new file mode 100644 index 00000000..64f867b8 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Attachment.java @@ -0,0 +1,82 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonFormat; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreateValidation; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.time.OffsetDateTime; + +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Attachment extends EntityBase implements Ownable { + + private int id; + + @NotNull(groups = CreateValidation.class) + @Size(min = 1, max = 50) + private String name; + + private String description; + + @NotNull(groups = CreateValidation.class) + @Size(min = 1, max = 1000) + private String mimeType; + + @NotNull(groups = CreateValidation.class) + @Size(min = 1, max = 1000) + private String identifier; + + @NotNull(groups = CreateValidation.class) + @Size(min = 1, max = 1000) + private String fileUrl; + + @NotNull + @Min(value = 0) + private int requirementId; + + private User creator; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime creationDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime lastUpdatedDate; + + @Override + public boolean isOwner(User user) { + return creator == user; + } + + @Override + public boolean isOwner(Integer userId) { + return creator.getId() == userId; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Category.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Category.java new file mode 100644 index 00000000..4a03b112 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Category.java @@ -0,0 +1,90 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.entities; + + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.databind.JsonNode; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreateValidation; +import io.swagger.annotations.ApiModelProperty; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.time.OffsetDateTime; + +/** + * @since 6/9/2014 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Category extends EntityBase implements Ownable { + + private int id; + + @NotNull(message = "name can't be null", groups = CreateValidation.class) + @Size(min = 1, max = 50, message = "name must have between 1 and 50 characters") + private String name; + + @NotNull(groups = CreateValidation.class) + @Size(min = 1) + private String description; + + @Min(value = 0, groups = CreateValidation.class) + private int projectId; + + private User creator; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime creationDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime lastUpdatedDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime lastActivity; + + private Integer numberOfRequirements; + private Integer numberOfFollowers; + + private UserContext userContext; + + @ApiModelProperty( + dataType = "java.util.Map" + ) + private JsonNode additionalProperties; + + @Override + public boolean isOwner(User user) { + return creator == user; + } + + @Override + public boolean isOwner(Integer userId) { + return creator.getId() == userId; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryContributors.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryContributors.java new file mode 100644 index 00000000..91a34dfd --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryContributors.java @@ -0,0 +1,34 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import java.util.List; + +/** + * Created by Martin on 15.06.2017. + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class CategoryContributors extends EntityBase { + + private final int id; + + private User leader; + private List requirementCreator; + private List leadDeveloper; + private List developers; + private List commentCreator; + private List attachmentCreator; + + @Override + @JsonIgnore + public int getId() { + return id; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryFollower.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryFollower.java new file mode 100644 index 00000000..eac84c31 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryFollower.java @@ -0,0 +1,16 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class CategoryFollower extends EntityBase { + private final int id; + private final int categoryId; + private final int userId; +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Comment.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Comment.java new file mode 100644 index 00000000..562d26e3 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Comment.java @@ -0,0 +1,81 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.entities; + + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreateValidation; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.time.OffsetDateTime; + +/** + * @since 6/11/2014 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Comment extends EntityBase implements Ownable { + + private int id; + + @NotNull(groups = CreateValidation.class) + @Size(min = 1) + private String message; + + @Min(value = 0, groups = CreateValidation.class) + private Integer replyToComment; + + @Min(value = 0, groups = CreateValidation.class) + private int requirementId; + + private User creator; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime creationDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime lastUpdatedDate; + + @lombok.Builder.Default + private Boolean deleted = false; + + @JsonProperty("_context") + private EntityContext context; + + @Override + public boolean isOwner(User user) { + return creator == user; + } + + @Override + public boolean isOwner(Integer userId) { + return creator.getId() == userId; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Dashboard.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Dashboard.java new file mode 100644 index 00000000..40ba5361 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Dashboard.java @@ -0,0 +1,34 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.UserVote; +import io.swagger.annotations.ApiModelProperty; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.NotNull; +import java.util.List; + +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Dashboard extends EntityBase { + + @NotNull + private List projects; + + @NotNull + private List categories; + + @NotNull + private List requirements; + + @JsonIgnore + @Override + public int getId() { + return 0; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Direction.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Direction.java new file mode 100644 index 00000000..634fce71 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Direction.java @@ -0,0 +1,16 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Getter; +import lombok.Setter; + +public class Direction { + @Getter + @Setter + private VoteDirection direction; + + @JsonIgnore + public boolean isUpVote() { + return direction == VoteDirection.up; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Email.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Email.java new file mode 100644 index 00000000..fa1b0cbd --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Email.java @@ -0,0 +1,35 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + + +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import java.time.OffsetDateTime; +import java.util.Set; + +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder", toBuilder = true) +public class Email extends EntityBase { + + private final transient int id; + + private final Set recipients; + private final String subject; + private final String starting; + private final String message; + private final String closing; + private final String footer; + private final OffsetDateTime creationDate; + + public static Activity.Builder getBuilder() { + return new Activity.Builder(); + } + + public void removeRecipient(User user) { + recipients.remove(user); + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java new file mode 100644 index 00000000..df72d589 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java @@ -0,0 +1,48 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.SerializerViews; + +/** + * @since 9/16/2014 + */ +public abstract class EntityBase implements IdentifiedById { + + public String toJSON() throws JsonProcessingException { + return new ObjectMapper().registerModule(new JavaTimeModule()) + .setSerializationInclusion(JsonInclude.Include.NON_NULL) + .writerWithView(SerializerViews.Public.class) + .writeValueAsString(this); + } + + public String toPrivateJSON() throws JsonProcessingException { + return new ObjectMapper() + .registerModule(new JavaTimeModule()) + .setSerializationInclusion(JsonInclude.Include.NON_NULL) + .writerWithView(SerializerViews.Private.class) + .writeValueAsString(this); + } +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityContext.java similarity index 64% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityContext.java index f7027257..5c5b1a35 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityBase.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityContext.java @@ -20,17 +20,29 @@ package de.rwth.dbis.acis.bazaar.service.dal.entities; + import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import lombok.Builder; +import lombok.Data; +import lombok.extern.jackson.Jacksonized; /** - * @author Adam Gavronek - * @since 9/16/2014 + * @since 30/01/2020 */ -public abstract class EntityBase implements IdentifiedById { +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class EntityContext { + private User user; + private Project project; + private Category[] categories; + private Requirement requirement; + private Comment comment; public String toJSON() throws JsonProcessingException { - return new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL).writeValueAsString(this); + return new ObjectMapper().registerModule(new JavaTimeModule()).setSerializationInclusion(JsonInclude.Include.NON_NULL).writeValueAsString(this); } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityOverview.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityOverview.java new file mode 100644 index 00000000..7e49d702 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/EntityOverview.java @@ -0,0 +1,51 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.entities; + + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import lombok.Builder; +import lombok.Data; +import lombok.extern.jackson.Jacksonized; + +import java.util.List; + +/** + * @since 22/01/2020 + */ +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class EntityOverview { + + private List projects; + private List categories; + private List requirements; + private List comments; + private List attachments; + + public String toJSON() throws JsonProcessingException { + return new ObjectMapper().registerModule(new JavaTimeModule()).setSerializationInclusion(JsonInclude.Include.NON_NULL).writeValueAsString(this); + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Feedback.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Feedback.java new file mode 100644 index 00000000..e5b9ee00 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Feedback.java @@ -0,0 +1,36 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreateValidation; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import java.time.OffsetDateTime; + +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Feedback extends EntityBase { + private int id; + + @NotNull(message = "feedback needs an associated project", groups = CreateValidation.class) + @Min(value = 0, groups = CreateValidation.class) + private int projectId; + + @NotNull(message = "feedback can not be null", groups = CreateValidation.class) + private String feedback; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime creationDate; + + @JsonProperty("email") + private String eMail; + + private Integer requirementId; +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/IdentifiedById.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/IdentifiedById.java similarity index 94% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/IdentifiedById.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/IdentifiedById.java index 70e65d51..077b68d9 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/IdentifiedById.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/IdentifiedById.java @@ -21,7 +21,6 @@ package de.rwth.dbis.acis.bazaar.service.dal.entities; /** - * @author Adam Gavronek * @since 6/9/2014 */ public interface IdentifiedById { diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Ownable.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Ownable.java new file mode 100644 index 00000000..388b03b7 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Ownable.java @@ -0,0 +1,11 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +public interface Ownable { + @JsonIgnore + boolean isOwner(User user); + + @JsonIgnore + boolean isOwner(Integer userId); +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/PersonalisationData.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/PersonalisationData.java new file mode 100644 index 00000000..1aa8833a --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/PersonalisationData.java @@ -0,0 +1,54 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; + +/** + * @since 26/11/2019 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class PersonalisationData extends EntityBase { + private int id; + + @NotNull + @Size(min = 1, max = 50, message = "Key must have between 1 and 50 characters") + private String key; + + @Min(value = 0) + private int version; + + private int userId; + + @NotNull + @Size(min = 1, max = 10000) + private String value; +} diff --git a/src/test/de/rwth/dbis/acis/bazaar/service/security/SpecialRightsTest.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Privilege.java similarity index 65% rename from src/test/de/rwth/dbis/acis/bazaar/service/security/SpecialRightsTest.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Privilege.java index 60fc2354..0a81ba33 100644 --- a/src/test/de/rwth/dbis/acis/bazaar/service/security/SpecialRightsTest.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Privilege.java @@ -18,12 +18,23 @@ * / */ -package de.rwth.dbis.acis.bazaar.service.security; +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; /** - * @author Adam Gavronek - * @since 2/25/2015 + * @since 2/17/2015 */ -public class SpecialRightsTest { +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Privilege extends EntityBase { + + private final int id; + private final PrivilegeEnum name; } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/PrivilegeEnum.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/PrivilegeEnum.java similarity index 86% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/PrivilegeEnum.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/PrivilegeEnum.java index 68e4b9ae..14987d37 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/PrivilegeEnum.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/PrivilegeEnum.java @@ -21,7 +21,6 @@ package de.rwth.dbis.acis.bazaar.service.dal.entities; /** - * @author Adam Gavronek * @since 2/17/2015 */ public enum PrivilegeEnum { @@ -29,6 +28,7 @@ public enum PrivilegeEnum { Read_PROJECT, Read_PUBLIC_PROJECT, Modify_PROJECT, + Delete_PROJECT, Create_CATEGORY, Read_CATEGORY, @@ -39,6 +39,7 @@ public enum PrivilegeEnum { Read_REQUIREMENT, Read_PUBLIC_REQUIREMENT, Modify_REQUIREMENT, + Realize_REQUIREMENT, Create_COMMENT, Read_COMMENT, @@ -54,4 +55,11 @@ public enum PrivilegeEnum { Create_FOLLOW, Delete_FOLLOW, Create_DEVELOP, Delete_DEVELOP, + Read_PERSONALISATION_DATA, Create_PERSONALISATION_DATA, //Create covers "PUT" Operation + + Read_FEEDBACK, + Modify_MEMBERS, + Modify_ADMIN_MEMBERS, + + Read_USERS, } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Project.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Project.java new file mode 100644 index 00000000..093736dc --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Project.java @@ -0,0 +1,90 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.databind.JsonNode; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreateValidation; +import io.swagger.annotations.ApiModelProperty; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.time.OffsetDateTime; + +/** + * @since 6/9/2014 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Project extends EntityBase implements Ownable { + + private int id; + + @NotNull(message = "name can not be null", groups = CreateValidation.class) + @Size(min = 1, max = 50, message = "name can't have more than 50 characters") + private String name; + + @NotNull(message = "description can not be null", groups = CreateValidation.class) + private String description; + + @lombok.Builder.Default + private Boolean visibility = true; + + private Integer defaultCategoryId; + + private User leader; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime creationDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime lastUpdatedDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime lastActivity; + + private Integer numberOfCategories; + private Integer numberOfRequirements; + private Integer numberOfFollowers; + + private UserContext userContext; + + @ApiModelProperty( + dataType = "java.util.Map" + ) + private JsonNode additionalProperties; + + @Override + public boolean isOwner(User user) { + return leader.equals(user); + } + + @Override + public boolean isOwner(Integer userId) { + return leader.getId() == userId; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectContributors.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectContributors.java new file mode 100644 index 00000000..8c574408 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectContributors.java @@ -0,0 +1,35 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import java.util.List; + +/** + * Created by Martin on 15.06.2017. + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class ProjectContributors extends EntityBase { + + private final int id; + + private User leader; + private List categoryLeader; + private List requirementCreator; + private List leadDeveloper; + private List developers; + private List commentCreator; + private List attachmentCreator; + + @Override + @JsonIgnore + public int getId() { + return id; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectFollower.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectFollower.java new file mode 100644 index 00000000..7df040ca --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectFollower.java @@ -0,0 +1,16 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class ProjectFollower extends EntityBase { + private final int id; + private final int projectId; + private final int userId; +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectMember.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectMember.java new file mode 100644 index 00000000..e10a19b3 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectMember.java @@ -0,0 +1,41 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonGetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.NotNull; + +/** + * Abstracts the project membership data + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class ProjectMember extends EntityBase { + + private int id; + + @NotNull + private int userId; + + @NotNull + private ProjectRole role; + + @JsonIgnore + private User user; + + @JsonGetter("userProfileImage") + public String getProfileImage() { + return user.getProfileImage(); + } + + @JsonGetter("userName") + public String getUserName() { + return user.getUserName(); + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectRole.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectRole.java new file mode 100644 index 00000000..b5add1ad --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectRole.java @@ -0,0 +1,7 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +public enum ProjectRole { + ProjectMember, + ProjectManager, + ProjectAdmin +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Requirement.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Requirement.java new file mode 100644 index 00000000..d97ed23d --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Requirement.java @@ -0,0 +1,96 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.JsonNode; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreateValidation; +import io.swagger.annotations.ApiModelProperty; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.List; + +/** + * Requirement entity + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Requirement extends EntityBase implements Ownable { + + private int id; + + @NotNull + @Size(min = 1, max = 50, message = "name must be between 1 and 50 characters") + private String name; + + @NotNull(message = "description should not be null", groups = CreateValidation.class) + @Size(min = 1, message = "Description can't be empty") + private String description; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime realized; + + @Min(value = 0) + @NotNull(message = "A project id must be provided", groups = CreateValidation.class) + private int projectId; + + private User creator; + private User leadDeveloper; + + @NotNull(message = "categories should not be null", groups = CreateValidation.class) + @Size(min = 1, groups = CreateValidation.class) + private List categories; + + // This field is not filled because attachments should be not included in requirements response. + // But the API still allows to create a requirement with attachments at the same time. + private List attachments; + + @lombok.Builder.Default + private List tags = new ArrayList<>(); + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime creationDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime lastUpdatedDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + private OffsetDateTime lastActivity; + + private Integer numberOfComments; + private Integer numberOfAttachments; + private Integer numberOfFollowers; + + private int upVotes; + private int downVotes; + + private UserContext userContext; + + @ApiModelProperty( + dataType = "java.util.Map" + ) + private JsonNode additionalProperties; + + @JsonProperty("_context") + private EntityContext context; + + @Override + public boolean isOwner(User user) { + return creator == user; + } + + @Override + public boolean isOwner(Integer userId) { + return creator.getId() == userId; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementCategory.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementCategory.java new file mode 100644 index 00000000..4de6229a --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementCategory.java @@ -0,0 +1,40 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +/** + * @since 6/11/2014 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class RequirementCategory extends EntityBase { + + private final int id; + private final int categoryId; + private final int requirementId; +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementContributors.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementContributors.java new file mode 100644 index 00000000..c07e0166 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementContributors.java @@ -0,0 +1,28 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import java.util.List; + +// import javax.ws.rs.core.Link; + +/** + * Created by Martin on 12.06.2017. + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class RequirementContributors extends EntityBase { + + private final int id; + + private User creator; + private User leadDeveloper; + private List developers; + private List commentCreator; + private List attachmentCreator; +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementDeveloper.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementDeveloper.java new file mode 100644 index 00000000..10e8bf36 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementDeveloper.java @@ -0,0 +1,39 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +/** + * @since 6/11/2014 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class RequirementDeveloper extends EntityBase { + private final int id; + private final int requirementId; + private final int userId; +} diff --git a/src/test/de/rwth/dbis/acis/bazaar/service/TestBase.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementFollower.java similarity index 62% rename from src/test/de/rwth/dbis/acis/bazaar/service/TestBase.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementFollower.java index 3726e2b5..14e4210a 100644 --- a/src/test/de/rwth/dbis/acis/bazaar/service/TestBase.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementFollower.java @@ -1,4 +1,4 @@ - /* +/* * * Copyright (c) 2014, RWTH Aachen University. * For a list of contributors see the AUTHORS file at the top-level directory @@ -18,10 +18,22 @@ * / */ -package de.rwth.dbis.acis.bazaar.service; +package de.rwth.dbis.acis.bazaar.service.dal.entities; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; -// TODO: update tests, see older revision -public abstract class TestBase { - +/** + * @since 6/11/2014 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class RequirementFollower extends EntityBase { + private final int id; + private final int requirementId; + private final int userId; } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementTag.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementTag.java new file mode 100644 index 00000000..e9b0e1c7 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementTag.java @@ -0,0 +1,17 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class RequirementTag extends EntityBase { + private final int id; + private final int requirementId; + + private int tagId; +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Role.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Role.java similarity index 51% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Role.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Role.java index 1c97c8ce..603acf0d 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Role.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Role.java @@ -20,68 +20,53 @@ package de.rwth.dbis.acis.bazaar.service.dal.entities; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; +import net.minidev.json.annotate.JsonIgnore; + import java.util.List; /** - * @author Adam Gavronek * @since 2/17/2015 */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") public class Role extends EntityBase { - private final int Id; + private final int id; private final List privileges; - private final String name; - private Role(Builder builder) { - Id = builder.id; - this.privileges = builder.privileges; - - this.name = builder.name; + @JsonIgnore + public boolean isProjectScoped() { + try { + ProjectRole.valueOf(name); + return true; + } catch (IllegalArgumentException e) { + return false; + } } @Override - public int getId() { - return Id; - } - - public List getPrivileges() { - return privileges; - } - - - public String getName() { - return name; - } - - public static Builder getBuilder(String name) { - return new Builder(name); - } - - public static class Builder { - private String name; - private int id; - private List privileges; - - - public Builder(String name) { - this.name = name; + public boolean equals(Object o) { + if (o == this) { + return true; } - - public Builder id(int id) { - this.id = id; - return this; - } - - public Builder privileges(List privileges) { - this.privileges = privileges; - return this; + if (!(o instanceof Role)) { + return false; } + Role other = (Role) o; - public Role build() { - return new Role(this); + if (isProjectScoped()) { + return id == other.id; } + return name.equals(other.name); } + } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Statistic.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Statistic.java new file mode 100644 index 00000000..0382e495 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Statistic.java @@ -0,0 +1,29 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import lombok.Builder; +import lombok.Data; +import lombok.extern.jackson.Jacksonized; + +/** + * Created by hugif on 26.12.2016. + */ +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Statistic { + + private int numberOfProjects; + private int numberOfCategories; + private int numberOfRequirements; + private int numberOfComments; + private int numberOfAttachments; + private int numberOfVotes; + + public String toJSON() throws JsonProcessingException { + return new ObjectMapper().registerModule(new JavaTimeModule()).setSerializationInclusion(JsonInclude.Include.NON_NULL).writeValueAsString(this); + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/SystemRole.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/SystemRole.java new file mode 100644 index 00000000..1dcaa357 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/SystemRole.java @@ -0,0 +1,7 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +public enum SystemRole { + Anonymous, + LoggedInUser, + SystemAdmin, +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Tag.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Tag.java new file mode 100644 index 00000000..d1beabb2 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Tag.java @@ -0,0 +1,27 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.NotNull; + +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Tag extends EntityBase { + + private final int id; + + @NotNull + private String name; + + @NotNull + private String colour; + + @JsonIgnore + private Integer projectId; +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/User.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/User.java new file mode 100644 index 00000000..d2091d73 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/User.java @@ -0,0 +1,126 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.entities; + + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonView; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.SerializerViews; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.time.OffsetDateTime; +import java.util.Objects; + +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class User extends EntityBase { + + private int id; + + @NotNull(message = "Username can't be null") + @Size(min = 1, max = 1000, message = "Username must have between 1 and 1000 characters") + private String userName; + + @Size(min = 1, max = 1000, message = "first name must have between 1 and 1000 characters") + @JsonView(SerializerViews.Private.class) + private String firstName; + + @Size(min = 1, max = 1000, message = "last name must have between 1 and 1000 characters") + @JsonView(SerializerViews.Private.class) + private String lastName; + + @NotNull(message = "eMail can't be null") + @Size(min = 1, max = 1000, message = "eMail must have between 1 and 1000 characters") + private transient String eMail; + + @NotNull(message = "las2peerId can't be null") + @Size(min = 1, max = 1000, message = "las2peerId must have between 1 and 1000 characters") + @JsonView(SerializerViews.Private.class) + private String las2peerId; + + private String profileImage; + + @JsonView(SerializerViews.Private.class) + private Boolean emailLeadSubscription; + + @JsonView(SerializerViews.Private.class) + private Boolean emailFollowSubscription; + + @JsonView(SerializerViews.Private.class) + private Boolean personalizationEnabled; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + @JsonView(SerializerViews.Private.class) + private OffsetDateTime creationDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + @JsonView(SerializerViews.Private.class) + private OffsetDateTime lastUpdatedDate; + + @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone = "Europe/Berlin") + @JsonView(SerializerViews.Private.class) + private OffsetDateTime lastLoginDate; + + @JsonView(SerializerViews.Private.class) + public String getEMail() { + return eMail; + } + + @JsonView(SerializerViews.Private.class) + public Boolean isEmailLeadSubscription() { + return emailLeadSubscription != null && emailLeadSubscription; + } + + @JsonView(SerializerViews.Private.class) + public Boolean isEmailFollowSubscription() { + return emailFollowSubscription != null && emailFollowSubscription; + } + + @JsonView(SerializerViews.Private.class) + public Boolean isPersonalizationEnabled() { + return personalizationEnabled != null && personalizationEnabled; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (!(o instanceof User)) { + return false; + } + User other = (User) o; + + return las2peerId.equals(other.las2peerId); + } + + @Override + public int hashCode() { + return Objects.hash(id, userName, firstName, lastName, eMail, las2peerId, profileImage, emailLeadSubscription, emailFollowSubscription, personalizationEnabled, creationDate, lastUpdatedDate, lastLoginDate); + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/UserContext.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/UserContext.java new file mode 100644 index 00000000..e5bc98f2 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/UserContext.java @@ -0,0 +1,50 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.UserVote; +import io.swagger.annotations.ApiModelProperty; +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +import javax.validation.constraints.NotNull; + +/** + * Dynamic object to provide the context the currently logged in user has provided to the related object + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class UserContext extends EntityBase { + + @ApiModelProperty( + value = "The role the user has within the project. Only returned when requesting project resources." + ) + private ProjectRole userRole; + + @ApiModelProperty( + value = "Only returned when requesting requirement resources." + ) + private UserVote userVoted; + + @NotNull + private Boolean isFollower; + + @ApiModelProperty( + value = "Only returned when requesting requirement resources." + ) + private Boolean isDeveloper; + + @ApiModelProperty( + value = "Only returned when requesting requirement resources." + ) + private Boolean isContributor; + + @JsonIgnore + @Override + public int getId() { + return 0; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Vote.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Vote.java new file mode 100644 index 00000000..95d43730 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/Vote.java @@ -0,0 +1,40 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +import lombok.Builder; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.extern.jackson.Jacksonized; + +/** + * @since 6/11/2014 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@Jacksonized +@Builder(builderClassName = "Builder") +public class Vote extends EntityBase { + private final int id; + private final boolean isUpvote; + private final int requirementId; + private final int userId; +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/VoteDirection.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/VoteDirection.java new file mode 100644 index 00000000..07f5c86b --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/entities/VoteDirection.java @@ -0,0 +1,6 @@ +package de.rwth.dbis.acis.bazaar.service.dal.entities; + +public enum VoteDirection { + up, + down, +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/CreateValidation.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/CreateValidation.java new file mode 100644 index 00000000..f62624ab --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/CreateValidation.java @@ -0,0 +1,11 @@ +package de.rwth.dbis.acis.bazaar.service.dal.helpers; + +import javax.validation.GroupSequence; +import javax.validation.groups.Default; + +/** + * Does nothing but acts as a group for hibernate validation + */ +@GroupSequence(Default.class) +public interface CreateValidation { +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/CreationStatus.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/CreationStatus.java similarity index 94% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/CreationStatus.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/CreationStatus.java index 804ae8fe..c170f1fc 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/CreationStatus.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/CreationStatus.java @@ -21,7 +21,6 @@ package de.rwth.dbis.acis.bazaar.service.dal.helpers; /** - * @author Adam Gavronek * @since 2/27/2015 */ public enum CreationStatus { diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/EntityContextFactory.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/EntityContextFactory.java new file mode 100644 index 00000000..a8df9ff7 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/EntityContextFactory.java @@ -0,0 +1,62 @@ +package de.rwth.dbis.acis.bazaar.service.dal.helpers; + + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.CategoryRecord; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.ProjectRecord; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Category; +import de.rwth.dbis.acis.bazaar.service.dal.entities.EntityContext; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Project; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Requirement; +import de.rwth.dbis.acis.bazaar.service.dal.transform.CategoryTransformer; +import de.rwth.dbis.acis.bazaar.service.dal.transform.ProjectTransformer; +import de.rwth.dbis.acis.bazaar.service.dal.transform.RequirementTransformer; +import org.jooq.Record; + +import java.util.List; + +public class EntityContextFactory{ + private static ProjectTransformer projectTransformer; + private static CategoryTransformer categoryTransformer; + private static RequirementTransformer requirementTransformer; + + + public static EntityContext create(List embed, Record record){ + EntityContext.Builder contextBuilder = EntityContext.builder(); + if(embed != null) { + for (String entry : embed) { + if (entry.equalsIgnoreCase("project")) { + contextBuilder.project(transformToProject(record)); + + } else if (entry.equalsIgnoreCase("category")) { + //TODO Need to handle multiple Categories + //context.category(transformToCategory(record)); + + } else if (entry.equalsIgnoreCase("requirement")) { + contextBuilder.requirement(transformToRequirement(record)); + } + } + } + return contextBuilder.build(); + } + + private static Project transformToProject(Record record){ + projectTransformer = (projectTransformer != null) ? projectTransformer : new ProjectTransformer(); + ProjectRecord projectRecord = record.into(ProjectRecord.class); + return projectTransformer.getEntityFromTableRecord(projectRecord); + } + private static Category transformToCategory(Record record){ + categoryTransformer = (categoryTransformer != null) ? categoryTransformer : new CategoryTransformer(); + CategoryRecord categoryRecord = record.into(CategoryRecord.class); + return categoryTransformer.getEntityFromTableRecord(categoryRecord); + } + private static Requirement transformToRequirement(Record record){ + requirementTransformer = (requirementTransformer != null) ? requirementTransformer : new RequirementTransformer(); + RequirementRecord requirementRecord= record.into(RequirementRecord.class); + return requirementTransformer.getEntityFromTableRecord(requirementRecord); + } + + + + +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/PageInfo.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/PageInfo.java similarity index 61% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/PageInfo.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/PageInfo.java index 1fa917b1..518339a3 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/PageInfo.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/PageInfo.java @@ -20,8 +20,7 @@ package de.rwth.dbis.acis.bazaar.service.dal.helpers; -import jodd.vtor.constraint.Min; - +import javax.validation.constraints.Min; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -32,6 +31,7 @@ * @since 6/15/2014 */ public class PageInfo implements Pageable { + @Min(-1) private final int pageNumber; @Min(0) @@ -39,21 +39,45 @@ public class PageInfo implements Pageable { private final Map filters; private final List sorts; private final String search; + private final List ids; + private final List embed; + private final Map options; + public PageInfo(int pageNumber, int pageSize) { - this(pageNumber, pageSize, new HashMap<>(), new ArrayList<>(), null); + this(pageNumber, pageSize, new HashMap<>(), new ArrayList<>(), null, null); } + public PageInfo(int pageNumber, int pageSize, Map filters) { this(pageNumber, pageSize, filters, new ArrayList<>(), null); } + public PageInfo(int pageNumber, int pageSize, Map filters, List sorts) { + this(pageNumber, pageSize, filters, sorts, null); + } + public PageInfo(int pageNumber, int pageSize, Map filters, List sorts, String search) { + this(pageNumber, pageSize, filters, sorts, search, null); + } + + public PageInfo(int pageNumber, int pageSize, Map filters, List sorts, String search, List ids) { + this(pageNumber, pageSize, filters, sorts, search, ids, null); + } + + public PageInfo(int pageNumber, int pageSize, Map filters, List sorts, String search, List ids, List embed) { + this(pageNumber, pageSize, filters, sorts, search, ids, embed, new HashMap<>()); + } + + public PageInfo(int pageNumber, int pageSize, Map filters, List sorts, String search, List ids, List embed, Map options) { this.pageNumber = pageNumber; this.pageSize = pageSize; this.filters = filters; this.sorts = sorts; this.search = search != null ? search : ""; + this.ids = ids != null ? ids : new ArrayList<>(); + this.embed = embed; + this.options = options; } @Override @@ -81,6 +105,21 @@ public List getSorts() { return sorts; } + @Override + public List getIds() { + return ids; + } + + @Override + public List getEmbed() { + return embed; + } + + @Override + public Map getOptions() { + return options; + } + @Override public String getSearch() { return search; diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/Pageable.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/Pageable.java similarity index 70% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/Pageable.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/Pageable.java index a7d66eb2..b2ea68d9 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/Pageable.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/Pageable.java @@ -22,9 +22,9 @@ import java.util.List; import java.util.Map; +import java.util.Objects; /** - * @author Adam Gavronek * @since 6/12/2014 */ public interface Pageable { @@ -40,13 +40,31 @@ public interface Pageable { String getSearch(); + List getIds(); + + List getEmbed(); + + Map getOptions(); + + enum SortDirection { + DEFAULT, ASC, DESC + } + class SortField { String field; SortDirection sortDirection; - public SortField(String field, SortDirection sortDirection) { + public SortField(String field, String sortDirection) { this.field = field; - this.sortDirection = sortDirection; + + // Use Object.equals here for no extra null check (else should cover this) + if (Objects.equals(sortDirection, "ASC")) { + this.sortDirection = SortDirection.ASC; + } else if (Objects.equals(sortDirection, "DESC")) { + this.sortDirection = SortDirection.DESC; + } else { + this.sortDirection = SortDirection.DEFAULT; + } } public String getField() { @@ -57,8 +75,4 @@ public SortDirection getSortDirection() { return sortDirection; } } - - enum SortDirection { - DEFAULT, ASC, DESC - } } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/PaginationResult.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/PaginationResult.java similarity index 81% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/PaginationResult.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/PaginationResult.java index 7d0d26ac..22dc545e 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/PaginationResult.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/PaginationResult.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import java.util.List; @@ -52,6 +53,9 @@ public int getNextPage() { } public String toJSON() throws JsonProcessingException { - return new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL).writeValueAsString(this.getElements()); + return new ObjectMapper().registerModule(new JavaTimeModule()) + .setSerializationInclusion(JsonInclude.Include.NON_NULL) + .writerWithView(SerializerViews.Public.class) + .writeValueAsString(this.getElements()); } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/SerializerViews.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/SerializerViews.java new file mode 100644 index 00000000..f3b0a5f7 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/SerializerViews.java @@ -0,0 +1,8 @@ +package de.rwth.dbis.acis.bazaar.service.dal.helpers; + +public class SerializerViews { + public static class Public { + } + public static class Private extends Public { + } +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/UserVote.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/UserVote.java similarity index 93% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/UserVote.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/UserVote.java index 71313e21..5be4c2e2 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/helpers/UserVote.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/helpers/UserVote.java @@ -21,7 +21,6 @@ package de.rwth.dbis.acis.bazaar.service.dal.helpers; /** - * @author Adam Gavronek * @since 2/27/2015 */ public enum UserVote { @@ -29,4 +28,3 @@ public enum UserVote { DOWN_VOTE, NO_VOTE } - diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/AttachmentRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/AttachmentRepository.java similarity index 100% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/AttachmentRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/AttachmentRepository.java diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/AttachmentRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/AttachmentRepositoryImpl.java similarity index 92% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/AttachmentRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/AttachmentRepositoryImpl.java index 276a149c..b4af8b59 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/AttachmentRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/AttachmentRepositoryImpl.java @@ -20,11 +20,11 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.AttachmentRecord; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.UserRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.Attachment; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.AttachmentRecord; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.UserRecord; import de.rwth.dbis.acis.bazaar.service.dal.transform.AttachmentTransformer; import de.rwth.dbis.acis.bazaar.service.dal.transform.UserTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; @@ -39,10 +39,9 @@ import java.util.ArrayList; import java.util.List; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.*; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.*; /** - * @author Adam Gavronek * @since 6/22/2014 */ public class AttachmentRepositoryImpl extends RepositoryImpl implements AttachmentRepository { @@ -58,7 +57,7 @@ public AttachmentRepositoryImpl(DSLContext jooq) { public Attachment findById(int id) throws Exception { Attachment attachment = null; try { - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User creatorUser = USER.as("creatorUser"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User creatorUser = USER.as("creatorUser"); Record record = jooq.selectFrom(ATTACHMENT .join(creatorUser).on(creatorUser.ID.equal(ATTACHMENT.USER_ID))) .where(transformer.getTableId().equal(id)) @@ -84,7 +83,7 @@ public PaginationResult findAllByRequirementId(int requirementId, Pa List attachments; try { attachments = new ArrayList<>(); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User creatorUser = USER.as("creatorUser"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User creatorUser = USER.as("creatorUser"); Field idCount = jooq.selectCount() .from(ATTACHMENT) diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryFollowerRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryFollowerRepository.java similarity index 100% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryFollowerRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryFollowerRepository.java diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryFollowerRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryFollowerRepositoryImpl.java similarity index 94% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryFollowerRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryFollowerRepositoryImpl.java index 416778ae..15fdefdd 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryFollowerRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryFollowerRepositoryImpl.java @@ -1,8 +1,8 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.CategoryFollowerMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.CategoryFollower; import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreationStatus; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.CategoryFollowerMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.transform.CategoryFollowerTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; @@ -11,7 +11,7 @@ import org.jooq.DSLContext; import org.jooq.exception.DataAccessException; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.CATEGORY_FOLLOWER_MAP; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.CATEGORY_FOLLOWER_MAP; public class CategoryFollowerRepositoryImpl extends RepositoryImpl implements CategoryFollowerRepository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepository.java similarity index 76% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepository.java index 97303852..50e34aaf 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepository.java @@ -26,10 +26,10 @@ import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -import java.sql.Timestamp; +import java.time.OffsetDateTime; +import java.util.List; /** - * @author Adam Gavronek * @since 6/9/2014 */ public interface CategoryRepository extends Repository { @@ -38,9 +38,15 @@ public interface CategoryRepository extends Repository { PaginationResult findByProjectId(int projectId, Pageable pageable, int userId) throws BazaarException; - PaginationResult findByRequirementId(int requirementId, Pageable pageable, int userId) throws BazaarException; + List findByRequirementId(int requirementId, int userId) throws BazaarException; + + PaginationResult findAll(Pageable pageable, int userId) throws BazaarException; + + List listAllCategoryIds(Pageable pageable, int userId) throws BazaarException; boolean belongsToPublicProject(int id) throws BazaarException; - Statistic getStatisticsForCategory(int userId, int categoryId, Timestamp timestamp) throws BazaarException; + Statistic getStatisticsForCategory(int userId, int categoryId, OffsetDateTime timestamp) throws BazaarException; + + List getFollowedCategories(int userId, int count) throws BazaarException; } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepositoryImpl.java similarity index 61% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepositoryImpl.java index 59ea7488..e8eb0920 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CategoryRepositoryImpl.java @@ -20,27 +20,30 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.CategoryRecord; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.UserRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.Category; import de.rwth.dbis.acis.bazaar.service.dal.entities.Statistic; +import de.rwth.dbis.acis.bazaar.service.dal.entities.UserContext; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.CategoryRecord; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.UserRecord; import de.rwth.dbis.acis.bazaar.service.dal.transform.CategoryTransformer; import de.rwth.dbis.acis.bazaar.service.dal.transform.UserTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.jooq.Record; import org.jooq.*; import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.List; +import java.time.OffsetDateTime; +import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.*; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.*; import static org.jooq.impl.DSL.*; public class CategoryRepositoryImpl extends RepositoryImpl implements CategoryRepository { @@ -102,6 +105,9 @@ public class CategoryRepositoryImpl extends RepositoryImpl, Integer> getFilteredCategories(Collection categoryFilter, Pageable pageable, int userId) throws Exception { + List categories; + categories = new ArrayList<>(); + + Field idCount = jooq.selectCount() + .from(CATEGORY) + .where(categoryFilter) + .asField("idCount"); + + Field isFollower = DSL.select(DSL.count()) + .from(CATEGORY_FOLLOWER_MAP) + .where(CATEGORY_FOLLOWER_MAP.CATEGORY_ID.equal(CATEGORY.ID).and(CATEGORY_FOLLOWER_MAP.USER_ID.equal(userId))) + .asField("isFollower"); + + Field lastActivity = DSL.select(LAST_ACTIVITY.field("last_activity")).from(LAST_ACTIVITY) + .where(LAST_ACTIVITY.field(CATEGORY.ID).equal(CATEGORY.ID)) + .asField("lastActivity"); + + List queryResults = jooq.select(CATEGORY.fields()) + .select(idCount) + .select(REQUIREMENT_COUNT) + .select(FOLLOWER_COUNT) + .select(isFollower) + .select(leaderUser.fields()) + .select(lastActivity) + .from(CATEGORY) + .leftOuterJoin(leaderUser).on(leaderUser.ID.equal(CATEGORY.LEADER_ID)) + //.leftOuterJoin(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID.equal(CATEGORY.ID)) + .leftOuterJoin(LAST_ACTIVITY).on(CATEGORY.ID.eq(LAST_ACTIVITY.field(CATEGORY.ID))) + .where(categoryFilter) + .orderBy(transformer.getSortFields(pageable.getSorts())) + .limit(pageable.getPageSize()) + .offset(pageable.getOffset()) + .fetch(); + + for (Record queryResult : queryResults) { + CategoryRecord categoryRecord = queryResult.into(CATEGORY); + Category category = transformer.getEntityFromTableRecord(categoryRecord); + UserTransformer userTransformer = new UserTransformer(); + UserRecord userRecord = queryResult.into(leaderUser); + UserContext.Builder userContext = UserContext.builder(); + + category.setCreator(userTransformer.getEntityFromTableRecord(userRecord)); + category.setNumberOfRequirements((Integer) queryResult.getValue(REQUIREMENT_COUNT)); + category.setNumberOfFollowers((Integer) queryResult.getValue(FOLLOWER_COUNT)); + category.setLastActivity((OffsetDateTime) queryResult.getValue(lastActivity)); + if (userId != 1) { + userContext.isFollower((Integer) queryResult.getValue(isFollower) != 0); + } + + category.setUserContext(userContext.build()); + categories.add(category); + } + int total = queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount")); + return ImmutablePair.of(categories, total); + } + + private ImmutablePair, Integer> getFilteredCategories(Condition categoryFilter, Pageable pageable, int userId) throws Exception { + return getFilteredCategories(Collections.singletonList(categoryFilter), pageable, userId); + } + + private ImmutablePair, Integer> getFilteredCategories(Condition categoryFilter, int userId) throws Exception { + return getFilteredCategories(categoryFilter, new PageInfo(0, 1000, new HashMap<>()), userId); + } + @Override public Category findById(int id, int userId) throws BazaarException { Category category = null; try { - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leaderUser = USER.as("leaderUser"); + Condition filterCondition = transformer.getTableId().equal(id); - Field isFollower = DSL.select(DSL.count()) - .from(CATEGORY_FOLLOWER_MAP) - .where(CATEGORY_FOLLOWER_MAP.CATEGORY_ID.equal(CATEGORY.ID).and(CATEGORY_FOLLOWER_MAP.USER_ID.equal(userId))) - .asField("isFollower"); - - Result queryResult = jooq.select(CATEGORY.fields()) - .select(REQUIREMENT_COUNT) - .select(FOLLOWER_COUNT) - .select(isFollower) - .select(leaderUser.fields()) - .from(CATEGORY) - .leftOuterJoin(leaderUser).on(leaderUser.ID.equal(CATEGORY.LEADER_ID)) - .where(transformer.getTableId().equal(id)) - .fetch(); + ImmutablePair, Integer> filteredCategories = getFilteredCategories(filterCondition, userId); - if (queryResult == null || queryResult.size() == 0) { + if (filteredCategories.left == null || filteredCategories.left.size() == 0) { ExceptionHandler.getInstance().convertAndThrowException( new Exception("No " + transformer.getRecordClass() + " found with id: " + id), ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); } - Category.Builder builder = Category.getBuilder(queryResult.getValues(CATEGORY.NAME).get(0)) - .description(queryResult.getValues(CATEGORY.DESCRIPTION).get(0)) - .projectId(queryResult.getValues(CATEGORY.PROJECT_ID).get(0)) - .id(queryResult.getValues(CATEGORY.ID).get(0)) - .creationDate(queryResult.getValues(CATEGORY.CREATION_DATE).get(0)) - .lastUpdatedDate(queryResult.getValues(CATEGORY.LAST_UPDATED_DATE).get(0)); - - UserTransformer userTransformer = new UserTransformer(); - //Filling up LeadDeveloper - builder.leader(userTransformer.getEntityFromQueryResult(leaderUser, queryResult)); - - category = builder.build(); - - // Filling additional information - category.setNumberOfRequirements((Integer) queryResult.getValues(REQUIREMENT_COUNT).get(0)); - category.setNumberOfFollowers((Integer) queryResult.getValues(FOLLOWER_COUNT).get(0)); - if (userId != 1) { - category.setFollower((Integer) queryResult.getValues(isFollower).get(0) == 0 ? false : true); - } + category = filteredCategories.left.get(0); } catch (BazaarException be) { ExceptionHandler.getInstance().convertAndThrowException(be); @@ -167,53 +207,13 @@ public Category findById(int id, int userId) throws BazaarException { @Override public PaginationResult findByProjectId(int projectId, Pageable pageable, int userId) throws BazaarException { PaginationResult result = null; - List categories; try { - categories = new ArrayList<>(); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leaderUser = USER.as("leaderUser"); + Condition filterCondition = CATEGORY.PROJECT_ID.equal(projectId) + .and(transformer.getSearchCondition(pageable.getSearch())); - Field idCount = jooq.selectCount() - .from(CATEGORY) - .where(CATEGORY.PROJECT_ID.equal(projectId)) - .and(transformer.getSearchCondition(pageable.getSearch())) - .asField("idCount"); + ImmutablePair, Integer> filteredCategories = getFilteredCategories(filterCondition, pageable, userId); - Field isFollower = DSL.select(DSL.count()) - .from(CATEGORY_FOLLOWER_MAP) - .where(CATEGORY_FOLLOWER_MAP.CATEGORY_ID.equal(CATEGORY.ID).and(CATEGORY_FOLLOWER_MAP.USER_ID.equal(userId))) - .asField("isFollower"); - - List queryResults = jooq.select(CATEGORY.fields()) - .select(idCount) - .select(REQUIREMENT_COUNT) - .select(FOLLOWER_COUNT) - .select(isFollower) - .select(leaderUser.fields()) - .from(CATEGORY) - .leftOuterJoin(leaderUser).on(leaderUser.ID.equal(CATEGORY.LEADER_ID)) - .leftOuterJoin(LAST_ACTIVITY).on(CATEGORY.ID.eq(LAST_ACTIVITY.field(CATEGORY.ID))) - .where(CATEGORY.PROJECT_ID.equal(projectId)) - .and(transformer.getSearchCondition(pageable.getSearch())) - .orderBy(transformer.getSortFields(pageable.getSorts())) - .limit(pageable.getPageSize()) - .offset(pageable.getOffset()) - .fetch(); - - for (Record queryResult : queryResults) { - CategoryRecord categoryRecord = queryResult.into(CATEGORY); - Category category = transformer.getEntityFromTableRecord(categoryRecord); - UserTransformer userTransformer = new UserTransformer(); - UserRecord userRecord = queryResult.into(leaderUser); - category.setLeader(userTransformer.getEntityFromTableRecord(userRecord)); - category.setNumberOfRequirements((Integer) queryResult.getValue(REQUIREMENT_COUNT)); - category.setNumberOfFollowers((Integer) queryResult.getValue(FOLLOWER_COUNT)); - if (userId != 1) { - category.setFollower((Integer) queryResult.getValue(isFollower) == 0 ? false : true); - } - categories.add(category); - } - int total = queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount")); - result = new PaginationResult<>(total, pageable, categories); + result = new PaginationResult<>(filteredCategories.right, pageable, filteredCategories.left); } catch (Exception e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); } @@ -221,55 +221,54 @@ public PaginationResult findByProjectId(int projectId, Pageable pageab } @Override - public PaginationResult findByRequirementId(int requirementId, Pageable pageable, int userId) throws BazaarException { + public PaginationResult findAll(Pageable pageable, int userId) throws BazaarException { PaginationResult result = null; - List categories; try { - categories = new ArrayList<>(); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leaderUser = USER.as("leaderUser"); + Collection filterCondition = (Collection) transformer.getFilterConditions(pageable.getFilters()); + filterCondition.add(transformer.getSearchCondition(pageable.getSearch())); - Field idCount = jooq.selectCount() - .from(CATEGORY) - .join(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID.equal(CATEGORY.ID)) - .where(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID.equal(requirementId)) - .asField("idCount"); + ImmutablePair, Integer> filteredCategories = getFilteredCategories(filterCondition, pageable, userId); - Field isFollower = DSL.select(DSL.count()) - .from(CATEGORY_FOLLOWER_MAP) - .where(CATEGORY_FOLLOWER_MAP.CATEGORY_ID.equal(CATEGORY.ID).and(CATEGORY_FOLLOWER_MAP.USER_ID.equal(userId))) - .asField("isFollower"); - - List queryResults = jooq.select(CATEGORY.fields()) - .select(idCount) - .select(REQUIREMENT_COUNT) - .select(FOLLOWER_COUNT) - .select(isFollower) - .select(leaderUser.fields()) + result = new PaginationResult<>(filteredCategories.right, pageable, filteredCategories.left); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return result; + } + + @Override + public List listAllCategoryIds(Pageable pageable, int userId) throws BazaarException { + List categoryIds = new ArrayList<>(); + try { + categoryIds = jooq.select() .from(CATEGORY) - .leftOuterJoin(leaderUser).on(leaderUser.ID.equal(CATEGORY.LEADER_ID)) - .leftOuterJoin(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID.equal(CATEGORY.ID)) - .where(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID.equal(requirementId)) + .where(transformer.getFilterConditions(pageable.getFilters())) + .and(transformer.getSearchCondition(pageable.getSearch())) .orderBy(transformer.getSortFields(pageable.getSorts())) - .limit(pageable.getPageSize()) - .offset(pageable.getOffset()) - .fetch(); - - for (Record queryResult : queryResults) { - CategoryRecord categoryRecord = queryResult.into(CATEGORY); - Category category = transformer.getEntityFromTableRecord(categoryRecord); - UserTransformer userTransformer = new UserTransformer(); - UserRecord userRecord = queryResult.into(leaderUser); - category.setLeader(userTransformer.getEntityFromTableRecord(userRecord)); - category.setNumberOfRequirements((Integer) queryResult.getValue(REQUIREMENT_COUNT)); - category.setNumberOfFollowers((Integer) queryResult.getValue(FOLLOWER_COUNT)); - if (userId != 1) { - category.setFollower((Integer) queryResult.getValue(isFollower) == 0 ? false : true); - } - categories.add(category); - } - int total = queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount")); - result = new PaginationResult<>(total, pageable, categories); - } catch (DataAccessException e) { + // .limit(pageable.getPageSize()) + // .offset(pageable.getOffset()) + .fetch(CATEGORY.ID); + + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return categoryIds; + } + + @Override + public List findByRequirementId(int requirementId, int userId) throws BazaarException { + List result = null; + try { + // Resolve map here, or the cartesian product will bite all other queries + List categoryIds = jooq.selectFrom(REQUIREMENT_CATEGORY_MAP).where(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID.equal(requirementId)).fetch(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID); + + Condition filterCondition = transformer.getTableId().in(categoryIds); + + + ImmutablePair, Integer> fileredCategories = getFilteredCategories(filterCondition, userId); + + result = fileredCategories.left; + } catch (Exception e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); } return result; @@ -292,7 +291,7 @@ public boolean belongsToPublicProject(int id) throws BazaarException { } @Override - public Statistic getStatisticsForCategory(int userId, int categoryId, Timestamp timestamp) throws BazaarException { + public Statistic getStatisticsForCategory(int userId, int categoryId, OffsetDateTime timestamp) throws BazaarException { Statistic result = null; try { // If you want to change something here, please know what you are doing! Its SQL and even worse JOOQ :-| @@ -341,7 +340,7 @@ public Statistic getStatisticsForCategory(int userId, int categoryId, Timestamp .where(CATEGORY.ID.eq(categoryId)) .fetchOne(); - result = Statistic.getBuilder() + result = Statistic.builder() .numberOfProjects((Integer) record1.get("numberOfProjects")) .numberOfCategories((Integer) record2.get("numberOfCategories")) .numberOfRequirements((Integer) record3.get("numberOfRequirements")) @@ -355,4 +354,30 @@ public Statistic getStatisticsForCategory(int userId, int categoryId, Timestamp } return result; } + + @Override + public List getFollowedCategories(int userId, int count) throws BazaarException { + List categories = null; + try { + List categoryIds; + categoryIds = jooq.select() + .from(CATEGORY_FOLLOWER_MAP) + .where(CATEGORY_FOLLOWER_MAP.USER_ID.eq(userId)) + .fetch(CATEGORY_FOLLOWER_MAP.CATEGORY_ID); + + Condition filterCondition = transformer.getTableId().in(categoryIds); + + Pageable.SortField sortField = new Pageable.SortField("last_activity", "DESC"); + List sortList = new ArrayList<>(); + sortList.add(sortField); + + PageInfo filterPage = new PageInfo(0, count, new HashMap<>(), sortList); + + categories = getFilteredCategories(filterCondition, filterPage, userId).left; + + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return categories; + } } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepository.java similarity index 77% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepository.java index ac164d23..089742a7 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepository.java @@ -25,12 +25,17 @@ import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import java.util.List; + /** - * @author Adam Gavronek * @since 6/22/2014 */ public interface CommentRepository extends Repository { - PaginationResult findAllByRequirementId(int requirementId, Pageable pageable) throws BazaarException; + List findAllByRequirementId(int requirementId) throws BazaarException; + PaginationResult findAllComments(Pageable pageable) throws BazaarException; + PaginationResult findAllAnswers(Pageable pageable, int userId) throws BazaarException; boolean belongsToPublicProject(int id) throws BazaarException; + + boolean hasAnswers(int id) throws BazaarException; } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepositoryImpl.java new file mode 100644 index 00000000..b6679e4a --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepositoryImpl.java @@ -0,0 +1,279 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.repositories; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.User; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.CommentRecord; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.UserRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Comment; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.EntityContextFactory; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; +import de.rwth.dbis.acis.bazaar.service.dal.transform.CommentTransformer; +import de.rwth.dbis.acis.bazaar.service.dal.transform.UserTransformer; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; + +import java.util.ArrayList; +import java.util.List; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.*; + +public class CommentRepositoryImpl extends RepositoryImpl implements CommentRepository { + + /** + * @param jooq DSLContext for JOOQ connection + */ + public CommentRepositoryImpl(DSLContext jooq) { + super(jooq, new CommentTransformer()); + } + + + @Override + public PaginationResult findAllAnswers(Pageable pageable, int userId) throws BazaarException { + PaginationResult result = null; + List comments; + try { + comments = new ArrayList<>(); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User creatorUser = USER.as("creatorUser"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Comment SUB_COMMENTS = COMMENT.as("sub_comments"); + + Field idCount = jooq.selectCount() + .from(COMMENT) + .where( + // transformer.getFilterConditions(pageable.getFilters())) + // .and( + transformer.getSearchCondition(pageable.getSearch()) + ) + .asField("idCount"); + + + List queryResults = jooq.select(COMMENT.fields()) + .select(creatorUser.fields()).select(idCount) + .from(COMMENT) + .leftSemiJoin(SUB_COMMENTS).on(( + COMMENT.REPLY_TO_COMMENT_ID.eq(SUB_COMMENTS.REPLY_TO_COMMENT_ID) //Refering same thread/base-comment + .and( + COMMENT.CREATION_DATE.greaterThan(SUB_COMMENTS.CREATION_DATE) //replies have greater timestamp than the users comment + ).and( + SUB_COMMENTS.USER_ID.eq(userId) //Comments the user wrote + )).or( + COMMENT.REPLY_TO_COMMENT_ID.eq(SUB_COMMENTS.ID).and(SUB_COMMENTS.USER_ID.eq(userId)) + ) + ) + .join(creatorUser).on(creatorUser.ID.equal(COMMENT.USER_ID)) + .where(COMMENT.USER_ID.notEqual(userId)) //Hide "own" answers + .orderBy(transformer.getSortFields(pageable.getSorts())) + .limit(pageable.getPageSize()) + .offset(pageable.getOffset()) + .fetch(); + + Comment entry = null; + for (Record record : queryResults) { + if (entry == null || transformer.getEntityFromTableRecord(record.into(CommentRecord.class)).getId() != entry.getId()) { + entry = convertToCommentWithUser(record, creatorUser); + comments.add(entry); + } + } + int total = (queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount"))); + result = new PaginationResult<>(total, pageable, comments); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + + return result; + } + + + @Override + public PaginationResult findAllComments(Pageable pageable) throws BazaarException { + PaginationResult result = null; + List comments; + try { + comments = new ArrayList<>(); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User creatorUser = USER.as("creatorUser"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Requirement requirement = REQUIREMENT.as("requirement"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Category category = CATEGORY.as("category"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project project = PROJECT.as("project"); + + Field idCount = jooq.selectCount() + .from(COMMENT) + .where( + transformer.getFilterConditions(pageable.getFilters())) + .and( + transformer.getSearchCondition(pageable.getSearch()) + ) + .asField("idCount"); + + + List queryResults = jooq.select(COMMENT.fields()) + .select(creatorUser.fields()).select(idCount).select(requirement.fields()).select(project.fields()).select(category.fields()) + .from(COMMENT) + .leftOuterJoin(requirement).on(COMMENT.REQUIREMENT_ID.eq(requirement.ID)) + .leftOuterJoin(PROJECT).on(requirement.PROJECT_ID.eq(project.ID)) + .leftOuterJoin(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID.eq(COMMENT.REQUIREMENT_ID)) + .leftOuterJoin(category).on(category.ID.eq(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID)) + .join(creatorUser).on(creatorUser.ID.equal(COMMENT.USER_ID)) + .where(transformer.getFilterConditions(pageable.getFilters())) + .orderBy(transformer.getSortFields(pageable.getSorts())) + .limit(pageable.getPageSize()) + .offset(pageable.getOffset()) + .fetch(); + + Comment entry = null; + for (Record record : queryResults) { + if (entry == null || transformer.getEntityFromTableRecord(record.into(CommentRecord.class)).getId() != entry.getId()) { + entry = convertToCommentWithUser(record, creatorUser); + entry.setContext(EntityContextFactory.create(pageable.getEmbed(), record)); + comments.add(entry); + } + } + int total = (queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount"))); + result = new PaginationResult<>(total, pageable, comments); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + + return result; + } + + + @Override + public List findAllByRequirementId(int requirementId) throws BazaarException { + List comments = new ArrayList<>(); + try { + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User creatorUser = USER.as("creatorUser"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Comment childComment = COMMENT.as("childComment"); + User childCommentCreatorUser = USER.as("childCommentCreatorUser"); + + Field idCount = jooq.selectCount() + .from(COMMENT) + .where(COMMENT.REQUIREMENT_ID.equal(requirementId)) + .asField("idCount"); + + List queryResults = jooq.select(COMMENT.fields()) + .select(childComment.fields()).select(creatorUser.fields()).select(childCommentCreatorUser.fields()).select(idCount) + .from(COMMENT) + .leftJoin(childComment).on(childComment.REPLY_TO_COMMENT_ID.equal(COMMENT.ID)) + .leftJoin(childCommentCreatorUser).on(childCommentCreatorUser.ID.equal(childComment.USER_ID)) + .join(creatorUser).on(creatorUser.ID.equal(COMMENT.USER_ID)) + .where(COMMENT.REQUIREMENT_ID.equal(requirementId).and(COMMENT.REPLY_TO_COMMENT_ID.isNull())) + .fetch(); + + Comment entry = null; + for (Record record : queryResults) { + if (entry == null || transformer.getEntityFromTableRecord(record.into(CommentRecord.class)).getId() != entry.getId()) { + entry = convertToCommentWithUser(record, creatorUser); + comments.add(entry); + } + CommentRecord childRecord = record.into(childComment); + if (childRecord.getId() != null) { + Comment childEntry = convertToCommentWithUser(record, childComment, childCommentCreatorUser); + comments.add(childEntry); + } + } + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + + return comments; + } + + + private Comment convertToCommentWithUser(Record record, de.rwth.dbis.acis.bazaar.dal.jooq.tables.User creatorUser) { + CommentRecord commentRecord = record.into(CommentRecord.class); + Comment entry = transformer.getEntityFromTableRecord(commentRecord); + if (!entry.getDeleted()) { + UserTransformer userTransformer = new UserTransformer(); + UserRecord userRecord = record.into(creatorUser); + entry.setCreator(userTransformer.getEntityFromTableRecord(userRecord)); + } + return entry; + } + + private Comment convertToCommentWithUser(Record record, de.rwth.dbis.acis.bazaar.dal.jooq.tables.Comment comment, de.rwth.dbis.acis.bazaar.dal.jooq.tables.User creatorUser) { + CommentRecord commentRecord = record.into(comment); + Comment entry = transformer.getEntityFromTableRecord(commentRecord); + UserTransformer userTransformer = new UserTransformer(); + UserRecord userRecord = record.into(creatorUser); + entry.setCreator(userTransformer.getEntityFromTableRecord(userRecord)); + return entry; + } + + @Override + public de.rwth.dbis.acis.bazaar.service.dal.entities.Comment findById(int id) throws Exception { + Comment returnComment = null; + try { + User creatorUser = USER.as("creatorUser"); + Record record = jooq.selectFrom(COMMENT + .join(creatorUser).on(creatorUser.ID.equal(COMMENT.USER_ID))) + .where(transformer.getTableId().equal(id)) + .fetchOne(); + returnComment = convertToCommentWithUser(record, creatorUser); + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } catch (NullPointerException e) { + ExceptionHandler.getInstance().convertAndThrowException( + new Exception("No " + transformer.getRecordClass() + " found with id: " + id), + ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); + } + return returnComment; + } + + @Override + public boolean belongsToPublicProject(int id) throws BazaarException { + try { + Integer countOfPublicProjects = jooq.selectCount() + .from(transformer.getTable()) + .join(REQUIREMENT).on(REQUIREMENT.ID.eq(COMMENT.REQUIREMENT_ID)) + .join(PROJECT).on(PROJECT.ID.eq(REQUIREMENT.PROJECT_ID)) + .where(transformer.getTableId().eq(id).and(PROJECT.VISIBILITY.isTrue())) + .fetchOne(0, int.class); + + return (countOfPublicProjects == 1); + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return false; + } + + @Override + public boolean hasAnswers(int id) throws BazaarException { + try { + Integer answerCount = jooq.selectCount() + .from(COMMENT) + .where(COMMENT.REPLY_TO_COMMENT_ID.eq(id)) + .fetchOne(0, int.class); + + return answerCount > 0; + + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return false; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/FeedbackRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/FeedbackRepository.java new file mode 100644 index 00000000..07e404f7 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/FeedbackRepository.java @@ -0,0 +1,13 @@ +package de.rwth.dbis.acis.bazaar.service.dal.repositories; + +import de.rwth.dbis.acis.bazaar.service.dal.entities.Feedback; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; + +public interface FeedbackRepository extends Repository { + + PaginationResult findAllByProject(int projectId, Pageable pageable) throws BazaarException; + + Feedback findById(int id) throws Exception; +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/FeedbackRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/FeedbackRepositoryImpl.java new file mode 100644 index 00000000..85ba6440 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/FeedbackRepositoryImpl.java @@ -0,0 +1,86 @@ +package de.rwth.dbis.acis.bazaar.service.dal.repositories; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.FeedbackRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Feedback; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; +import de.rwth.dbis.acis.bazaar.service.dal.transform.FeedbackTransformer; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; + +import java.util.ArrayList; +import java.util.List; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.FEEDBACK; + +public class FeedbackRepositoryImpl extends RepositoryImpl implements FeedbackRepository { + + /** + * @param jooq DSLContext for JOOQ connection + */ + public FeedbackRepositoryImpl(DSLContext jooq) { + super(jooq, new FeedbackTransformer()); + } + + + @Override + public PaginationResult findAllByProject(int projectId, Pageable pageable) throws BazaarException { + PaginationResult result = null; + List feedbacks; + try { + feedbacks = new ArrayList<>(); + + Field idCount = jooq.selectCount() + .from(FEEDBACK) + .where(transformer.getFilterConditions(pageable.getFilters())) + //.and(transformer.getSearchCondition(pageable.getSearch())) + .and(FEEDBACK.PROJECT_ID.eq(projectId)) + .asField("idCount"); + + List queryResults = jooq.select(FEEDBACK.fields()) + .select(idCount) + .from(FEEDBACK) + .where(FEEDBACK.PROJECT_ID.eq(projectId)) + .limit(pageable.getPageSize()) + .offset(pageable.getOffset()) + .fetch(); + + for (Record queryResult : queryResults) { + FeedbackRecord feedbackRecord = queryResult.into(FEEDBACK); + Feedback feedback = transformer.getEntityFromTableRecord(feedbackRecord); + feedbacks.add(findById(feedback.getId())); // TODO: Remove the getId call and create the objects themself here + } + int total = queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount")); + result = new PaginationResult<>(total, pageable, feedbacks); + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return result; + } + + public Feedback findById(int id) throws Exception { + Feedback returnFeedback = null; + try { + FeedbackRecord record = jooq.selectFrom(FEEDBACK) + .where(transformer.getTableId().equal(id)) + .fetchOne(); + returnFeedback = transformer.getEntityFromTableRecord(record); + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } catch (NullPointerException e) { + ExceptionHandler.getInstance().convertAndThrowException( + new Exception("No " + transformer.getRecordClass() + " found with id: " + id), + ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); + } + return returnFeedback; + } + +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PersonalisationDataRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PersonalisationDataRepository.java new file mode 100644 index 00000000..84c630bb --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PersonalisationDataRepository.java @@ -0,0 +1,11 @@ +package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.service.dal.entities.PersonalisationData; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; + +public interface PersonalisationDataRepository extends Repository { + + PersonalisationData findByKey(int userId, int version, String key) throws BazaarException; + void insertOrUpdate(PersonalisationData data) throws BazaarException; + + +} \ No newline at end of file diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PersonalisationDataRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PersonalisationDataRepositoryImpl.java new file mode 100644 index 00000000..133a95d1 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PersonalisationDataRepositoryImpl.java @@ -0,0 +1,53 @@ +package de.rwth.dbis.acis.bazaar.service.dal.repositories; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.PersonalisationDataRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.PersonalisationData; +import de.rwth.dbis.acis.bazaar.service.dal.transform.PersonalisationDataTransformer; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.exception.DataAccessException; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.PERSONALISATION_DATA; + +public class PersonalisationDataRepositoryImpl extends RepositoryImpl implements PersonalisationDataRepository { + + + public PersonalisationDataRepositoryImpl(DSLContext jooq) { + super(jooq, new PersonalisationDataTransformer()); + } + + + @Override + public PersonalisationData findByKey(int userId, int version, String key) throws BazaarException{ + PersonalisationData data = null; + try { + Record record = jooq.select().from(PERSONALISATION_DATA) + .where(PERSONALISATION_DATA.USER_ID.eq(userId)) + .and(PERSONALISATION_DATA.VERSION.eq(version)) + .and(PERSONALISATION_DATA.IDENTIFIER.eq(key)) + .fetchOne(); + PersonalisationDataRecord personalisationDataRecord = record.into(PersonalisationDataRecord.class); + data = transformer.getEntityFromTableRecord(personalisationDataRecord); + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } catch (NullPointerException e) { + ExceptionHandler.getInstance().convertAndThrowException( + new Exception("No " + transformer.getRecordClass() + " found with userId: " + userId + " version: "+version + " key: "+key), + ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); + } + return data; + } + @Override + public void insertOrUpdate(PersonalisationData data) throws BazaarException{ + jooq.insertInto(PERSONALISATION_DATA, PERSONALISATION_DATA.IDENTIFIER, PERSONALISATION_DATA.USER_ID, PERSONALISATION_DATA.VERSION, PERSONALISATION_DATA.SETTING) + .values(data.getKey(), data.getUserId(), data.getVersion(), data.getValue()) + .onDuplicateKeyUpdate() + .set(PERSONALISATION_DATA.SETTING, data.getValue()) + .execute(); + } + +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepository.java similarity index 95% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepository.java index 3fb277ad..6dd22152 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepository.java @@ -24,7 +24,6 @@ import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; /** - * @author Adam Gavronek * @since 2/18/2015 */ public interface PrivilegeRepository extends Repository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepositoryImpl.java similarity index 90% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepositoryImpl.java index 779983aa..31d95f99 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/PrivilegeRepositoryImpl.java @@ -20,8 +20,8 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.PrivilegeRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.Privilege; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.PrivilegeRecord; import de.rwth.dbis.acis.bazaar.service.dal.transform.PrivilegeTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; @@ -29,10 +29,9 @@ import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; import org.jooq.DSLContext; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.PRIVILEGE; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.PRIVILEGE; /** - * @author Adam Gavronek * @since 2/18/2015 */ public class PrivilegeRepositoryImpl extends RepositoryImpl implements PrivilegeRepository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectFollowerRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectFollowerRepository.java similarity index 100% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectFollowerRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectFollowerRepository.java diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectFollowerRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectFollowerRepositoryImpl.java similarity index 94% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectFollowerRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectFollowerRepositoryImpl.java index cf44aab6..1946379c 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectFollowerRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectFollowerRepositoryImpl.java @@ -1,8 +1,8 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.ProjectFollowerMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.ProjectFollower; import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreationStatus; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.ProjectFollowerMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.transform.ProjectFollowerTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; @@ -11,7 +11,7 @@ import org.jooq.DSLContext; import org.jooq.exception.DataAccessException; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.PROJECT_FOLLOWER_MAP; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.PROJECT_FOLLOWER_MAP; public class ProjectFollowerRepositoryImpl extends RepositoryImpl implements ProjectFollowerRepository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepository.java similarity index 74% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepository.java index 95608cea..219c5789 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepository.java @@ -22,15 +22,14 @@ import de.rwth.dbis.acis.bazaar.service.dal.entities.Project; import de.rwth.dbis.acis.bazaar.service.dal.entities.Statistic; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -import java.sql.Timestamp; +import java.time.OffsetDateTime; +import java.util.List; /** - * @author Adam Gavronek * @since 6/9/2014 */ public interface ProjectRepository extends Repository { @@ -39,11 +38,15 @@ public interface ProjectRepository extends Repository { PaginationResult findAllPublic(Pageable pageable, int userId) throws BazaarException; - PaginationResult findAllPublicAndAuthorized(PageInfo pageable, int userId) throws BazaarException; + PaginationResult findAllPublicAndAuthorized(Pageable pageable, int userId) throws BazaarException; boolean belongsToPublicProject(int id) throws BazaarException; - Statistic getStatisticsForVisibleProjects(int userId, Timestamp timestamp) throws BazaarException; + Statistic getStatisticsForVisibleProjects(int userId, OffsetDateTime timestamp) throws BazaarException; - Statistic getStatisticsForProject(int userId, int projectId, Timestamp timestamp) throws BazaarException; + Statistic getStatisticsForProject(int userId, int projectId, OffsetDateTime timestamp) throws BazaarException; + + List listAllProjectIds(Pageable pageable, int userId) throws BazaarException; + + List getFollowedProjects(int userId, int count) throws BazaarException; } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepositoryImpl.java similarity index 64% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepositoryImpl.java index 6d5ebd20..721cad8b 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/ProjectRepositoryImpl.java @@ -20,31 +20,35 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.ProjectRecord; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.UserRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.Project; import de.rwth.dbis.acis.bazaar.service.dal.entities.Statistic; +import de.rwth.dbis.acis.bazaar.service.dal.entities.UserContext; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.ProjectRecord; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.UserRecord; import de.rwth.dbis.acis.bazaar.service.dal.transform.ProjectTransformer; import de.rwth.dbis.acis.bazaar.service.dal.transform.UserTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.jooq.Record; import org.jooq.*; import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; +import java.time.OffsetDateTime; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.*; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.*; import static org.jooq.impl.DSL.*; /** - * @author Adam Gavronek * @since 6/9/2014 */ public class ProjectRepositoryImpl extends RepositoryImpl implements ProjectRepository { @@ -110,6 +114,9 @@ public class ProjectRepositoryImpl extends RepositoryImpl, Integer> getFilteredProjects(Condition searchCondition, Pageable pageable, int userId) throws Exception { + + List projects = new ArrayList<>(); + Field idCount = jooq.selectCount() + .from(PROJECT) + .where(searchCondition) + .asField("idCount"); + + Field isFollower = DSL.select(DSL.count()) + .from(PROJECT_FOLLOWER_MAP) + .where(PROJECT_FOLLOWER_MAP.PROJECT_ID.equal(PROJECT.ID).and(PROJECT_FOLLOWER_MAP.USER_ID.equal(userId))) + .asField("isFollower"); + Field lastActivity = DSL.select(LAST_ACTIVITY.field("last_activity")).from(LAST_ACTIVITY) + .where(LAST_ACTIVITY.field(PROJECT.ID).equal(PROJECT.ID)) + .asField("lastActivity"); + + List matchingRequirementProjects = null; + if (pageable.getOptions().getOrDefault("recursive", false)) { + matchingRequirementProjects = jooq.selectDistinct().from(REQUIREMENT) + .where(DSL.condition("to_tsvector({0} || {1}) @@ websearch_to_tsquery({2})", + REQUIREMENT.NAME, REQUIREMENT.DESCRIPTION, pageable.getSearch())) + .fetch().getValues(REQUIREMENT.PROJECT_ID); + searchCondition = searchCondition.or(PROJECT.ID.in(matchingRequirementProjects)); + } + + Result queryResults = jooq.select(PROJECT.fields()) + .select(idCount) + .select(CATEGORY_COUNT) + .select(REQUIREMENT_COUNT) + .select(FOLLOWER_COUNT) + .select(isFollower) + .select(leaderUser.fields()) + .select(lastActivity) + .from(PROJECT) + .leftOuterJoin(leaderUser).on(leaderUser.ID.equal(PROJECT.LEADER_ID)) + .leftOuterJoin(LAST_ACTIVITY).on(PROJECT.ID.eq(LAST_ACTIVITY.field(PROJECT.ID))) + .where(searchCondition) + .orderBy(transformer.getSortFields(pageable.getSorts())) + .limit(pageable.getPageSize()) + .offset(pageable.getOffset()) + .fetch(); + + for (Record queryResult : queryResults) { + ProjectRecord projectRecord = queryResult.into(PROJECT); + Project project = transformer.getEntityFromTableRecord(projectRecord); + UserTransformer userTransformer = new UserTransformer(); + UserRecord userRecord = queryResult.into(leaderUser); + UserContext.Builder userContext = UserContext.builder(); + + project.setLeader(userTransformer.getEntityFromTableRecord(userRecord)); + project.setNumberOfCategories((Integer) queryResult.getValue(CATEGORY_COUNT)); + project.setNumberOfRequirements((Integer) queryResult.getValue(REQUIREMENT_COUNT)); + project.setNumberOfFollowers((Integer) queryResult.getValue(FOLLOWER_COUNT)); + project.setLastActivity((OffsetDateTime) queryResult.getValue(lastActivity)); + if (userId != 1) { + userContext.isFollower(0 != (Integer) queryResult.getValue(isFollower)); + } + RoleRepositoryImpl roleRepository = new RoleRepositoryImpl(jooq); + userContext.userRole(roleRepository.getProjectRole(userId, project.getId())); + + project.setUserContext(userContext.build()); + projects.add(project); + } + int total = queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount")); + + return ImmutablePair.of(projects, total); + } + + private ImmutablePair, Integer> getFilteredProjects(Condition searchCondition, int userId) throws Exception { + return getFilteredProjects(searchCondition, new PageInfo(0, 1000, new HashMap<>()), userId); + } + @Override public Project findById(int id, int userId) throws BazaarException { Project project = null; try { - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leaderUser = USER.as("leaderUser"); + Condition filterCondition = transformer.getTableId().equal(id); - Field isFollower = DSL.select(DSL.count()) - .from(PROJECT_FOLLOWER_MAP) - .where(PROJECT_FOLLOWER_MAP.PROJECT_ID.equal(PROJECT.ID).and(PROJECT_FOLLOWER_MAP.USER_ID.equal(userId))) - .asField("isFollower"); - - Result queryResult = jooq.select(PROJECT.fields()) - .select(CATEGORY_COUNT) - .select(REQUIREMENT_COUNT) - .select(FOLLOWER_COUNT) - .select(isFollower) - .select(leaderUser.fields()) - .from(PROJECT) - .leftOuterJoin(leaderUser).on(leaderUser.ID.equal(PROJECT.LEADER_ID)) - .where(transformer.getTableId().equal(id)) - .fetch(); + ImmutablePair, Integer> filteredProjects = getFilteredProjects(filterCondition, userId); - if (queryResult == null || queryResult.size() == 0) { + if (filteredProjects.left == null || filteredProjects.left.size() == 0) { ExceptionHandler.getInstance().convertAndThrowException( new Exception("No " + transformer.getRecordClass() + " found with id: " + id), ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); } - Project.Builder builder = Project.getBuilder(queryResult.getValues(PROJECT.NAME).get(0)) - .description(queryResult.getValues(PROJECT.DESCRIPTION).get(0)) - .id(queryResult.getValues(PROJECT.ID).get(0)) - .defaultCategoryId(queryResult.getValues(PROJECT.DEFAULT_CATEGORY_ID).get(0)) - .visibility(queryResult.getValues(PROJECT.VISIBILITY).get(0) == 1) - .creationDate(queryResult.getValues(PROJECT.CREATION_DATE).get(0)) - .lastUpdatedDate(queryResult.getValues(PROJECT.LAST_UPDATED_DATE).get(0)); - - UserTransformer userTransformer = new UserTransformer(); - //Filling up LeadDeveloper - builder.leader(userTransformer.getEntityFromQueryResult(leaderUser, queryResult)); - - project = builder.build(); - - // Filling additional information - project.setNumberOfCategories((Integer) queryResult.getValues(CATEGORY_COUNT).get(0)); - project.setNumberOfRequirements((Integer) queryResult.getValues(REQUIREMENT_COUNT).get(0)); - project.setNumberOfFollowers((Integer) queryResult.getValues(FOLLOWER_COUNT).get(0)); - if (userId != 1) { - project.setFollower((Integer) queryResult.getValues(isFollower).get(0) == 0 ? false : true); - } + project = filteredProjects.left.get(0); } catch (BazaarException be) { ExceptionHandler.getInstance().convertAndThrowException(be); @@ -178,55 +223,13 @@ public Project findById(int id, int userId) throws BazaarException { @Override public PaginationResult findAllPublic(Pageable pageable, int userId) throws BazaarException { PaginationResult result = null; - List projects; try { - projects = new ArrayList<>(); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leaderUser = USER.as("leaderUser"); + Condition searchConditions = transformer.getSearchCondition(pageable.getSearch()) + .and((pageable.getIds().size() > 0) ? PROJECT.ID.in(pageable.getIds()) : trueCondition()); - Field idCount = jooq.selectCount() - .from(PROJECT) - .where(PROJECT.VISIBILITY.isTrue()) - .and(transformer.getSearchCondition(pageable.getSearch())) - .asField("idCount"); + ImmutablePair, Integer> filteredProjects = getFilteredProjects(searchConditions, pageable, userId); - Field isFollower = DSL.select(DSL.count()) - .from(PROJECT_FOLLOWER_MAP) - .where(PROJECT_FOLLOWER_MAP.PROJECT_ID.equal(PROJECT.ID).and(PROJECT_FOLLOWER_MAP.USER_ID.equal(userId))) - .asField("isFollower"); - - Result queryResults = jooq.select(PROJECT.fields()) - .select(idCount) - .select(CATEGORY_COUNT) - .select(REQUIREMENT_COUNT) - .select(FOLLOWER_COUNT) - .select(isFollower) - .select(leaderUser.fields()) - .from(PROJECT) - .leftOuterJoin(leaderUser).on(leaderUser.ID.equal(PROJECT.LEADER_ID)) - .leftOuterJoin(LAST_ACTIVITY).on(PROJECT.ID.eq(LAST_ACTIVITY.field(PROJECT.ID))) - .where(PROJECT.VISIBILITY.isTrue()) - .and(transformer.getSearchCondition(pageable.getSearch())) - .orderBy(transformer.getSortFields(pageable.getSorts())) - .limit(pageable.getPageSize()) - .offset(pageable.getOffset()) - .fetch(); - - for (Record queryResult : queryResults) { - ProjectRecord projectRecord = queryResult.into(PROJECT); - Project project = transformer.getEntityFromTableRecord(projectRecord); - UserTransformer userTransformer = new UserTransformer(); - UserRecord userRecord = queryResult.into(leaderUser); - project.setLeader(userTransformer.getEntityFromTableRecord(userRecord)); - project.setNumberOfCategories((Integer) queryResult.getValue(CATEGORY_COUNT)); - project.setNumberOfRequirements((Integer) queryResult.getValue(REQUIREMENT_COUNT)); - project.setNumberOfFollowers((Integer) queryResult.getValue(FOLLOWER_COUNT)); - if (userId != 1) { - project.setFollower((Integer) queryResult.getValue(isFollower) == 0 ? false : true); - } - projects.add(project); - } - int total = queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount")); - result = new PaginationResult<>(total, pageable, projects); + result = new PaginationResult<>(filteredProjects.right, pageable, filteredProjects.left); } catch (Exception e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); } @@ -234,66 +237,71 @@ public PaginationResult findAllPublic(Pageable pageable, int userId) th } @Override - public PaginationResult findAllPublicAndAuthorized(PageInfo pageable, int userId) throws BazaarException { + public PaginationResult findAllPublicAndAuthorized(Pageable pageable, int userId) throws BazaarException { PaginationResult result = null; - List projects; try { - projects = new ArrayList<>(); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leaderUser = USER.as("leaderUser"); - - Field idCount = jooq.selectCount() - .from(PROJECT) - .where(transformer.getSearchCondition(pageable.getSearch())) - .asField("idCount"); + Condition searchConditions = transformer.getSearchCondition(pageable.getSearch()) + .and((pageable.getIds().size() > 0) ? PROJECT.ID.in(pageable.getIds()) : trueCondition()) + .and( + // TODO: Include permission check by project membership query + PROJECT.VISIBILITY.isTrue().or(leaderUser.ID.equal(userId)) + ); + ImmutablePair, Integer> filteredProjects = getFilteredProjects(searchConditions, pageable, userId); + + result = new PaginationResult<>(filteredProjects.right, pageable, filteredProjects.left); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return result; + } - Field isFollower = DSL.select(DSL.count()) - .from(PROJECT_FOLLOWER_MAP) - .where(PROJECT_FOLLOWER_MAP.PROJECT_ID.equal(PROJECT.ID).and(PROJECT_FOLLOWER_MAP.USER_ID.equal(userId))) - .asField("isFollower"); - - //TODO only authorized projects? - List queryResults = jooq.select(PROJECT.fields()) - .select(idCount) - .select(CATEGORY_COUNT) - .select(REQUIREMENT_COUNT) - .select(FOLLOWER_COUNT) - .select(isFollower) - .select(leaderUser.fields()) + @Override + public List listAllProjectIds(Pageable pageable, int userId) throws BazaarException { + List projectIds = new ArrayList<>(); + try { + projectIds = jooq.select() .from(PROJECT) - .leftOuterJoin(leaderUser).on(leaderUser.ID.equal(PROJECT.LEADER_ID)) - .leftOuterJoin(LAST_ACTIVITY).on(PROJECT.ID.eq(LAST_ACTIVITY.field(PROJECT.ID))) -// .leftOuterJoin(AUTHORIZATIONS).on(AUTHORIZATIONS.PROJECT_ID.equal(PROJECTS.ID)) -// .join(USERS).on(AUTHORIZATIONS.USER_ID.equal(USERS.ID)) -// .where(PROJECTS.VISIBILITY.eq(Project.ProjectVisibility.PUBLIC.asChar()) - .where(PROJECT.VISIBILITY.isTrue().or(leaderUser.ID.equal(userId)) + .where(transformer.getFilterConditions(pageable.getFilters())) + .and(PROJECT.VISIBILITY.isTrue().or(PROJECT.LEADER_ID.equal(userId)) .and(transformer.getSearchCondition(pageable.getSearch()))) .orderBy(transformer.getSortFields(pageable.getSorts())) - .limit(pageable.getPageSize()) - .offset(pageable.getOffset()) - .fetch(); - - for (Record queryResult : queryResults) { - ProjectRecord projectRecord = queryResult.into(PROJECT); - Project project = transformer.getEntityFromTableRecord(projectRecord); - UserTransformer userTransformer = new UserTransformer(); - UserRecord userRecord = queryResult.into(leaderUser); - project.setLeader(userTransformer.getEntityFromTableRecord(userRecord)); - project.setNumberOfCategories((Integer) queryResult.getValue(CATEGORY_COUNT)); - project.setNumberOfRequirements((Integer) queryResult.getValue(REQUIREMENT_COUNT)); - project.setNumberOfFollowers((Integer) queryResult.getValue(FOLLOWER_COUNT)); - if (userId != 1) { - project.setFollower((Integer) queryResult.getValue(isFollower) == 0 ? false : true); - } - projects.add(project); - } - int total = queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount")); - result = new PaginationResult<>(total, pageable, projects); + // .limit(pageable.getPageSize()) + // .offset(pageable.getOffset()) + .fetch(PROJECT.ID); + } catch (Exception e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); } - return result; + return projectIds; } + @Override + public List getFollowedProjects(int userId, int count) throws BazaarException { + List projects = null; + try { + List projectIds; + projectIds = jooq.select() + .from(PROJECT_FOLLOWER_MAP) + .where(PROJECT_FOLLOWER_MAP.USER_ID.eq(userId)) + .fetch(PROJECT_FOLLOWER_MAP.PROJECT_ID); + + Condition filterCondition = transformer.getTableId().in(projectIds); + + Pageable.SortField sortField = new Pageable.SortField("last_activity", "DESC"); + List sortList = new ArrayList<>(); + sortList.add(sortField); + + PageInfo filterPage = new PageInfo(0, count, new HashMap<>(), sortList); + + projects = getFilteredProjects(filterCondition, filterPage, userId).left; + + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return projects; + } + + @Override public boolean belongsToPublicProject(int id) throws BazaarException { try { @@ -310,7 +318,7 @@ public boolean belongsToPublicProject(int id) throws BazaarException { } @Override - public Statistic getStatisticsForVisibleProjects(int userId, java.sql.Timestamp timestamp) throws BazaarException { + public Statistic getStatisticsForVisibleProjects(int userId, OffsetDateTime timestamp) throws BazaarException { Statistic result = null; try { // If you want to change something here, please know what you are doing! Its SQL and even worse JOOQ :-| @@ -352,7 +360,7 @@ public Statistic getStatisticsForVisibleProjects(int userId, java.sql.Timestamp .where(PROJECT.VISIBILITY.isTrue()) .fetchOne(); - result = Statistic.getBuilder() + result = Statistic.builder() .numberOfProjects((Integer) record1.get("numberOfProjects")) .numberOfCategories((Integer) record2.get("numberOfCategories")) .numberOfRequirements((Integer) record2.get("numberOfRequirements")) @@ -368,7 +376,8 @@ public Statistic getStatisticsForVisibleProjects(int userId, java.sql.Timestamp } @Override - public Statistic getStatisticsForProject(int userId, int projectId, java.sql.Timestamp timestamp) throws BazaarException { + public Statistic getStatisticsForProject(int userId, int projectId, OffsetDateTime timestamp) throws + BazaarException { Statistic result = null; try { // If you want to change something here, please know what you are doing! Its SQL and even worse JOOQ :-| @@ -411,7 +420,7 @@ public Statistic getStatisticsForProject(int userId, int projectId, java.sql.Tim .where(PROJECT.ID.eq(projectId)) .fetchOne(); - result = Statistic.getBuilder() + result = Statistic.builder() .numberOfProjects((Integer) record1.get("numberOfProjects")) .numberOfCategories((Integer) record2.get("numberOfCategories")) .numberOfRequirements((Integer) record2.get("numberOfRequirements")) diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/Repository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/Repository.java similarity index 97% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/Repository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/Repository.java index cc9439d9..6d2728bd 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/Repository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/Repository.java @@ -29,7 +29,6 @@ /** * @param Type of the Entity, which should be added, deleted, updated, got using the repo. - * @author Adam Gavronek * @since 6/9/2014 */ public interface Repository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RepositoryImpl.java similarity index 96% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RepositoryImpl.java index ec73409d..21ac8079 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RepositoryImpl.java @@ -27,6 +27,7 @@ import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import org.jooq.Record; import org.jooq.*; import org.jooq.exception.DataAccessException; @@ -35,7 +36,6 @@ import java.util.Map; /** - * @author Adam Gavronek * @since 6/9/2014 */ public class RepositoryImpl implements Repository { @@ -57,6 +57,7 @@ public RepositoryImpl(DSLContext jooq, Transformer transformer) { * @param entity to add * @return the persisted entity */ + @Override public E add(E entity) throws BazaarException { E transformedEntity = null; try { @@ -80,10 +81,11 @@ public E add(E entity) throws BazaarException { * @throws Exception */ //TODO transaction (findById,delete) + @Override public E delete(int id) throws Exception { E deleted = null; try { - deleted = this.findById(id); + deleted = findById(id); int deletedRecordCount = jooq.delete(transformer.getTable()) .where(transformer.getTableId().equal(id)) @@ -100,6 +102,7 @@ public E delete(int id) throws Exception { /** * @return all the entities currently in the database */ + @Override public List findAll() throws BazaarException { List entries = null; try { @@ -107,10 +110,7 @@ public List findAll() throws BazaarException { List queryResults = jooq.selectFrom(transformer.getTable()).fetchInto(transformer.getRecordClass()); - for (R queryResult : queryResults) { - E entry = transformer.getEntityFromTableRecord(queryResult); - entries.add(entry); - } + } catch (DataAccessException e) { ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN, e.getMessage()); } @@ -173,6 +173,7 @@ public List searchAll(String searchTerm, Pageable pageable) throws Exception * @return the entity from the database with the given Id * @throws Exception */ + @Override public E findById(int id) throws Exception { R queryResult = null; try { @@ -208,10 +209,11 @@ public E update(E entity) throws Exception { for (Map.Entry item : map.entrySet()) { Field key = item.getKey(); Object value = item.getValue(); - if (moreStep == null) + if (moreStep == null) { moreStep = update.set(key, value); - else + } else { moreStep.set(key, value); + } } assert moreStep != null; moreStep.where(transformer.getTableId().equal(entity.getId())).execute(); diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepository.java similarity index 95% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepository.java index 5f2b4263..b958a858 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepository.java @@ -24,7 +24,6 @@ import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; /** - * @author Adam Gavronek * @since 6/22/2014 */ public interface RequirementCategoryRepository extends Repository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepositoryImpl.java similarity index 90% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepositoryImpl.java index 3b94b683..17d63aa4 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementCategoryRepositoryImpl.java @@ -20,8 +20,8 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementCategoryMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.RequirementCategory; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementCategoryMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.transform.RequirementCategoryTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; @@ -30,10 +30,9 @@ import org.jooq.DSLContext; import org.jooq.exception.DataAccessException; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.REQUIREMENT_CATEGORY_MAP; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.REQUIREMENT_CATEGORY_MAP; /** - * @author Adam Gavronek * @since 6/23/2014 */ public class RequirementCategoryRepositoryImpl extends RepositoryImpl implements RequirementCategoryRepository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepository.java similarity index 96% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepository.java index 4b4cf161..886e347a 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepository.java @@ -25,7 +25,6 @@ import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; /** - * @author Adam Gavronek * @since 6/22/2014 */ public interface RequirementDeveloperRepository extends Repository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepositoryImpl.java similarity index 93% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepositoryImpl.java index 6d56606e..dda95d90 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementDeveloperRepositoryImpl.java @@ -20,9 +20,9 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementDeveloperMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.RequirementDeveloper; import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreationStatus; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementDeveloperMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.transform.RequirementDeveloperTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; @@ -31,10 +31,9 @@ import org.jooq.DSLContext; import org.jooq.exception.DataAccessException; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.REQUIREMENT_DEVELOPER_MAP; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.REQUIREMENT_DEVELOPER_MAP; /** - * @author Adam Gavronek * @since 6/23/2014 */ public class RequirementDeveloperRepositoryImpl extends RepositoryImpl implements RequirementDeveloperRepository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepository.java similarity index 96% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepository.java index d0079ddd..5ca284a1 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepository.java @@ -25,7 +25,6 @@ import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; /** - * @author Adam Gavronek * @since 6/22/2014 */ public interface RequirementFollowerRepository extends Repository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepositoryImpl.java similarity index 93% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepositoryImpl.java index 99749390..c385c538 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementFollowerRepositoryImpl.java @@ -20,9 +20,9 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementFollowerMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.RequirementFollower; import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreationStatus; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementFollowerMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.transform.RequirementFollowerTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; @@ -31,10 +31,9 @@ import org.jooq.DSLContext; import org.jooq.exception.DataAccessException; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.REQUIREMENT_FOLLOWER_MAP; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.REQUIREMENT_FOLLOWER_MAP; /** - * @author Adam Gavronek * @since 6/23/2014 */ public class RequirementFollowerRepositoryImpl extends RepositoryImpl implements RequirementFollowerRepository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepository.java similarity index 75% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepository.java index 6241a6cb..0371a733 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepository.java @@ -26,7 +26,8 @@ import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -import java.sql.Timestamp; +import java.time.OffsetDateTime; +import java.util.List; public interface RequirementRepository extends Repository { @@ -34,13 +35,21 @@ public interface RequirementRepository extends Repository { PaginationResult findAllByCategory(int categoryId, Pageable pageable, int userId) throws BazaarException; + PaginationResult findAll(Pageable pageable, int userId) throws BazaarException; + + List listAllRequirementIds(Pageable pageable, int userId) throws BazaarException; + boolean belongsToPublicProject(int id) throws BazaarException; Requirement findById(int id, int userId) throws Exception; - void setRealized(int id, Timestamp realized) throws BazaarException; + Requirement findById(int id, int userId, List embed) throws Exception; + + void setRealized(int id, OffsetDateTime realized) throws BazaarException; void setLeadDeveloper(int id, Integer userId) throws BazaarException; - Statistic getStatisticsForRequirement(int userId, int requirementId, Timestamp timestamp) throws BazaarException; + Statistic getStatisticsForRequirement(int userId, int requirementId, OffsetDateTime timestamp) throws BazaarException; + + List getFollowedRequirements(int userId, int count) throws BazaarException; } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepositoryImpl.java new file mode 100644 index 00000000..6c808a33 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepositoryImpl.java @@ -0,0 +1,515 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.repositories; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementCategoryMapRecord; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementRecord; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.TagRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.*; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.*; +import de.rwth.dbis.acis.bazaar.service.dal.transform.RequirementTransformer; +import de.rwth.dbis.acis.bazaar.service.dal.transform.TagTransformer; +import de.rwth.dbis.acis.bazaar.service.dal.transform.UserTransformer; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.jooq.Record; +import org.jooq.*; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; + +import java.math.BigDecimal; +import java.time.OffsetDateTime; +import java.util.*; +import java.util.stream.Collectors; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.*; +import static org.jooq.impl.DSL.*; + +public class RequirementRepositoryImpl extends RepositoryImpl implements RequirementRepository { + + // derived table for activities inside requirement + public static final Table ACTIVITY = table( + select(REQUIREMENT.ID, REQUIREMENT.CREATION_DATE) + .from(REQUIREMENT) + .unionAll( + select(REQUIREMENT.ID, REQUIREMENT.LAST_UPDATED_DATE) + .from(REQUIREMENT)) + .unionAll( + select(COMMENT.REQUIREMENT_ID, COMMENT.CREATION_DATE) + .from(COMMENT)) + .unionAll( + select(COMMENT.REQUIREMENT_ID, COMMENT.LAST_UPDATED_DATE) + .from(COMMENT)) + .unionAll( + select(ATTACHMENT.REQUIREMENT_ID, ATTACHMENT.CREATION_DATE) + .from(ATTACHMENT)) + .unionAll( + select(ATTACHMENT.REQUIREMENT_ID, ATTACHMENT.LAST_UPDATED_DATE) + .from(ATTACHMENT)) + ).as("ACTIVITY"); + + // derived table for last activity inside requirement + public static final Table LAST_ACTIVITY = table( + select( + ACTIVITY.field(REQUIREMENT.ID), + max(ACTIVITY.field(REQUIREMENT.CREATION_DATE)).as("last_activity")) + .from(ACTIVITY) + .groupBy(ACTIVITY.field(REQUIREMENT.ID))) + .as("last_activity"); + + public static final Field VOTE_COUNT = select(DSL.count(DSL.nullif(VOTE.IS_UPVOTE, false))) + .from(VOTE) + .where(VOTE.REQUIREMENT_ID.equal(REQUIREMENT.ID)) + .asField("voteCount"); + + public static final Field COMMENT_COUNT = select(DSL.count()) + .from(COMMENT) + .where(COMMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID)) + .asField("commentCount"); + + public static final Field ATTACHMENT_COUNT = select(DSL.count()) + .from(ATTACHMENT) + .where(ATTACHMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID)) + .asField("attachmentCount"); + + public static final Field FOLLOWER_COUNT = select(DSL.count()) + .from(REQUIREMENT_FOLLOWER_MAP) + .where(REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID)) + .asField("followerCount"); + + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User creatorUser = USER.as("creatorUser"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User leadDeveloperUser = USER.as("leadDeveloperUser"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Vote vote = VOTE.as("vote"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Vote userVote = VOTE.as("userVote"); + + /** + * @param jooq DSLContext object to initialize JOOQ connection. For more see JOOQ documentation. + */ + public RequirementRepositoryImpl(DSLContext jooq) { + super(jooq, new RequirementTransformer()); + } + + private ImmutablePair, Integer> getFilteredRequirements(Collection requirementFilter, Pageable pageable, int userId) throws Exception { + List requirements = new ArrayList<>(); + + Field idCount = jooq.selectCount() + .from(REQUIREMENT) + .where(requirementFilter) + .asField("idCount"); + + Field isFollower = DSL.select(DSL.count()) + .from(REQUIREMENT_FOLLOWER_MAP) + .where(REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID).and(REQUIREMENT_FOLLOWER_MAP.USER_ID.equal(userId))) + .asField("isFollower"); + + Field isDeveloper = DSL.select(DSL.count()) + .from(REQUIREMENT_DEVELOPER_MAP) + .where(REQUIREMENT_DEVELOPER_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID).and(REQUIREMENT_DEVELOPER_MAP.USER_ID.equal(userId))) + .asField("isDeveloper"); + + Condition isAuthorizedCondition = REQUIREMENT.PROJECT_ID.in( + DSL.select(PROJECT.ID) + .from(PROJECT) + .where(PROJECT.ID.eq(REQUIREMENT.PROJECT_ID)) + .and(PROJECT.VISIBILITY.isTrue().or(PROJECT.LEADER_ID.eq(userId))) + ); + + Field lastActivity = DSL.select(LAST_ACTIVITY.field("last_activity")).from(LAST_ACTIVITY) + .where(LAST_ACTIVITY.field(REQUIREMENT.ID).equal(REQUIREMENT.ID)) + .asField("lastActivity"); + + // Contributors = {Creator, Lead Developer, Developers, Comments creators, Attachments creators} + // This code could be improved so that not only "1" or "0" will return but how much contributions an user made + // I tried this for 2-3 hours. SQL ... yeah ... I leave this to someone else. :-> + // TODO: Try the first idea from here: http://stackoverflow.com/questions/43717672/sum-over-multiple-count-field/43721212?noredirect=1#comment74498115_43721212 + Field isContributor = select(sum(choose() + .when(REQUIREMENT.CREATOR_ID.eq(userId), inline(1)) + .when(REQUIREMENT.LEAD_DEVELOPER_ID.eq(userId), inline(1)) + .when(REQUIREMENT_DEVELOPER_MAP.USER_ID.eq(userId), inline(1)) + .when(COMMENT.USER_ID.eq(userId), inline(1)) + .when(ATTACHMENT.USER_ID.eq(userId), inline(1)) + .otherwise(inline(0)) + )) + .from(REQUIREMENT) + .leftOuterJoin(REQUIREMENT_DEVELOPER_MAP).on(REQUIREMENT_DEVELOPER_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID)) + .leftOuterJoin(COMMENT).on(COMMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID)) + .leftOuterJoin(ATTACHMENT).on(ATTACHMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID)) + .asField("isContributor"); + + + Result queryResults = jooq.select(REQUIREMENT.fields()) + .select(idCount) + .select(COMMENT_COUNT) + .select(ATTACHMENT_COUNT) + .select(FOLLOWER_COUNT) + .select(isFollower) + .select(isDeveloper) + .select(isContributor) + .select(creatorUser.fields()) + .select(leadDeveloperUser.fields()) + .select(PROJECT.fields()) + .select(lastActivity) + .from(REQUIREMENT) + .join(creatorUser).on(creatorUser.ID.equal(REQUIREMENT.CREATOR_ID)) + .leftOuterJoin(leadDeveloperUser).on(leadDeveloperUser.ID.equal(REQUIREMENT.LEAD_DEVELOPER_ID)) + .leftOuterJoin(PROJECT).on(PROJECT.ID.equal(REQUIREMENT.PROJECT_ID)) + .leftOuterJoin(LAST_ACTIVITY).on(REQUIREMENT.ID.eq(LAST_ACTIVITY.field(REQUIREMENT.ID))) + .leftOuterJoin(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT.ID.eq(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID)) + .where(requirementFilter) + .and(isAuthorizedCondition) + .fetch(); + + for (Record queryResult : queryResults) { + RequirementRecord requirementRecord = queryResult.into(REQUIREMENT); + Requirement requirement = transformer.getEntityFromTableRecord(requirementRecord); + UserContext.Builder userContext = UserContext.builder(); + + requirement.setLastActivity((OffsetDateTime) queryResult.getValue(lastActivity)); + + UserTransformer userTransformer = new UserTransformer(); + //Filling up Creator + requirement.setCreator( + userTransformer.getEntityFromTableRecord(queryResult.into(creatorUser)) + ); + + //Filling up LeadDeveloper + if (queryResult.getValue(leadDeveloperUser.ID) != null) { + requirement.setLeadDeveloper( + userTransformer.getEntityFromTableRecord(queryResult.into(leadDeveloperUser)) + ); + } + + //Filling up votes + Result voteQueryResult = jooq.select(DSL.count(DSL.nullif(vote.IS_UPVOTE, false)).as("upVotes")) + .select(DSL.count(DSL.nullif(vote.IS_UPVOTE, true)).as("downVotes")) + .select(userVote.IS_UPVOTE.as("userVoted")) + .from(REQUIREMENT) + .leftOuterJoin(vote).on(vote.REQUIREMENT_ID.eq(REQUIREMENT.ID)) + .leftOuterJoin(userVote).on(userVote.REQUIREMENT_ID.eq(REQUIREMENT.ID).and(userVote.USER_ID.eq(userId))) + .where(transformer.getTableId().equal(requirement.getId())) + .groupBy(userVote.IS_UPVOTE) + .fetch(); + + requirement.setUpVotes(voteQueryResult.get(0).getValue("upVotes", Integer.class)); + requirement.setDownVotes(voteQueryResult.get(0).getValue("downVotes", Integer.class)); + + userContext.userVoted(transformToUserVoted(voteQueryResult.get(0).getValue("userVoted", Integer.class))); + + //Filling up categories + List categories = new ArrayList<>(); + + Result categoryRecord = jooq.selectFrom(REQUIREMENT_CATEGORY_MAP).where(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID.eq(requirement.getId())).fetch(); + + categoryRecord.forEach(record -> categories.add(record.getValue(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID))); + + requirement.setCategories(categories); + + // Filling up tags + Result tagRecords = jooq.select(TAG.fields()) + .from(TAG) + .leftOuterJoin(REQUIREMENT_TAG_MAP).on(REQUIREMENT_TAG_MAP.TAG_ID.eq(TAG.ID)) + .where(REQUIREMENT_TAG_MAP.REQUIREMENT_ID.eq(requirement.getId())).fetchInto(TAG); + + TagTransformer tagTransformer = new TagTransformer(); + List tags = tagRecords.stream() + .map(tagTransformer::getEntityFromTableRecord) + .collect(Collectors.toList()); + + requirement.setTags(tags); + + //Filling up additional information + requirement.setNumberOfComments((Integer) queryResult.getValue(COMMENT_COUNT)); + requirement.setNumberOfAttachments((Integer) queryResult.getValue(ATTACHMENT_COUNT)); + requirement.setNumberOfFollowers((Integer) queryResult.getValue(FOLLOWER_COUNT)); + if (userId != 1) { + userContext.isFollower(0 != (Integer) queryResult.getValue(isFollower)); + userContext.isDeveloper(0 != (Integer) queryResult.getValue(isDeveloper)); + userContext.isContributor(!Objects.equals(queryResult.getValue(isContributor), new BigDecimal(0))); + } + + if (requirement.getNumberOfAttachments() > 0) { + AttachmentRepository attachmentRepository = new AttachmentRepositoryImpl(jooq); + List attachmentList = attachmentRepository.findAllByRequirementId(requirement.getId(), new PageInfo(0, 1000, new HashMap<>())).getElements(); + requirement.setAttachments(attachmentList); + } + + requirement.setContext(EntityContextFactory.create(pageable.getEmbed(), queryResult)); + requirement.setUserContext(userContext.build()); + requirements.add(requirement); + } + int total = queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount")); + + return ImmutablePair.of(requirements, total); + } + + private ImmutablePair, Integer> getFilteredRequirements(Condition requirementFilter, Pageable pageable, int userId) throws Exception { + return getFilteredRequirements(Collections.singletonList(requirementFilter), pageable, userId); + } + + private ImmutablePair, Integer> getFilteredRequirements(Condition requirementFilter, int userId) throws Exception { + return getFilteredRequirements(requirementFilter, new PageInfo(0, 1000, new HashMap<>()), userId); + } + + @Override + public List listAllRequirementIds(Pageable pageable, int userId) throws BazaarException { + List requirementIds = new ArrayList<>(); + try { + requirementIds = jooq.select() + .from(REQUIREMENT) + .where(transformer.getFilterConditions(pageable.getFilters())) + .and(transformer.getSearchCondition(pageable.getSearch())) + .orderBy(transformer.getSortFields(pageable.getSorts())) + // .limit(pageable.getPageSize()) + // .offset(pageable.getOffset()) + .fetch(REQUIREMENT.ID); + + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return requirementIds; + } + + @Override + public PaginationResult findAll(Pageable pageable, int userId) throws BazaarException { + PaginationResult result = null; + try { + Collection filterCondition = (Collection) transformer.getFilterConditions(pageable.getFilters()); + filterCondition.add(transformer.getSearchCondition(pageable.getSearch())); + + ImmutablePair, Integer> filteredRequirements = getFilteredRequirements(filterCondition, pageable, userId); + + result = new PaginationResult<>(filteredRequirements.right, pageable, filteredRequirements.left); + + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return result; + } + + @Override + public PaginationResult findAllByProject(int projectId, Pageable pageable, int userId) throws BazaarException { + PaginationResult result = null; + try { + Collection filterCondition = (Collection) transformer.getFilterConditions(pageable.getFilters()); + filterCondition.add(transformer.getSearchCondition(pageable.getSearch())); + filterCondition.add(REQUIREMENT.PROJECT_ID.eq(projectId)); + + ImmutablePair, Integer> filteredRequirements = getFilteredRequirements(filterCondition, pageable, userId); + + result = new PaginationResult<>(filteredRequirements.right, pageable, filteredRequirements.left); + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return result; + } + + private UserVote transformToUserVoted(Integer userVotedInt) { + UserVote userVoted; + if (userVotedInt == null) { + return UserVote.NO_VOTE; + } + switch (userVotedInt) { + case 0: + userVoted = UserVote.DOWN_VOTE; + break; + case 1: + userVoted = UserVote.UP_VOTE; + break; + default: + userVoted = UserVote.NO_VOTE; + } + return userVoted; + } + + @Override + public PaginationResult findAllByCategory(int categoryId, Pageable pageable, int userId) throws BazaarException { + PaginationResult result = null; + try { + Collection filterCondition = (Collection) transformer.getFilterConditions(pageable.getFilters()); + filterCondition.add(transformer.getSearchCondition(pageable.getSearch())); + filterCondition.add(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID.eq(categoryId)); + + ImmutablePair, Integer> filteredRequirements = getFilteredRequirements(filterCondition, pageable, userId); + + result = new PaginationResult<>(filteredRequirements.right, pageable, filteredRequirements.left); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return result; + } + + @Override + public boolean belongsToPublicProject(int id) throws BazaarException { + try { + Integer countOfPublicProjects = jooq.selectCount() + .from(transformer.getTable()) + .join(PROJECT).on(PROJECT.ID.eq(REQUIREMENT.PROJECT_ID)) + .where(transformer.getTableId().eq(id).and(PROJECT.VISIBILITY.isTrue())) + .fetchOne(0, int.class); + return (countOfPublicProjects == 1); + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return false; + } + + @Override + public Requirement findById(int id, int userId) throws Exception { + return findById(id, userId, null); + } + + @Override + public Requirement findById(int id, int userId, List embed) throws Exception { + Requirement requirement = null; + try { + + Condition filterCondition = transformer.getTableId().equal(id); + + ImmutablePair, Integer> filteredRequirements = getFilteredRequirements(filterCondition, userId); + + if (filteredRequirements.left == null || filteredRequirements.left.size() == 0) { + ExceptionHandler.getInstance().convertAndThrowException( + new Exception("No " + transformer.getRecordClass() + " found with id: " + id), + ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); + } + + requirement = filteredRequirements.left.get(0); + + } catch (BazaarException be) { + ExceptionHandler.getInstance().convertAndThrowException(be); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return requirement; + } + + @Override + public void setRealized(int id, OffsetDateTime realized) throws BazaarException { + try { + jooq.update(REQUIREMENT) + .set(REQUIREMENT.REALIZED, realized) + .set(REQUIREMENT.LAST_UPDATED_DATE, OffsetDateTime.now()) + .where(REQUIREMENT.ID.eq(id)) + .execute(); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); + } + } + + @Override + public void setLeadDeveloper(int id, Integer userId) throws BazaarException { + try { + jooq.update(REQUIREMENT) + .set(REQUIREMENT.LEAD_DEVELOPER_ID, userId) + .set(REQUIREMENT.LAST_UPDATED_DATE, OffsetDateTime.now()) + .where(REQUIREMENT.ID.eq(id)) + .execute(); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); + } + } + + @Override + public Statistic getStatisticsForRequirement(int userId, int requirementId, OffsetDateTime timestamp) throws BazaarException { + Statistic result = null; + try { + // If you want to change something here, please know what you are doing! Its SQL and even worse JOOQ :-| + Record record1 = jooq + .select(DSL.countDistinct(PROJECT.ID).as("numberOfProjects")) + .select(DSL.countDistinct(CATEGORY.ID).as("numberOfCategories")) + .select(DSL.countDistinct(COMMENT.ID).as("numberOfComments")) + .select(DSL.countDistinct(ATTACHMENT.ID).as("numberOfAttachments")) + .select(DSL.countDistinct(VOTE.ID).as("numberOfVotes")) + .from(REQUIREMENT) + .leftJoin(PROJECT).on(PROJECT.CREATION_DATE.greaterOrEqual(timestamp) + .or(PROJECT.LAST_UPDATED_DATE.greaterOrEqual(timestamp)) + .and(PROJECT.ID.equal(REQUIREMENT.PROJECT_ID))) + .leftJoin(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID)) + .leftJoin(CATEGORY).on(CATEGORY.CREATION_DATE.greaterOrEqual(timestamp) + .or(CATEGORY.LAST_UPDATED_DATE.greaterOrEqual(timestamp)) + .and(CATEGORY.ID.equal(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID))) + .leftJoin(COMMENT).on(COMMENT.CREATION_DATE.greaterOrEqual(timestamp) + .or(COMMENT.LAST_UPDATED_DATE.greaterOrEqual(timestamp)) + .and(COMMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID))) + .leftJoin(ATTACHMENT).on(ATTACHMENT.CREATION_DATE.greaterOrEqual(timestamp) + .or(ATTACHMENT.LAST_UPDATED_DATE.greaterOrEqual(timestamp)) + .and(ATTACHMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID))) + .leftJoin(VOTE).on(VOTE.CREATION_DATE.greaterOrEqual(timestamp) + .and(VOTE.REQUIREMENT_ID.equal(REQUIREMENT.ID))) + .where(REQUIREMENT.ID.eq(requirementId)) + .fetchOne(); + + Record record2 = jooq + .select(DSL.countDistinct(REQUIREMENT.ID).as("numberOfRequirements")) + .from(REQUIREMENT) + .where(REQUIREMENT.CREATION_DATE.greaterOrEqual(timestamp) + .or(REQUIREMENT.LAST_UPDATED_DATE.greaterOrEqual(timestamp)) + .and(REQUIREMENT.ID.eq(requirementId))) + .fetchOne(); + + result = Statistic.builder() + .numberOfProjects((Integer) record1.get("numberOfProjects")) + .numberOfCategories((Integer) record1.get("numberOfCategories")) + .numberOfRequirements((Integer) record2.get("numberOfRequirements")) + .numberOfComments((Integer) record1.get("numberOfComments")) + .numberOfAttachments((Integer) record1.get("numberOfAttachments")) + .numberOfVotes((Integer) record1.get("numberOfVotes")) + .build(); + + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return result; + } + + @Override + public List getFollowedRequirements(int userId, int count) throws BazaarException { + List requirements = null; + try { + List requirementIds; + requirementIds = jooq.select() + .from(REQUIREMENT_FOLLOWER_MAP) + .where(REQUIREMENT_FOLLOWER_MAP.USER_ID.eq(userId)) + .fetch(REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID); + + Condition filterCondition = transformer.getTableId().in(requirementIds); + + Pageable.SortField sortField = new Pageable.SortField("last_activity", "DESC"); + List sortList = new ArrayList<>(); + sortList.add(sortField); + + PageInfo filterPage = new PageInfo(0, count, new HashMap<>(), sortList); + + requirements = getFilteredRequirements(filterCondition, filterPage, userId).left; + + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return requirements; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementTagRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementTagRepository.java new file mode 100644 index 00000000..72cc091f --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementTagRepository.java @@ -0,0 +1,14 @@ +package de.rwth.dbis.acis.bazaar.service.dal.repositories; + +import de.rwth.dbis.acis.bazaar.service.dal.entities.RequirementTag; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreationStatus; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; + +/** + * @since 6/22/2014 + */ +public interface RequirementTagRepository extends Repository { + CreationStatus addOrUpdate(RequirementTag tag) throws BazaarException; + + void delete(int tagId, int requirementId); +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementTagRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementTagRepositoryImpl.java new file mode 100644 index 00000000..ae7b6065 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementTagRepositoryImpl.java @@ -0,0 +1,46 @@ +package de.rwth.dbis.acis.bazaar.service.dal.repositories; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementTagMapRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.RequirementTag; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreationStatus; +import de.rwth.dbis.acis.bazaar.service.dal.transform.RequirementTagTransformer; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import org.jooq.DSLContext; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.REQUIREMENT_TAG_MAP; + +public class RequirementTagRepositoryImpl extends RepositoryImpl implements RequirementTagRepository { + /** + * @param jooq DSLContext for JOOQ connection + */ + public RequirementTagRepositoryImpl(DSLContext jooq) { + super(jooq, new RequirementTagTransformer()); + } + + @Override + public CreationStatus addOrUpdate(RequirementTag requirementTag) throws BazaarException { + RequirementTagMapRecord record = jooq.selectFrom(REQUIREMENT_TAG_MAP) + .where(REQUIREMENT_TAG_MAP.REQUIREMENT_ID.eq(requirementTag.getRequirementId())) + .and(REQUIREMENT_TAG_MAP.TAG_ID.eq(requirementTag.getTagId())) + .fetchOne(); + + if (record != null) { + return CreationStatus.UNCHANGED; + } else { + try { + add(requirementTag); + } catch (Exception ex) { + ExceptionHandler.getInstance().convertAndThrowException(ex, ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); + } + return CreationStatus.CREATED; + } + } + + @Override + public void delete(int tagId, int requirementId) { + jooq.deleteFrom(REQUIREMENT_TAG_MAP).where(REQUIREMENT_TAG_MAP.TAG_ID.eq(tagId)).and(REQUIREMENT_TAG_MAP.REQUIREMENT_ID.eq(requirementId)).execute(); + } +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepository.java similarity index 55% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepository.java index def0a233..30977b05 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepository.java @@ -20,21 +20,38 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.service.dal.entities.ProjectMember; +import de.rwth.dbis.acis.bazaar.service.dal.entities.ProjectRole; import de.rwth.dbis.acis.bazaar.service.dal.entities.Role; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import java.util.List; /** - * @author Adam Gavronek * @since 2/17/2015 */ public interface RoleRepository extends Repository { List listParentsForRole(int roleId) throws BazaarException; - List listRolesOfUser(int userId, String context) throws BazaarException; + List listRolesOfUser(int userId, Integer context) throws BazaarException; - void addUserToRole(int userId, String roleName, String context) throws BazaarException; + void addUserToRole(int userId, String roleName, Integer context) throws BazaarException; Role findByRoleName(String roleName) throws BazaarException; + + PaginationResult listProjectMembers(int projectId, Pageable pageable) throws BazaarException; + + /** + * Return the project role or null + * + * @param userId id of the user + * @param projectId id of the project + * @return projectrole or null + * @throws BazaarException + */ + ProjectRole getProjectRole(int userId, int projectId) throws BazaarException; + + void removeUserFromRole(int userId, Integer context) throws BazaarException; } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepositoryImpl.java similarity index 52% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepositoryImpl.java index ac9935bf..6bb7d179 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/RoleRepositoryImpl.java @@ -20,10 +20,11 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; -import de.rwth.dbis.acis.bazaar.service.dal.entities.Privilege; -import de.rwth.dbis.acis.bazaar.service.dal.entities.Role; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RoleRecord; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.UserRoleMapRecord; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RoleRecord; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.UserRoleMapRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.*; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; import de.rwth.dbis.acis.bazaar.service.dal.transform.PrivilegeEnumConverter; import de.rwth.dbis.acis.bazaar.service.dal.transform.RoleTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; @@ -38,10 +39,9 @@ import java.util.List; import java.util.Map; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.*; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.*; /** - * @author Adam Gavronek * @since 2/17/2015 */ public class RoleRepositoryImpl extends RepositoryImpl implements RoleRepository { @@ -50,22 +50,22 @@ public RoleRepositoryImpl(DSLContext jooq) { } @Override - public List listRolesOfUser(int userId, String context) throws BazaarException { + public List listRolesOfUser(int userId, Integer context) throws BazaarException { List roles = null; try { - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Role roleTable = ROLE.as("role"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Privilege privilegeTable = PRIVILEGE.as("privilege"); + roles = new ArrayList<>(); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Role roleTable = ROLE.as("role"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Privilege privilegeTable = PRIVILEGE.as("privilege"); Result queryResult = jooq.selectFrom( USER_ROLE_MAP .join(roleTable).on(USER_ROLE_MAP.ROLE_ID.eq(roleTable.ID)) - .leftOuterJoin(ROLE_PRIVILEGE_MAP).on(ROLE_PRIVILEGE_MAP.ROLE_ID.eq(ROLE.ID)) + .leftOuterJoin(ROLE_PRIVILEGE_MAP).on(ROLE_PRIVILEGE_MAP.ROLE_ID.eq(roleTable.ID)) .leftOuterJoin(PRIVILEGE).on(PRIVILEGE.ID.eq(ROLE_PRIVILEGE_MAP.PRIVILEGE_ID)) ).where(USER_ROLE_MAP.USER_ID.equal(userId).and(USER_ROLE_MAP.CONTEXT_INFO.eq(context).or(USER_ROLE_MAP.CONTEXT_INFO.isNull()))).fetch(); - if (queryResult != null && !queryResult.isEmpty()) { - roles = new ArrayList<>(); + if (!queryResult.isEmpty()) { convertToRoles(roles, roleTable, privilegeTable, queryResult); } @@ -76,7 +76,7 @@ public List listRolesOfUser(int userId, String context) throws BazaarExcep } @Override - public void addUserToRole(int userId, String roleName, String context) throws BazaarException { + public void addUserToRole(int userId, String roleName, Integer context) throws BazaarException { Role role = findByRoleName(roleName); UserRoleMapRecord record = new UserRoleMapRecord(); record.setRoleId(role.getId()); @@ -105,13 +105,79 @@ public Role findByRoleName(String roleName) throws BazaarException { return role; } + @Override + public PaginationResult listProjectMembers(int projectId, Pageable pageable) throws BazaarException { + List projectMembers = null; + int total = 0; + + try { + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Role roleTable = ROLE.as("role"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User userTable = USER.as("user"); + + Result queryResult = jooq.selectFrom( + USER_ROLE_MAP + .join(roleTable).on(USER_ROLE_MAP.ROLE_ID.eq(roleTable.ID)) + .leftOuterJoin(USER).on(USER.ID.eq(USER_ROLE_MAP.USER_ID)) + ).where(USER_ROLE_MAP.CONTEXT_INFO.equal(projectId)).fetch(); + + if (queryResult != null && !queryResult.isEmpty()) { + total = queryResult.size(); + projectMembers = new ArrayList<>(); + for (Record entry : queryResult) { + User user = User.builder() + .eMail(entry.getValue(userTable.EMAIL)) + .id(entry.getValue(userTable.ID)) + .firstName(entry.getValue(userTable.FIRST_NAME)) + .lastName(entry.getValue(userTable.LAST_NAME)) + .las2peerId(entry.getValue(userTable.LAS2PEER_ID)) + .userName(entry.getValue(userTable.USER_NAME)) + .profileImage(entry.getValue(userTable.PROFILE_IMAGE)) + .emailLeadSubscription(entry.getValue(userTable.EMAIL_LEAD_SUBSCRIPTION)) + .emailFollowSubscription(entry.getValue(userTable.EMAIL_FOLLOW_SUBSCRIPTION)) + .personalizationEnabled(entry.getValue(userTable.PERSONALIZATION_ENABLED)) + .build(); + ProjectMember member = ProjectMember.builder() + .id(entry.getValue(USER_ROLE_MAP.ID)) + .user(user) + .userId(user.getId()) + .role(ProjectRole.valueOf(entry.getValue(roleTable.NAME))) + .build(); + projectMembers.add(member); + } + + } + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + return new PaginationResult<>(total, pageable, projectMembers); + } + + @Override + public ProjectRole getProjectRole(int userId, int projectId) throws BazaarException { + List roles = listRolesOfUser(userId, projectId); + + for (Role role : roles) { + if (role.getName().equals("SystemAdmin")) { + return ProjectRole.ProjectAdmin; + } else if (role.isProjectScoped()) { + return ProjectRole.valueOf(role.getName()); + } + } + return null; + } + + @Override + public void removeUserFromRole(int userId, Integer context) throws BazaarException { + jooq.deleteFrom(USER_ROLE_MAP).where(USER_ROLE_MAP.USER_ID.equal(userId).and(USER_ROLE_MAP.CONTEXT_INFO.eq(context))).execute(); + } + @Override public List listParentsForRole(int roleId) throws BazaarException { List roles = null; try { - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Role roleTable = ROLE.as("role"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Privilege privilegeTable = PRIVILEGE.as("privilege"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Role roleTable = ROLE.as("role"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Privilege privilegeTable = PRIVILEGE.as("privilege"); Result queryResult = jooq.selectFrom( ROLE_ROLE_MAP @@ -131,25 +197,30 @@ public List listParentsForRole(int roleId) throws BazaarException { return roles; } - private void convertToRoles(List roles, de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Role roleTable, - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Privilege privilegeTable, Result queryResult) { + private void convertToRoles(List roles, de.rwth.dbis.acis.bazaar.dal.jooq.tables.Role roleTable, + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Privilege privilegeTable, Result queryResult) { for (Map.Entry> entry : queryResult.intoGroups(roleTable.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); List rolesToAddPrivileges = new ArrayList<>(); for (Map.Entry> privilegeEntry : records.intoGroups(privilegeTable.ID).entrySet()) { - if (privilegeEntry.getKey() == null) continue; + if (privilegeEntry.getKey() == null) { + continue; + } Result privileges = privilegeEntry.getValue(); - Privilege privilege = Privilege.getBuilder(new PrivilegeEnumConverter().from(privileges.getValues(privilegeTable.NAME).get(0))) + Privilege privilege = Privilege.builder().name(new PrivilegeEnumConverter().from(privileges.getValues(privilegeTable.NAME).get(0))) .id(privileges.getValues(privilegeTable.ID).get(0)) .build(); rolesToAddPrivileges.add(privilege); } - Role roleToAdd = Role.getBuilder(records.getValues(roleTable.NAME).get(0)) + Role roleToAdd = Role.builder() + .name(records.getValues(roleTable.NAME).get(0)) .id(records.getValues(roleTable.ID).get(0)) .privileges(rolesToAddPrivileges) .build(); diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/TagRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/TagRepository.java new file mode 100644 index 00000000..ea6a1c61 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/TagRepository.java @@ -0,0 +1,13 @@ +package de.rwth.dbis.acis.bazaar.service.dal.repositories; + +import de.rwth.dbis.acis.bazaar.service.dal.entities.Tag; + +import java.util.List; + +public interface TagRepository extends Repository { + + @Override + Tag findById(int id) throws Exception; + + List findByProjectId(int projectId) throws Exception; +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/TagRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/TagRepositoryImpl.java new file mode 100644 index 00000000..b5efca1f --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/TagRepositoryImpl.java @@ -0,0 +1,47 @@ +package de.rwth.dbis.acis.bazaar.service.dal.repositories; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.TagRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Tag; +import de.rwth.dbis.acis.bazaar.service.dal.transform.TagTransformer; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import org.jooq.DSLContext; +import org.jooq.exception.DataAccessException; + +import java.util.ArrayList; +import java.util.List; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.TAG; + +public class TagRepositoryImpl extends RepositoryImpl implements TagRepository { + + /** + * @param jooq DSLContext for JOOQ connection + */ + public TagRepositoryImpl(DSLContext jooq) { + super(jooq, new TagTransformer()); + } + + @Override + public List findByProjectId(int projectId) throws BazaarException { + List tags = new ArrayList<>(); + try { + + List queryResults = jooq.selectFrom(TAG) + .where(TAG.PROJECT_ID.eq(projectId)) + .orderBy(TAG.NAME) + .fetchInto(transformer.getRecordClass()); + + for (TagRecord queryResult : queryResults) { + Tag entry = transformer.getEntityFromTableRecord(queryResult); + tags.add(entry); + } + } catch (DataAccessException e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + + return tags; + } +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepository.java similarity index 92% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepository.java index a6dd699f..aaea1a5d 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepository.java @@ -32,7 +32,6 @@ import java.util.List; /** - * @author Adam Gavronek * @since 6/22/2014 */ public interface UserRepository extends Repository { @@ -60,4 +59,13 @@ public interface UserRepository extends Repository { List getEmailReceiverForCategory(int categoryId) throws BazaarException; List getEmailReceiverForRequirement(int requirementId) throws BazaarException; + + /** + * Search with custom search and order logic + * + * @param pageable + * @return + * @throws BazaarException + */ + List search(Pageable pageable) throws BazaarException; } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepositoryImpl.java similarity index 85% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepositoryImpl.java index 25e00f85..7520e380 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/UserRepositoryImpl.java @@ -20,13 +20,13 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.UserRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.CategoryContributors; import de.rwth.dbis.acis.bazaar.service.dal.entities.ProjectContributors; import de.rwth.dbis.acis.bazaar.service.dal.entities.RequirementContributors; import de.rwth.dbis.acis.bazaar.service.dal.entities.User; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.UserRecord; import de.rwth.dbis.acis.bazaar.service.dal.transform.UserTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; @@ -39,15 +39,14 @@ import org.jooq.Record; import org.jooq.Result; +import java.time.OffsetDateTime; import java.util.ArrayList; -import java.util.Calendar; import java.util.List; import java.util.Map; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.*; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.*; /** - * @author Adam Gavronek * @since 6/23/2014 */ public class UserRepositoryImpl extends RepositoryImpl implements UserRepository { @@ -74,6 +73,7 @@ public Integer getIdByLas2PeerId(String las2PeerId) throws BazaarException { /** * Hash agent sub field. This was needed to update from las2peer 0.6.* to 0.7.*. * The las2peer id changed, and with the hashAgentSub method the old las2peer id can be generated. + * * @param agent * @return hashed agent sub * @throws BazaarException @@ -109,7 +109,7 @@ public void updateLas2peerId(int userId, String las2PeerId) throws BazaarExcepti @Override public void updateLastLoginDate(int userId) throws Exception { try { - jooq.update(USER).set(USER.LAST_LOGIN_DATE, new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())) + jooq.update(USER).set(USER.LAST_LOGIN_DATE, OffsetDateTime.now()) .where(USER.ID.equal(userId)) .execute(); } catch (Exception e) { @@ -121,11 +121,11 @@ public void updateLastLoginDate(int userId) throws Exception { public RequirementContributors findRequirementContributors(int requirementId) throws BazaarException { RequirementContributors contributors = null; try { - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User creator = USER.as("creator"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leadDeveloper = USER.as("leadDeveloper"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User developer = USER.as("developer"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User commentCreator = USER.as("commentCreator"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User attachmentCreator = USER.as("attachmentCreator"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User creator = USER.as("creator"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User leadDeveloper = USER.as("leadDeveloper"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User developer = USER.as("developer"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User commentCreator = USER.as("commentCreator"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User attachmentCreator = USER.as("attachmentCreator"); Result queryResult = jooq.select(REQUIREMENT.fields()) .select(creator.fields()) @@ -152,7 +152,7 @@ public RequirementContributors findRequirementContributors(int requirementId) th } UserTransformer userTransformer = new UserTransformer(); - RequirementContributors.Builder builder = new RequirementContributors.Builder(); + RequirementContributors.Builder builder = RequirementContributors.builder(); builder.creator( userTransformer.getEntityFromQueryResult(creator, queryResult) @@ -164,7 +164,9 @@ public RequirementContributors findRequirementContributors(int requirementId) th } List developers = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(developer.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); developers.add( userTransformer.getEntityFromQueryResult(developer, records) @@ -174,7 +176,9 @@ public RequirementContributors findRequirementContributors(int requirementId) th List commentCreators = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(commentCreator.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); commentCreators.add( userTransformer.getEntityFromQueryResult(commentCreator, records) @@ -184,7 +188,9 @@ public RequirementContributors findRequirementContributors(int requirementId) th List attachmentCreators = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(attachmentCreator.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); attachmentCreators.add( userTransformer.getEntityFromQueryResult(attachmentCreator, records) @@ -204,12 +210,12 @@ public RequirementContributors findRequirementContributors(int requirementId) th public CategoryContributors findCategoryContributors(int categoryId) throws BazaarException { CategoryContributors contributors = null; try { - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leader = USER.as("leader"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User requirementCreator = USER.as("requirementCreator"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leadDeveloper = USER.as("leadDeveloper"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User developer = USER.as("developer"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User commentCreator = USER.as("commentCreator"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User attachmentCreator = USER.as("attachmentCreator"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User leader = USER.as("leader"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User requirementCreator = USER.as("requirementCreator"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User leadDeveloper = USER.as("leadDeveloper"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User developer = USER.as("developer"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User commentCreator = USER.as("commentCreator"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User attachmentCreator = USER.as("attachmentCreator"); Result queryResult = jooq.select(CATEGORY.fields()) .select(leader.fields()) @@ -241,7 +247,7 @@ public CategoryContributors findCategoryContributors(int categoryId) throws Baza } UserTransformer userTransformer = new UserTransformer(); - CategoryContributors.Builder builder = new CategoryContributors.Builder(); + CategoryContributors.Builder builder = CategoryContributors.builder(); builder.leader( userTransformer.getEntityFromQueryResult(leader, queryResult) @@ -249,7 +255,9 @@ public CategoryContributors findCategoryContributors(int categoryId) throws Baza List requirementCreators = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(requirementCreator.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); requirementCreators.add( userTransformer.getEntityFromQueryResult(requirementCreator, records) @@ -259,7 +267,9 @@ public CategoryContributors findCategoryContributors(int categoryId) throws Baza List leadDevelopers = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(leadDeveloper.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); leadDevelopers.add( userTransformer.getEntityFromQueryResult(leadDeveloper, records) @@ -269,7 +279,9 @@ public CategoryContributors findCategoryContributors(int categoryId) throws Baza List developers = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(developer.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); developers.add( userTransformer.getEntityFromQueryResult(developer, records) @@ -279,7 +291,9 @@ public CategoryContributors findCategoryContributors(int categoryId) throws Baza List commentCreators = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(commentCreator.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); commentCreators.add( userTransformer.getEntityFromQueryResult(commentCreator, records) @@ -289,7 +303,9 @@ public CategoryContributors findCategoryContributors(int categoryId) throws Baza List attachmentCreators = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(attachmentCreator.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); attachmentCreators.add( userTransformer.getEntityFromQueryResult(attachmentCreator, records) @@ -309,13 +325,13 @@ public CategoryContributors findCategoryContributors(int categoryId) throws Baza public ProjectContributors findProjectContributors(int projectId) throws BazaarException { ProjectContributors contributors = null; try { - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leader = USER.as("leader"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User categoryLeader = USER.as("categoryLeader"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User requirementCreator = USER.as("requirementCreator"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leadDeveloper = USER.as("leadDeveloper"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User developer = USER.as("developer"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User commentCreator = USER.as("commentCreator"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User attachmentCreator = USER.as("attachmentCreator"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User leader = USER.as("leader"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User categoryLeader = USER.as("categoryLeader"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User requirementCreator = USER.as("requirementCreator"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User leadDeveloper = USER.as("leadDeveloper"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User developer = USER.as("developer"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User commentCreator = USER.as("commentCreator"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.User attachmentCreator = USER.as("attachmentCreator"); Result queryResult = jooq.select(PROJECT.fields()) .select(leader.fields()) @@ -353,7 +369,7 @@ public ProjectContributors findProjectContributors(int projectId) throws BazaarE } UserTransformer userTransformer = new UserTransformer(); - ProjectContributors.Builder builder = new ProjectContributors.Builder(); + ProjectContributors.Builder builder = ProjectContributors.builder(); builder.leader( userTransformer.getEntityFromQueryResult(leader, queryResult) @@ -361,7 +377,9 @@ public ProjectContributors findProjectContributors(int projectId) throws BazaarE List categoriesLeaders = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(categoryLeader.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); categoriesLeaders.add( userTransformer.getEntityFromQueryResult(categoryLeader, records) @@ -371,7 +389,9 @@ public ProjectContributors findProjectContributors(int projectId) throws BazaarE List requirementCreators = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(requirementCreator.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); requirementCreators.add( userTransformer.getEntityFromQueryResult(requirementCreator, records) @@ -381,7 +401,9 @@ public ProjectContributors findProjectContributors(int projectId) throws BazaarE List leadDevelopers = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(leadDeveloper.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); leadDevelopers.add( userTransformer.getEntityFromQueryResult(leadDeveloper, records) @@ -391,7 +413,9 @@ public ProjectContributors findProjectContributors(int projectId) throws BazaarE List developers = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(developer.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); developers.add( userTransformer.getEntityFromQueryResult(developer, records) @@ -401,7 +425,9 @@ public ProjectContributors findProjectContributors(int projectId) throws BazaarE List commentCreators = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(commentCreator.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); commentCreators.add( userTransformer.getEntityFromQueryResult(commentCreator, records) @@ -411,7 +437,9 @@ public ProjectContributors findProjectContributors(int projectId) throws BazaarE List attachmentCreators = new ArrayList<>(); for (Map.Entry> entry : queryResult.intoGroups(attachmentCreator.ID).entrySet()) { - if (entry.getKey() == null) continue; + if (entry.getKey() == null) { + continue; + } Result records = entry.getValue(); attachmentCreators.add( userTransformer.getEntityFromQueryResult(attachmentCreator, records) @@ -521,13 +549,13 @@ public List getEmailReceiverForProject(int projectId) throws BazaarExcepti .from(USER .join(PROJECT).on(USER.ID.eq(PROJECT.LEADER_ID))) .where(PROJECT.ID.eq(projectId)) - .and(USER.EMAIL_LEAD_SUBSCRIPTION.eq(ONE)) + .and(USER.EMAIL_LEAD_SUBSCRIPTION.isTrue()) .union(jooq.selectDistinct(USER.fields()) .from(USER .join(PROJECT_FOLLOWER_MAP).on(USER.ID.eq(PROJECT_FOLLOWER_MAP.USER_ID))) .where(PROJECT_FOLLOWER_MAP.PROJECT_ID.eq(projectId)) - .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.eq(ONE))) + .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.isTrue())) .fetch(); for (Record queryResult : queryResults) { @@ -551,20 +579,20 @@ public List getEmailReceiverForCategory(int categoryId) throws BazaarExcep .from(USER .join(CATEGORY).on(USER.ID.eq(CATEGORY.LEADER_ID))) .where(CATEGORY.ID.eq(categoryId)) - .and(USER.EMAIL_LEAD_SUBSCRIPTION.eq(ONE)) + .and(USER.EMAIL_LEAD_SUBSCRIPTION.isTrue()) .union(jooq.selectDistinct(USER.fields()) .from(USER .join(CATEGORY_FOLLOWER_MAP).on(USER.ID.eq(CATEGORY_FOLLOWER_MAP.USER_ID))) .where(CATEGORY_FOLLOWER_MAP.CATEGORY_ID.eq(categoryId)) - .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.eq(ONE))) + .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.isTrue())) .union(jooq.selectDistinct(USER.fields()) .from(USER .join(PROJECT).on(USER.ID.eq(PROJECT.LEADER_ID)) .join(CATEGORY).on(CATEGORY.PROJECT_ID.eq(PROJECT.ID))) .where(CATEGORY.ID.eq(categoryId)) - .and(USER.EMAIL_LEAD_SUBSCRIPTION.eq(ONE))) + .and(USER.EMAIL_LEAD_SUBSCRIPTION.isTrue())) .union(jooq.selectDistinct(USER.fields()) .from(USER @@ -572,7 +600,7 @@ public List getEmailReceiverForCategory(int categoryId) throws BazaarExcep .join(CATEGORY).on(CATEGORY.PROJECT_ID.eq(PROJECT_FOLLOWER_MAP.PROJECT_ID))) .where(CATEGORY.ID.eq(categoryId)) .and(PROJECT_FOLLOWER_MAP.PROJECT_ID.eq(CATEGORY.PROJECT_ID)) - .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.eq(ONE))) + .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.isTrue())) .fetch(); @@ -598,14 +626,14 @@ public List getEmailReceiverForRequirement(int requirementId) throws Bazaa .from(USER .join(REQUIREMENT).on(REQUIREMENT.LEAD_DEVELOPER_ID.eq(USER.ID))) .where(REQUIREMENT.ID.eq(requirementId)) - .and(USER.EMAIL_LEAD_SUBSCRIPTION.eq(ONE)) + .and(USER.EMAIL_LEAD_SUBSCRIPTION.isTrue()) // req follower .union(jooq.selectDistinct(USER.fields()) .from(USER .join(REQUIREMENT_FOLLOWER_MAP).on(USER.ID.eq(REQUIREMENT_FOLLOWER_MAP.USER_ID))) .where(REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID.eq(requirementId)) - .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.eq(ONE))) + .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.isTrue())) // category leader .union(jooq.selectDistinct(USER.fields()) @@ -613,7 +641,7 @@ public List getEmailReceiverForRequirement(int requirementId) throws Bazaa .join(CATEGORY).on(USER.ID.eq(CATEGORY.LEADER_ID)) .join(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID.eq(CATEGORY.ID))) .where(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID.eq(requirementId)) - .and(USER.EMAIL_LEAD_SUBSCRIPTION.eq(ONE))) + .and(USER.EMAIL_LEAD_SUBSCRIPTION.isTrue())) // category follower .union(jooq.selectDistinct(USER.fields()) @@ -622,7 +650,7 @@ public List getEmailReceiverForRequirement(int requirementId) throws Bazaa .join(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID.eq(CATEGORY_FOLLOWER_MAP.CATEGORY_ID)) .join(REQUIREMENT).on(REQUIREMENT.ID.eq(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID))) .where(REQUIREMENT.ID.eq(requirementId)) - .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.eq(ONE))) + .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.isTrue())) // project leader .union(jooq.selectDistinct(USER.fields()) @@ -630,7 +658,7 @@ public List getEmailReceiverForRequirement(int requirementId) throws Bazaa .join(PROJECT).on(USER.ID.eq(PROJECT.LEADER_ID)) .join(REQUIREMENT).on(REQUIREMENT.PROJECT_ID.eq(PROJECT.ID))) .where(REQUIREMENT.ID.eq(requirementId)) - .and(USER.EMAIL_LEAD_SUBSCRIPTION.eq(ONE))) + .and(USER.EMAIL_LEAD_SUBSCRIPTION.isTrue())) // project follower .union(jooq.selectDistinct(USER.fields()) @@ -639,7 +667,7 @@ public List getEmailReceiverForRequirement(int requirementId) throws Bazaa .join(REQUIREMENT).on(REQUIREMENT.PROJECT_ID.eq(PROJECT_FOLLOWER_MAP.PROJECT_ID))) .where(REQUIREMENT.ID.eq(requirementId)) .and(PROJECT_FOLLOWER_MAP.PROJECT_ID.eq(REQUIREMENT.PROJECT_ID)) - .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.eq(ONE))) + .and(USER.EMAIL_FOLLOW_SUBSCRIPTION.isTrue())) .fetch(); @@ -652,4 +680,28 @@ public List getEmailReceiverForRequirement(int requirementId) throws Bazaa } return entries; } + + @Override + public List search(Pageable pageable) throws BazaarException { + List entries = null; + try { + entries = new ArrayList<>(); + List queryResults = jooq.selectFrom(transformer.getTable()) + .where(transformer.getSearchCondition(pageable.getSearch())) + .limit(pageable.getPageSize()) + .offset(pageable.getOffset()) + .fetchInto(transformer.getRecordClass()); + + for (UserRecord queryResult : queryResults) { + User entry = transformer.getEntityFromTableRecord(queryResult); + entries.add(entry); + } + } catch (BazaarException ex) { + ExceptionHandler.getInstance().convertAndThrowException(ex); + } catch (Exception e) { + ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); + } + + return entries; + } } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepository.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepository.java similarity index 95% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepository.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepository.java index e5b6bc21..bac8aac4 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepository.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepository.java @@ -25,7 +25,6 @@ import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; /** - * @author Adam Gavronek * @since 6/22/2014 */ public interface VoteRepository extends Repository { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepositoryImpl.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepositoryImpl.java similarity index 93% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepositoryImpl.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepositoryImpl.java index 55a0cf5c..46dd9852 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepositoryImpl.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/repositories/VoteRepositoryImpl.java @@ -20,9 +20,9 @@ package de.rwth.dbis.acis.bazaar.service.dal.repositories; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.VoteRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.Vote; import de.rwth.dbis.acis.bazaar.service.dal.helpers.CreationStatus; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.VoteRecord; import de.rwth.dbis.acis.bazaar.service.dal.transform.VoteTransformer; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; @@ -36,10 +36,9 @@ import java.util.Map; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.VOTE; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.VOTE; /** - * @author Adam Gavronek * @since 6/23/2014 */ public class VoteRepositoryImpl extends RepositoryImpl implements VoteRepository { @@ -81,7 +80,7 @@ public CreationStatus addOrUpdate(Vote vote) throws BazaarException { .fetchOne(); if (record != null) { - if (record.getIsUpvote() != (byte) (vote.isUpvote() ? 1 : 0)) { + if (record.getIsUpvote()) { UpdateSetFirstStep update = jooq.update(transformer.getTable()); Map map = transformer.getUpdateMap(vote); UpdateSetMoreStep moreStep = null; diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/AttachmentTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/AttachmentTransformer.java similarity index 75% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/AttachmentTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/AttachmentTransformer.java index 12039e68..8fd090c3 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/AttachmentTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/AttachmentTransformer.java @@ -20,23 +20,20 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; -import com.vdurmont.emoji.EmojiParser; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.AttachmentRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.Attachment; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.AttachmentRecord; import org.jooq.*; -import java.sql.Timestamp; +import java.time.OffsetDateTime; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.ATTACHMENT; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.ATTACHMENT; public class AttachmentTransformer implements Transformer { @Override public AttachmentRecord createRecord(Attachment entity) { - entity = this.cleanEntry(entity); - AttachmentRecord record = new AttachmentRecord(); record.setLastUpdatedDate(record.getCreationDate()); record.setRequirementId(entity.getRequirementId()); @@ -46,13 +43,13 @@ public AttachmentRecord createRecord(Attachment entity) { record.setMimeType(entity.getMimeType()); record.setIdentifier(entity.getIdentifier()); record.setFileUrl(entity.getFileUrl()); - record.setCreationDate(new Timestamp(Calendar.getInstance().getTime().getTime())); + record.setCreationDate(OffsetDateTime.now()); return record; } @Override public Attachment getEntityFromTableRecord(AttachmentRecord record) { - return Attachment.getBuilder() + return Attachment.builder() .id(record.getId()) .requirementId(record.getRequirementId()) .name(record.getName()) @@ -81,11 +78,11 @@ public Class getRecordClass() { } @Override - public Map getUpdateMap(final Attachment entity) { - HashMap updateMap = new HashMap() {{ + public Map getUpdateMap(Attachment entity) { + HashMap updateMap = new HashMap<>() {{ }}; if (!updateMap.isEmpty()) { - updateMap.put(ATTACHMENT.LAST_UPDATED_DATE, new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); + updateMap.put(ATTACHMENT.LAST_UPDATED_DATE, OffsetDateTime.now()); } return updateMap; } @@ -107,16 +104,4 @@ public Condition getSearchCondition(String search) throws Exception { public Collection getFilterConditions(Map filters) throws Exception { return new ArrayList<>(); } - - private Attachment cleanEntry(Attachment attachment) { - if (attachment.getName() != null) { - attachment.setName(EmojiParser.parseToAliases(attachment.getName())); - } - if (attachment.getDescription() != null) { - attachment.setDescription(EmojiParser.parseToAliases(attachment.getDescription())); - } - return attachment; - } } - - diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryFollowerTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryFollowerTransformer.java similarity index 90% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryFollowerTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryFollowerTransformer.java index 4315be8d..31b69501 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryFollowerTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryFollowerTransformer.java @@ -1,13 +1,13 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.CategoryFollowerMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.CategoryFollower; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.CategoryFollowerMapRecord; import org.jooq.*; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.CATEGORY_FOLLOWER_MAP; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.CATEGORY_FOLLOWER_MAP; public class CategoryFollowerTransformer implements Transformer { @Override @@ -20,7 +20,7 @@ public CategoryFollowerMapRecord createRecord(CategoryFollower entity) { @Override public CategoryFollower getEntityFromTableRecord(CategoryFollowerMapRecord record) { - return CategoryFollower.getBuilder() + return CategoryFollower.builder() .id(record.getId()) .userId(record.getUserId()) .categoryId(record.getCategoryId()) diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryTransformer.java similarity index 68% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryTransformer.java index 19a71849..a8a19210 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/CategoryTransformer.java @@ -20,44 +20,63 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; -import com.vdurmont.emoji.EmojiParser; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyNamingStrategy; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.CategoryRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.Category; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.CategoryRecord; import de.rwth.dbis.acis.bazaar.service.dal.repositories.CategoryRepositoryImpl; import org.jooq.*; +import org.jooq.impl.DSL; +import java.time.OffsetDateTime; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.CATEGORY; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.CATEGORY; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.CATEGORY_FOLLOWER_MAP; /** - * @author Adam Gavronek * @since 6/9/2014 */ public class CategoryTransformer implements Transformer { @Override public CategoryRecord createRecord(Category entry) { - entry = this.cleanEntry(entry); - CategoryRecord record = new CategoryRecord(); record.setDescription(entry.getDescription()); record.setName(entry.getName()); record.setProjectId(entry.getProjectId()); - record.setLeaderId(entry.getLeader().getId()); - record.setCreationDate(new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); + record.setLeaderId(entry.getCreator().getId()); + record.setCreationDate(OffsetDateTime.now()); + if (entry.getAdditionalProperties() != null) { + record.setAdditionalProperties(JSONB.jsonb(entry.getAdditionalProperties().toString())); + } return record; } @Override public Category getEntityFromTableRecord(CategoryRecord record) { - return Category.getBuilder(record.getName()) + ObjectMapper mapper = new ObjectMapper(); + mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + Category.Builder categoryBuilder = Category.builder() + .name(record.getName()) .description(record.getDescription()) .projectId(record.getProjectId()) .id(record.getId()) .creationDate(record.getCreationDate()) - .lastUpdatedDate(record.getLastUpdatedDate()) - .build(); + .lastUpdatedDate(record.getLastUpdatedDate()); + + try { + return categoryBuilder + .additionalProperties( + mapper.readTree(record.getAdditionalProperties().data()) + ) + .build(); + } catch (Exception e) { + return categoryBuilder.build(); + } } @Override @@ -76,20 +95,23 @@ public Class getRecordClass() { } @Override - public Map getUpdateMap(final Category entry) { - HashMap updateMap = new HashMap() {{ + public Map getUpdateMap(Category entry) { + HashMap updateMap = new HashMap<>() {{ if (entry.getDescription() != null) { put(CATEGORY.DESCRIPTION, entry.getDescription()); } if (entry.getName() != null) { put(CATEGORY.NAME, entry.getName()); } - if (entry.getLeader() != null) { - put(CATEGORY.LEADER_ID, entry.getLeader().getId()); + if (entry.getCreator() != null) { + put(CATEGORY.LEADER_ID, entry.getCreator().getId()); + } + if (entry.getAdditionalProperties() != null) { + put(CATEGORY.ADDITIONAL_PROPERTIES, entry.getAdditionalProperties()); } }}; if (!updateMap.isEmpty()) { - updateMap.put(CATEGORY.LAST_UPDATED_DATE, new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); + updateMap.put(CATEGORY.LAST_UPDATED_DATE, OffsetDateTime.now()); } return updateMap; } @@ -104,10 +126,8 @@ public Collection> getSortFields(List switch (sort.getField()) { case "name": switch (sort.getSortDirection()) { - case ASC: - sortFields.add(CATEGORY.NAME.asc()); - break; case DESC: + // 50 is derived from the name max length sortFields.add(CATEGORY.NAME.desc()); break; default: @@ -180,16 +200,26 @@ public Condition getSearchCondition(String search) throws Exception { @Override public Collection getFilterConditions(Map filters) throws Exception { - return new ArrayList<>(); - } + List conditions = new ArrayList<>(); + for (Map.Entry filterEntry : filters.entrySet()) { - private Category cleanEntry(Category category) { - if (category.getName() != null) { - category.setName(EmojiParser.parseToAliases(category.getName())); - } - if (category.getDescription() != null) { - category.setDescription(EmojiParser.parseToAliases(category.getDescription())); + + if (filterEntry.getKey().equals("created")) { + conditions.add( + CATEGORY.LEADER_ID.eq(Integer.parseInt(filterEntry.getValue())) + ); + } else if (filterEntry.getKey().equals("following")) { + conditions.add( + CATEGORY.ID.in( + DSL.select(CATEGORY_FOLLOWER_MAP.CATEGORY_ID) + .from(CATEGORY_FOLLOWER_MAP) + .where(CATEGORY_FOLLOWER_MAP.USER_ID.eq(Integer.parseInt(filterEntry.getValue()))) + ) + ); + } else { + conditions.add(DSL.falseCondition()); + } } - return category; + return conditions; } } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/CommentTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/CommentTransformer.java new file mode 100644 index 00000000..9d904ffa --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/CommentTransformer.java @@ -0,0 +1,219 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.transform; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.CommentRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Comment; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import org.jooq.*; +import org.jooq.impl.DSL; + +import java.time.OffsetDateTime; +import java.util.*; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.*; + +/** + * @since 6/23/2014 + */ +public class CommentTransformer implements Transformer { + @Override + public CommentRecord createRecord(Comment entity) { + CommentRecord record = new CommentRecord(); + record.setUserId(entity.getCreator().getId()); + record.setMessage(entity.getMessage()); + record.setRequirementId(entity.getRequirementId()); + record.setReplyToCommentId(entity.getReplyToComment()); + record.setCreationDate(OffsetDateTime.now()); + record.setDeleted(entity.getDeleted()); + return record; + } + + @Override + public Comment getEntityFromTableRecord(CommentRecord record) { + return Comment.builder() + .message(record.getMessage()) + .id(record.getId()) + .requirementId(record.getRequirementId()) + .replyToComment(record.getReplyToCommentId()) + .creationDate(record.getCreationDate()) + .lastUpdatedDate(record.getLastUpdatedDate()) + .deleted(record.getDeleted()) + .build(); + } + + @Override + public Table getTable() { + return COMMENT; + } + + @Override + public TableField getTableId() { + return COMMENT.ID; + } + + @Override + public Class getRecordClass() { + return CommentRecord.class; + } + + @Override + public Map getUpdateMap(Comment entity) { + HashMap updateMap = new HashMap<>() {{ + put(COMMENT.REQUIREMENT_ID, entity.getRequirementId()); + put(COMMENT.MESSAGE, entity.getMessage()); + put(COMMENT.DELETED, entity.getDeleted()); + }}; + if (!updateMap.isEmpty()) { + updateMap.put(COMMENT.LAST_UPDATED_DATE, OffsetDateTime.now()); + } + return updateMap; + } + + @Override + public Collection> getSortFields(List sorts) { + if (sorts.isEmpty()) { + return Collections.singletonList(COMMENT.CREATION_DATE.asc()); + } + + + List> sortFields = new ArrayList<>(); + for (Pageable.SortField sort : sorts) { + switch (sort.getField()) { + case "date": + switch (sort.getSortDirection()) { + case ASC: + sortFields.add(COMMENT.CREATION_DATE.asc()); + break; + case DESC: + sortFields.add(COMMENT.CREATION_DATE.desc()); + break; + default: + sortFields.add(COMMENT.CREATION_DATE.desc()); + break; + } + break; + case "last_activity": + switch (sort.getSortDirection()) { + case ASC: + sortFields.add(COMMENT.LAST_UPDATED_DATE.asc()); + break; + case DESC: + sortFields.add(COMMENT.LAST_UPDATED_DATE.desc()); + break; + default: + sortFields.add(COMMENT.LAST_UPDATED_DATE.desc()); + break; + } + break; + } + } + return sortFields; + } + + @Override + public Condition getSearchCondition(String search) throws Exception { + //throw new Exception("Search is not supported!"); + if (search != "") { + return COMMENT.MESSAGE.likeIgnoreCase("%" + search + "%"); + } + return DSL.trueCondition(); + } + + @Override + public Collection getFilterConditions(Map filters) throws Exception { + List conditions = new ArrayList<>(); + + for (Map.Entry filterEntry : filters.entrySet()) { + + if (filterEntry.getKey().equals("created")) { + conditions.add( + COMMENT.USER_ID.eq(Integer.parseInt(filterEntry.getValue())) + ); + } else if (filterEntry.getKey().equals("following")) { + conditions.add( + COMMENT.REQUIREMENT_ID.in( + DSL.select(REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID) + .from(REQUIREMENT_FOLLOWER_MAP) + .where(REQUIREMENT_FOLLOWER_MAP.USER_ID.eq(Integer.parseInt(filterEntry.getValue()))) + .union( + DSL.select(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID) + .from(REQUIREMENT_CATEGORY_MAP) + .join(CATEGORY_FOLLOWER_MAP) + .on(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID.eq(CATEGORY_FOLLOWER_MAP.CATEGORY_ID) + .and(CATEGORY_FOLLOWER_MAP.USER_ID.eq(Integer.parseInt(filterEntry.getValue())))) + ).union( + DSL.select(REQUIREMENT.ID) + .from(REQUIREMENT) + .join(PROJECT_FOLLOWER_MAP) + .on(REQUIREMENT.PROJECT_ID.eq(PROJECT_FOLLOWER_MAP.PROJECT_ID) + .and(PROJECT_FOLLOWER_MAP.USER_ID.eq(Integer.parseInt(filterEntry.getValue())))) + ) + ) + ); + + } else if (filterEntry.getKey().equals("replies")) { + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Comment SUB_COMMENTS = COMMENT.as("sub_comments"); + de.rwth.dbis.acis.bazaar.dal.jooq.tables.Comment IN_COMMENTS = COMMENT.as("in_comments"); + conditions.add( + COMMENT.ID.in( + DSL.select(IN_COMMENTS.ID) + .from(IN_COMMENTS) + .leftSemiJoin(SUB_COMMENTS).on( + ( + IN_COMMENTS.REPLY_TO_COMMENT_ID.eq(SUB_COMMENTS.REPLY_TO_COMMENT_ID) //Refering same thread/base-comment + .and( + IN_COMMENTS.CREATION_DATE.greaterThan(SUB_COMMENTS.CREATION_DATE) //replies have greater timestamp than the users comment + ).and( + SUB_COMMENTS.USER_ID.eq(Integer.parseInt(filterEntry.getValue())) //Comments the user wrote + ) + ).or( + IN_COMMENTS.REPLY_TO_COMMENT_ID.eq(SUB_COMMENTS.ID).and(SUB_COMMENTS.USER_ID.eq(Integer.parseInt(filterEntry.getValue()))) //User is Thread-Owner + ) + ).where(IN_COMMENTS.USER_ID.notEqual(Integer.parseInt(filterEntry.getValue()))) // Remove Users "Own" Comments + ) + ); + } + +/* + if(filterEntry.getKey().equals("developing")){ + conditions.add( + COMMENT.REQUIREMENT_ID.in( + DSL.select(REQUIREMENT_DEVELOPER_MAP.REQUIREMENT_ID) + .from(REQUIREMENT_DEVELOPER_MAP) + .where(REQUIREMENT_DEVELOPER_MAP.USER_ID.eq(Integer.parseInt(filterEntry.getValue()))) + .or(REQUIREMENT.LEAD_DEVELOPER_ID.eq(Integer.parseInt(filterEntry.getValue()))) + ) + ); + + + }else + */ + else { + + conditions.add( + DSL.falseCondition() + ); + } + } + return conditions; + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/FeedbackTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/FeedbackTransformer.java new file mode 100644 index 00000000..55ce1f61 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/FeedbackTransformer.java @@ -0,0 +1,80 @@ +package de.rwth.dbis.acis.bazaar.service.dal.transform; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.FeedbackRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Feedback; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import org.jooq.*; + +import java.time.OffsetDateTime; +import java.util.*; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.FEEDBACK; + +public class FeedbackTransformer implements Transformer { + @Override + public FeedbackRecord createRecord(Feedback entity) { + FeedbackRecord record = new FeedbackRecord(); + record.setProjectId(entity.getProjectId()); + record.setFeedback(entity.getFeedback()); + record.setEmail(entity.getEMail()); + record.setRequirementId(entity.getRequirementId()); + record.setCreationDate(OffsetDateTime.now()); + return record; + } + + @Override + public Feedback getEntityFromTableRecord(FeedbackRecord record) { + return Feedback.builder() + .id(record.getId()) + .creationDate(record.getCreationDate()) + .projectId(record.getProjectId()) + .eMail(record.getEmail()) + .feedback(record.getFeedback()) + .requirementId(record.getRequirementId()) + .build(); + } + + @Override + public Table getTable() { + return FEEDBACK; + } + + @Override + public TableField getTableId() { + return FEEDBACK.ID; + } + + @Override + public Class getRecordClass() { + return FeedbackRecord.class; + } + + @Override + public Map getUpdateMap(Feedback entity) { + HashMap updateMap = new HashMap<>() {{ + + if (entity.getRequirementId() != null) { + put(FEEDBACK.REQUIREMENT_ID, entity.getRequirementId()); + } + }}; + return updateMap; + } + + @Override + public Collection> getSortFields(List sorts) { + if (sorts.isEmpty()) { + return Collections.singletonList(FEEDBACK.CREATION_DATE.desc()); + } + return null; + } + + @Override + public Condition getSearchCondition(String search) throws Exception { + throw new Exception("Search is not supported!"); + } + + @Override + public Collection getFilterConditions(Map filters) throws Exception { + return new ArrayList<>(); + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/PersonalisationDataTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/PersonalisationDataTransformer.java new file mode 100644 index 00000000..921e5e24 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/PersonalisationDataTransformer.java @@ -0,0 +1,102 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.transform; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.PersonalisationDataRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.PersonalisationData; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import org.jooq.*; + +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.PERSONALISATION_DATA; + +/** + * @since 6/23/2014 + */ +public class PersonalisationDataTransformer implements Transformer { + @Override + public PersonalisationDataRecord createRecord(PersonalisationData entity) { + PersonalisationDataRecord record = new PersonalisationDataRecord(); + record.setVersion(entity.getVersion()); + record.setUserId(entity.getUserId()); + record.setIdentifier(entity.getKey()); + record.setSetting(entity.getValue()); + record.setUserId(entity.getUserId()); + return record; + } + + @Override + public PersonalisationData getEntityFromTableRecord(PersonalisationDataRecord record) { + return PersonalisationData.builder() + .id(record.getId()) + .userId(record.getUserId()) + .version(record.getVersion()) + .userId(record.getUserId()) + .value(record.getSetting()) + .build(); + } + + @Override + public Table getTable() { + return PERSONALISATION_DATA; + } + + @Override + public TableField getTableId() { + return PERSONALISATION_DATA.ID; + } + + @Override + public Class getRecordClass() { + return PersonalisationDataRecord.class; + } + + @Override + public Map getUpdateMap(final PersonalisationData entity) { + return new HashMap() {{ + put(PERSONALISATION_DATA.SETTING, entity.getValue()); + //put(PERSONALISATION_DATA.LAST_UPDATED_DATE, time); + }}; + } + + @Override + public Collection> getSortFields(List sorts){ + /* if (sorts.isEmpty()) { + return Collections.singletonList(VOTE.ID.asc()); + } */ + return null; + } + + @Override + public Condition getSearchCondition(String search) throws Exception { + throw new Exception("Search is not supported!"); + } + + @Override + public Collection getFilterConditions(Map filters) throws Exception { + //return new ArrayList<>(); + throw new Exception("Filtering is not supported!"); + } +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/PrivilegeEnumConverter.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/PrivilegeEnumConverter.java similarity index 100% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/PrivilegeEnumConverter.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/PrivilegeEnumConverter.java diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/PrivilegeTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/PrivilegeTransformer.java similarity index 87% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/PrivilegeTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/PrivilegeTransformer.java index 5596213b..fb8d3f76 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/PrivilegeTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/PrivilegeTransformer.java @@ -20,18 +20,17 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.PrivilegeRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.Privilege; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.PrivilegeRecord; import org.jooq.*; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.PRIVILEGE; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.ROLE; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.PRIVILEGE; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.ROLE; /** - * @author Adam Gavronek * @since 2/18/2015 */ public class PrivilegeTransformer implements Transformer { @@ -45,7 +44,8 @@ public PrivilegeRecord createRecord(Privilege entity) { @Override public Privilege getEntityFromTableRecord(PrivilegeRecord record) { - return Privilege.getBuilder(new PrivilegeEnumConverter().from(record.getName())) + return Privilege.builder() + .name(new PrivilegeEnumConverter().from(record.getName())) .id(record.getId()) .build(); } @@ -90,4 +90,3 @@ public Collection getFilterConditions(Map f return new ArrayList<>(); } } - diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectFollowerTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectFollowerTransformer.java similarity index 90% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectFollowerTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectFollowerTransformer.java index c0bb5a68..e3db2369 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectFollowerTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectFollowerTransformer.java @@ -1,13 +1,13 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.ProjectFollowerMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.ProjectFollower; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.ProjectFollowerMapRecord; import org.jooq.*; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.PROJECT_FOLLOWER_MAP; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.PROJECT_FOLLOWER_MAP; public class ProjectFollowerTransformer implements Transformer { @@ -21,7 +21,7 @@ public ProjectFollowerMapRecord createRecord(ProjectFollower entity) { @Override public ProjectFollower getEntityFromTableRecord(ProjectFollowerMapRecord record) { - return ProjectFollower.getBuilder() + return ProjectFollower.builder() .id(record.getId()) .userId(record.getUserId()) .projectId(record.getProjectId()) diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectTransformer.java similarity index 57% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectTransformer.java index e2725898..9b99942e 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/ProjectTransformer.java @@ -20,44 +20,62 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; -import com.vdurmont.emoji.EmojiParser; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyNamingStrategy; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.ProjectRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.Project; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.ProjectRecord; import de.rwth.dbis.acis.bazaar.service.dal.repositories.ProjectRepositoryImpl; import org.jooq.*; import org.jooq.impl.DSL; +import java.time.OffsetDateTime; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.*; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.*; public class ProjectTransformer implements Transformer { @Override public ProjectRecord createRecord(Project entry) { - entry = this.cleanEntry(entry); - ProjectRecord record = new ProjectRecord(); record.setDescription(entry.getDescription()); record.setName(entry.getName()); record.setLeaderId(entry.getLeader().getId()); - record.setVisibility((byte) (entry.getVisibility() ? 1 : 0)); + record.setVisibility(entry.getVisibility()); record.setDefaultCategoryId(entry.getDefaultCategoryId()); - record.setCreationDate(new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); + record.setCreationDate(OffsetDateTime.now()); + if (entry.getAdditionalProperties() != null) { + record.setAdditionalProperties(JSONB.jsonb(entry.getAdditionalProperties().toString())); + } return record; } @Override public Project getEntityFromTableRecord(ProjectRecord record) { - return Project.getBuilder(record.getName()) + ObjectMapper mapper = new ObjectMapper(); + mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + Project.Builder projectBuilder = Project.builder() + .name(record.getName()) .description(record.getDescription()) .id(record.getId()) .defaultCategoryId(record.getDefaultCategoryId()) - .visibility(record.getVisibility() == 1) + .visibility(record.getVisibility()) .creationDate(record.getCreationDate()) - .lastUpdatedDate(record.getLastUpdatedDate()) - .build(); + .lastUpdatedDate(record.getLastUpdatedDate()); + + try { + return projectBuilder + .additionalProperties( + mapper.readTree(record.getAdditionalProperties().data()) + ) + .build(); + } catch (Exception e) { + return projectBuilder.build(); + } } @Override @@ -76,8 +94,8 @@ public Class getRecordClass() { } @Override - public Map getUpdateMap(final Project entry) { - HashMap updateMap = new HashMap() {{ + public Map getUpdateMap(Project entry) { + HashMap updateMap = new HashMap<>() {{ if (entry.getDescription() != null) { put(PROJECT.DESCRIPTION, entry.getDescription()); } @@ -93,9 +111,12 @@ public Map getUpdateMap(final Project entry) { if (entry.getVisibility() != null) { put(PROJECT.VISIBILITY, entry.getVisibility()); } + if (entry.getAdditionalProperties() != null) { + put(PROJECT.ADDITIONAL_PROPERTIES, entry.getAdditionalProperties()); + } }}; if (!updateMap.isEmpty()) { - updateMap.put(PROJECT.LAST_UPDATED_DATE, new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); + updateMap.put(PROJECT.LAST_UPDATED_DATE, OffsetDateTime.now()); } return updateMap; } @@ -103,48 +124,32 @@ public Map getUpdateMap(final Project entry) { @Override public Collection> getSortFields(List sorts) { if (sorts.isEmpty()) { - return Collections.singletonList(PROJECT.NAME.asc()); + return Collections.singletonList(ProjectRepositoryImpl.LAST_ACTIVITY.field("last_activity").desc()); } List> sortFields = new ArrayList<>(); for (Pageable.SortField sort : sorts) { switch (sort.getField()) { case "name": - switch (sort.getSortDirection()) { - case ASC: - sortFields.add(PROJECT.NAME.asc()); - break; - case DESC: - sortFields.add(PROJECT.NAME.desc()); - break; - default: - sortFields.add(PROJECT.NAME.asc()); - break; + if (sort.getSortDirection() == Pageable.SortDirection.DESC) { + // 50 is derived from the max length of the project name + sortFields.add(PROJECT.NAME.desc()); + } else { + sortFields.add(PROJECT.NAME.asc()); + } break; case "date": - switch (sort.getSortDirection()) { - case ASC: - sortFields.add(PROJECT.CREATION_DATE.asc()); - break; - case DESC: - sortFields.add(PROJECT.CREATION_DATE.desc()); - break; - default: - sortFields.add(PROJECT.CREATION_DATE.desc()); - break; + if (sort.getSortDirection() == Pageable.SortDirection.ASC) { + sortFields.add(PROJECT.CREATION_DATE.asc()); + } else { + sortFields.add(PROJECT.CREATION_DATE.desc()); } break; case "last_activity": - switch (sort.getSortDirection()) { - case ASC: - sortFields.add(ProjectRepositoryImpl.LAST_ACTIVITY.field("last_activity").asc()); - break; - case DESC: - sortFields.add(ProjectRepositoryImpl.LAST_ACTIVITY.field("last_activity").desc()); - break; - default: - sortFields.add(ProjectRepositoryImpl.LAST_ACTIVITY.field("last_activity").desc()); - break; + if (sort.getSortDirection() == Pageable.SortDirection.ASC) { + sortFields.add(ProjectRepositoryImpl.LAST_ACTIVITY.field("last_activity").asc()); + } else { + sortFields.add(ProjectRepositoryImpl.LAST_ACTIVITY.field("last_activity").desc()); } break; case "requirement": @@ -192,22 +197,38 @@ public Collection> getSortFields(List @Override public Condition getSearchCondition(String search) throws Exception { - return PROJECT.NAME.likeIgnoreCase("%" + search + "%") - .or(PROJECT.DESCRIPTION.likeIgnoreCase("%" + search + "%")); + // Catch issues with empty tsvector matching causing nothing to be found + if (search.equals("")) { + return PROJECT.NAME.likeIgnoreCase("%"); + } + return DSL.condition("to_tsvector({0} || {1}) @@ websearch_to_tsquery({2})", + PROJECT.NAME, PROJECT.DESCRIPTION, search); } @Override public Collection getFilterConditions(Map filters) throws Exception { - return new ArrayList<>(); - } - - private Project cleanEntry(Project project) { - if (project.getName() != null) { - project.setName(EmojiParser.parseToAliases(project.getName())); - } - if (project.getDescription() != null) { - project.setDescription(EmojiParser.parseToAliases(project.getDescription())); + List conditions = new ArrayList<>(); + for (Map.Entry filterEntry : filters.entrySet()) { + if (filterEntry.getKey().equals("all")) { + conditions.add( + DSL.trueCondition() + ); + } else if (filterEntry.getKey().equals("created")) { + conditions.add( + PROJECT.LEADER_ID.eq(Integer.parseInt(filterEntry.getValue())) + ); + } else if (filterEntry.getKey().equals("following")) { + conditions.add( + PROJECT.ID.in( + DSL.select(PROJECT_FOLLOWER_MAP.PROJECT_ID) + .from(PROJECT_FOLLOWER_MAP) + .where(PROJECT_FOLLOWER_MAP.USER_ID.eq(Integer.parseInt(filterEntry.getValue()))) + ) + ); + } else { + conditions.add(DSL.falseCondition()); + } } - return project; + return conditions; } } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementCategoryTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementCategoryTransformer.java similarity index 90% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementCategoryTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementCategoryTransformer.java index a30b9d46..2b1a3cfd 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementCategoryTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementCategoryTransformer.java @@ -20,17 +20,16 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementCategoryMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.RequirementCategory; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementCategoryMapRecord; import org.jooq.*; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.REQUIREMENT_CATEGORY_MAP; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.REQUIREMENT_CATEGORY_MAP; /** - * @author Adam Gavronek * @since 6/23/2014 */ public class RequirementCategoryTransformer implements Transformer { @@ -44,7 +43,8 @@ public RequirementCategoryMapRecord createRecord(RequirementCategory entity) { @Override public RequirementCategory getEntityFromTableRecord(RequirementCategoryMapRecord record) { - return RequirementCategory.getBuilder(record.getCategoryId()) + return RequirementCategory.builder() + .categoryId(record.getCategoryId()) .id(record.getId()) .requirementId(record.getRequirementId()) .build(); diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementDeveloperTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementDeveloperTransformer.java similarity index 91% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementDeveloperTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementDeveloperTransformer.java index c28ce74a..8213b3c8 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementDeveloperTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementDeveloperTransformer.java @@ -20,17 +20,16 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementDeveloperMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.RequirementDeveloper; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementDeveloperMapRecord; import org.jooq.*; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.REQUIREMENT_DEVELOPER_MAP; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.REQUIREMENT_DEVELOPER_MAP; /** - * @author Adam Gavronek * @since 6/23/2014 */ public class RequirementDeveloperTransformer implements Transformer { @@ -44,7 +43,7 @@ public RequirementDeveloperMapRecord createRecord(RequirementDeveloper entity) { @Override public RequirementDeveloper getEntityFromTableRecord(RequirementDeveloperMapRecord record) { - return RequirementDeveloper.getBuilder() + return RequirementDeveloper.builder() .id(record.getId()) .userId(record.getUserId()) .requirementId(record.getRequirementId()) diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementFollowerTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementFollowerTransformer.java similarity index 89% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementFollowerTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementFollowerTransformer.java index 68057046..1b8b65b8 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementFollowerTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementFollowerTransformer.java @@ -20,17 +20,16 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementFollowerMapRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.RequirementFollower; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementFollowerMapRecord; import org.jooq.*; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.REQUIREMENT_FOLLOWER_MAP; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.REQUIREMENT_FOLLOWER_MAP; /** - * @author Adam Gavronek * @since 6/23/2014 */ public class RequirementFollowerTransformer implements Transformer { @@ -44,7 +43,7 @@ public RequirementFollowerMapRecord createRecord(RequirementFollower entity) { @Override public RequirementFollower getEntityFromTableRecord(RequirementFollowerMapRecord record) { - return RequirementFollower.getBuilder() + return RequirementFollower.builder() .id(record.getId()) .userId(record.getUserId()) .requirementId(record.getRequirementId()) @@ -68,7 +67,7 @@ public Class getRecordClass() { @Override public Map getUpdateMap(final RequirementFollower entity) { - return new HashMap() {{ + return new HashMap<>() {{ put(REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID, entity.getRequirementId()); put(REQUIREMENT_FOLLOWER_MAP.USER_ID, entity.getUserId()); }}; diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementTagTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementTagTransformer.java new file mode 100644 index 00000000..cb4226f1 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementTagTransformer.java @@ -0,0 +1,70 @@ +package de.rwth.dbis.acis.bazaar.service.dal.transform; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementTagMapRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.RequirementTag; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import org.jooq.*; + +import java.util.*; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.REQUIREMENT_TAG_MAP; + +public class RequirementTagTransformer implements Transformer { + @Override + public RequirementTagMapRecord createRecord(RequirementTag entity) { + RequirementTagMapRecord record = new RequirementTagMapRecord(); + record.setRequirementId(entity.getRequirementId()); + record.setTagId(entity.getTagId()); + return record; + } + + @Override + public RequirementTag getEntityFromTableRecord(RequirementTagMapRecord record) { + return RequirementTag.builder() + .id(record.getId()) + .tagId(record.getTagId()) + .requirementId(record.getRequirementId()) + .build(); + } + + @Override + public Table getTable() { + return REQUIREMENT_TAG_MAP; + } + + @Override + public TableField getTableId() { + return REQUIREMENT_TAG_MAP.ID; + } + + @Override + public Class getRecordClass() { + return RequirementTagMapRecord.class; + } + + @Override + public Map getUpdateMap(RequirementTag entity) { + return new HashMap<>() {{ + put(REQUIREMENT_TAG_MAP.REQUIREMENT_ID, entity.getRequirementId()); + put(REQUIREMENT_TAG_MAP.TAG_ID, entity.getTagId()); + }}; + } + + @Override + public Collection> getSortFields(List sorts) { + if (sorts.isEmpty()) { + return Collections.singletonList(REQUIREMENT_TAG_MAP.ID.asc()); + } + return null; + } + + @Override + public Condition getSearchCondition(String search) throws Exception { + throw new Exception("Search is not supported!"); + } + + @Override + public Collection getFilterConditions(Map filters) throws Exception { + return new ArrayList<>(); + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementTransformer.java new file mode 100644 index 00000000..9b62c83d --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementTransformer.java @@ -0,0 +1,230 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal.transform; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyNamingStrategy; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RequirementRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Requirement; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import de.rwth.dbis.acis.bazaar.service.dal.repositories.RequirementRepositoryImpl; +import org.jooq.*; +import org.jooq.impl.DSL; + +import java.time.OffsetDateTime; +import java.util.*; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.*; + +public class RequirementTransformer implements Transformer { + @Override + public RequirementRecord createRecord(Requirement entry) { + RequirementRecord record = new RequirementRecord(); + record.setDescription(entry.getDescription()); + record.setName(entry.getName()); + record.setCreationDate(OffsetDateTime.now()); + record.setCreatorId(entry.getCreator().getId()); + record.setProjectId(entry.getProjectId()); + if (entry.getAdditionalProperties() != null) { + record.setAdditionalProperties(JSONB.jsonb(entry.getAdditionalProperties().toString())); + } + return record; + } + + public Requirement.Builder mapToEntityBuilder(RequirementRecord record) { + ObjectMapper mapper = new ObjectMapper(); + mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + Requirement.Builder requirementBuilder = Requirement.builder() + .name(record.getName()) + .description(record.getDescription()) + .id(record.getId()) + .realized(record.getRealized()) + .creationDate(record.getCreationDate()) + .lastUpdatedDate(record.getLastUpdatedDate()) + .projectId(record.getProjectId()); + + try { + return requirementBuilder + .additionalProperties( + mapper.readTree(record.getAdditionalProperties().data()) + ); + } catch (Exception e) { + return requirementBuilder; + } + } + + @Override + public Requirement getEntityFromTableRecord(RequirementRecord record) { + return mapToEntityBuilder(record) + .build(); + } + + @Override + public Table getTable() { + return REQUIREMENT; + } + + @Override + public TableField getTableId() { + return REQUIREMENT.ID; + } + + @Override + public Class getRecordClass() { + return RequirementRecord.class; + } + + @Override + public Map getUpdateMap(Requirement entry) { + HashMap updateMap = new HashMap<>() {{ + if (entry.getDescription() != null) { + put(REQUIREMENT.DESCRIPTION, entry.getDescription()); + } + if (entry.getName() != null) { + put(REQUIREMENT.NAME, entry.getName()); + } + if (entry.getAdditionalProperties() != null) { + put(REQUIREMENT.ADDITIONAL_PROPERTIES, entry.getAdditionalProperties()); + } + }}; + if (!updateMap.isEmpty()) { + updateMap.put(REQUIREMENT.LAST_UPDATED_DATE, OffsetDateTime.now()); + } + return updateMap; + } + + @Override + public Collection> getSortFields(List sorts) { + if (sorts.isEmpty()) { + return Collections.singletonList(RequirementRepositoryImpl.LAST_ACTIVITY.field("last_activity").desc()); + } + List> sortFields = new ArrayList<>(); + for (Pageable.SortField sort : sorts) { + switch (sort.getField()) { + case "last_activity": + if (sort.getSortDirection() == Pageable.SortDirection.ASC) { + sortFields.add(RequirementRepositoryImpl.LAST_ACTIVITY.field("last_activity").asc()); + } else { + sortFields.add(RequirementRepositoryImpl.LAST_ACTIVITY.field("last_activity").desc()); + } + break; + case "date": + if (sort.getSortDirection() == Pageable.SortDirection.ASC) { + sortFields.add(REQUIREMENT.CREATION_DATE.asc()); + } else { + sortFields.add(REQUIREMENT.CREATION_DATE.desc()); + } + break; + case "name": + if (sort.getSortDirection() == Pageable.SortDirection.DESC) { + sortFields.add(REQUIREMENT.NAME.desc()); + } else { + sortFields.add(REQUIREMENT.NAME.asc()); + } + break; + case "vote": + if (sort.getSortDirection() == Pageable.SortDirection.ASC) { + sortFields.add(RequirementRepositoryImpl.VOTE_COUNT.asc()); + } else { + sortFields.add(RequirementRepositoryImpl.VOTE_COUNT.desc()); + } + break; + case "comment": + if (sort.getSortDirection() == Pageable.SortDirection.ASC) { + sortFields.add(RequirementRepositoryImpl.COMMENT_COUNT.asc()); + } else { + sortFields.add(RequirementRepositoryImpl.COMMENT_COUNT.desc()); + } + break; + case "follower": + if (sort.getSortDirection() == Pageable.SortDirection.ASC) { + sortFields.add(RequirementRepositoryImpl.FOLLOWER_COUNT.asc()); + } else { + sortFields.add(RequirementRepositoryImpl.FOLLOWER_COUNT.desc()); + } + break; + case "realized": + if (sort.getSortDirection() == Pageable.SortDirection.ASC) { + sortFields.add(REQUIREMENT.REALIZED.asc()); + } else { + sortFields.add(REQUIREMENT.REALIZED.desc()); + } + break; + } + } + return sortFields; + } + + @Override + public Condition getSearchCondition(String search) throws Exception { + // Catch issues with empty tsvector matching causing nothing to be found + if (search.equals("")) { + return REQUIREMENT.NAME.likeIgnoreCase("%"); + } + return DSL.condition("to_tsvector({0} || {1}) @@ websearch_to_tsquery({2})", + REQUIREMENT.NAME, REQUIREMENT.DESCRIPTION, search); + } + + @Override + public Collection getFilterConditions(Map filters) throws Exception { + List conditions = new ArrayList<>(); + for (Map.Entry filterEntry : filters.entrySet()) { + if (filterEntry.getKey().equals("realized")) { + if (filterEntry.getValue().equals("realized")) { + conditions.add(REQUIREMENT.REALIZED.isNotNull()); + } + if (filterEntry.getValue().equals("open")) { + conditions.add(REQUIREMENT.REALIZED.isNull()); + } + } else if (filterEntry.getKey().equals("created")) { + conditions.add( + REQUIREMENT.CREATOR_ID.eq(Integer.parseInt(filterEntry.getValue())) + ); + } else if (filterEntry.getKey().equals("following")) { + conditions.add( + REQUIREMENT.ID.in( + DSL.select(REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID) + .from(REQUIREMENT_FOLLOWER_MAP) + .where(REQUIREMENT_FOLLOWER_MAP.USER_ID.eq(Integer.parseInt(filterEntry.getValue()))) + ) + ); + } else if (filterEntry.getKey().equals("developing")) { + conditions.add( + REQUIREMENT.ID.in( + DSL.select(REQUIREMENT_DEVELOPER_MAP.REQUIREMENT_ID) + .from(REQUIREMENT_DEVELOPER_MAP) + .where(REQUIREMENT_DEVELOPER_MAP.USER_ID.eq(Integer.parseInt(filterEntry.getValue()))) + ).or( + REQUIREMENT.LEAD_DEVELOPER_ID.eq(Integer.parseInt(filterEntry.getValue())) + ) + ); + } else { + conditions.add( + DSL.falseCondition() + ); + } + } + return conditions; + } +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RoleTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RoleTransformer.java similarity index 90% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RoleTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RoleTransformer.java index e10c160b..7be8369f 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RoleTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/RoleTransformer.java @@ -20,17 +20,16 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.RoleRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.Role; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RoleRecord; import org.jooq.*; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.ROLE; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.ROLE; /** - * @author Adam Gavronek * @since 2/17/2015 */ public class RoleTransformer implements Transformer { @@ -45,7 +44,8 @@ public RoleRecord createRecord(Role entity) { @Override public Role getEntityFromTableRecord(RoleRecord record) { - return Role.getBuilder(record.getName()) + return Role.builder() + .name(record.getName()) .id(record.getId()) .build(); } @@ -89,4 +89,4 @@ public Condition getSearchCondition(String search) throws Exception { public Collection getFilterConditions(Map filters) throws Exception { return new ArrayList<>(); } -} \ No newline at end of file +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/TagTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/TagTransformer.java new file mode 100644 index 00000000..270255f7 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/TagTransformer.java @@ -0,0 +1,80 @@ +package de.rwth.dbis.acis.bazaar.service.dal.transform; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.TagRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Tag; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import org.jooq.*; + +import java.time.OffsetDateTime; +import java.util.*; + +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.TAG; + +public class TagTransformer implements Transformer { + @Override + public TagRecord createRecord(Tag entity) { + TagRecord record = new TagRecord(); + record.setProjectId(entity.getProjectId()); + record.setName(entity.getName()); + record.setColour(entity.getColour()); + record.setCreationDate(OffsetDateTime.now()); + return record; + } + + @Override + public Tag getEntityFromTableRecord(TagRecord record) { + return Tag.builder() + .id(record.getId()) + .projectId(record.getProjectId()) + .colour(record.getColour()) + .name(record.getName()) + .build(); + } + + @Override + public Table getTable() { + return TAG; + } + + @Override + public TableField getTableId() { + return TAG.ID; + } + + @Override + public Class getRecordClass() { + return TagRecord.class; + } + + @Override + public Map getUpdateMap(Tag entity) { + HashMap updateMap = new HashMap<>() {{ + + if (entity.getName() != null) { + put(TAG.NAME, entity.getName()); + } + if (entity.getColour() != null) { + put(TAG.COLOUR, entity.getColour()); + } + }}; + return updateMap; + } + + @Override + public Collection> getSortFields(List sorts) { + if (sorts.isEmpty()) { + return Collections.singletonList(TAG.NAME.asc()); + } + return null; + } + + @Override + public Condition getSearchCondition(String search) throws Exception { + throw new Exception("Search is not supported!"); + } + + @Override + public Collection getFilterConditions(Map filters) throws Exception { + return new ArrayList<>(); + } +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/Transformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/Transformer.java similarity index 97% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/Transformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/Transformer.java index ddc1d08c..83b83a09 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/Transformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/Transformer.java @@ -21,6 +21,7 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import org.jooq.Record; import org.jooq.*; import java.util.Collection; @@ -30,7 +31,6 @@ /** * @param type parameter for the entity * @param type parameter for the record - * @author Adam Gavronek * @since 6/9/2014 */ public interface Transformer { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/UserTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/UserTransformer.java similarity index 77% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/UserTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/UserTransformer.java index b941bded..febaacee 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/UserTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/UserTransformer.java @@ -20,61 +20,66 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.UserRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.User; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.UserRecord; +import org.jooq.Record; import org.jooq.*; +import java.time.OffsetDateTime; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.USER; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.USER; public class UserTransformer implements Transformer { @Override public UserRecord createRecord(User entity) { UserRecord record = new UserRecord(); record.setLas2peerId(entity.getLas2peerId()); - record.setAdmin(entity.getAdmin()); record.setEmail(entity.getEMail()); record.setFirstName(entity.getFirstName()); record.setLastName(entity.getLastName()); record.setUserName(entity.getUserName()); record.setProfileImage(entity.getProfileImage()); - record.setEmailLeadSubscription((byte) (entity.isEmailLeadSubscription() ? 1 : 0)); - record.setEmailFollowSubscription((byte) (entity.isEmailFollowSubscription() ? 1 : 0)); - record.setCreationDate(new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); + record.setEmailLeadSubscription(entity.isEmailLeadSubscription()); + record.setEmailFollowSubscription(entity.isEmailFollowSubscription()); + record.setPersonalizationEnabled(entity.isPersonalizationEnabled()); + record.setCreationDate(OffsetDateTime.now()); + return record; } @Override public User getEntityFromTableRecord(UserRecord record) { - return User.geBuilder(record.getEmail()) + return User.builder() + .eMail(record.getEmail()) .id(record.getId()) - .admin(record.getAdmin()) .firstName(record.getFirstName()) .lastName(record.getLastName()) .las2peerId(record.getLas2peerId()) .profileImage(record.getProfileImage()) .userName(record.getUserName()) - .emailLeadSubscription(record.getEmailLeadSubscription() != 0) - .emailFollowSubscription(record.getEmailFollowSubscription() != 0) + .emailLeadSubscription(record.getEmailLeadSubscription()) + .emailFollowSubscription(record.getEmailFollowSubscription()) .creationDate(record.getCreationDate()) .lastUpdatedDate(record.getLastUpdatedDate()) .lastLoginDate(record.getLastLoginDate()) + .personalizationEnabled(record.getPersonalizationEnabled()) .build(); } - public User getEntityFromQueryResult(de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User user, Result queryResult) { - return User.geBuilder(queryResult.getValues(user.EMAIL).get(0)) + public User getEntityFromQueryResult(de.rwth.dbis.acis.bazaar.dal.jooq.tables.User user, Result queryResult) { + return User.builder() + .eMail(queryResult.getValues(user.EMAIL).get(0)) .id(queryResult.getValues(user.ID).get(0)) - .admin(queryResult.getValues(user.ADMIN).get(0)) .firstName(queryResult.getValues(user.FIRST_NAME).get(0)) .lastName(queryResult.getValues(user.LAST_NAME).get(0)) .las2peerId(queryResult.getValues(user.LAS2PEER_ID).get(0)) .userName(queryResult.getValues(user.USER_NAME).get(0)) .profileImage(queryResult.getValues(user.PROFILE_IMAGE).get(0)) - .emailLeadSubscription(queryResult.getValues(user.EMAIL_LEAD_SUBSCRIPTION).get(0) != 0) - .emailFollowSubscription(queryResult.getValues(user.EMAIL_FOLLOW_SUBSCRIPTION).get(0) != 0) + .emailLeadSubscription(queryResult.getValues(user.EMAIL_LEAD_SUBSCRIPTION).get(0)) + .emailFollowSubscription(queryResult.getValues(user.EMAIL_FOLLOW_SUBSCRIPTION).get(0)) + .personalizationEnabled(queryResult.getValues(user.PERSONALIZATION_ENABLED).get(0)) .build(); } @@ -94,8 +99,8 @@ public Class getRecordClass() { } @Override - public Map getUpdateMap(final User entity) { - HashMap updateMap = new HashMap() {{ + public Map getUpdateMap(User entity) { + HashMap updateMap = new HashMap<>() {{ if (entity.getEMail() != null) { put(USER.EMAIL, entity.getEMail()); } @@ -117,9 +122,12 @@ public Map getUpdateMap(final User entity) { if (entity.isEmailFollowSubscription() != null) { put(USER.EMAIL_FOLLOW_SUBSCRIPTION, entity.isEmailFollowSubscription()); } + if (entity.isPersonalizationEnabled() != null) { + put(USER.PERSONALIZATION_ENABLED, entity.isPersonalizationEnabled()); + } }}; if (!updateMap.isEmpty()) { - updateMap.put(USER.LAST_UPDATED_DATE, new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); + updateMap.put(USER.LAST_UPDATED_DATE, OffsetDateTime.now()); } return updateMap; } @@ -135,7 +143,7 @@ public Collection> getSortFields(List @Override public Condition getSearchCondition(String search) throws Exception { return USER.USER_NAME.likeIgnoreCase("%" + search + "%") - .or(USER.EMAIL.likeIgnoreCase("%" + search + "%")) + .or(USER.EMAIL.likeIgnoreCase(search)) .or(USER.FIRST_NAME.likeIgnoreCase("%" + search + "%")) .or(USER.LAST_NAME.likeIgnoreCase("%" + search + "%")); } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/VoteTransformer.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/VoteTransformer.java similarity index 87% rename from src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/VoteTransformer.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/VoteTransformer.java index d2777ec7..877ed457 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/VoteTransformer.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/dal/transform/VoteTransformer.java @@ -20,17 +20,16 @@ package de.rwth.dbis.acis.bazaar.service.dal.transform; +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.VoteRecord; import de.rwth.dbis.acis.bazaar.service.dal.entities.Vote; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.VoteRecord; import org.jooq.*; import java.util.*; -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.VOTE; +import static de.rwth.dbis.acis.bazaar.dal.jooq.Tables.VOTE; /** - * @author Adam Gavronek * @since 6/23/2014 */ public class VoteTransformer implements Transformer { @@ -39,17 +38,17 @@ public VoteRecord createRecord(Vote entity) { VoteRecord record = new VoteRecord(); record.setUserId(entity.getUserId()); record.setRequirementId(entity.getRequirementId()); - record.setIsUpvote((byte) (entity.isUpvote() ? 1 : 0)); + record.setIsUpvote(entity.isUpvote()); return record; } @Override public Vote getEntityFromTableRecord(VoteRecord record) { - return Vote.getBuilder() + return Vote.builder() .id(record.getId()) .userId(record.getUserId()) .requirementId(record.getRequirementId()) - .isUpvote(record.getIsUpvote() != 0) + .isUpvote(record.getIsUpvote()) .build(); } @@ -70,7 +69,7 @@ public Class getRecordClass() { @Override public Map getUpdateMap(final Vote entity) { - return new HashMap() {{ + return new HashMap<>() {{ put(VOTE.IS_UPVOTE, entity.isUpvote()); put(VOTE.REQUIREMENT_ID, entity.getRequirementId()); put(VOTE.USER_ID, entity.getUserId()); diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/exception/BazaarException.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/BazaarException.java similarity index 90% rename from src/main/de/rwth/dbis/acis/bazaar/service/exception/BazaarException.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/BazaarException.java index ab491776..457ae3ca 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/exception/BazaarException.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/BazaarException.java @@ -20,25 +20,24 @@ package de.rwth.dbis.acis.bazaar.service.exception; +import com.fasterxml.jackson.annotation.JsonIgnore; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; /** - * @author Adam Gavronek * @since 10/6/2014 */ public class BazaarException extends Exception { + private final ExceptionLocation location; private String message; - private ErrorCode errorCode; - private final ExceptionLocation location; - protected BazaarException(ExceptionLocation location) { this.location = location; message = ""; } + @Override public String getMessage() { return message; } @@ -62,4 +61,11 @@ public int getExceptionCode() { public String getExceptionMessage() { return String.format(Localization.getInstance().getResourceBundle().getString("error.unknown_exception"), message, location.getMessage(), errorCode.getMessage(), getExceptionCode()); } + + @JsonIgnore + @Override + public StackTraceElement[] getStackTrace() { + return super.getStackTrace(); + } + } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/exception/ErrorCode.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/ErrorCode.java similarity index 96% rename from src/main/de/rwth/dbis/acis/bazaar/service/exception/ErrorCode.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/ErrorCode.java index fb67b634..b315f682 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/exception/ErrorCode.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/ErrorCode.java @@ -21,7 +21,6 @@ package de.rwth.dbis.acis.bazaar.service.exception; /** - * @author Adam Gavronek * @since 10/6/2014 */ public enum ErrorCode { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/exception/ExceptionHandler.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/ExceptionHandler.java similarity index 86% rename from src/main/de/rwth/dbis/acis/bazaar/service/exception/ExceptionHandler.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/ExceptionHandler.java index 676b69bf..bcbd0aa6 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/exception/ExceptionHandler.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/ExceptionHandler.java @@ -23,13 +23,13 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import de.rwth.dbis.acis.bazaar.service.internalization.Localization; -import jodd.vtor.Violation; -import java.util.List; +import javax.validation.ConstraintViolation; +import java.util.Set; /** - * @author Adam Gavronek * @since 10/6/2014 */ public enum ExceptionHandler { @@ -40,7 +40,7 @@ public static ExceptionHandler getInstance() { return INSTANCE; } - ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL); + ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule()).setSerializationInclusion(JsonInclude.Include.NON_NULL); public BazaarException convert(Exception ex, ExceptionLocation location, ErrorCode errorCode, String message) { BazaarException bazaarException = new BazaarException(location); @@ -70,12 +70,12 @@ public String toJSON(BazaarException exception) { return null; } - public void handleViolations(List violations) throws BazaarException { + public void handleViolations(Set> violations) throws BazaarException { BazaarException bazaarException = new BazaarException(ExceptionLocation.BAZAARSERVICE); bazaarException.setErrorCode(ErrorCode.VALIDATION); StringBuilder builder = new StringBuilder(); - for (Violation violation : violations) { - builder.append(String.format(Localization.getInstance().getResourceBundle().getString("error.validation"), violation.getName(), violation.getInvalidValue(), violation.toString())); + for (ConstraintViolation violation : violations) { + builder.append(String.format(Localization.getInstance().getResourceBundle().getString("error.validation"), violation.getMessage(), violation.getInvalidValue())); } bazaarException.setMessage(builder.toString()); throw bazaarException; diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/exception/ExceptionLocation.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/ExceptionLocation.java similarity index 96% rename from src/main/de/rwth/dbis/acis/bazaar/service/exception/ExceptionLocation.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/ExceptionLocation.java index 49685079..77c19fd9 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/exception/ExceptionLocation.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/exception/ExceptionLocation.java @@ -21,7 +21,6 @@ package de.rwth.dbis.acis.bazaar.service.exception; /** - * @author Adam Gavronek * @since 10/6/2014 */ public enum ExceptionLocation { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/internalization/Localization.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/internalization/Localization.java similarity index 96% rename from src/main/de/rwth/dbis/acis/bazaar/service/internalization/Localization.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/internalization/Localization.java index 73f43683..cfc7f513 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/internalization/Localization.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/internalization/Localization.java @@ -23,7 +23,6 @@ import java.util.ResourceBundle; /** - * @author Adam Gavronek * @since 3/12/2015 */ public class Localization { @@ -48,4 +47,4 @@ public static Localization getInstance() { } return instance; } -} \ No newline at end of file +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/notification/ActivityDispatcher.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/ActivityDispatcher.java similarity index 88% rename from src/main/de/rwth/dbis/acis/bazaar/service/notification/ActivityDispatcher.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/ActivityDispatcher.java index 30f0ef18..e2b01019 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/notification/ActivityDispatcher.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/ActivityDispatcher.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; @@ -15,7 +16,7 @@ import i5.las2peer.logging.L2pLogger; import javax.ws.rs.core.Response; -import java.util.Date; +import java.time.OffsetDateTime; /** * Created by martin on 15.02.2016. @@ -27,7 +28,7 @@ public class ActivityDispatcher { private final String activityOrigin; private final String baseURL; private final String frontendBaseURL; - private BazaarService bazaarService; + private final BazaarService bazaarService; public ActivityDispatcher(BazaarService bazaarService, String activityTrackerService, String activityOrigin, String baseURL, String frontendBaseURL) { this.bazaarService = bazaarService; @@ -37,13 +38,13 @@ public ActivityDispatcher(BazaarService bazaarService, String activityTrackerSer this.frontendBaseURL = frontendBaseURL; } - public void sendActivityOverRMI(Date creationDate, Activity.ActivityAction activityAction, + public void sendActivityOverRMI(OffsetDateTime creationDate, Activity.ActivityAction activityAction, int dataId, Activity.DataType dataType, int userId, Activity.AdditionalObject additionalObject) { DALFacade dalFacade; try { dalFacade = bazaarService.getDBConnection(); - Activity.Builder activityBuilder = Activity.getBuilder(); + Activity.Builder activityBuilder = Activity.builder(); activityBuilder = activityBuilder.creationDate(creationDate); activityBuilder = activityBuilder.activityAction(activityAction); @@ -68,8 +69,8 @@ public void sendActivityOverRMI(Date creationDate, Activity.ActivityAction activ parentResourcePath = "categories"; Requirement requirement = dalFacade.getRequirementById(dataId, userId); frontendResourcePath = "projects" + "/" + requirement.getProjectId() + "/" + "categories" + "/" + - requirement.getCategories().get(0).getId() + "/" + "requirements" + "/" + String.valueOf(dataId); - parentDataId = requirement.getCategories().get(0).getId(); + requirement.getCategories().get(0) + "/" + "requirements" + "/" + String.valueOf(dataId); + parentDataId = requirement.getCategories().get(0); parentDataTyp = Activity.DataType.CATEGORY; } else if (dataType.equals(Activity.DataType.COMMENT)) { resourcePath = "comments"; @@ -77,7 +78,7 @@ public void sendActivityOverRMI(Date creationDate, Activity.ActivityAction activ Comment comment = dalFacade.getCommentById(dataId); Requirement requirement = dalFacade.getRequirementById(comment.getRequirementId(), userId); frontendResourcePath = "projects" + "/" + requirement.getProjectId() + "/" + "categories" + "/" + - requirement.getCategories().get(0).getId() + "/" + "requirements" + "/" + String.valueOf(requirement.getId()); + requirement.getCategories().get(0) + "/" + "requirements" + "/" + String.valueOf(requirement.getId()); parentDataId = requirement.getId(); parentDataTyp = Activity.DataType.REQUIREMENT; } else if (dataType.equals(Activity.DataType.ATTACHMENT)) { @@ -86,13 +87,13 @@ public void sendActivityOverRMI(Date creationDate, Activity.ActivityAction activ Attachment attachment = dalFacade.getAttachmentById(dataId); Requirement requirement = dalFacade.getRequirementById(attachment.getRequirementId(), userId); frontendResourcePath = "projects" + "/" + requirement.getProjectId() + "/" + "categories" + "/" + - requirement.getCategories().get(0).getId() + "/" + "requirements" + "/" + String.valueOf(requirement.getId()); + requirement.getCategories().get(0) + "/" + "requirements" + "/" + String.valueOf(requirement.getId()); parentDataId = requirement.getId(); parentDataTyp = Activity.DataType.REQUIREMENT; } else if (dataType.equals(Activity.DataType.USER)) { resourcePath = "users"; frontendResourcePath = "users" + "/" + dataId; - } + } resourcePath = resourcePath + "/" + String.valueOf(dataId); if (parentResourcePath != null) { parentResourcePath = parentResourcePath + "/" + String.valueOf(parentDataId); @@ -110,7 +111,7 @@ public void sendActivityOverRMI(Date creationDate, Activity.ActivityAction activ } activityBuilder = activityBuilder.userUrl(baseURL + "users" + "/" + String.valueOf(userId)); activityBuilder = activityBuilder.origin(activityOrigin); - activityBuilder = activityBuilder.addititionalObject(additionalObject); + activityBuilder = activityBuilder.additionalObject(additionalObject); Activity activity = activityBuilder.build(); FilterProvider filters = @@ -120,7 +121,8 @@ public void sendActivityOverRMI(Date creationDate, Activity.ActivityAction activ ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.setFilters(filters); + mapper.registerModule(new JavaTimeModule()); + mapper.setFilterProvider(filters); Object result = Context.get().invoke(activityTrackerService, "createActivity", mapper.writeValueAsString(activity)); if (!(result).equals(Integer.toString(Response.Status.CREATED.getStatusCode()))) { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/notification/EmailDispatcher.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/EmailDispatcher.java similarity index 92% rename from src/main/de/rwth/dbis/acis/bazaar/service/notification/EmailDispatcher.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/EmailDispatcher.java index c7b7c2cb..d5958c05 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/notification/EmailDispatcher.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/EmailDispatcher.java @@ -11,6 +11,7 @@ import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; +import java.time.OffsetDateTime; import java.util.*; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @@ -21,25 +22,25 @@ public class EmailDispatcher { private final L2pLogger logger = L2pLogger.getInstance(EmailDispatcher.class.getName()); - private String smtpServer; - private String emailFromAddress; - private BazaarService bazaarService; - private String frontendBaseURL; - private String emailSummaryTimePeriodInMinutes; - private Map> notificationSummery; + private final String smtpServer; + private final String emailFromAddress; + private final BazaarService bazaarService; + private final String frontendBaseURL; + private final String emailSummaryTimePeriodInMinutes; + private final Map> notificationSummery; - private ExecutorService executorService = Executors.newCachedThreadPool(); + private final ExecutorService executorService = Executors.newCachedThreadPool(); public EmailDispatcher(BazaarService bazaarService, String smtpServer, String emailFromAddress, String frontendBaseURL, String emailSummaryTimePeriodInMinutes) throws Exception { this.smtpServer = smtpServer; this.emailFromAddress = emailFromAddress; this.bazaarService = bazaarService; this.frontendBaseURL = frontendBaseURL; - this.notificationSummery = new LinkedHashMap<>(); + notificationSummery = new LinkedHashMap<>(); this.emailSummaryTimePeriodInMinutes = emailSummaryTimePeriodInMinutes; } - public void addEmailNotification(Date creationDate, Activity.ActivityAction activityAction, + public void addEmailNotification(OffsetDateTime creationDate, Activity.ActivityAction activityAction, int dataId, Activity.DataType dataType, int userId, Activity.AdditionalObject additionalObject) { DALFacade dalFacade; try { @@ -74,7 +75,7 @@ public void addEmailNotification(Date creationDate, Activity.ActivityAction acti notificationSummery.put(recipient.getId(), new ArrayList<>()); } else if (!emailSummaryTimePeriodInMinutes.isEmpty()) { //if user has notificationsummery, add this email to it and remove from recipient - notificationSummery.get(recipient.getId()).add(new Email.Builder(email).recipients(new HashSet<>(Arrays.asList(recipient))).build()); + notificationSummery.get(recipient.getId()).add(email.toBuilder().recipients(new HashSet<>(Arrays.asList(recipient))).build()); recipientsIterator.remove(); email.removeRecipient(recipient); } @@ -88,14 +89,14 @@ public void addEmailNotification(Date creationDate, Activity.ActivityAction acti } } - private Email generateEmail(List recipients, Date creationDate, Activity.ActivityAction activityAction, + private Email generateEmail(List recipients, OffsetDateTime creationDate, Activity.ActivityAction activityAction, int dataId, Activity.DataType dataType, Activity.AdditionalObject additionalObject) throws Exception { DALFacade dalFacade = bazaarService.getDBConnection(); - String subject = new String(); - String bodyText = new String(); + String subject = ""; + String bodyText = ""; String objectName; - String resourcePath = new String(); - String activity = new String(); + String resourcePath = ""; + String activity = ""; if (activityAction == Activity.ActivityAction.CREATE) { activity = Localization.getInstance().getResourceBundle().getString("email.bodyText.created"); subject = Localization.getInstance().getResourceBundle().getString("email.subject.New"); @@ -110,7 +111,7 @@ private Email generateEmail(List recipients, Date creationDate, Activity.A if (dataType == Activity.DataType.PROJECT) { Project project = additionalObject.getProject(); objectName = project.getName(); - resourcePath = "projects" + "/" + String.valueOf(dataId); + resourcePath = "projects" + "/" + dataId; subject = subject.concat(" " + Localization.getInstance().getResourceBundle().getString("email.bodyText.project") + ": " + (objectName.length() > 40 ? objectName.substring(0, 39) : objectName)); bodyText = bodyText.concat(Localization.getInstance().getResourceBundle().getString("email.bodyText.user") + " " + additionalObject.getUser().getUserName()); bodyText = bodyText.concat(" " + activity); @@ -122,7 +123,7 @@ private Email generateEmail(List recipients, Date creationDate, Activity.A } else if (dataType == Activity.DataType.CATEGORY) { Category category = additionalObject.getCategory(); objectName = category.getName(); - resourcePath = "projects" + "/" + category.getProjectId() + "/" + "categories" + "/" + String.valueOf(dataId); + resourcePath = "projects" + "/" + category.getProjectId() + "/" + "categories" + "/" + dataId; subject = subject.concat(" " + Localization.getInstance().getResourceBundle().getString("email.bodyText.category") + ": " + (objectName.length() > 40 ? objectName.substring(0, 39) : objectName)); bodyText = bodyText.concat(Localization.getInstance().getResourceBundle().getString("email.bodyText.user") + " " + additionalObject.getUser().getUserName()); bodyText = bodyText.concat(" " + activity); @@ -138,7 +139,7 @@ private Email generateEmail(List recipients, Date creationDate, Activity.A Requirement requirement = additionalObject.getRequirement(); objectName = requirement.getName(); resourcePath = "projects" + "/" + requirement.getProjectId() + "/" + "categories" + "/" + - requirement.getCategories().get(0).getId() + "/" + "requirements" + "/" + String.valueOf(dataId); + requirement.getCategories().get(0) + "/" + "requirements" + "/" + dataId; subject = subject.concat(" " + Localization.getInstance().getResourceBundle().getString("email.bodyText.requirement") + ": " + (objectName.length() > 40 ? objectName.substring(0, 39) : objectName)); bodyText = bodyText.concat(Localization.getInstance().getResourceBundle().getString("email.bodyText.user") + " " + additionalObject.getUser().getUserName()); bodyText = bodyText.concat(" " + activity); @@ -155,7 +156,7 @@ private Email generateEmail(List recipients, Date creationDate, Activity.A Requirement requirement = additionalObject.getRequirement(); objectName = requirement.getName(); resourcePath = "projects" + "/" + requirement.getProjectId() + "/" + "categories" + "/" + - requirement.getCategories().get(0).getId() + "/" + "requirements" + "/" + String.valueOf(requirement.getId()); + requirement.getCategories().get(0) + "/" + "requirements" + "/" + requirement.getId(); subject = subject.concat(" " + Localization.getInstance().getResourceBundle().getString("email.bodyText.comment") + " " + Localization.getInstance().getResourceBundle().getString("email.bodyText.for") + " " + Localization.getInstance().getResourceBundle().getString("email.bodyText.requirement") + ": " + (objectName.length() > 40 ? objectName.substring(0, 39) : objectName)); @@ -171,7 +172,7 @@ private Email generateEmail(List recipients, Date creationDate, Activity.A Requirement requirement = additionalObject.getRequirement(); objectName = requirement.getName(); resourcePath = "projects" + "/" + requirement.getProjectId() + "/" + "categories" + "/" + - requirement.getCategories().get(0).getId() + "/" + "requirements" + "/" + String.valueOf(requirement.getId()); + requirement.getCategories().get(0) + "/" + "requirements" + "/" + requirement.getId(); subject = subject.concat(" " + Localization.getInstance().getResourceBundle().getString("email.bodyText.attachment") + " " + Localization.getInstance().getResourceBundle().getString("email.bodyText.for") + " " + Localization.getInstance().getResourceBundle().getString("email.bodyText.requirement") + ": " + (objectName.length() > 40 ? objectName.substring(0, 39) : objectName)); @@ -191,7 +192,7 @@ private Email generateEmail(List recipients, Date creationDate, Activity.A Localization.getInstance().getResourceBundle().getString("email.bodyText.bestWishes"); String footer = Localization.getInstance().getResourceBundle().getString("email.bodyText.footer"); - Email.Builder emailBuilder = new Email.Builder(); + Email.Builder emailBuilder = Email.builder(); emailBuilder.recipients(new HashSet<>(recipients)); emailBuilder.subject(subject); emailBuilder.starting(greeting + "\r\n\r\n" + news); @@ -236,14 +237,14 @@ public void emptyNotificationSummery() { notificationIterator.remove(); } - Email.Builder emailBuilder = new Email.Builder(); + Email.Builder emailBuilder = Email.builder(); emailBuilder.recipients(new HashSet<>(Arrays.asList(user))); emailBuilder.subject(subject); emailBuilder.starting(greeting); emailBuilder.message(message); emailBuilder.closing(closing); emailBuilder.footer(footer); - emailBuilder.creationDate(new Date()); + emailBuilder.creationDate(OffsetDateTime.now()); Email summary = emailBuilder.build(); sendEmail(summary); @@ -278,7 +279,7 @@ private void sendEmail(Email mail) { text = text.concat(mail.getFooter()); mailMessage.setText(text); mailMessage.setHeader("X-Mailer", "msgsend"); - mailMessage.setSentDate(mail.getCreationDate()); + mailMessage.setSentDate(java.sql.Timestamp.valueOf(mail.getCreationDate().toLocalDateTime())); Transport.send(mailMessage); diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcher.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcher.java similarity index 78% rename from src/main/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcher.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcher.java index bfa3e1d4..a567e1c2 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcher.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcher.java @@ -4,13 +4,13 @@ import de.rwth.dbis.acis.bazaar.service.dal.entities.Activity; import i5.las2peer.api.logging.MonitoringEvent; -import java.util.Date; +import java.time.OffsetDateTime; /** * Created by martin on 15.02.2016. */ public interface NotificationDispatcher extends Runnable { - void dispatchNotification(Date creationDate, Activity.ActivityAction activityAction, final MonitoringEvent mobSOSEvent, + void dispatchNotification(OffsetDateTime creationDate, Activity.ActivityAction activityAction, MonitoringEvent mobSOSEvent, int dataId, Activity.DataType dataType, int userId); void setBazaarService(BazaarService service); diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcherImp.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcherImp.java similarity index 89% rename from src/main/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcherImp.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcherImp.java index 9863dc61..0d8b9409 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcherImp.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/notification/NotificationDispatcherImp.java @@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ser.FilterProvider; import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter; import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; @@ -13,7 +14,7 @@ import i5.las2peer.api.logging.MonitoringEvent; import i5.las2peer.logging.L2pLogger; -import java.util.Date; +import java.time.OffsetDateTime; import java.util.TimerTask; /** @@ -21,27 +22,30 @@ */ public class NotificationDispatcherImp extends TimerTask implements NotificationDispatcher { - private L2pLogger logger = L2pLogger.getInstance(NotificationDispatcherImp.class.getName()); + private final L2pLogger logger = L2pLogger.getInstance(NotificationDispatcherImp.class.getName()); private ActivityDispatcher activityDispatcher; private EmailDispatcher emailDispatcher; private BazaarService bazaarService; private ObjectMapper mapper; + @Override public void setBazaarService(BazaarService service) { - this.bazaarService = service; + bazaarService = service; } + @Override public void setActivityDispatcher(ActivityDispatcher activityDispatcher) { this.activityDispatcher = activityDispatcher; } + @Override public void setEmailDispatcher(EmailDispatcher emailDispatcher) { this.emailDispatcher = emailDispatcher; } @Override - public void dispatchNotification(final Date creationDate, final Activity.ActivityAction activityAction, final MonitoringEvent mobSOSEvent, - final int dataId, final Activity.DataType dataType, final int userId) { + public void dispatchNotification(OffsetDateTime creationDate, Activity.ActivityAction activityAction, MonitoringEvent mobSOSEvent, + int dataId, Activity.DataType dataType, int userId) { // Filters to generate JSON elements FilterProvider filters = @@ -49,6 +53,7 @@ public void dispatchNotification(final Date creationDate, final Activity.Activit "ActivityFilter", SimpleBeanPropertyFilter.filterOutAllExcept("id", "name")); mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.setFilters(filters); @@ -92,19 +97,19 @@ private Activity.AdditionalObject generateAdditionalObject(Activity.DataType dat additionalObject = new Activity.AdditionalObject(project, category, null, user); } else if (dataType.equals(Activity.DataType.REQUIREMENT)) { Requirement requirement = dalFacade.getRequirementById(dataId, userId); - Category category = dalFacade.getCategoryById(requirement.getCategories().get(0).getId(), userId); + Category category = dalFacade.getCategoryById(requirement.getCategories().get(0), userId); Project project = dalFacade.getProjectById(requirement.getProjectId(), userId); additionalObject = new Activity.AdditionalObject(project, category, requirement, user); } else if (dataType.equals(Activity.DataType.COMMENT)) { Comment comment = dalFacade.getCommentById(dataId); Requirement requirement = dalFacade.getRequirementById(comment.getRequirementId(), userId); - Category category = dalFacade.getCategoryById(requirement.getCategories().get(0).getId(), userId); + Category category = dalFacade.getCategoryById(requirement.getCategories().get(0), userId); Project project = dalFacade.getProjectById(requirement.getProjectId(), userId); additionalObject = new Activity.AdditionalObject(project, category, requirement, user); } else if (dataType.equals(Activity.DataType.ATTACHMENT)) { Attachment attachment = dalFacade.getAttachmentById(dataId); Requirement requirement = dalFacade.getRequirementById(attachment.getRequirementId(), userId); - Category category = dalFacade.getCategoryById(requirement.getCategories().get(0).getId(), userId); + Category category = dalFacade.getCategoryById(requirement.getCategories().get(0), userId); Project project = dalFacade.getProjectById(requirement.getProjectId(), userId); additionalObject = new Activity.AdditionalObject(project, category, requirement, user); } else { diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/CategoryResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java similarity index 91% rename from src/main/de/rwth/dbis/acis/bazaar/service/CategoryResource.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java index bcefdfc2..0112fe96 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/CategoryResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CategoryResource.java @@ -1,5 +1,7 @@ -package de.rwth.dbis.acis.bazaar.service; +package de.rwth.dbis.acis.bazaar.service.resources; +import de.rwth.dbis.acis.bazaar.service.BazaarFunction; +import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; @@ -16,14 +18,15 @@ import i5.las2peer.api.security.Agent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; -import jodd.vtor.Vtor; +import javax.validation.ConstraintViolation; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.bind.DatatypeConverter; import java.net.HttpURLConnection; import java.text.MessageFormat; +import java.time.OffsetDateTime; import java.util.*; @@ -31,7 +34,7 @@ @SwaggerDefinition( info = @Info( title = "Requirements Bazaar", - version = "0.6", + version = "0.9.0", description = "Requirements Bazaar project", termsOfService = "http://requirements-bazaar.org", contact = @Contact( @@ -49,9 +52,8 @@ @Path("/categories") public class CategoryResource { - private BazaarService bazaarService; - private final L2pLogger logger = L2pLogger.getInstance(CategoryResource.class.getName()); + private final BazaarService bazaarService; public CategoryResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); @@ -60,14 +62,15 @@ public CategoryResource() throws Exception { /** * This method returns the list of categories under a given project. * - * @param projectId id of the project - * @param page page number - * @param perPage number of projects by page - * @param search search string - * @param sort sort order + * @param projectId id of the project + * @param page page number + * @param perPage number of projects by page + * @param search search string + * @param sort item to sort by + * @param sortDirection sort order * @return Response with categories as a JSON array. */ - public Response getCategoriesForProject(int projectId, int page, int perPage, String search, List sort) { + public Response getCategoriesForProject(int projectId, int page, int perPage, String search, List sort, String sortDirection) { DALFacade dalFacade = null; try { Agent agent = Context.getCurrent().getMainAgent(); @@ -78,42 +81,34 @@ public Response getCategoriesForProject(int projectId, int page, int perPage, St } List sortList = new ArrayList<>(); for (String sortOption : sort) { - Pageable.SortDirection direction = Pageable.SortDirection.DEFAULT; - if (sortOption.startsWith("+") || sortOption.startsWith(" ")) { // " " is needed because jersey does not pass "+" - direction = Pageable.SortDirection.ASC; - sortOption = sortOption.substring(1); - - } else if (sortOption.startsWith("-")) { - direction = Pageable.SortDirection.DESC; - sortOption = sortOption.substring(1); - } - Pageable.SortField sortField = new Pageable.SortField(sortOption, direction); + Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); sortList.add(sortField); } PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), sortList, search); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); if (dalFacade.getProjectById(projectId, internalUserId) == null) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "category")); } if (dalFacade.isProjectPublic(projectId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, String.valueOf(projectId), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, projectId, dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); } } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_CATEGORY, String.valueOf(projectId), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_CATEGORY, projectId, dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); } } PaginationResult categoriesResult = dalFacade.listCategoriesByProjectId(projectId, pageInfo, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_13, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_13, projectId, Activity.DataType.PROJECT, internalUserId); Map> parameter = new HashMap<>(); parameter.put("page", new ArrayList() {{ @@ -183,15 +178,15 @@ public Response getCategory(@PathParam("categoryId") int categoryId) { dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category categoryToReturn = dalFacade.getCategoryById(categoryId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_15, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_15, categoryId, Activity.DataType.CATEGORY, internalUserId); if (dalFacade.isCategoryPublic(categoryId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, String.valueOf(categoryId), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_CATEGORY, categoryToReturn.getProjectId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); } } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_CATEGORY, String.valueOf(categoryId), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_CATEGORY, categoryToReturn.getProjectId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); } @@ -244,19 +239,19 @@ public Response createCategory(@ApiParam(value = "Category entity", required = t if (registrarErrors != null) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); } - Vtor vtor = bazaarService.getValidators(); - vtor.useProfiles("create"); - vtor.validate(categoryToCreate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + Set> violations = bazaarService.validateCreate(categoryToCreate); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_CATEGORY, String.valueOf(categoryToCreate.getProjectId()), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_CATEGORY, categoryToCreate.getProjectId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.create")); } - categoryToCreate.setLeader(dalFacade.getUserById(internalUserId)); + categoryToCreate.setCreator(dalFacade.getUserById(internalUserId)); Category createdCategory = dalFacade.createCategory(categoryToCreate, internalUserId); bazaarService.getNotificationDispatcher().dispatchNotification(createdCategory.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_16, createdCategory.getId(), Activity.DataType.CATEGORY, internalUserId); @@ -282,12 +277,11 @@ public Response createCategory(@ApiParam(value = "Category entity", required = t /** * Allows to update a certain category. * - * @param categoryId id of the category under a given project * @param categoryToUpdate updated category as a JSON object * @return Response with the updated category as a JSON object. */ @PUT - @Path("/{categoryId}") + @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "This method allows to update a certain category.") @@ -297,8 +291,7 @@ public Response createCategory(@ApiParam(value = "Category entity", required = t @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") }) - public Response updateCategory(@PathParam("categoryId") int categoryId, - @ApiParam(value = "Category entity", required = true) Category categoryToUpdate) { + public Response updateCategory(@ApiParam(value = "Category entity", required = true) Category categoryToUpdate) { DALFacade dalFacade = null; try { @@ -308,20 +301,22 @@ public Response updateCategory(@PathParam("categoryId") int categoryId, } Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(categoryToUpdate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + Set> violations = bazaarService.validate(categoryToUpdate); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_CATEGORY, dalFacade); + + // Prevent forged project ids + Category internalCategory = dalFacade.getCategoryById(categoryToUpdate.getId(), internalUserId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_CATEGORY, internalCategory.getProjectId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.modify")); } - if (categoryToUpdate.getId() != 0 && categoryId != categoryToUpdate.getId()) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, "Id does not match"); - } + Category updatedCategory = dalFacade.modifyCategory(categoryToUpdate); bazaarService.getNotificationDispatcher().dispatchNotification(updatedCategory.getLastUpdatedDate(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_17, updatedCategory.getId(), Activity.DataType.CATEGORY, internalUserId); @@ -333,13 +328,13 @@ public Response updateCategory(@PathParam("categoryId") int categoryId, return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); } else { logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update category " + categoryId); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update category " + categoryToUpdate.getId()); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); } } catch (Exception ex) { BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update category " + categoryId); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update category " + categoryToUpdate.getId()); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); } finally { bazaarService.closeDBConnection(dalFacade); @@ -375,7 +370,7 @@ public Response deleteCategory(@PathParam("categoryId") int categoryId) { Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category categoryToDelete = dalFacade.getCategoryById(categoryId, internalUserId); Project project = dalFacade.getProjectById(categoryToDelete.getProjectId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_CATEGORY, String.valueOf(project.getId()), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_CATEGORY, project.getId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.modify")); } @@ -444,7 +439,7 @@ public Response followCategory(@PathParam("categoryId") int categoryId) { } dalFacade.followCategory(internalUserId, categoryId); Category category = dalFacade.getCategoryById(categoryId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_19, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_19, category.getId(), Activity.DataType.CATEGORY, internalUserId); return Response.status(Response.Status.CREATED).entity(category.toJSON()).build(); } catch (BazaarException bex) { @@ -500,7 +495,7 @@ public Response unfollowCategory(@PathParam("categoryId") int categoryId) { } dalFacade.unFollowCategory(internalUserId, categoryId); Category category = dalFacade.getCategoryById(categoryId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_20, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_20, category.getId(), Activity.DataType.CATEGORY, internalUserId); return Response.ok(category.toJSON()).build(); } catch (BazaarException bex) { @@ -556,7 +551,7 @@ public Response getStatisticsForCategory( Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category category = dalFacade.getCategoryById(categoryId, internalUserId); Statistic categoryStatistics = dalFacade.getStatisticsForCategory(internalUserId, categoryId, sinceCal); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_21, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_21, categoryId, Activity.DataType.CATEGORY, internalUserId); return Response.ok(categoryStatistics.toJSON()).build(); } catch (BazaarException bex) { @@ -608,7 +603,7 @@ public Response getContributorsForCategory(@PathParam("categoryId") int category Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category category = dalFacade.getCategoryById(categoryId, internalUserId); CategoryContributors categoryContributors = dalFacade.listContributorsForCategory(categoryId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_22, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_22, categoryId, Activity.DataType.CATEGORY, internalUserId); return Response.ok(categoryContributors.toJSON()).build(); } catch (BazaarException bex) { @@ -661,16 +656,17 @@ public Response getFollowersForCategory(@PathParam("categoryId") int categoryId, ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); } PageInfo pageInfo = new PageInfo(page, perPage); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Category category = dalFacade.getCategoryById(categoryId, internalUserId); PaginationResult categoryFollowers = dalFacade.listFollowersForCategory(categoryId, pageInfo); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_23, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_23, categoryId, Activity.DataType.CATEGORY, internalUserId); Map> parameter = new HashMap<>(); parameter.put("page", new ArrayList() {{ @@ -722,7 +718,7 @@ public Response getFollowersForCategory(@PathParam("categoryId") int categoryId, @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "This method returns the list of requirements for a specific category.") @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of requirements for a given project", response = Category.class, responseContainer = "List"), + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of requirements for a given project", response = Requirement.class, responseContainer = "List"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") @@ -732,8 +728,10 @@ public Response getRequirementsForCategory(@PathParam("categoryId") int category @ApiParam(value = "Elements of requirements by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage, @ApiParam(value = "Search filter", required = false) @QueryParam("search") String search, @ApiParam(value = "State filter", required = false, allowableValues = "all,open,realized") @DefaultValue("all") @QueryParam("state") String stateFilter, - @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "date,last_activity,name,vote,comment,follower,realized") @DefaultValue("date") @QueryParam("sort") List sort) throws Exception { + @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "date,last_activity,name,vote,comment,follower") @DefaultValue("date") @QueryParam("sort") List sort, + @ApiParam(value = "SortDirection", allowableValues = "ASC,DESC") @DefaultValue("DESC") @QueryParam("sortDirection") String sortDirection + ) throws Exception { RequirementsResource requirementsResource = new RequirementsResource(); - return requirementsResource.getRequirementsForCategory(categoryId, page, perPage, search, stateFilter, sort); + return requirementsResource.getRequirementsForCategory(categoryId, page, perPage, search, stateFilter, sort, sortDirection); } -} \ No newline at end of file +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/CommentsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java similarity index 60% rename from src/main/de/rwth/dbis/acis/bazaar/service/CommentsResource.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java index 70c02f47..07aa8298 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/CommentsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/CommentsResource.java @@ -1,8 +1,11 @@ -package de.rwth.dbis.acis.bazaar.service; +package de.rwth.dbis.acis.bazaar.service.resources; +import de.rwth.dbis.acis.bazaar.service.BazaarFunction; +import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; @@ -13,14 +16,16 @@ import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; import i5.las2peer.api.security.Agent; +import i5.las2peer.api.security.AnonymousAgent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; -import jodd.vtor.Vtor; +import javax.validation.ConstraintViolation; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.HttpURLConnection; +import java.time.OffsetDateTime; import java.util.*; @@ -28,7 +33,7 @@ @SwaggerDefinition( info = @Info( title = "Requirements Bazaar", - version = "0.6", + version = "0.9.0", description = "Requirements Bazaar project", termsOfService = "http://requirements-bazaar.org", contact = @Contact( @@ -46,23 +51,133 @@ @Path("/comments") public class CommentsResource { - private BazaarService bazaarService; - private final L2pLogger logger = L2pLogger.getInstance(CommentsResource.class.getName()); + private final BazaarService bazaarService; public CommentsResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); } + + /** + * This method returns the list of comments on the server. + * + * @param page page number + * @param perPage number of comments by page + * @param embedParents embed context/parents of comment (project, requirement) + * @param search search string + * @param sort sort order + * @return Response with list of all requirements + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method returns the list of comments on the server.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "List of comments", response = Comment.class, responseContainer = "List"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getAllComments( + @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, + @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage, + @ApiParam(value = "Search filter", required = false) @QueryParam("search") String search, + @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "name,date") @DefaultValue("name") @QueryParam("sort") List sort, + @ApiParam(value = "SortDirection", allowableValues = "ASC,DESC") @QueryParam("sortDirection") String sortDirection, + @ApiParam(value = "Filter", required = true, allowMultiple = false, allowableValues = "created, following, replies") @QueryParam("filters") List filters, + @ApiParam(value = "Embed parents", required = true, allowMultiple = true, allowableValues = "project, requirement") @QueryParam("embedParents") List embedParents) { + + DALFacade dalFacade = null; + try { + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + List sortList = new ArrayList<>(); + for (String sortOption : sort) { + Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); + sortList.add(sortField); + } + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + HashMap filterMap = new HashMap<>(); + for (String filterOption : filters) { + filterMap.put(filterOption, internalUserId.toString()); + } + PageInfo pageInfo = new PageInfo(page, perPage, filterMap, sortList, search, null, embedParents); + + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + + PaginationResult commentResult = null; + + //Might want to change this to allow anonymous agents to get all public requirements? + if (agent instanceof AnonymousAgent) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comments.read")); + } else { + commentResult = dalFacade.listAllComments(pageInfo); + } + + //TODO Results in "No CommentRecord found with id: 0" + //bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, + // 0, Activity.DataType.COMMENT, internalUserId); + + Map> parameter = new HashMap<>(); + parameter.put("page", new ArrayList() {{ + add(String.valueOf(page)); + }}); + parameter.put("per_page", new ArrayList() {{ + add(String.valueOf(perPage)); + }}); + if (search != null) { + parameter.put("search", new ArrayList() {{ + add(String.valueOf(search)); + }}); + } + parameter.put("embedParents", embedParents); + parameter.put("sort", sort); + parameter.put("filters", filters); + + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(commentResult.toJSON()); + responseBuilder = bazaarService.paginationLinks(responseBuilder, commentResult, "comments", parameter); + responseBuilder = bazaarService.xHeaderFields(responseBuilder, commentResult); + + return responseBuilder.build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get all comments"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get all comments"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** * This method returns the list of comments for a specific requirement. * * @param requirementId id of the requirement - * @param page page number - * @param perPage number of projects by page * @return Response with comments as a JSON array. */ - public Response getCommentsForRequirement(int requirementId, int page, int perPage) { + public Response getCommentsForRequirement(int requirementId) { DALFacade dalFacade = null; try { Agent agent = Context.getCurrent().getMainAgent(); @@ -71,41 +186,29 @@ public Response getCommentsForRequirement(int requirementId, int page, int perPa if (registrarErrors != null) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); } - PageInfo pageInfo = new PageInfo(page, perPage); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + dalFacade = bazaarService.getDBConnection(); //Todo use requirement's projectId for security context, not the one sent from client Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); Project project = dalFacade.getProjectById(requirement.getProjectId(), internalUserId); if (dalFacade.isRequirementPublic(requirementId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, String.valueOf(project.getId()), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, project.getId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); } } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, String.valueOf(project.getId()), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, project.getId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); } } - PaginationResult commentsResult = dalFacade.listCommentsByRequirementId(requirementId, pageInfo); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_43, + List commentsResult = dalFacade.listCommentsByRequirementId(requirementId); + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_43, requirementId, Activity.DataType.REQUIREMENT, internalUserId); - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); Response.ResponseBuilder responseBuilder = Response.ok(); - responseBuilder = responseBuilder.entity(commentsResult.toJSON()); - responseBuilder = bazaarService.paginationLinks(responseBuilder, commentsResult, "requirements/" + String.valueOf(requirementId) + "/comments", parameter); - responseBuilder = bazaarService.xHeaderFields(responseBuilder, commentsResult); + responseBuilder = responseBuilder.entity(bazaarService.getMapper().writeValueAsString(commentsResult)); return responseBuilder.build(); } catch (BazaarException bex) { @@ -157,15 +260,15 @@ public Response getComment(@PathParam("commentId") int commentId) { Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Comment comment = dalFacade.getCommentById(commentId); Requirement requirement = dalFacade.getRequirementById(comment.getRequirementId(), internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_45, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_45, commentId, Activity.DataType.COMMENT, internalUserId); if (dalFacade.isProjectPublic(requirement.getProjectId())) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, requirement.getProjectId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); } } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, requirement.getProjectId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); } @@ -222,17 +325,17 @@ public Response createComment(@ApiParam(value = "Comment entity", required = tru dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(commentToCreate.getRequirementId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_COMMENT, String.valueOf(requirement.getProjectId()), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_COMMENT, requirement.getProjectId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.create")); } commentToCreate.setCreator(dalFacade.getUserById(internalUserId)); - Vtor vtor = bazaarService.getValidators(); - vtor.useProfiles("create"); - vtor.validate(commentToCreate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + Set> violations = bazaarService.validateCreate(commentToCreate); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade.followRequirement(internalUserId, requirement.getId()); Comment createdComment = dalFacade.createComment(commentToCreate); bazaarService.getNotificationDispatcher().dispatchNotification(createdComment.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_46, @@ -256,6 +359,68 @@ public Response createComment(@ApiParam(value = "Comment entity", required = tru } } + /** + * This method updates a specific comment. + * + * @return Response with the updated comment as a JSON object. + */ + @PUT + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method modifies a specific comment.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated comment", response = Comment.class), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response updateComment(@ApiParam(value = "Comment entity", required = true) Comment commentToUpdate) { + DALFacade dalFacade = null; + try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + Comment internalComment = dalFacade.getCommentById(commentToUpdate.getId()); + Requirement requirement = dalFacade.getRequirementById(internalComment.getRequirementId(), internalUserId); + + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade); + if (!authorized && !internalComment.isOwner(internalUserId)) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.modify")); + } + + internalComment.setMessage(commentToUpdate.getMessage()); + + Comment updatedComment = dalFacade.updateComment(internalComment); + + bazaarService.getNotificationDispatcher().dispatchNotification(internalComment.getCreationDate(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_48, + internalComment.getId(), Activity.DataType.COMMENT, internalUserId); + return Response.ok(updatedComment.toJSON()).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete comment " + commentToUpdate.getId()); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete comment " + commentToUpdate.getId()); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + /** * This method deletes a specific comment. * @@ -282,11 +447,13 @@ public Response deleteComment(@PathParam("commentId") int commentId) { if (registrarErrors != null) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Comment commentToDelete = dalFacade.getCommentById(commentId); Requirement requirement = dalFacade.getRequirementById(commentToDelete.getRequirementId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_COMMENT, Arrays.asList(String.valueOf(commentId), String.valueOf(requirement.getProjectId())), dalFacade); + + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_COMMENT, requirement.getProjectId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.modify")); } diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java new file mode 100644 index 00000000..dabe9bd0 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/FeedbackResource.java @@ -0,0 +1,182 @@ +package de.rwth.dbis.acis.bazaar.service.resources; + +import de.rwth.dbis.acis.bazaar.service.BazaarFunction; +import de.rwth.dbis.acis.bazaar.service.BazaarService; +import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Activity; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Feedback; +import de.rwth.dbis.acis.bazaar.service.dal.entities.PrivilegeEnum; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Project; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; +import i5.las2peer.api.Context; +import i5.las2peer.api.logging.MonitoringEvent; +import i5.las2peer.api.security.Agent; +import i5.las2peer.logging.L2pLogger; +import io.swagger.annotations.*; + +import javax.validation.ConstraintViolation; +import javax.ws.rs.Consumes; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.HttpURLConnection; +import java.time.OffsetDateTime; +import java.util.*; + +@Api(value = "feedback") +@SwaggerDefinition( + info = @Info( + title = "Requirements Bazaar", + version = "0.9.0", + description = "Requirements Bazaar project", + termsOfService = "http://requirements-bazaar.org", + contact = @Contact( + name = "Requirements Bazaar Dev Team", + url = "http://requirements-bazaar.org", + email = "info@requirements-bazaar.org" + ), + license = @License( + name = "Apache2", + url = "http://requirements-bazaar.org/license" + ) + ), + schemes = SwaggerDefinition.Scheme.HTTPS +) +@Path("/feedback") +public class FeedbackResource { + + private final L2pLogger logger = L2pLogger.getInstance(CommentsResource.class.getName()); + private final BazaarService bazaarService; + + public FeedbackResource() throws Exception { + bazaarService = (BazaarService) Context.getCurrent().getService(); + } + + /** + * This method returns the list of feedback for a given project. + * + * @param projectId id of the project + * @param page page number + * @param perPage number of projects by page + * @return Response with comments as a JSON array. + */ + public Response getFeedbackForProject(int projectId, int page, int perPage) { + DALFacade dalFacade = null; + try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + PageInfo pageInfo = new PageInfo(page, perPage); + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + + dalFacade = bazaarService.getDBConnection(); + //Todo use requirement's projectId for security context, not the one sent from client + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + Project project = dalFacade.getProjectById(projectId, internalUserId); + + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_FEEDBACK, project.getId(), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.feedback.read")); + } + + PaginationResult feedbackResult = dalFacade.getFeedbackByProject(projectId, pageInfo); + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_43, + projectId, Activity.DataType.FEEDBACK, internalUserId); + Map> parameter = new HashMap<>(); + parameter.put("page", new ArrayList() {{ + add(String.valueOf(page)); + }}); + parameter.put("per_page", new ArrayList() {{ + add(String.valueOf(perPage)); + }}); + + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(feedbackResult.toJSON()); + responseBuilder = bazaarService.paginationLinks(responseBuilder, feedbackResult, "project/" + String.valueOf(projectId) + "/feedbacks", parameter); + responseBuilder = bazaarService.xHeaderFields(responseBuilder, feedbackResult); + + return responseBuilder.build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get feedback for project " + projectId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get feedback for project " + projectId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** + * This method allows to create a new comment. + * + * @param givenFeedback feedback as JSON object + * @return Response with the created comment as JSON object. + */ + @POST + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to anonymously submit feedback.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created comment", response = Feedback.class), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response sendFeedback(@ApiParam(value = "Feedback entity", required = true) Feedback givenFeedback) { + DALFacade dalFacade = null; + try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + + dalFacade = bazaarService.getDBConnection(); + Set> violations = bazaarService.validateCreate(givenFeedback); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + + Feedback createdFeedback = dalFacade.createFeedback(givenFeedback); + return Response.status(Response.Status.CREATED).entity(createdFeedback.toJSON()).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create feedback"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create feedback"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java new file mode 100644 index 00000000..b1b81085 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/PersonalisationDataResource.java @@ -0,0 +1,180 @@ +package de.rwth.dbis.acis.bazaar.service.resources; + +import de.rwth.dbis.acis.bazaar.service.BazaarFunction; +import de.rwth.dbis.acis.bazaar.service.BazaarService; +import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; +import de.rwth.dbis.acis.bazaar.service.dal.entities.PersonalisationData; +import de.rwth.dbis.acis.bazaar.service.dal.entities.PrivilegeEnum; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; +import i5.las2peer.api.Context; +import i5.las2peer.api.logging.MonitoringEvent; +import i5.las2peer.api.security.Agent; +import i5.las2peer.logging.L2pLogger; +import io.swagger.annotations.*; + +import javax.validation.ConstraintViolation; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.HttpURLConnection; +import java.util.EnumSet; +import java.util.Set; + + +@Api(value = "personalisation", description = "Personalisation Data resource") +@SwaggerDefinition( + info = @Info( + title = "Requirements Bazaar", + version = "0.9.0", + description = "Requirements Bazaar project", + termsOfService = "http://requirements-bazaar.org", + contact = @Contact( + name = "Requirements Bazaar Dev Team", + url = "http://requirements-bazaar.org", + email = "info@requirements-bazaar.org" + ), + license = @License( + name = "Apache2", + url = "http://requirements-bazaar.org/license" + ) + ), + schemes = SwaggerDefinition.Scheme.HTTPS +) +@Path("/personalisation") +public class PersonalisationDataResource { + + private final L2pLogger logger = L2pLogger.getInstance(PersonalisationDataResource.class.getName()); + private BazaarService bazaarService; + + public PersonalisationDataResource() throws Exception { + bazaarService = (BazaarService) Context.getCurrent().getService(); + } + + + + /** + * This method allows to retrieve a certain stored personalisationData value. + * + * @param key The plugins identifier + * @param version The plugins identifier + * @return Response with attachment as a JSON object. + */ + @GET + @Path("/{key}-{version}/") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to retrieve a certain personalisationData value") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain personalisationData", response = PersonalisationData.class), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NO_CONTENT, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getPersonalisationData(@PathParam("key") String key, @PathParam("version") int version) { + DALFacade dalFacade = null; + try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PERSONALISATION_DATA, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.personalisationData.read")); + } + PersonalisationData data = dalFacade.getPersonalisationData(internalUserId, key, version); + return Response.ok(data.toJSON()).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NO_CONTENT).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get personalisationData " + key+" version:"+version ); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get personalisationData " + key+" version:"+version ); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** + * This method allows to save a personalisationData + * + * @param data as JSON object + * @return Response with the created attachment as JSON object. + */ + @PUT + @Path("/{key}-{version}/") + @Consumes(MediaType.APPLICATION_JSON) + //@Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to save a personalisationData item") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Success", response = PersonalisationData.class), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response setPersonalisationData(@PathParam("key") String key, @PathParam("version") int version, @ApiParam(value = "PersonalisationData as JSON", required = true) PersonalisationData data) { + DALFacade dalFacade = null; + try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PERSONALISATION_DATA, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.create")); + } + + PersonalisationData fullData = PersonalisationData.builder().key(key).userId(internalUserId).version(version).value(data.getValue()).build(); + + // Take Object for generic error handling + Set> violations = bazaarService.validateCreate(fullData); + if (violations.size() > 0) ExceptionHandler.getInstance().handleViolations(violations); + + dalFacade.setPersonalisationData(fullData); + + return Response.ok(fullData.toJSON()).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Set personalisationData"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Set personalisationData"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/ProjectsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java similarity index 55% rename from src/main/de/rwth/dbis/acis/bazaar/service/ProjectsResource.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java index 3a4ba9f0..feffa2bf 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/ProjectsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/ProjectsResource.java @@ -1,6 +1,9 @@ -package de.rwth.dbis.acis.bazaar.service; +package de.rwth.dbis.acis.bazaar.service.resources; +import de.rwth.dbis.acis.bazaar.service.BazaarFunction; +import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Tag; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; @@ -17,20 +20,22 @@ import i5.las2peer.api.security.AnonymousAgent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; -import jodd.vtor.Vtor; +import javax.validation.ConstraintViolation; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.bind.DatatypeConverter; import java.net.HttpURLConnection; +import java.time.OffsetDateTime; import java.util.*; +import java.util.concurrent.atomic.AtomicReference; @Api(value = "projects", description = "Projects resource") @SwaggerDefinition( info = @Info( title = "Requirements Bazaar", - version = "0.6", + version = "0.9.0", description = "Requirements Bazaar project", termsOfService = "http://requirements-bazaar.org", contact = @Contact( @@ -48,9 +53,8 @@ @Path("/projects") public class ProjectsResource { - private BazaarService bazaarService; - private final L2pLogger logger = L2pLogger.getInstance(ProjectsResource.class.getName()); + private final BazaarService bazaarService; public ProjectsResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); @@ -78,8 +82,11 @@ public Response getProjects( @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, @ApiParam(value = "Elements of project by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage, @ApiParam(value = "Search filter", required = false) @QueryParam("search") String search, - @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "name,date,last_activity,requirement,follower") @DefaultValue("name") @QueryParam("sort") List sort) { - + @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "name,date,last_activity,requirement,follower") @DefaultValue("name") @QueryParam("sort") List sort, + @ApiParam(value = "SortDirection", allowableValues = "ASC,DESC") @QueryParam("sortDirection") String sortDirection, + @ApiParam(value = "Filter", required = false, allowMultiple = true, allowableValues = "all, created, following") @QueryParam("filters") List filters, + @ApiParam(value = "Ids", required = false, allowMultiple = true) @QueryParam("ids") List ids, + @ApiParam(value = "Also search in projects requirements", required = false) @DefaultValue("false") @QueryParam("recursive") boolean recursive) { DALFacade dalFacade = null; try { String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); @@ -90,26 +97,29 @@ public Response getProjects( String userId = agent.getIdentifier(); List sortList = new ArrayList<>(); for (String sortOption : sort) { - Pageable.SortDirection direction = Pageable.SortDirection.DEFAULT; - if (sortOption.startsWith("+") || sortOption.startsWith(" ")) { // " " is needed because jersey does not pass "+" - direction = Pageable.SortDirection.ASC; - sortOption = sortOption.substring(1); - - } else if (sortOption.startsWith("-")) { - direction = Pageable.SortDirection.DESC; - sortOption = sortOption.substring(1); - } - Pageable.SortField sortField = new Pageable.SortField(sortOption, direction); + Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); sortList.add(sortField); } - PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), sortList, search); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + HashMap filterMap = new HashMap<>(); + for (String filterOption : filters) { + filterMap.put(filterOption, internalUserId.toString()); + } + + HashMap options = new HashMap<>(); + options.put("recursive", recursive); + + PageInfo pageInfo = new PageInfo(page, perPage, filterMap, sortList, search, ids, null, options); + + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + PaginationResult projectsResult; if (agent instanceof AnonymousAgent) { // return only public projects @@ -118,7 +128,7 @@ public Response getProjects( // return public projects and the ones the user belongs to projectsResult = dalFacade.listPublicAndAuthorizedProjects(pageInfo, internalUserId); } - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, 0, Activity.DataType.PROJECT, internalUserId); Map> parameter = new HashMap<>(); @@ -178,23 +188,30 @@ public Response getProject(@PathParam("projectId") int projectId) { if (registrarErrors != null) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); } + Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - if (dalFacade.isProjectPublic(projectId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_PROJECT, String.valueOf(projectId), dalFacade); + + Project projectToReturn = dalFacade.getProjectById(projectId, internalUserId); + + if (projectToReturn == null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "project")); + } + + if (projectToReturn.getVisibility()) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_PROJECT, projectId, dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); } } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PROJECT, String.valueOf(projectId), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PROJECT, projectId, dalFacade); if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.read")); } } - Project projectToReturn = dalFacade.getProjectById(projectId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_4, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_4, projectId, Activity.DataType.PROJECT, internalUserId); return Response.ok(projectToReturn.toJSON()).build(); } catch (BazaarException bex) { @@ -242,10 +259,13 @@ public Response createProject(@ApiParam(value = "Project entity", required = tru } Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - Vtor vtor = bazaarService.getValidators(); - vtor.useProfiles("create"); - vtor.validate(projectToCreate); - if (vtor.hasViolations()) ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + + // Validate input + Set> violations = bazaarService.validateCreate(projectToCreate); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_PROJECT, dalFacade); @@ -254,7 +274,7 @@ public Response createProject(@ApiParam(value = "Project entity", required = tru } projectToCreate.setLeader(dalFacade.getUserById(internalUserId)); Project createdProject = dalFacade.createProject(projectToCreate, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_5, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_5, createdProject.getId(), Activity.DataType.PROJECT, internalUserId); return Response.status(Response.Status.CREATED).entity(createdProject.toJSON()).build(); } catch (BazaarException bex) { @@ -278,12 +298,11 @@ public Response createProject(@ApiParam(value = "Project entity", required = tru /** * Allows to update a certain project. * - * @param projectId id of the project to update * @param projectToUpdate updated project * @return Response with the updated project as a JSON object. */ @PUT - @Path("/{projectId}") + @Path("/") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "This method allows to update a certain project.") @@ -293,8 +312,7 @@ public Response createProject(@ApiParam(value = "Project entity", required = tru @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") }) - public Response updateProject(@PathParam("projectId") int projectId, - @ApiParam(value = "Project entity", required = true) Project projectToUpdate) { + public Response updateProject(@ApiParam(value = "Project entity", required = true) Project projectToUpdate) { DALFacade dalFacade = null; try { String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); @@ -303,22 +321,22 @@ public Response updateProject(@PathParam("projectId") int projectId, } Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(projectToUpdate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + + // Take Object for generic error handling + Set> violations = bazaarService.validate(projectToUpdate); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_PROJECT, dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_PROJECT, projectToUpdate.getId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.modify")); } - if (projectToUpdate.getId() != 0 && projectId != projectToUpdate.getId()) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, "Id does not match"); - } + Project updatedProject = dalFacade.modifyProject(projectToUpdate); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_6, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_6, updatedProject.getId(), Activity.DataType.PROJECT, internalUserId); return Response.ok(updatedProject.toJSON()).build(); } catch (BazaarException bex) { @@ -341,6 +359,63 @@ public Response updateProject(@PathParam("projectId") int projectId, } } + /** + * This method deletes a specific project. + * + * @param projectId id of the project to delete + * @return Empty Response. + */ + @DELETE + @Path("/{projectId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method deletes a specific project.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_NO_CONTENT, message = "Successfully deleted"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response deleteProject(@PathParam("projectId") int projectId) { + DALFacade dalFacade = null; + try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + Project projectToDelete = dalFacade.getProjectById(projectId, internalUserId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Delete_PROJECT, projectId, dalFacade); + if (!authorized && !projectToDelete.isOwner(internalUserId)) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.delete")); + } + dalFacade.deleteProjectById(projectId, internalUserId); + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_28, + projectId, Activity.DataType.PROJECT, internalUserId); + return Response.noContent().build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete project " + projectId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete project " + projectId); + logger.warning(bex.getMessage()); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + /** * This method add the current user to the followers list of a given project. * @@ -374,7 +449,7 @@ public Response followProject(@PathParam("projectId") int projectId) { } dalFacade.followProject(internalUserId, projectId); Project project = dalFacade.getProjectById(projectId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_8, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_8, projectId, Activity.DataType.PROJECT, internalUserId); return Response.status(Response.Status.CREATED).entity(project.toJSON()).build(); } catch (BazaarException bex) { @@ -430,7 +505,7 @@ public Response unfollowProject(@PathParam("projectId") int projectId) { } dalFacade.unFollowProject(internalUserId, projectId); Project project = dalFacade.getProjectById(projectId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_9, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_9, projectId, Activity.DataType.PROJECT, internalUserId); return Response.ok(project.toJSON()).build(); } catch (BazaarException bex) { @@ -485,7 +560,7 @@ public Response getStatisticsForProject( Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Calendar sinceCal = since == null ? null : DatatypeConverter.parseDateTime(since); Statistic projectStatistics = dalFacade.getStatisticsForProject(internalUserId, projectId, sinceCal); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_10, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_10, projectId, Activity.DataType.PROJECT, internalUserId); return Response.ok(projectStatistics.toJSON()).build(); } catch (BazaarException bex) { @@ -536,7 +611,7 @@ public Response getContributorsForProject(@PathParam("projectId") int projectId) dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); ProjectContributors projectContributors = dalFacade.listContributorsForProject(projectId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_11, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_11, projectId, Activity.DataType.PROJECT, internalUserId); return Response.ok(projectContributors.toJSON()).build(); } catch (BazaarException bex) { @@ -589,15 +664,17 @@ public Response getFollowersForProject(@PathParam("projectId") int projectId, ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); } PageInfo pageInfo = new PageInfo(page, perPage); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); PaginationResult projectFollowers = dalFacade.listFollowersForProject(projectId, pageInfo); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_12, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_12, projectId, Activity.DataType.PROJECT, internalUserId); Map> parameter = new HashMap<>(); @@ -659,9 +736,11 @@ public Response getCategoriesForProject( @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, @ApiParam(value = "Elements of categories by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage, @ApiParam(value = "Search filter", required = false) @QueryParam("search") String search, - @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "name,date,last_activity,requirement,follower") @DefaultValue("name") @QueryParam("sort") List sort) throws Exception { + @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "name,date,last_activity,requirement,follower") @DefaultValue("name") @QueryParam("sort") List sort, + @ApiParam(value = "SortDirection", allowableValues = "ASC,DESC") @QueryParam("sortDirection") String sortDirection + ) throws Exception { CategoryResource categoryResource = new CategoryResource(); - return categoryResource.getCategoriesForProject(projectId, page, perPage, search, sort); + return categoryResource.getCategoriesForProject(projectId, page, perPage, search, sort, sortDirection); } /** @@ -690,8 +769,399 @@ public Response getRequirementsForProject(@PathParam("projectId") int projectId, @ApiParam(value = "Elements of requirements by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage, @ApiParam(value = "Search filter", required = false) @QueryParam("search") String search, @ApiParam(value = "State filter", required = false, allowableValues = "all,open,realized") @DefaultValue("all") @QueryParam("state") String stateFilter, - @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "date,last_activity,name,vote,comment,follower,realized") @DefaultValue("date") @QueryParam("sort") List sort) throws Exception { + @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "date,last_activity,name,vote,comment,follower") @DefaultValue("date") @QueryParam("sort") List sort, + @ApiParam(value = "SortDirection", allowableValues = "ASC,DESC") @QueryParam("sortDirection") String sortDirection + ) throws Exception { RequirementsResource requirementsResource = new RequirementsResource(); - return requirementsResource.getRequirementsForProject(projectId, page, perPage, search, stateFilter, sort); + return requirementsResource.getRequirementsForProject(projectId, page, perPage, search, stateFilter, sort, sortDirection); + } + + /** + * This method returns the list of feedbacks for a specific project. + * + * @param projectId id of the project to retrieve requirements for + * @param page page number + * @param perPage number of requirements by page + * @param search search string + * @param stateFilter requirement state + * @param sort sort order + * @return Response with requirements as a JSON array. + */ + @GET + @Path("/{projectId}/feedbacks") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method returns the list of given feedbacks for a specific project.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of feedbacks for a given project", response = Feedback.class, responseContainer = "List"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getFeedbacksForProject(@PathParam("projectId") int projectId, + @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, + @ApiParam(value = "Elements of feedbacks by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage, + @ApiParam(value = "Search filter", required = false) @QueryParam("search") String search, + @ApiParam(value = "State filter", required = false, allowableValues = "all,open") @DefaultValue("all") @QueryParam("state") String stateFilter, + @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "date") @DefaultValue("date") @QueryParam("sort") List sort, + @ApiParam(value = "SortDirection", allowableValues = "ASC,DESC") @QueryParam("sortDirection") String sortDirection + ) throws Exception { + FeedbackResource feedbackResource = new FeedbackResource(); + return feedbackResource.getFeedbackForProject(projectId, page, perPage); + } + + @GET + @Path("/{projectId}/tags") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method returns the list of tags under a given project.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a list of tags for a given project", response = Tag.class, responseContainer = "List"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getTagsForProject( + @PathParam("projectId") int projectId + ) { + DALFacade dalFacade = null; + try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + Project project = dalFacade.getProjectById(projectId, internalUserId); + + if (project == null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "project")); + } + + if (project.getVisibility()) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_PROJECT, projectId, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PROJECT, projectId, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.read")); + } + } + + List tags = dalFacade.getTagsByProjectId(projectId); + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_12, + projectId, Activity.DataType.PROJECT, internalUserId); + + Response.ResponseBuilder responseBuilder = Response.ok() + .entity(bazaarService.getMapper().writeValueAsString(tags)); + + return responseBuilder.build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get followers for project " + projectId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get followers for project " + projectId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** + * This method add the current user to the followers list of a given project. + * + * @param projectId id of the project + * @param tag Tag to be created + * @return Response with project as a JSON object. + */ + @POST + @Path("/{projectId}/tags") + @Produces(MediaType.APPLICATION_JSON) + @Consumes(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method adds a new tag to a given project.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Path to parent project", response = Tag.class), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response createTag(@PathParam("projectId") int projectId, + @ApiParam(value = "New Tag Representation", required = true) Tag tag) { + DALFacade dalFacade = null; + try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + // TODO: Discuss permission model + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_CATEGORY, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.create")); + } + + // Ensure no cross-injection happens + tag.setProjectId(projectId); + Tag createdTag = dalFacade.createTag(tag); + + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_8, + projectId, Activity.DataType.TAG, internalUserId); + return Response.status(Response.Status.CREATED).entity(createdTag.toJSON()).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Create tag in project " + projectId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Follow project " + projectId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** + * Allows to update a certain project. + * + * @param projectId id of the project to update + * @param projectMembers New or modified project members + * @return Response with the updated project as a JSON object. + */ + @PUT + @Path("/{projectId}/members") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to modify the project members.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_NO_CONTENT, message = "Member modified"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response updateMembership(@PathParam("projectId") int projectId, + @ApiParam(value = "New or updated project member", required = true) List projectMembers) { + DALFacade dalFacade = null; + try { + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + + // Take Object for generic error handling + Set> violations = bazaarService.validate(projectMembers); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + AtomicReference privilege = new AtomicReference<>(PrivilegeEnum.Modify_MEMBERS); + projectMembers.forEach(projectMember -> { + // Only Admins should be able to create new admins. + // Differentiate here + if (projectMember.getRole() == ProjectRole.ProjectAdmin) { + privilege.set(PrivilegeEnum.Modify_ADMIN_MEMBERS); + } + }); + + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, privilege.get(), projectId, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.modify")); + } + + for (ProjectMember projectMember : projectMembers) { + User member = dalFacade.getUserById(projectMember.getUserId()); + dalFacade.addUserToRole(member.getId(), projectMember.getRole().name(), projectId); + + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_6, projectId, Activity.DataType.PROJECT, internalUserId); + } + return Response.noContent().build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** + * Allows to update a certain project. + * + * @param projectId id of the project + * @return Response with a list of project members as a JSON object. + */ + @GET + @Path("/{projectId}/members") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to retrieve the project members.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Members", responseContainer = "List", response = ProjectMember.class), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getMembers(@PathParam("projectId") int projectId, + @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, + @ApiParam(value = "Elements of memebers by page", required = false) @DefaultValue("20") @QueryParam("per_page") int perPage) throws Exception { + + DALFacade dalFacade = null; + try { + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + + PageInfo pageInfo = new PageInfo(page, perPage); + + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + PrivilegeEnum privilege = PrivilegeEnum.Read_PUBLIC_PROJECT; + + if (!dalFacade.isProjectPublic(projectId)) { + privilege = PrivilegeEnum.Read_PROJECT; + } + + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, privilege, projectId, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.modify")); + } + + PaginationResult members = dalFacade.getProjectMembers(projectId, pageInfo); + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_12, + projectId, Activity.DataType.PROJECT, internalUserId); + + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(members.toJSON()); + responseBuilder = bazaarService.xHeaderFields(responseBuilder, members); + + return responseBuilder.build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + @DELETE + @Path("/{projectId}/members/{memberId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to remove a project member.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_NO_CONTENT, message = "Member removed"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response removeMember(@PathParam("projectId") int projectId, @PathParam("memberId") int memberId) { + DALFacade dalFacade = null; + try { + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + // Get roles of the member to modify to prevent admins being removed by managers + List modifiedMemberRoles = dalFacade.getRolesByUserId(memberId, projectId); + + // Only Admins should be able to remove admins. + // Differentiate here by checking if a user is a project admin + PrivilegeEnum privilege = PrivilegeEnum.Modify_MEMBERS; + if (modifiedMemberRoles.stream().anyMatch(role -> role.getName().equals(ProjectRole.ProjectAdmin.name()))) { + privilege = PrivilegeEnum.Modify_ADMIN_MEMBERS; + } + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, privilege, projectId, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.project.modify")); + } + + dalFacade.removeUserFromProject(memberId, projectId); + + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_6, projectId, Activity.DataType.PROJECT, internalUserId); + + return Response.noContent().build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update project"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } } } diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/RequirementsResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java similarity index 81% rename from src/main/de/rwth/dbis/acis/bazaar/service/RequirementsResource.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java index ffb282eb..8181f1c7 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/RequirementsResource.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/RequirementsResource.java @@ -1,6 +1,9 @@ -package de.rwth.dbis.acis.bazaar.service; +package de.rwth.dbis.acis.bazaar.service.resources; +import de.rwth.dbis.acis.bazaar.service.BazaarFunction; +import de.rwth.dbis.acis.bazaar.service.BazaarService; import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Tag; import de.rwth.dbis.acis.bazaar.service.dal.entities.*; import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; @@ -14,23 +17,25 @@ import i5.las2peer.api.Context; import i5.las2peer.api.logging.MonitoringEvent; import i5.las2peer.api.security.Agent; +import i5.las2peer.api.security.AnonymousAgent; import i5.las2peer.logging.L2pLogger; import io.swagger.annotations.*; -import jodd.vtor.Violation; -import jodd.vtor.Vtor; +import javax.validation.ConstraintViolation; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.bind.DatatypeConverter; import java.net.HttpURLConnection; +import java.net.URI; +import java.time.OffsetDateTime; import java.util.*; @Api(value = "requirements", description = "Requirements resource") @SwaggerDefinition( info = @Info( title = "Requirements Bazaar", - version = "0.6", + version = "0.9.0", description = "Requirements Bazaar project", termsOfService = "http://requirements-bazaar.org", contact = @Contact( @@ -48,14 +53,122 @@ @Path("/requirements") public class RequirementsResource { - private BazaarService bazaarService; - private final L2pLogger logger = L2pLogger.getInstance(RequirementsResource.class.getName()); + private final BazaarService bazaarService; public RequirementsResource() throws Exception { bazaarService = (BazaarService) Context.getCurrent().getService(); } + + /** + * This method returns the list of requirements on the server. + * + * @param page page number + * @param perPage number of requirements by page + * @param search search string + * @param sort sort order + * @return Response with list of all requirements + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method returns the list of requirements on the server.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "List of requirements", response = Requirement.class, responseContainer = "List"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getRequirements( + @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, + @ApiParam(value = "Elements of requirements by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage, + @ApiParam(value = "Search filter", required = false) @QueryParam("search") String search, + @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "name,date,last_activity,requirement,follower") @DefaultValue("name") @QueryParam("sort") List sort, + @ApiParam(value = "SortDirection", allowableValues = "ASC,DESC") @QueryParam("sortDirection") String sortDirection, + @ApiParam(value = "Filter", required = true, allowMultiple = true, allowableValues = "created, following") @QueryParam("filters") List filters, + @ApiParam(value = "Embed parents", required = true, allowMultiple = true, allowableValues = "project") @QueryParam("embedParents") List embedParents) { + + DALFacade dalFacade = null; + try { + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + List sortList = new ArrayList<>(); + for (String sortOption : sort) { + Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); + sortList.add(sortField); + } + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + HashMap filterMap = new HashMap<>(); + for (String filterOption : filters) { + filterMap.put(filterOption, internalUserId.toString()); + } + PageInfo pageInfo = new PageInfo(page, perPage, filterMap, sortList, search, null, embedParents); + + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + + PaginationResult requirementsResult = null; + + //Might want to change this to allow anonymous agents to get all public requirements? + if (agent instanceof AnonymousAgent) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirements.read")); + } else { + requirementsResult = dalFacade.listAllRequirements(pageInfo, internalUserId); + } + //TODO NotificationDispatcher tries to find Requirement with id 0 as additional Object, need to implement logic for multiple + //bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, + // 0, Activity.DataType.REQUIREMENT, internalUserId); + + Map> parameter = new HashMap<>(); + parameter.put("page", new ArrayList() {{ + add(String.valueOf(page)); + }}); + parameter.put("per_page", new ArrayList() {{ + add(String.valueOf(perPage)); + }}); + if (search != null) { + parameter.put("search", new ArrayList() {{ + add(String.valueOf(search)); + }}); + } + parameter.put("sort", sort); + + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(requirementsResult.toJSON()); + responseBuilder = bazaarService.paginationLinks(responseBuilder, requirementsResult, "requirements", parameter); + responseBuilder = bazaarService.xHeaderFields(responseBuilder, requirementsResult); + + return responseBuilder.build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get all requirements"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get all requirements"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** * This method returns the list of requirements for a specific project. * @@ -67,7 +180,7 @@ public RequirementsResource() throws Exception { * @param sort sort order * @return Response with requirements as a JSON array. */ - public Response getRequirementsForProject(int projectId, int page, int perPage, String search, String stateFilter, List sort) { + public Response getRequirementsForProject(int projectId, int page, int perPage, String search, String stateFilter, List sort, String sortDirection) { DALFacade dalFacade = null; try { Agent agent = Context.getCurrent().getMainAgent(); @@ -82,42 +195,34 @@ public Response getRequirementsForProject(int projectId, int page, int perPage, } List sortList = new ArrayList<>(); for (String sortOption : sort) { - Pageable.SortDirection direction = Pageable.SortDirection.DEFAULT; - if (sortOption.startsWith("+") || sortOption.startsWith(" ")) { // " " is needed because jersey does not pass "+" - direction = Pageable.SortDirection.ASC; - sortOption = sortOption.substring(1); - - } else if (sortOption.startsWith("-")) { - direction = Pageable.SortDirection.DESC; - sortOption = sortOption.substring(1); - } - Pageable.SortField sortField = new Pageable.SortField(sortOption, direction); + Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); sortList.add(sortField); } PageInfo pageInfo = new PageInfo(page, perPage, filters, sortList, search); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); if (dalFacade.getProjectById(projectId, internalUserId) == null) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.NOT_FOUND, String.format(Localization.getInstance().getResourceBundle().getString("error.resource.notfound"), "resource")); } if (dalFacade.isProjectPublic(projectId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, String.valueOf(projectId), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, projectId, dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); } } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, String.valueOf(projectId), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, projectId, dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); } } PaginationResult requirementsResult = dalFacade.listRequirementsByProject(projectId, pageInfo, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_14, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_14, projectId, Activity.DataType.PROJECT, internalUserId); Map> parameter = new HashMap<>(); @@ -166,15 +271,16 @@ public Response getRequirementsForProject(int projectId, int page, int perPage, /** * This method returns the list of requirements for a specific category. * - * @param categoryId id of the category under a given project - * @param page page number - * @param perPage number of projects by page - * @param search search string - * @param stateFilter requirement state - * @param sort sort order + * @param categoryId id of the category under a given project + * @param page page number + * @param perPage number of projects by page + * @param search search string + * @param stateFilter requirement state + * @param sort parameter to sort by + * @param sortDirection orientation to sort by * @return Response with requirements as a JSON array. */ - public Response getRequirementsForCategory(int categoryId, int page, int perPage, String search, String stateFilter, List sort) { + public Response getRequirementsForCategory(int categoryId, int page, int perPage, String search, String stateFilter, List sort, String sortDirection) { DALFacade dalFacade = null; try { Agent agent = Context.getCurrent().getMainAgent(); @@ -189,24 +295,16 @@ public Response getRequirementsForCategory(int categoryId, int page, int perPage } List sortList = new ArrayList<>(); for (String sortOption : sort) { - Pageable.SortDirection direction = Pageable.SortDirection.DEFAULT; - if (sortOption.startsWith("+") || sortOption.startsWith(" ")) { // " " is needed because jersey does not pass "+" - direction = Pageable.SortDirection.ASC; - sortOption = sortOption.substring(1); - - } else if (sortOption.startsWith("-")) { - direction = Pageable.SortDirection.DESC; - sortOption = sortOption.substring(1); - } - Pageable.SortField sortField = new Pageable.SortField(sortOption, direction); + Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); sortList.add(sortField); } PageInfo pageInfo = new PageInfo(page, perPage, filters, sortList, search); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); if (dalFacade.getCategoryById(categoryId, internalUserId) == null) { @@ -215,18 +313,18 @@ public Response getRequirementsForCategory(int categoryId, int page, int perPage Category category = dalFacade.getCategoryById(categoryId, internalUserId); Project project = dalFacade.getProjectById(category.getProjectId(), internalUserId); if (dalFacade.isCategoryPublic(categoryId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, String.valueOf(project.getId()), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, project.getId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); } } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, String.valueOf(project.getId()), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, project.getId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); } } PaginationResult requirementsResult = dalFacade.listRequirementsByCategory(categoryId, pageInfo, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_24, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_24, categoryId, Activity.DataType.CATEGORY, internalUserId); Map> parameter = new HashMap<>(); @@ -272,6 +370,7 @@ public Response getRequirementsForCategory(int categoryId, int page, int perPage } } + /** * This method returns a specific requirement. * @@ -300,15 +399,15 @@ public Response getRequirement(@PathParam("requirementId") int requirementId) { dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_25, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_25, requirementId, Activity.DataType.REQUIREMENT, internalUserId); if (dalFacade.isRequirementPublic(requirementId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, String.valueOf(requirement.getProjectId()), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_REQUIREMENT, requirement.getProjectId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); } } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, String.valueOf(requirement.getProjectId()), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_REQUIREMENT, requirement.getProjectId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.category.read")); } @@ -355,34 +454,47 @@ public Response createRequirement(@ApiParam(value = "Requirement entity", requir try { Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); if (registrarErrors != null) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); } - // TODO: check whether the current user may create a new requirement - dalFacade = bazaarService.getDBConnection(); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_REQUIREMENT, requirementToCreate.getProjectId(), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.create")); + } - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); requirementToCreate.setCreator(dalFacade.getUserById(internalUserId)); - Vtor vtor = bazaarService.getValidators(); - vtor.useProfiles("create"); - vtor.validate(requirementToCreate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + Set> violations = bazaarService.validateCreate(requirementToCreate); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } - vtor.resetProfiles(); // check if all categories are in the same project - for (Category category : requirementToCreate.getCategories()) { - category = dalFacade.getCategoryById(category.getId(), internalUserId); + for (Integer catId : requirementToCreate.getCategories()) { + Category category = dalFacade.getCategoryById(catId, internalUserId); if (requirementToCreate.getProjectId() != category.getProjectId()) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.VALIDATION, "Category does not fit with project"); } } - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_REQUIREMENT, String.valueOf(requirementToCreate.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.create")); + + List validatedTags = new ArrayList<>(); + for (Tag tag : requirementToCreate.getTags()) { + Tag internalTag = dalFacade.getTagById(tag.getId()); + if (internalTag == null) { + tag.setProjectId(requirementToCreate.getProjectId()); + internalTag = dalFacade.createTag(tag); + } else if (requirementToCreate.getProjectId() != tag.getProjectId()) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.VALIDATION, "Tag does not fit with project"); + } + validatedTags.add(internalTag); } + requirementToCreate.setTags(validatedTags); + Requirement createdRequirement = dalFacade.createRequirement(requirementToCreate, internalUserId); // check if attachments are given @@ -390,16 +502,17 @@ public Response createRequirement(@ApiParam(value = "Requirement entity", requir for (Attachment attachment : requirementToCreate.getAttachments()) { attachment.setCreator(dalFacade.getUserById(internalUserId)); attachment.setRequirementId(createdRequirement.getId()); - vtor.validate(attachment); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + violations = bazaarService.validate(attachment); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } - vtor.resetProfiles(); + dalFacade.createAttachment(attachment); } } createdRequirement = dalFacade.getRequirementById(createdRequirement.getId(), internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_26, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_26, createdRequirement.getId(), Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(createdRequirement.toJSON()).build(); } catch (BazaarException bex) { @@ -423,23 +536,20 @@ public Response createRequirement(@ApiParam(value = "Requirement entity", requir /** * This method updates a specific requirement within a project and category. * - * @param requirementId id of the requirement to update * @param requirementToUpdate requirement as a JSON object * @return Response with updated requirement as a JSON object. */ @PUT - @Path("/{requirementId}") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method updates a specific requirement.") + @ApiOperation(value = "This method updates a requirement.") @ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated requirement", response = Requirement.class), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") }) - public Response updateRequirement(@PathParam("requirementId") int requirementId, - @ApiParam(value = "Requirement entity", required = true) Requirement requirementToUpdate) { + public Response updateRequirement(@ApiParam(value = "Requirement entity", required = true) Requirement requirementToUpdate) { DALFacade dalFacade = null; try { String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); @@ -448,24 +558,27 @@ public Response updateRequirement(@PathParam("requirementId") int requirementId, } Agent agent = Context.getCurrent().getMainAgent(); String userId = agent.getIdentifier(); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(requirementToUpdate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + Set> violations = bazaarService.validate(requirementToUpdate); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade); - if (!authorized) { + + // Get internal requirement, so a malicious actor can't provide another project id + Requirement internalRequirement = dalFacade.getRequirementById(requirementToUpdate.getId(), internalUserId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, internalRequirement.getProjectId(), dalFacade); + if (!authorized && !internalRequirement.isOwner(internalUserId)) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.modify")); } - if (requirementToUpdate.getId() != 0 && requirementId != requirementToUpdate.getId()) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, "Id does not match"); - } + dalFacade.followRequirement(internalUserId, requirementToUpdate.getId()); Requirement updatedRequirement = dalFacade.modifyRequirement(requirementToUpdate, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_27, - requirementId, Activity.DataType.REQUIREMENT, internalUserId); + + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_27, + updatedRequirement.getId(), Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(updatedRequirement.toJSON()).build(); } catch (BazaarException bex) { if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { @@ -474,13 +587,13 @@ public Response updateRequirement(@PathParam("requirementId") int requirementId, return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); } else { logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update requirement " + requirementId); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update requirement " + requirementToUpdate.getId()); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); } } catch (Exception ex) { BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update requirement " + requirementId); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update requirement " + requirementToUpdate.getId()); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); } finally { bazaarService.closeDBConnection(dalFacade); @@ -516,12 +629,12 @@ public Response deleteRequirement(@PathParam("requirementId") int requirementId) Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Requirement requirementToDelete = dalFacade.getRequirementById(requirementId, internalUserId); Project project = dalFacade.getProjectById(requirementToDelete.getProjectId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, Arrays.asList(String.valueOf(project.getId()), String.valueOf(requirementId)), dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, project.getId(), dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.delete")); } Requirement deletedRequirement = dalFacade.deleteRequirementById(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_28, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_28, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(deletedRequirement.toJSON()).build(); } catch (BazaarException bex) { @@ -576,7 +689,7 @@ public Response leaddevelopRequirement(@PathParam("requirementId") int requireme ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.create")); } Requirement requirement = dalFacade.setUserAsLeadDeveloper(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.LEADDEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_29, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.LEADDEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_29, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { @@ -635,7 +748,7 @@ public Response unleaddevelopRequirement(@PathParam("requirementId") int require ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, "You are not lead developer."); } requirement = dalFacade.deleteUserAsLeadDeveloper(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.UNLEADDEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_30, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNLEADDEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_30, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { @@ -692,7 +805,7 @@ public Response developRequirement(@PathParam("requirementId") int requirementId dalFacade.wantToDevelop(internalUserId, requirementId); dalFacade.followRequirement(internalUserId, requirementId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.DEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_31, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.DEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_31, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { @@ -748,7 +861,7 @@ public Response undevelopRequirement(@PathParam("requirementId") int requirement } dalFacade.notWantToDevelop(internalUserId, requirementId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.UNDEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_32, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNDEVELOP, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_32, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { @@ -804,7 +917,7 @@ public Response followRequirement(@PathParam("requirementId") int requirementId) } dalFacade.followRequirement(internalUserId, requirementId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_33, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.FOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_33, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { @@ -860,7 +973,7 @@ public Response unfollowRequirement(@PathParam("requirementId") int requirementI } dalFacade.unFollowRequirement(internalUserId, requirementId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_34, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNFOLLOW, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_34, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { @@ -895,13 +1008,13 @@ public Response unfollowRequirement(@PathParam("requirementId") int requirementI @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "This method creates a vote for the given requirement in the name of the current user.") @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the requirement", response = Requirement.class), + @ApiResponse(code = HttpURLConnection.HTTP_SEE_OTHER, message = "Path to parent requirement"), @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") }) public Response vote(@PathParam("requirementId") int requirementId, - @ApiParam(value = "Vote direction", allowableValues = "up, down") @DefaultValue("up") @QueryParam("direction") String direction) { + @ApiParam(value = "Vote direction", required = true) Direction direction) { DALFacade dalFacade = null; try { Agent agent = Context.getCurrent().getMainAgent(); @@ -910,25 +1023,20 @@ public Response vote(@PathParam("requirementId") int requirementId, if (registrarErrors != null) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); } - if (!(direction.equals("up") || direction.equals("down"))) { - Vtor vtor = bazaarService.getValidators(); - vtor.addViolation(new Violation("Direction can only be \"up\" or \"down\"", direction, direction)); - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_VOTE, dalFacade); if (!authorized) { ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.create")); } - dalFacade.vote(internalUserId, requirementId, direction.equals("up")); - if (direction.equals("up")) { + dalFacade.vote(internalUserId, requirementId, direction.isUpVote()); + if (direction.isUpVote()) { dalFacade.followRequirement(internalUserId, requirementId); } - Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.VOTE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_35, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.VOTE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_35, requirementId, Activity.DataType.REQUIREMENT, internalUserId); - return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); + return Response.status(Response.Status.SEE_OTHER).location(URI.create(bazaarService.getBaseURL() + "requirements/" + requirementId)).build(); } catch (BazaarException bex) { if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); @@ -982,9 +1090,9 @@ public Response unvote(@PathParam("requirementId") int requirementId) { } dalFacade.unVote(internalUserId, requirementId); Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.UNVOTE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_36, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNVOTE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_36, requirementId, Activity.DataType.REQUIREMENT, internalUserId); - return Response.ok(requirement.toJSON()).build(); + return Response.status(Response.Status.SEE_OTHER).location(URI.create(bazaarService.getBaseURL() + "requirements/" + requirementId)).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); @@ -1032,12 +1140,13 @@ public Response realize(@PathParam("requirementId") int requirementId) { } dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade); + Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, requirement.getProjectId(), dalFacade); if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.create")); + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.realize")); } - Requirement requirement = dalFacade.setRequirementToRealized(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.REALIZE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_37, + requirement = dalFacade.setRequirementToRealized(requirementId, internalUserId); + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.REALIZE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_37, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.status(Response.Status.CREATED).entity(requirement.toJSON()).build(); } catch (BazaarException bex) { @@ -1087,12 +1196,12 @@ public Response unrealize(@PathParam("requirementId") int requirementId) { } dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_REQUIREMENT, dalFacade); + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Realize_REQUIREMENT, dalFacade); if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.vote.delete")); + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.requirement.realize")); } Requirement requirement = dalFacade.setRequirementToUnRealized(requirementId, internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.UNREALIZE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_38, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UNREALIZE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_38, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirement.toJSON()).build(); } catch (BazaarException bex) { @@ -1147,7 +1256,7 @@ public Response getStatisticsForRequirement( Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); Calendar sinceCal = since == null ? null : DatatypeConverter.parseDateTime(since); Statistic requirementStatistics = dalFacade.getStatisticsForRequirement(internalUserId, requirementId, sinceCal); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_39, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_39, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirementStatistics.toJSON()).build(); } catch (BazaarException bex) { @@ -1200,15 +1309,16 @@ public Response getDevelopersForRequirement(@PathParam("requirementId") int requ ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); } PageInfo pageInfo = new PageInfo(page, perPage); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); PaginationResult requirementDevelopers = dalFacade.listDevelopersForRequirement(requirementId, pageInfo); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_40, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_40, requirementId, Activity.DataType.REQUIREMENT, internalUserId); Map> parameter = new HashMap<>(); @@ -1273,7 +1383,7 @@ public Response getContributorsForRequirement(@PathParam("requirementId") int re dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); RequirementContributors requirementContributors = dalFacade.listContributorsForRequirement(requirementId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_41, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_41, requirementId, Activity.DataType.REQUIREMENT, internalUserId); return Response.ok(requirementContributors.toJSON()).build(); } catch (BazaarException bex) { @@ -1326,15 +1436,16 @@ public Response getFollowersForRequirement(@PathParam("requirementId") int requi ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); } PageInfo pageInfo = new PageInfo(page, perPage); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); } + dalFacade = bazaarService.getDBConnection(); Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); PaginationResult requirementFollowers = dalFacade.listFollowersForRequirement(requirementId, pageInfo); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_42, + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_42, requirementId, Activity.DataType.REQUIREMENT, internalUserId); Map> parameter = new HashMap<>(); @@ -1375,8 +1486,6 @@ public Response getFollowersForRequirement(@PathParam("requirementId") int requi * This method returns the list of comments for a specific requirement. * * @param requirementId id of the requirement - * @param page page number - * @param perPage number of projects by page * @return Response with comments as a JSON array. */ @GET @@ -1389,11 +1498,9 @@ public Response getFollowersForRequirement(@PathParam("requirementId") int requi @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") }) - public Response getCommentsForRequirement(@PathParam("requirementId") int requirementId, - @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, - @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) throws Exception { + public Response getCommentsForRequirement(@PathParam("requirementId") int requirementId) throws Exception { CommentsResource commentsResource = new CommentsResource(); - return commentsResource.getCommentsForRequirement(requirementId, page, perPage); + return commentsResource.getCommentsForRequirement(requirementId); } /** @@ -1416,8 +1523,72 @@ public Response getCommentsForRequirement(@PathParam("requirementId") int requir }) public Response getAttachmentsForRequirement(@PathParam("requirementId") int requirementId, @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, - @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) throws Exception { - AttachmentsResource attachmentsResource = new AttachmentsResource(); - return attachmentsResource.getAttachmentsForRequirement(requirementId, page, perPage); + @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) { + DALFacade dalFacade = null; + try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + PageInfo pageInfo = new PageInfo(page, perPage); + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + + dalFacade = bazaarService.getDBConnection(); + //Todo use requirement's projectId for security context, not the one sent from client + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); + Project project = dalFacade.getProjectById(requirement.getProjectId(), internalUserId); + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_44, + requirement.getId(), Activity.DataType.REQUIREMENT, internalUserId); + if (dalFacade.isRequirementPublic(requirementId)) { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, project.getId(), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + } else { + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, project.getId(), dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); + } + } + PaginationResult attachmentsResult = dalFacade.listAttachmentsByRequirementId(requirementId, pageInfo); + + Map> parameter = new HashMap<>(); + parameter.put("page", new ArrayList() {{ + add(String.valueOf(page)); + }}); + parameter.put("per_page", new ArrayList() {{ + add(String.valueOf(perPage)); + }}); + + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(attachmentsResult.toJSON()); + responseBuilder = bazaarService.paginationLinks(responseBuilder, attachmentsResult, "requirements/" + String.valueOf(requirementId) + "/attachments", parameter); + responseBuilder = bazaarService.xHeaderFields(responseBuilder, attachmentsResult); + + return responseBuilder.build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get attachments for requirement " + requirementId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get attachments for requirement " + requirementId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } } -} \ No newline at end of file +} diff --git a/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java new file mode 100644 index 00000000..8e52beb3 --- /dev/null +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/resources/UsersResource.java @@ -0,0 +1,446 @@ +package de.rwth.dbis.acis.bazaar.service.resources; + +import de.rwth.dbis.acis.bazaar.service.BazaarFunction; +import de.rwth.dbis.acis.bazaar.service.BazaarService; +import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; +import de.rwth.dbis.acis.bazaar.service.dal.entities.*; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; +import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; +import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; +import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; +import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; +import i5.las2peer.api.Context; +import i5.las2peer.api.logging.MonitoringEvent; +import i5.las2peer.api.security.Agent; +import i5.las2peer.logging.L2pLogger; +import io.swagger.annotations.*; + +import javax.validation.ConstraintViolation; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.net.HttpURLConnection; +import java.time.OffsetDateTime; +import java.util.*; + + +@Api(value = "users", description = "Users resource") +@SwaggerDefinition( + info = @Info( + title = "Requirements Bazaar", + version = "0.9.0", + description = "Requirements Bazaar project", + termsOfService = "http://requirements-bazaar.org", + contact = @Contact( + name = "Requirements Bazaar Dev Team", + url = "http://requirements-bazaar.org", + email = "info@requirements-bazaar.org" + ), + license = @License( + name = "Apache2", + url = "http://requirements-bazaar.org/license" + ) + ), + schemes = SwaggerDefinition.Scheme.HTTPS +) +@Path("/users") +public class UsersResource { + + private final L2pLogger logger = L2pLogger.getInstance(UsersResource.class.getName()); + private final BazaarService bazaarService; + + public UsersResource() throws Exception { + bazaarService = (BazaarService) Context.getCurrent().getService(); + } + + /** + * This method allows to search for users. + * + * @return Response with user as a JSON object. + */ + @GET + @Path("/") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to search for users.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "List of matching users", response = User.class, responseContainer = "List"), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response searchUser(@ApiParam(value = "Search filter", required = false) @QueryParam("search") String search, + @ApiParam(value = "Page number", required = false) @DefaultValue("0") @QueryParam("page") int page, + @ApiParam(value = "Elements of comments by page", required = false) @DefaultValue("10") @QueryParam("per_page") int perPage) { + DALFacade dalFacade = null; + try { + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_USERS, dalFacade); + if (!authorized) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); + } + + PageInfo pageInfo = new PageInfo(page, perPage, new HashMap<>(), new ArrayList<>(), search); + + // Take Object for generic error handling + Set> violations = bazaarService.validate(pageInfo); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + + PaginationResult users = dalFacade.searchUsers(pageInfo); + + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_53, + internalUserId, Activity.DataType.USER, internalUserId); + + Map> parameter = new HashMap<>(); + parameter.put("page", new ArrayList() {{ + add(String.valueOf(page)); + }}); + parameter.put("per_page", new ArrayList() {{ + add(String.valueOf(perPage)); + }}); + if (search != null) { + parameter.put("search", new ArrayList() {{ + add(String.valueOf(search)); + }}); + } + + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(users.toJSON()); + responseBuilder = bazaarService.paginationLinks(responseBuilder, users, "users", parameter); + responseBuilder = bazaarService.xHeaderFields(responseBuilder, users); + + return responseBuilder.build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Search users"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Search users"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** + * This method allows to retrieve a certain user. + * + * @param userId the id of the user to be returned + * @return Response with user as a JSON object. + */ + @GET + @Path("/{userId}") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to retrieve a certain user.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain user", response = User.class), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getUser(@PathParam("userId") int userId) { + DALFacade dalFacade = null; + try { + // TODO: check whether the current user may request this project + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + dalFacade = bazaarService.getDBConnection(); + User user = dalFacade.getUserById(userId); + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_53, + userId, Activity.DataType.USER, userId); + + return Response.ok(user.toJSON()).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get user " + userId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get user " + userId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** + * This method allows to retrieve the active user. + * + * @return Response with active user as a JSON object. + */ + @GET + @Path("/me") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to retrieve the active user.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the active user", response = User.class), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getActiveUser() { + DALFacade dalFacade = null; + try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + + // Block anonymous user + if (userId.equals("anonymous")) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.user.read")); + } + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + User user = dalFacade.getUserById(internalUserId); + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_54, + internalUserId, Activity.DataType.USER, internalUserId); + + return Response.ok(user.toPrivateJSON()).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get active user"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get active user"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** + * This method allows to retrieve the current users individual dashboard. + * + * @return Response with active user as a JSON object. + */ + @GET + @Path("/me/dashboard") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to retrieve the current users individual dashboard.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns user dashboard data", response = Dashboard.class), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getUserDashboard() { + DALFacade dalFacade = null; + try { + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + + // Block anonymous user + if (userId.equals("anonymous")) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.user.read")); + } + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_54, + internalUserId, Activity.DataType.USER, internalUserId); + + Dashboard data = dalFacade.getDashboardData(internalUserId, 10); + + return Response.ok(data.toJSON()).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get active user"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get active user"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** + * Allows to update a certain user. + * + * @param userId id of the user to update + * @param userToUpdate updated user as a JSON object + * @return Response with the updated user as a JSON object. + */ + @PUT + @Path("/{userId}") + @Consumes(MediaType.APPLICATION_JSON) + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to update the user profile.") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated user", response = User.class), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response updateUser(@PathParam("userId") int userId, + @ApiParam(value = "User entity as JSON", required = true) User userToUpdate) { + DALFacade dalFacade = null; + try { + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + Agent agent = Context.getCurrent().getMainAgent(); + + // Take Object for generic error handling + Set> violations = bazaarService.validate(userToUpdate); + if (violations.size() > 0) { + ExceptionHandler.getInstance().handleViolations(violations); + } + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(agent.getIdentifier()); + if (!internalUserId.equals(userId)) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, + "UserId is not identical with user sending this request."); + } + User updatedUser = dalFacade.modifyUser(userToUpdate); + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_56, + userId, Activity.DataType.USER, internalUserId); + return Response.ok(updatedUser.toJSON()).build(); + } catch (BazaarException bex) { + if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { + return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { + return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } else { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update user " + userId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update user " + userId); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + /** + * This method returns an entityOverview for the logged in user + * + * @param search search string + * @param include which entities to include in the overview //TODO Add Comments/Attachments + * @param sort sort order + * @param filters set of entities that should be returned + * @return Response as EntityOverview including the entities selected in include + */ + @GET + @Path("/me/entities") + @Produces(MediaType.APPLICATION_JSON) + @ApiOperation(value = "This method allows to receive an overview of entities related to the user") + @ApiResponses(value = { + @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated user", response = EntityOverview.class), + @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), + @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), + @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") + }) + public Response getEntityOverview( + @ApiParam(value = "Search filter", required = false) @QueryParam("search") String search, + @ApiParam(value = "Types of entities to include", required = true, allowMultiple = true, allowableValues = "projects,categories,requirements") @QueryParam("include") List include, + @ApiParam(value = "Sort", required = false, allowMultiple = true, allowableValues = "name,date,last_activity,requirement,follower") @DefaultValue("date") @QueryParam("sort") List sort, + @ApiParam(value = "SortDirection", allowableValues = "ASC,DESC") @QueryParam("sortDirection") String sortDirection, + @ApiParam(value = "Filter", required = false, allowMultiple = true, allowableValues = "created, following, developing") @DefaultValue("created") @QueryParam("filters") List filters) { + //Possibly allow filtertype "all"? + DALFacade dalFacade = null; + try { + String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); + if (registrarErrors != null) { + ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); + } + Agent agent = Context.getCurrent().getMainAgent(); + String userId = agent.getIdentifier(); + List sortList = new ArrayList<>(); + for (String sortOption : sort) { + Pageable.SortField sortField = new Pageable.SortField(sortOption, sortDirection); + sortList.add(sortField); + } + + dalFacade = bazaarService.getDBConnection(); + Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); + + HashMap filterMap = new HashMap<>(); + for (String filterOption : filters) { + filterMap.put(filterOption, internalUserId.toString()); + } + PageInfo pageInfo = new PageInfo(0, 0, filterMap, sortList, search); + + + EntityOverview result = dalFacade.getEntitiesForUser(include, pageInfo, internalUserId); + // Wrong SERVICE_CUSTOM_MESSAGE_3 ? + bazaarService.getNotificationDispatcher().dispatchNotification(OffsetDateTime.now(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_3, + 0, Activity.DataType.USER, internalUserId); + + + Response.ResponseBuilder responseBuilder = Response.ok(); + responseBuilder = responseBuilder.entity(result.toJSON()); + + return responseBuilder.build(); + } catch (BazaarException bex) { + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get entityOverview failed"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } catch (Exception ex) { + BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); + logger.warning(bex.getMessage()); + Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get entityOverview failed"); + return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); + } finally { + bazaarService.closeDBConnection(dalFacade); + } + } + + +} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/security/AuthorizationManager.java b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/security/AuthorizationManager.java similarity index 81% rename from src/main/de/rwth/dbis/acis/bazaar/service/security/AuthorizationManager.java rename to reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/security/AuthorizationManager.java index 3cd3c0b6..a33d2c7d 100644 --- a/src/main/de/rwth/dbis/acis/bazaar/service/security/AuthorizationManager.java +++ b/reqbaz/src/main/java/de/rwth/dbis/acis/bazaar/service/security/AuthorizationManager.java @@ -30,20 +30,15 @@ import java.util.List; /** - * @author Adam Gavronek * @since 2/17/2015 */ public class AuthorizationManager { - public boolean isAuthorized(int userId, PrivilegeEnum privilege, List contexts, DALFacade facade) throws BazaarException { - for (String context : contexts) { - List userRoles = facade.getRolesByUserId(userId, context); - boolean authorized = isAuthorized(userRoles, privilege, facade); - if (authorized) - return true; + public static void SyncPrivileges(DALFacade facade) throws BazaarException { + EnumSet privileges = EnumSet.allOf(PrivilegeEnum.class); + for (PrivilegeEnum privilege : privileges) { + facade.createPrivilegeIfNotExists(privilege); } - - return false; } public boolean isAuthorized(int userId, PrivilegeEnum privilege, DALFacade facade) throws BazaarException { @@ -53,24 +48,33 @@ public boolean isAuthorized(int userId, PrivilegeEnum privilege, DALFacade facad } - public boolean isAuthorized(int userId, PrivilegeEnum privilege, String context, DALFacade facade) throws BazaarException { + public boolean isAuthorized(int userId, PrivilegeEnum privilege, Integer context, DALFacade facade) throws BazaarException { List userRoles = facade.getRolesByUserId(userId, context); return isAuthorized(userRoles, privilege, facade); } + public boolean isAuthorized(int userId, Role role, DALFacade facade) throws BazaarException { + List userRoles = facade.getRolesByUserId(userId, null); + + return userRoles.contains(role); + + } public boolean isAuthorized(List userRoles, PrivilegeEnum privilege, DALFacade facade) throws BazaarException { - if (userRoles == null || userRoles.isEmpty()) return false; + if (userRoles == null || userRoles.isEmpty()) { + return false; + } for (Role role : userRoles) { if (hasPrivilege(role, privilege)) { return true; } else { List parents = facade.getParentsForRole(role.getId()); if (parents != null && !parents.isEmpty()) { - if (isAuthorized(parents, privilege, facade)) + if (isAuthorized(parents, privilege, facade)) { return true; + } } } } @@ -81,18 +85,11 @@ public boolean hasPrivilege(Role role, PrivilegeEnum demandedPrivilege) { List privileges = role.getPrivileges(); if (privileges != null && !privileges.isEmpty()) { for (Privilege privilege : privileges) { - if (privilege.getName() == demandedPrivilege) + if (privilege.getName() == demandedPrivilege) { return true; + } } } return false; } - - public static void SyncPrivileges(DALFacade facade) throws BazaarException { - EnumSet privileges = EnumSet.allOf(PrivilegeEnum.class); - for (PrivilegeEnum privilege : privileges) { - facade.createPrivilegeIfNotExists(privilege); - } - - } } diff --git a/reqbaz/src/main/resources/base-permissions.sql b/reqbaz/src/main/resources/base-permissions.sql new file mode 100644 index 00000000..5326c282 --- /dev/null +++ b/reqbaz/src/main/resources/base-permissions.sql @@ -0,0 +1,105 @@ +INSERT INTO role + (id, name) +VALUES (1, 'Anonymous'), + (2, 'LoggedInUser'), + (3, 'ProjectAdmin'), + (4, 'SystemAdmin'), + (5, 'ProjectManager'), + (6, 'ProjectMember'); + +INSERT INTO privilege + (id, name) +VALUES (1, 'Create_PROJECT'), + (2, 'Read_PROJECT'), + (3, 'Read_PUBLIC_PROJECT'), + (4, 'Modify_PROJECT'), + (5, 'Create_CATEGORY'), + (6, 'Read_CATEGORY'), + (7, 'Read_PUBLIC_CATEGORY'), + (8, 'Modify_CATEGORY'), + (9, 'Create_REQUIREMENT'), + (10, 'Read_REQUIREMENT'), + (11, 'Read_PUBLIC_REQUIREMENT'), + (12, 'Modify_REQUIREMENT'), + (13, 'Create_COMMENT'), + (14, 'Read_COMMENT'), + (15, 'Read_PUBLIC_COMMENT'), + (16, 'Modify_COMMENT'), + (17, 'Create_ATTACHMENT'), + (18, 'Read_ATTACHMENT'), + (19, 'Read_PUBLIC_ATTACHMENT'), + (20, 'Modify_ATTACHMENT'), + (21, 'Create_VOTE'), + (22, 'Delete_VOTE'), + (23, 'Create_FOLLOW'), + (24, 'Delete_FOLLOW'), + (25, 'Create_DEVELOP'), + (26, 'Delete_DEVELOP'), + (27, 'Read_PERSONALISATION_DATA'), + (28, 'Create_PERSONALISATION_DATA'), + (29, 'Read_FEEDBACK'), + (31, 'Promote_USER'), + (32, 'Realize_REQUIREMENT'), + (34, 'Modify_MEMBERS'), + (35, 'Modify_ADMIN_MEMBERS'), + (36, 'Read_USERS'); + +INSERT INTO "user" +(first_name, last_name, email, las2peer_id, user_name, profile_image, email_lead_subscription, + email_follow_subscription) +VALUES (NULL, NULL, 'anonymous@requirements-bazaar.org', '-1722613621014065292', 'anonymous', + 'https://api.learning-layers.eu/profile.png', true, true); + +INSERT INTO user_role_map + (role_id, user_id) +VALUES (1, 1); + + +INSERT INTO role_privilege_map + (role_id, privilege_id) +VALUES (1, 3), + (1, 7), + (1, 11), + (1, 15), + (1, 19), + + (2, 1), + (2, 9), + (2, 13), + (2, 17), + (2, 21), + (2, 22), + (2, 23), + (2, 24), + (2, 27), + (2, 28), + (2, 36), + + (3, 4), + (3, 8), + (3, 35), + + (5, 29), + (5, 31), + (5, 12), + (5, 16), + (5, 20), + (5, 5), + (5, 34), + + (6, 2), + (6, 6), + (6, 25), + (6, 26), + (6, 18), + (6, 14), + (6, 10), + (6, 32); + +INSERT INTO role_role_map + (child_id, parent_id) +VALUES (4, 3), + (3, 5), + (5, 6), + (6, 2), + (2, 1); diff --git a/reqbaz/src/main/resources/changelog.yaml b/reqbaz/src/main/resources/changelog.yaml new file mode 100644 index 00000000..9c2e8bb2 --- /dev/null +++ b/reqbaz/src/main/resources/changelog.yaml @@ -0,0 +1,1684 @@ +databaseChangeLog: + - changeSet: + id: 1624138981933-1 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: feedback_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: project_id + type: INTEGER + - column: + name: requirement_id + type: INTEGER + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + - column: + name: email + type: VARCHAR(255) + - column: + constraints: + nullable: false + name: feedback + type: TEXT + tableName: feedback + - changeSet: + id: 1624138981933-2 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: project_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: name + type: VARCHAR(255) + - column: + constraints: + nullable: false + name: description + type: TEXT + - column: + constraints: + nullable: false + name: visibility + type: BOOLEAN + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + - column: + name: last_updated_date + type: TIMESTAMP WITH TIME ZONE + - column: + constraints: + nullable: false + name: leader_id + type: INTEGER + - column: + name: default_category_id + type: INTEGER + - column: + name: additional_properties + type: JSONB + tableName: project + - changeSet: + id: 1624138981933-3 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: role_role_map_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: child_id + type: INTEGER + - column: + constraints: + nullable: false + name: parent_id + type: INTEGER + tableName: role_role_map + - changeSet: + id: 1624138981933-4 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: category_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: name + type: VARCHAR(255) + - column: + constraints: + nullable: false + name: description + type: TEXT + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + - column: + name: last_updated_date + type: TIMESTAMP WITH TIME ZONE + - column: + constraints: + nullable: false + name: project_id + type: INTEGER + - column: + constraints: + nullable: false + name: leader_id + type: INTEGER + - column: + name: additional_properties + type: JSONB + tableName: category + - changeSet: + id: 1624138981933-5 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: personalisation_data_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + - column: + defaultValueComputed: now() + name: last_updated_date + type: TIMESTAMP WITH TIME ZONE + - column: + constraints: + nullable: false + name: identifier + type: VARCHAR(50) + - column: + constraints: + nullable: false + name: user_id + type: INTEGER + - column: + constraints: + nullable: false + name: version + type: INTEGER + - column: + name: setting + type: TEXT + tableName: personalisation_data + - changeSet: + id: 1624138981933-6 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: category_follower_map_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: category_id + type: INTEGER + - column: + constraints: + nullable: false + name: user_id + type: INTEGER + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + tableName: category_follower_map + - changeSet: + id: 1624138981933-7 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: requirement_category_map_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: category_id + type: INTEGER + - column: + constraints: + nullable: false + name: requirement_id + type: INTEGER + tableName: requirement_category_map + - changeSet: + id: 1624138981933-8 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: requirement_developer_map_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: requirement_id + type: INTEGER + - column: + constraints: + nullable: false + name: user_id + type: INTEGER + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + tableName: requirement_developer_map + - changeSet: + id: 1624138981933-9 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: user_role_map_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: role_id + type: INTEGER + - column: + constraints: + nullable: false + name: user_id + type: INTEGER + - column: + name: context_info + type: INTEGER + tableName: user_role_map + - changeSet: + id: 1624138981933-10 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: vote_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: is_upvote + type: BOOLEAN + - column: + constraints: + nullable: false + name: requirement_id + type: INTEGER + - column: + constraints: + nullable: false + name: user_id + type: INTEGER + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + tableName: vote + - changeSet: + id: 1624138981933-11 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: attachment_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + - column: + name: last_updated_date + type: TIMESTAMP WITH TIME ZONE + - column: + constraints: + nullable: false + name: requirement_id + type: INTEGER + - column: + constraints: + nullable: false + name: user_id + type: INTEGER + - column: + constraints: + nullable: false + name: name + type: VARCHAR(255) + - column: + name: description + type: TEXT + - column: + constraints: + nullable: false + name: mime_type + type: VARCHAR(255) + - column: + constraints: + nullable: false + name: identifier + type: VARCHAR(900) + - column: + constraints: + nullable: false + name: file_url + type: VARCHAR(1000) + tableName: attachment + - changeSet: + id: 1624138981933-13 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: user_pkey + name: id + type: INTEGER + - column: + name: first_name + type: VARCHAR(150) + - column: + name: last_name + type: VARCHAR(150) + - column: + constraints: + nullable: false + name: email + type: VARCHAR(255) + - column: + name: las2peer_id + type: VARCHAR(128) + - column: + name: user_name + type: VARCHAR(255) + - column: + name: profile_image + type: TEXT + - column: + constraints: + nullable: false + defaultValueBoolean: true + name: email_lead_subscription + type: BOOLEAN + - column: + constraints: + nullable: false + defaultValueBoolean: true + name: email_follow_subscription + type: BOOLEAN + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + - column: + name: last_updated_date + type: TIMESTAMP WITH TIME ZONE + - column: + name: last_login_date + type: TIMESTAMP WITH TIME ZONE + - column: + defaultValueBoolean: true + name: personalization_enabled + type: BOOLEAN + tableName: user + - changeSet: + id: 1624138981933-14 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: privilege_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: name + type: VARCHAR(100) + tableName: privilege + - changeSet: + id: 1624138981933-15 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: requirement_tag_map_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: tag_id + type: INTEGER + - column: + constraints: + nullable: false + name: requirement_id + type: INTEGER + tableName: requirement_tag_map + - changeSet: + id: 1624138981933-16 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: comment_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: message + type: TEXT + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + - column: + name: last_updated_date + type: TIMESTAMP WITH TIME ZONE + - column: + constraints: + nullable: false + name: requirement_id + type: INTEGER + - column: + constraints: + nullable: false + name: user_id + type: INTEGER + - column: + name: reply_to_comment_id + type: INTEGER + - column: + constraints: + nullable: false + defaultValueBoolean: false + name: deleted + type: BOOLEAN + tableName: comment + - changeSet: + id: 1624138981933-17 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: requirement_follower_map_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: requirement_id + type: INTEGER + - column: + constraints: + nullable: false + name: user_id + type: INTEGER + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + tableName: requirement_follower_map + - changeSet: + id: 1624138981933-18 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: role_pkey + name: id + type: INTEGER + - column: + name: name + type: VARCHAR(50) + tableName: role + - changeSet: + id: 1624138981933-19 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: tag_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: project_id + type: INTEGER + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + - column: + constraints: + nullable: false + name: name + type: VARCHAR(20) + - column: + constraints: + nullable: false + name: colour + type: VARCHAR(7) + tableName: tag + - changeSet: + id: 1624138981933-20 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: requirement_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: name + type: VARCHAR(255) + - column: + name: description + type: TEXT + - column: + name: realized + type: TIMESTAMP WITH TIME ZONE + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + - column: + name: last_updated_date + type: TIMESTAMP WITH TIME ZONE + - column: + name: lead_developer_id + type: INTEGER + - column: + constraints: + nullable: false + name: creator_id + type: INTEGER + - column: + constraints: + nullable: false + name: project_id + type: INTEGER + - column: + name: additional_properties + type: JSONB + tableName: requirement + - changeSet: + id: 1624138981933-21 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: project_follower_map_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: project_id + type: INTEGER + - column: + constraints: + nullable: false + name: user_id + type: INTEGER + - column: + constraints: + nullable: false + defaultValueComputed: now() + name: creation_date + type: TIMESTAMP WITH TIME ZONE + tableName: project_follower_map + - changeSet: + id: 1624138981933-22 + author: thore (generated) + changes: + - createTable: + columns: + - column: + autoIncrement: true + constraints: + primaryKey: true + primaryKeyName: role_privilege_map_pkey + name: id + type: INTEGER + - column: + constraints: + nullable: false + name: role_id + type: INTEGER + - column: + constraints: + nullable: false + name: privilege_id + type: INTEGER + tableName: role_privilege_map + - changeSet: + id: 1624138981933-23 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: project_id + indexName: requirement_project + tableName: requirement + - changeSet: + id: 1624138981933-24 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: project_id + baseTableName: requirement + constraintName: requirement_project + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: project + validate: true + - changeSet: + id: 1624138981933-25 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: context_info + indexName: role_project_context + tableName: user_role_map + - changeSet: + id: 1624138981933-26 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: context_info + baseTableName: user_role_map + constraintName: role_project_context + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: project + validate: true + - changeSet: + id: 1624138981933-27 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: project_id + indexName: tag_project + tableName: tag + - changeSet: + id: 1624138981933-28 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: project_id + baseTableName: tag + constraintName: tag_project + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: project + validate: true + - changeSet: + id: 1624138981933-29 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: project_id + indexName: category_project + tableName: category + - changeSet: + id: 1624138981933-30 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: project_id + baseTableName: category + constraintName: category_project + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: project + validate: true + - changeSet: + id: 1624138981933-31 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: default_category_id + indexName: project_category + tableName: project + - changeSet: + id: 1624138981933-32 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: default_category_id + baseTableName: project + constraintName: project_category + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: category + validate: true + - changeSet: + id: 1624138981933-33 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: category_id + indexName: requirement_category_map_category + tableName: requirement_category_map + - changeSet: + id: 1624138981933-34 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: category_id + baseTableName: requirement_category_map + constraintName: requirement_category_map_category + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: category + validate: true + - changeSet: + id: 1624138981933-35 + author: thore (generated) + changes: + - addUniqueConstraint: + columnNames: identifier, user_id, version + constraintName: personalisation_key + tableName: personalisation_data + - changeSet: + id: 1624138981933-36 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: category_id + indexName: category_follower_map_category + tableName: category_follower_map + - changeSet: + id: 1624138981933-37 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: category_id + baseTableName: category_follower_map + constraintName: category_follower_map_category + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: category + validate: true + - changeSet: + id: 1624138981933-39 + author: thore (generated) + changes: + - addUniqueConstraint: + columnNames: las2peer_id + constraintName: user_las2peer_id_key + tableName: user + - changeSet: + id: 1624138981933-40 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: user_id + indexName: user_role_map_user + tableName: user_role_map + - changeSet: + id: 1624138981933-41 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: user_id + baseTableName: user_role_map + constraintName: user_role_map_user + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-42 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: user_id + indexName: vote_user + tableName: vote + - changeSet: + id: 1624138981933-43 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: user_id + baseTableName: vote + constraintName: vote_user + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-44 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: privilege_id + indexName: role_privilege_map_privilege + tableName: role_privilege_map + - changeSet: + id: 1624138981933-45 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: privilege_id + baseTableName: role_privilege_map + constraintName: role_privilege_map_privilege + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: privilege + validate: true + - changeSet: + id: 1624138981933-46 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: user_id + indexName: comment_user + tableName: comment + - changeSet: + id: 1624138981933-47 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: user_id + baseTableName: comment + constraintName: comment_user + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-48 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: reply_to_comment_id + indexName: reply_comment + tableName: comment + - changeSet: + id: 1624138981933-49 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: reply_to_comment_id + baseTableName: comment + constraintName: reply_comment + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: comment + validate: true + - changeSet: + id: 1624138981933-50 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: user_id + indexName: requirement_follower_map_user + tableName: requirement_follower_map + - changeSet: + id: 1624138981933-51 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: user_id + baseTableName: requirement_follower_map + constraintName: requirement_follower_map_user + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-52 + author: thore (generated) + changes: + - addUniqueConstraint: + columnNames: name + constraintName: role_name_key + tableName: role + - changeSet: + id: 1624138981933-53 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: role_id + indexName: role_privilege_map_role + tableName: role_privilege_map + - changeSet: + id: 1624138981933-54 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: role_id + baseTableName: role_privilege_map + constraintName: role_privilege_map_role + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: role + validate: true + - changeSet: + id: 1624138981933-55 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: child_id + indexName: role_role_map_child + tableName: role_role_map + - changeSet: + id: 1624138981933-56 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: child_id + baseTableName: role_role_map + constraintName: role_role_map_child + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: role + validate: true + - changeSet: + id: 1624138981933-57 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: parent_id + indexName: role_role_map_parent + tableName: role_role_map + - changeSet: + id: 1624138981933-58 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: parent_id + baseTableName: role_role_map + constraintName: role_role_map_parent + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: role + validate: true + - changeSet: + id: 1624138981933-59 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: role_id + indexName: user_role_map_role + tableName: user_role_map + - changeSet: + id: 1624138981933-60 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: role_id + baseTableName: user_role_map + constraintName: user_role_map_role + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: role + validate: true + - changeSet: + id: 1624138981933-61 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: creator_id + indexName: creator + tableName: requirement + - changeSet: + id: 1624138981933-62 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: creator_id + baseTableName: requirement + constraintName: creator + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-63 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: lead_developer_id + indexName: lead_developer + tableName: requirement + - changeSet: + id: 1624138981933-64 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: lead_developer_id + baseTableName: requirement + constraintName: lead_developer + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-65 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: requirement_id + indexName: requirement_tag_map_requirement + tableName: requirement_tag_map + - changeSet: + id: 1624138981933-66 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: requirement_id + baseTableName: requirement_tag_map + constraintName: requirement_tag_map_requirement + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: requirement + validate: true + - changeSet: + id: 1624138981933-67 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: requirement_id + indexName: vote_requirement + tableName: vote + - changeSet: + id: 1624138981933-68 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: requirement_id + baseTableName: vote + constraintName: vote_requirement + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: requirement + validate: true + - changeSet: + id: 1624138981933-69 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: project_id + indexName: project_follower_map_project + tableName: project_follower_map + - changeSet: + id: 1624138981933-70 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: project_id + baseTableName: project_follower_map + constraintName: project_follower_map_project + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: project + validate: true + - changeSet: + id: 1624138981933-71 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: user_id + indexName: project_follower_map_user + tableName: project_follower_map + - changeSet: + id: 1624138981933-72 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: user_id + baseTableName: project_follower_map + constraintName: project_follower_map_user + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-73 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: project_id + indexName: feedback_project + tableName: feedback + - changeSet: + id: 1624138981933-74 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: project_id + baseTableName: feedback + constraintName: feedback_project + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: project + validate: true + - changeSet: + id: 1624138981933-75 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: leader_id + indexName: project_user + tableName: project + - changeSet: + id: 1624138981933-76 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: leader_id + baseTableName: project + constraintName: project_user + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-77 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: leader_id + indexName: category_user + tableName: category + - changeSet: + id: 1624138981933-78 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: leader_id + baseTableName: category + constraintName: category_user + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-79 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: user_id + indexName: personalisation_user + tableName: personalisation_data + - changeSet: + id: 1624138981933-80 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: user_id + baseTableName: personalisation_data + constraintName: personalisation_user + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-81 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: user_id + indexName: category_follower_map_user + tableName: category_follower_map + - changeSet: + id: 1624138981933-82 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: user_id + baseTableName: category_follower_map + constraintName: category_follower_map_user + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-83 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: requirement_id + indexName: requirement_category_map_requirement + tableName: requirement_category_map + - changeSet: + id: 1624138981933-84 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: requirement_id + baseTableName: requirement_category_map + constraintName: requirement_category_map_requirement + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: requirement + validate: true + - changeSet: + id: 1624138981933-85 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: requirement_id + indexName: requirement_developer_map_requirement + tableName: requirement_developer_map + - changeSet: + id: 1624138981933-86 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: requirement_id + baseTableName: requirement_developer_map + constraintName: requirement_developer_map_requirement + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: requirement + validate: true + - changeSet: + id: 1624138981933-87 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: user_id + indexName: requirement_developer_map_user + tableName: requirement_developer_map + - changeSet: + id: 1624138981933-88 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: user_id + baseTableName: requirement_developer_map + constraintName: requirement_developer_map_user + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-89 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: requirement_id + indexName: attachment_requirement + tableName: attachment + - changeSet: + id: 1624138981933-90 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: requirement_id + baseTableName: attachment + constraintName: attachment_requirement + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: requirement + validate: true + - changeSet: + id: 1624138981933-91 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: user_id + indexName: attachment_user + tableName: attachment + - changeSet: + id: 1624138981933-92 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: user_id + baseTableName: attachment + constraintName: attachment_user + deferrable: false + initiallyDeferred: false + onDelete: RESTRICT + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: user + validate: true + - changeSet: + id: 1624138981933-93 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: tag_id + indexName: requirement_tag_map_tag + tableName: requirement_tag_map + - changeSet: + id: 1624138981933-94 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: tag_id + baseTableName: requirement_tag_map + constraintName: requirement_tag_map_tag + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: tag + validate: true + - changeSet: + id: 1624138981933-95 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: requirement_id + indexName: comment_requirement + tableName: comment + - changeSet: + id: 1624138981933-96 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: requirement_id + baseTableName: comment + constraintName: comment_requirement + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: requirement + validate: true + - changeSet: + id: 1624138981933-97 + author: thore (generated) + changes: + - createIndex: + columns: + - column: + name: requirement_id + indexName: requirement_follower_map_requirement + tableName: requirement_follower_map + - changeSet: + id: 1624138981933-98 + author: thore (generated) + changes: + - addForeignKeyConstraint: + baseColumnNames: requirement_id + baseTableName: requirement_follower_map + constraintName: requirement_follower_map_requirement + deferrable: false + initiallyDeferred: false + onDelete: CASCADE + onUpdate: RESTRICT + referencedColumnNames: id + referencedTableName: requirement + validate: true + - changeSet: + id: load-permissions + author: thore + changes: + - sqlFile: + comment: Basic Role and Permission Maps + endDelimiter: \nGO + splitStatements: true + path: base-permissions.sql + stripComments: true + - changeSet: + id: fix-anonymous-las2peerid + author: thore + changes: + - update: + columns: + - column: + name: las2peer_id + value: anonymous + schemaName: public + tableName: user + where: las2peer_id='-1722613621014065292' diff --git a/src/i18n/Translation_de.properties b/reqbaz/src/main/resources/i18n/Translation_de.properties similarity index 85% rename from src/i18n/Translation_de.properties rename to reqbaz/src/main/resources/i18n/Translation_de.properties index 5d10e85f..48dcbb89 100644 --- a/src/i18n/Translation_de.properties +++ b/reqbaz/src/main/resources/i18n/Translation_de.properties @@ -27,12 +27,14 @@ error.authorization.category.read=Nur Projektmitarbeiter können Projektkomponen error.authorization.category.create=Nur Administratoren können Projektkomponenten erstellen. error.authorization.category.modify=Nur Administratoren können Projektkomponenten verändern. error.authorization.category.delete=Die Projektkomoponente mit id {0} kann nicht gelöscht werden, da sie die Standardkomponente des Projects ist. +error.authorization.requirements.read=Nur eingeloggte Mitglieder können Requirements lesen. error.authorization.requirement.create=Nur Projektmitglieder könnnen Anforderungen erstellen. error.authorization.requirement.delete=Nur der Ersteller einer Anforderung kann eine Anforderung löschen. error.authorization.develop.create=Nur Projektmitglieder können sich als Entwickler eintragen. error.authorization.develop.delete=Nur Projektmitglieder können sich als Entwickler austragen. error.authorization.follow.create=Nur Projekmitglieder können ein Projekt folgen. error.authorization.follow.delete=Nur Projektmitglieder können ein Projekt nicht weiter folgen. +error.authorization.user.read=Nur authentifizierte Benutzer können diese Ressource einsehen. error.authorization.vote.create=Nur Projektmitglieder können abstimmen. error.authorization.vote.delete=Nur Projektmitglieder können ihre Abstimmung löschen. error.authorization.comment.read=Nur Projektmiglieder können Kommentare sehen. @@ -40,10 +42,14 @@ error.authorization.comment.create=Nur Projektmitglieder können Kommentare erst error.authorization.comment.modify=Nur der Ersteller eines Kommentars kann ein Kommentar verändern. error.authorization.attachment.create=Nur Projektmitglieder können Anhänge erstellen. error.authorization.attachment.modify=Nur der Ersteller von einem Anhang kann einen Anhang verändern. +error.authorization.personalisationData.read=Nur angemeldete Benutzer können ihre Daten lesen. +error.authorization.personalisationData.create=Nur angemeldete Benutzer können ihre Daten schreiben. error.unknown_exception=%s Fehler in %s\: %s Fehlercode\: %d category.uncategorized.Name=Generelle Anforderungen category.uncategorized.Description=Anforderungen welche zu keiner Projektkategorie gehörten. error.validation=Fehler bei der Validierung von %s festgestellt. Ihre Eingabe von %s erzeugt den Fehler\: %s. +error.authorization.project.read=Sie haben nicht das Recht dieses Projekt zu lesen. error.authorization.project.modify=Sie haben nicht das Recht dieses Projekt zu ändern. error.authorization.requirement.modify=Nur der Ersteller einer Anforderung kann eine Anforderung verändern. -error.resource.notfound=$s nicht gerunden. \ No newline at end of file +error.authorization.feedback.read=Nur Projektadmins können Feedback einsehen. +error.resource.notfound=$s nicht gefunden. diff --git a/src/i18n/Translation_en.properties b/reqbaz/src/main/resources/i18n/Translation_en.properties similarity index 84% rename from src/i18n/Translation_en.properties rename to reqbaz/src/main/resources/i18n/Translation_en.properties index 9732d71b..388c4bbd 100644 --- a/src/i18n/Translation_en.properties +++ b/reqbaz/src/main/resources/i18n/Translation_en.properties @@ -27,12 +27,15 @@ error.authorization.category.read=Only project members can see categories. error.authorization.category.create=Only admins can create categories. error.authorization.category.modify=Only admins can modify categories. error.authorization.category.delete=This category item with id {0} cannot be deleted, because it is the default category for the project. +error.authorization.requirements.read=Only logged in users can read requirements. error.authorization.requirement.create=Only project members can create requirements. error.authorization.requirement.delete=Only the creator can delete requirements. +error.authorization.requirement.realize=Only project members can set requirements as realized. error.authorization.develop.create=Only project members can register to develop a requirement. error.authorization.develop.delete=Only project members can deregister from developing a requirement. error.authorization.follow.create=Only project members can register to follow a requirement. error.authorization.follow.delete=Only project members can deregister following a requirement. +error.authorization.user.read=Only logged in users can access this resource. error.authorization.vote.create=Only project members can vote. error.authorization.vote.delete=Only project members can delete vote. error.authorization.comment.read=Only project members can see comments. @@ -40,14 +43,18 @@ error.authorization.comment.create=Only project members can create comments. error.authorization.comment.modify=Only the creator can modify comments. error.authorization.attachment.create=Only project members can create attachments. error.authorization.attachment.modify=Only the creator can modify attachments. +error.authorization.personalisationData.read=Only logged in users can read their personal data. +error.authorization.personalisationData.create=Only logged in users can write their personal data. +error.authorization.feedback.read=Only project admins can read feedback. +error.authorization.notifications=Only Administrators can flush the notification queue. error.unknown_exception=%s Error in %s\: %s ExceptionCode\: %d. category.uncategorized.Name=General Requirements category.uncategorized.Description=Requirements which do not belong to any category. error.validation=On %s constraint violation has been detected, because you sent %s and the problem is\: %s. -error.authorization.project.modify=You does not have rights to modify this project. +error.authorization.project.read=You do not have rights to read this project. +error.authorization.project.modify=You do not have rights to modify this project. error.authorization.requirement.modify=Only the creator can modify requirements. error.resource.notfound=$s not found. - # email fields. english only at the moment. email.bodyText.greeting=Hello, email.bodyText.user=User @@ -73,4 +80,4 @@ email.subject.realized=Realized email.bodyText.news=Requirements Bazaar has news for an item you are following: email.bodyText.nextSummary=In case there is more activity on Requirements Bazaar, we will send you another notification in around %s minutes. email.bodyText.bestWishes=Best,\r\n Requirements Bazaar -email.bodyText.footer=This email was generated automatically by Requirements Bazaar.\r\nTo change your email notification settings, please log in and check your profile settings:\r\nhttps://requirements-bazaar.org \ No newline at end of file +email.bodyText.footer=This email was generated automatically by Requirements Bazaar.\r\nTo change your email notification settings, please log in and check your profile settings:\r\nhttps://requirements-bazaar.org diff --git a/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/BazaarTest.java b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/BazaarTest.java new file mode 100644 index 00000000..f13c7c46 --- /dev/null +++ b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/BazaarTest.java @@ -0,0 +1,592 @@ +package de.rwth.dbis.acis.bazaar.service; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import i5.las2peer.connectors.webConnector.client.ClientResponse; +import i5.las2peer.connectors.webConnector.client.MiniClient; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import javax.ws.rs.core.MediaType; +import java.util.HashMap; + +import static org.junit.Assert.*; + +public class BazaarTest extends TestBase { + + private int adamId; + + @Before + public void adamSetup() { + MiniClient client = getClient(); + + ClientResponse result = client.sendRequest("GET", mainPath + "users/me", ""); + assertEquals(200, result.getHttpCode()); + + JsonObject response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + System.out.println(response.toString()); + assertTrue(response.isJsonObject()); + adamId = response.get("id").getAsInt(); + } + + /** + * Test to get the version from the version endpoint + */ + @Test + public void testGetVersion() { + try { + MiniClient client = getClient(); + + ClientResponse result = client.sendRequest("GET", mainPath + "version", ""); + JsonObject response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + System.out.println(response.toString()); + assertTrue(response.isJsonObject()); + assertEquals(response.get("version").getAsString(), BazaarService.class.getName() + "@" + testVersion); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + + /** + * Test to get the statistics + */ + @Test + public void testStatistics() { + try { + MiniClient client = getClient(); + + ClientResponse result = client.sendRequest("GET", mainPath + "statistics", ""); + JsonObject response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + System.out.println(response.toString()); + assertTrue(response.isJsonObject()); + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + + /** + * Test to get a list of projects + */ + @Test + public void testCreateProject() { + try { + MiniClient client = getClient(); + + String testProject = "{\"name\": \"Test Project\", \"description\": \"A test Project\", \"additionalProperties\": {\"testProperty\": \"test\"}}"; + ClientResponse result = client.sendRequest("POST", mainPath + "projects", testProject, + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + System.out.println(result.toString()); + System.out.println("Result of 'testPost': " + result.getResponse().trim()); + assertEquals(201, result.getHttpCode()); + + JsonObject response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + assertTrue(response.isJsonObject()); + + // gson doesn't remove the quotes + assertTrue(isValidISO8601(response.get("creationDate").toString().replace("\"", ""))); + assertTrue(response.has("userContext")); + assertTrue(response.has("additionalProperties")); + + JsonObject userContext = response.getAsJsonObject("userContext"); + assertTrue(userContext.has("userRole")); + assertTrue(userContext.has("isFollower")); + + result = client.sendRequest("DELETE", mainPath + "projects/" + response.get("id").getAsString(), ""); + assertEquals(204, result.getHttpCode()); + + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(e.toString()); + } + } + + /** + * Test to get a list of projects + */ + @Test + public void testGetProjects() { + try { + MiniClient client = getClient(); + MiniClient adminClient = getAdminClient(); + + ClientResponse result = client.sendRequest("GET", mainPath + "projects?recursive=true", ""); + + assertEquals(200, result.getHttpCode()); + JsonElement response = JsonParser.parseString(result.getResponse()); + System.out.println(response.toString()); + assertTrue(response.isJsonArray()); + + // Now for a specific project + result = client.sendRequest("GET", mainPath + "projects/" + testProject.getId(), ""); + + assertEquals(200, result.getHttpCode()); + response = JsonParser.parseString(result.getResponse()); + System.out.println(response.toString()); + assertTrue(response.isJsonObject()); + + JsonObject jsonObject = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + assertTrue(isValidISO8601(jsonObject.get("creationDate").toString().replace("\"", ""))); + // Normal user has no project role + assertTrue(jsonObject.has("userContext")); + JsonObject userContext = jsonObject.getAsJsonObject("userContext"); + assertFalse(userContext.has("userRole")); + assertTrue(userContext.has("isFollower")); + + // Test with admin + // Now for a specific project + result = adminClient.sendRequest("GET", mainPath + "projects/" + testProject.getId(), ""); + assertEquals(200, result.getHttpCode()); + + response = JsonParser.parseString(result.getResponse()); + System.out.println(response.toString()); + assertTrue(response.isJsonObject()); + + jsonObject = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + userContext = jsonObject.getAsJsonObject("userContext"); + assertTrue(userContext.has("userRole")); + assertTrue(userContext.has("isFollower")); + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + + /** + * Test create a new category + */ + @Test + public void testCategories() { + try { + MiniClient client = getClient(); + MiniClient adminClient = getAdminClient(); + + String testCategory = "{\"name\": \"Test Category\", \"description\": \"A test category\", \"additionalProperties\": {\"testProperty\": \"test\"}, \"projectId\":" + testProject.getId() + "}"; + String path = mainPath + "categories"; + + // Plebs --> no permission + ClientResponse result = client.sendRequest("POST", path, testCategory, + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + assertEquals(401, result.getHttpCode()); + + // Admin and owner --> permission + result = adminClient.sendRequest("POST", path, testCategory, + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + assertEquals(201, result.getHttpCode()); + + JsonObject response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + assertTrue(response.isJsonObject()); + System.out.println(response); + + result = client.sendRequest("GET", mainPath + "projects/" + testProject.getId() + "/categories", ""); + assertEquals(200, result.getHttpCode()); + + JsonElement resp = JsonParser.parseString(result.getResponse()); + System.out.println(resp); + assertTrue(resp.isJsonArray()); + assertEquals(2, resp.getAsJsonArray().size()); + + JsonObject createdCategory = resp.getAsJsonArray().get(1).getAsJsonObject(); + + assertTrue(createdCategory.has("lastActivity")); + assertTrue(createdCategory.has("additionalProperties")); + + assertTrue(isValidISO8601(createdCategory.get("creationDate").toString().replace("\"", ""))); + assertTrue(isValidISO8601(createdCategory.get("lastActivity").toString().replace("\"", ""))); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + + /** + * Test create a new requirement + */ + @Test + public void testRequirements() { + try { + MiniClient client = getClient(); + + String testRequirement = String.format("{\"name\": \"Test Requirements\", \"description\": \"A test requirement\", \"categories\": [%s], \"projectId\": \"%s\", \"tags\": [{\"name\": \"CreateTest\", \"colour\": \"#FFFFFF\"}], \"additionalProperties\": {\"testProperty\": \"test\"}, \"attachments\": [ { \"name\": \"wine.jpg\", \"mimeType\": \"image/jpeg\", \"identifier\": \"dc5562a3-fd6f-4401-b6d3-d97830cd2b5d\", \"fileUrl\": \"http://localhost/files/dc5562a3-fd6f-4401-b6d3-d97830cd2b5d\"}]}", testProject.getDefaultCategoryId(), testProject.getId()); + ClientResponse result = client.sendRequest("POST", mainPath + "requirements", testRequirement, + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + assertEquals(201, result.getHttpCode()); + JsonObject response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + assertTrue(response.isJsonObject()); + System.out.println(response); + + result = client.sendRequest("GET", mainPath + "requirements", ""); + assertEquals(200, result.getHttpCode()); + + JsonElement resp = JsonParser.parseString(result.getResponse()); + System.out.println(resp); + assertTrue(resp.isJsonArray()); + assertEquals(2, resp.getAsJsonArray().size()); + + JsonObject createdRequirement = resp.getAsJsonArray().get(1).getAsJsonObject(); + + assertTrue(createdRequirement.has("lastActivity")); + assertTrue(createdRequirement.has("additionalProperties")); + assertTrue(isValidISO8601(createdRequirement.get("creationDate").toString().replace("\"", ""))); + assertTrue(isValidISO8601(createdRequirement.get("lastActivity").toString().replace("\"", ""))); + + + // Test by category + result = client.sendRequest("GET", mainPath + "categories/" + testProject.getDefaultCategoryId() + "/requirements", ""); + assertEquals(200, result.getHttpCode()); + + resp = JsonParser.parseString(result.getResponse()); + System.out.println(resp); + assertTrue(resp.isJsonArray()); + assertEquals(2, resp.getAsJsonArray().size()); + + createdRequirement = resp.getAsJsonArray().get(1).getAsJsonObject(); + + assertTrue(createdRequirement.has("lastActivity")); + assertTrue(isValidISO8601(createdRequirement.get("creationDate").toString().replace("\"", ""))); + assertTrue(isValidISO8601(createdRequirement.get("lastActivity").toString().replace("\"", ""))); + + // Test update + createdRequirement.addProperty("description", "Updated Description"); + createdRequirement.add("attachments", JsonParser.parseString("[{ \"name\": \"wine.jpg\", \"mimeType\": \"image/jpeg\", \"identifier\": \"06e42de9-fc36-4d31-b341-09f01d012d9c\", \"fileUrl\": \"http://localhost/files/06e42de9-fc36-4d31-b341-09f01d012d9c\"}]")); + result = client.sendRequest("PUT", mainPath + "requirements", createdRequirement.toString(), + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + assertEquals(200, result.getHttpCode()); + response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + assertTrue(response.isJsonObject()); + System.out.println(response); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + + /** + * Test to get a list of projects + */ + @Test + public void testMembers() { + try { + MiniClient client = getClient(); + MiniClient adminClient = getAdminClient(); + + String path = mainPath + "projects/" + testProject.getId() + "/members"; + ClientResponse result = client.sendRequest("GET", path, ""); + assertEquals(200, result.getHttpCode()); + + JsonElement response = JsonParser.parseString(result.getResponse()); + System.out.println(response.toString()); + assertTrue(response.isJsonArray()); + + // Now add user role + String testRequest = String.format("[{\"userId\": %s, \"role\": \"ProjectMember\"}]", adamId); + result = adminClient.sendRequest("PUT", path, testRequest, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + assertEquals(204, result.getHttpCode()); + + result = client.sendRequest("GET", path, ""); + assertEquals(200, result.getHttpCode()); + + response = JsonParser.parseString(result.getResponse()); + System.out.println(response.toString()); + assertTrue(response.isJsonArray()); + + assertEquals(2, response.getAsJsonArray().size()); + + // And now delete again + String delPath = mainPath + "projects/" + testProject.getId() + "/members/" + adamId; + result = client.sendRequest("DELETE", delPath, ""); + assertEquals(401, result.getHttpCode()); + result = adminClient.sendRequest("DELETE", delPath, ""); + assertEquals(204, result.getHttpCode()); + + result = client.sendRequest("GET", path, ""); + assertEquals(200, result.getHttpCode()); + + response = JsonParser.parseString(result.getResponse()); + System.out.println(response.toString()); + assertTrue(response.isJsonArray()); + + assertEquals(1, response.getAsJsonArray().size()); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + + /** + * Test to create feedback for the reference project + */ + @Test + public void testCreateFeedback() { + try { + MiniClient client = getClient(); + + String testFeedback = String.format("{\"feedback\": \"Crashes all the time\", \"projectId\": %s}", testProject.getId()); + ClientResponse result = client.sendRequest("POST", mainPath + "feedback", testFeedback, + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + System.out.println(result.toString()); + System.out.println("Result of 'testPost': " + result.getResponse().trim()); + assertEquals(201, result.getHttpCode()); + + JsonObject response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + assertTrue(response.isJsonObject()); + + // gson doesn't remove the quotes + assertTrue(isValidISO8601(response.get("creationDate").toString().replace("\"", ""))); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + + /** + * Test to create feedback for the reference project + * but include an email in the request + */ + @Test + public void testCreateFeedbackWithMail() { + try { + MiniClient client = getClient(); + + String testFeedback = String.format("{\"feedback\": \"Crashes all the time\", \"projectId\": %s, \"email\": \"%s\"}", testProject.getId(), initUser.getEMail()); + ClientResponse result = client.sendRequest("POST", mainPath + "feedback", testFeedback, + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + System.out.println(result.toString()); + System.out.println("Result of 'testPost': " + result.getResponse().trim()); + assertEquals(201, result.getHttpCode()); + + JsonObject response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + Assert.assertTrue(response.isJsonObject()); + + // gson doesn't remove the quotes + Assert.assertTrue(isValidISO8601(response.get("creationDate").toString().replace("\"", ""))); + + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(e.toString()); + } + } + + /** + * Test to not authorized on feedbacks + */ + @Test + public void testGetFeedbacks() { + try { + MiniClient client = getClient(); + MiniClient adminClient = getAdminClient(); + + String path = mainPath + "projects/" + testProject.getId() + "/feedbacks"; + ClientResponse result = client.sendRequest("GET", path, ""); + + System.out.println(result.getResponse()); + + assertEquals(401, result.getHttpCode()); + + result = adminClient.sendRequest("GET", path, ""); + + System.out.println(result.getResponse()); + + assertEquals(200, result.getHttpCode()); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(e.toString()); + } + } + + /** + * Test to search for a user + */ + @Test + public void testSearchUser() { + try { + MiniClient client = getClient(); + + ClientResponse result = client.sendRequest("GET", mainPath + "users?search=elek", ""); + JsonElement response = JsonParser.parseString(result.getResponse()); + System.out.println(response.toString()); + assertEquals(200, result.getHttpCode()); + + assertTrue(response.isJsonArray()); + assertEquals(1, response.getAsJsonArray().size()); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + + /** + * Test to search for a user + */ + @Test + public void testUserJsonView() { + try { + MiniClient client = getClient(); + + ClientResponse result = client.sendRequest("GET", mainPath + "users/me", ""); + System.out.println(result.toString()); + assertEquals(200, result.getHttpCode()); + + JsonObject response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + assertTrue(response.isJsonObject()); + assertTrue(response.has("email")); + assertTrue(response.has("emailFollowSubscription")); + + result = client.sendRequest("GET", mainPath + "users/" + initUser.getId(), ""); + System.out.println(result.toString()); + assertEquals(200, result.getHttpCode()); + + response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + assertTrue(response.isJsonObject()); + assertFalse(response.has("email")); + assertFalse(response.has("emailFollowSubscription")); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + + /** + * Test to get user dashboard + */ + @Test + public void testDashboard() { + try { + MiniClient client = getAdminClient(); + + ClientResponse result = client.sendRequest("GET", mainPath + "users/me/dashboard", ""); + System.out.println(result.toString()); + assertEquals(200, result.getHttpCode()); + + JsonObject response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + assertTrue(response.isJsonObject()); + assertTrue(response.has("projects")); + assertTrue(response.has("categories")); + assertTrue(response.has("requirements")); + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + + /** + * Test creating and updating comments + */ + @Test + public void testComments() { + MiniClient client = getClient(); + String testComment = String.format("{\"message\": \"Crashes all the time\", \"requirementId\": %s}", testRequirement.getId()); + ClientResponse result = client.sendRequest("POST", mainPath + "comments", testComment, + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + System.out.println(result.toString()); + System.out.println("Result of 'testPost': " + result.getResponse().trim()); + assertEquals(201, result.getHttpCode()); + + JsonObject response = JsonParser.parseString(result.getResponse()).getAsJsonObject(); + Assert.assertTrue(response.isJsonObject()); + + assertTrue(response.has("id")); + assertTrue(isValidISO8601(response.get("creationDate").toString().replace("\"", ""))); + + // Test update + response.addProperty("message", "Updated message"); + result = client.sendRequest("PUT", mainPath + "comments", response.toString(), + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + assertEquals(200, result.getHttpCode()); + } + + /** + * Test to get a list of tags on a project + */ + @Test + public void testTags() { + try { + MiniClient client = getClient(); + MiniClient adminClient = getAdminClient(); + + String path = mainPath + "projects/" + testProject.getId() + "/tags"; + ClientResponse result = client.sendRequest("GET", path, ""); + assertEquals(200, result.getHttpCode()); + + JsonElement response = JsonParser.parseString(result.getResponse()); + System.out.println(response.toString()); + assertTrue(response.isJsonArray()); + + // Now create + String testRequest = "{\"name\": \"Feature\", \"colour\": \"#00FF00\"}"; + ClientResponse newResult = adminClient.sendRequest("POST", path, testRequest, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + assertEquals(201, newResult.getHttpCode()); + Integer tagId = JsonParser.parseString(newResult.getResponse()).getAsJsonObject().get("id").getAsInt(); + + result = client.sendRequest("GET", path, ""); + assertEquals(200, result.getHttpCode()); + + response = JsonParser.parseString(result.getResponse()); + System.out.println(response.toString()); + assertTrue(response.isJsonArray()); + assertEquals(2, response.getAsJsonArray().size()); + + // Now try to add one of these tags and an entirely new one to a requirement + result = client.sendRequest("GET", mainPath + "requirements/" + testRequirement.getId(), ""); + assertEquals(200, result.getHttpCode()); + + JsonElement resp = JsonParser.parseString(result.getResponse()); + JsonObject requirement = resp.getAsJsonObject(); + + // Create Tag array and add it to the JsonObject + JsonArray newTags = JsonParser.parseString(String.format("[{\"id\": %s, \"name\": \"Feature\", \"colour\": \"#00FF00\"}, {\"name\": \"Test\", \"colour\": \"#0000FF\"}]", tagId)).getAsJsonArray(); + requirement.add("tags", newTags); + + + result = adminClient.sendRequest("PUT", mainPath + "requirements", requirement.toString(), + MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, new HashMap<>()); + System.out.println(result.getResponse()); + assertEquals(200, result.getHttpCode()); + + response = JsonParser.parseString(result.getResponse()); + assertTrue(response.isJsonObject()); + assertEquals(2, response.getAsJsonObject().get("tags").getAsJsonArray().size()); + + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + + + /** + * Test notification flush endpoint authorizations + */ + @Test + public void testNotifications() { + try { + MiniClient client = getClient(); + MiniClient adminClient = getAdminClient(); + + String path = mainPath + "notifications"; + ClientResponse result = client.sendRequest("POST", path, ""); + assertEquals(401, result.getHttpCode()); + + // Admin privilege check should pass + result = adminClient.sendRequest("POST", path, ""); + assertEquals(200, result.getHttpCode()); + + + } catch (Exception e) { + e.printStackTrace(); + fail(e.toString()); + } + } + +} diff --git a/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/TestBase.java b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/TestBase.java new file mode 100644 index 00000000..1ed1f4b1 --- /dev/null +++ b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/TestBase.java @@ -0,0 +1,119 @@ +package de.rwth.dbis.acis.bazaar.service; + +import de.rwth.dbis.acis.bazaar.service.helpers.SetupData; +import i5.las2peer.api.p2p.ServiceNameVersion; +import i5.las2peer.connectors.webConnector.WebConnector; +import i5.las2peer.connectors.webConnector.client.MiniClient; +import i5.las2peer.p2p.LocalNode; +import i5.las2peer.p2p.LocalNodeManager; +import i5.las2peer.security.UserAgentImpl; +import i5.las2peer.testing.MockAgentFactory; +import org.junit.After; +import org.junit.Before; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Example Test Class demonstrating a basic JUnit test structure. + */ +public abstract class TestBase extends SetupData { + + static final String mainPath = "bazaar/"; + static final String testVersion = "1.0.0"; + private static final String testPass = "adamspass"; + private static final String adminPass = "evespass"; + private static LocalNode node; + private static WebConnector connector; + private static ByteArrayOutputStream logStream; + private static UserAgentImpl testAgent; + private static UserAgentImpl adminAgent; + + + /** + * Called before a test starts. + *

+ * Sets up the node, initializes connector and adds user agent that can be used throughout the test. + * + * @throws Exception + */ + @Before + public void startServer() throws Exception { + // start node + node = new LocalNodeManager().newNode(); + node.launch(); + + // add agent to node + testAgent = MockAgentFactory.getAdam(); + testAgent.unlock(testPass); // agents must be unlocked in order to be stored + node.storeAgent(testAgent); + + // add agent to node + adminAgent = MockAgentFactory.getEve(); + adminAgent.unlock(adminPass); // agents must be unlocked in order to be stored + node.storeAgent(adminAgent); + + + // start service + // during testing, the specified service version does not matter + node.startService(new ServiceNameVersion(BazaarService.class.getName(), testVersion), "a pass"); + + // start connector + connector = new WebConnector(true, 0, false, 0); // port 0 means use system defined port + logStream = new ByteArrayOutputStream(); + connector.setLogStream(new PrintStream(logStream)); + connector.start(node); + } + + /** + * Called after the test has finished. Shuts down the server and prints out the connector log file for reference. + * + * @throws Exception + */ + @After + public void shutDownServer() throws Exception { + if (connector != null) { + connector.stop(); + connector = null; + } + if (node != null) { + node.shutDown(); + node = null; + } + if (logStream != null) { + System.out.println("Connector-Log:"); + System.out.println("--------------"); + System.out.println(logStream.toString()); + logStream = null; + } + } + + MiniClient getClient() { + MiniClient client = new MiniClient(); + client.setConnectorEndpoint(connector.getHttpEndpoint()); + + client.setLogin(testAgent.getIdentifier(), testPass); + return client; + } + + MiniClient getAdminClient() { + MiniClient client = new MiniClient(); + client.setConnectorEndpoint(connector.getHttpEndpoint()); + + client.setLogin(adminAgent.getIdentifier(), adminPass); + return client; + } + + boolean isValidISO8601(String dateStr) { + DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + try { + dateFormatter.parse(dateStr); + } catch (DateTimeParseException e) { + e.printStackTrace(); + return false; + } + return true; + } +} diff --git a/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java new file mode 100644 index 00000000..0c053333 --- /dev/null +++ b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java @@ -0,0 +1,392 @@ +/* + * + * Copyright (c) 2014, RWTH Aachen University. + * For a list of contributors see the AUTHORS file at the top-level directory + * of this distribution. + * + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * / + */ + +package de.rwth.dbis.acis.bazaar.service.dal; + +import de.rwth.dbis.acis.bazaar.dal.jooq.tables.records.ProjectRecord; +import de.rwth.dbis.acis.bazaar.service.dal.entities.*; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; +import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; +import de.rwth.dbis.acis.bazaar.service.helpers.SetupData; +import org.junit.Assert; +import org.junit.Test; + +import java.util.List; + +import static junit.framework.TestCase.*; + +//TODO Pagination testing +public class DALFacadeTest extends SetupData { + + public static final PageInfo ALL_IN_ONE_PAGE = new PageInfo(0, 100); + + @Test + public void testCreateUser() { + try { + facade.createUser(User.builder().eMail("unittest@test.hu").firstName("Max").lastName("Zimmermann").las2peerId("9999").userName("MaxZim").personalizationEnabled(false).emailFollowSubscription(false).emailLeadSubscription(false).build()); + + Integer userId = facade.getUserIdByLAS2PeerId("9999"); + User user = facade.getUserById(userId); + + assertEquals("unittest@test.hu", user.getEMail()); + assertEquals("Max", user.getFirstName()); + assertEquals("Zimmermann", user.getLastName()); + assertEquals("9999", user.getLas2peerId()); + + jooq.delete(de.rwth.dbis.acis.bazaar.dal.jooq.tables.User.USER).where(de.rwth.dbis.acis.bazaar.dal.jooq.tables.User.USER.ID.eq(userId)).execute(); + + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(e.toString()); + } + } + + @Test + public void testGetUserById() throws Exception { + Integer userId = facade.getUserIdByLAS2PeerId(eveId); + User user = facade.getUserById(userId); + + assertEquals("test@test.hu", user.getEMail()); + assertEquals("Elek", user.getFirstName()); + assertEquals("Test", user.getLastName()); + assertEquals(eveId, user.getLas2peerId()); + } + + @Test + public void testCreateGetProject() throws Exception { + Project project = Project.builder().name("Project3 \uD83D\uDC69\u200D\uD83D\uDC69\u200D\uD83D\uDC67\u200D\uD83D\uDC66").description("An \uD83D\uDE00awesome \uD83D\uDE03string with a few \uD83D\uDE09emojis!").id(1).leader(initUser).visibility(true).build(); + + facade.createProject(project, initUser.getId()); + + // This can't work reliably without fetching by name + // Id is set by the database but never returned + ProjectRecord projectRecord = jooq.selectFrom(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project.PROJECT).where(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project.PROJECT.NAME.equal("Project3 \uD83D\uDC69\u200D\uD83D\uDC69\u200D\uD83D\uDC67\u200D\uD83D\uDC66")).fetchOne(); + assertNotNull(projectRecord); + Integer projectID = projectRecord.getId(); // .get(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project.PROJECT.ID); + + Project projectById = facade.getProjectById(projectID, initUser.getId()); + + assertEquals(project.getName(), projectById.getName()); + assertEquals(project.getDescription(), projectById.getDescription()); + assertEquals("An 😀awesome 😃string with a few 😉emojis!", projectById.getDescription()); + assertEquals(project.getLeader().getId(), projectById.getLeader().getId()); + assertEquals(project.getVisibility(), projectById.getVisibility()); + assertTrue(projectById.isOwner(initUser)); + assertEquals(ProjectRole.ProjectAdmin, projectById.getUserContext().getUserRole()); + + // Now check if this can also be found as a public project + PaginationResult projectsPage = facade.listPublicProjects(new PageInfo(0, 10), initUser.getId()); + + List projects = projectsPage.getElements(); + + assertNotNull(projects); + + Project proj = null; + for (Project pr : projects) { + assertTrue(pr.getVisibility()); + + if (pr.getId() == projectById.getId()) proj = pr; + } + + assertNotNull(proj); + + assertEquals(projectById.getId(), proj.getId()); + assertEquals(projectById.getName(), proj.getName()); + assertEquals(projectById.getDescription(), proj.getDescription()); + assertEquals(projectById.getLeader().getId(), proj.getLeader().getId()); + assertEquals(projectById.getVisibility(), proj.getVisibility()); + + + jooq.delete(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project.PROJECT).where(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project.PROJECT.ID.equal(project.getId())).execute(); + } + + @Test + public void testGetProjectMembers() throws Exception { + PaginationResult membersPage = facade.getProjectMembers(testProject.getId(), new PageInfo(0, 100)); + + List members = membersPage.getElements(); + + assertNotNull(members); + assertEquals(1, members.size()); + } + + @Test + public void testListPublicProjects() throws Exception { + + } + + @Test + public void testFeedback() { + try { + Feedback createdFeedback = facade.createFeedback(Feedback.builder().projectId(testProject.getId()).feedback("Crashes all the time.").build()); + + assertNull(createdFeedback.getEMail()); + assertNotNull(createdFeedback.getCreationDate()); + assertEquals("Crashes all the time.", createdFeedback.getFeedback()); + assertEquals(testProject.getId(), createdFeedback.getProjectId()); + + Feedback createdFeedbackWithMail = facade.createFeedback(Feedback.builder().projectId(testProject.getId()).feedback("Crashes all the time.").eMail(initUser.getEMail()).build()); + assertEquals(initUser.getEMail(), createdFeedbackWithMail.getEMail()); + + PaginationResult feedbackPage = facade.getFeedbackByProject(testProject.getId(), new PageInfo(0, 20)); + + List feedbackByProject = feedbackPage.getElements(); + + assertNotNull(feedbackByProject); + assertEquals(2, feedbackByProject.size()); + + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(e.toString()); + } + + } + + @Test + public void testCreateCategory() throws Exception { + String name = "TestComp9"; + Category testComp9 = Category.builder() + .name(name) + .description("Very testing") + .projectId(testProject.getId()) + .creator(initUser) + .build(); + + facade.createCategory(testComp9, initUser.getId()); + + List components = facade.listCategoriesByProjectId(testProject.getId(), ALL_IN_ONE_PAGE, initUser.getId()).getElements(); + + assertNotNull(components); + assertEquals(2,components.size()); + + components.forEach(category -> { + if (category.getName().equals(name)) { + jooq.delete(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Category.CATEGORY).where(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Category.CATEGORY.ID.equal(category.getId())).execute(); + } + }); + } + + @Test + public void testComments() throws Exception { + Comment testComment = Comment.builder() + .message("TestComment") + .requirementId(testRequirement.getId()) + .creator(initUser) + .build(); + + Comment createdComment = facade.createComment(testComment); + + List comments = facade.listCommentsByRequirementId(testRequirement.getId()); + + assertNotNull(comments); + assertEquals(1,comments.size()); + assertEquals(createdComment.getId(), comments.get(0).getId()); + + createdComment.setMessage("Updated message"); + + Comment updatedComment = facade.updateComment(createdComment); + + assertNotNull(updatedComment); + assertEquals("Updated message", updatedComment.getMessage()); + + facade.deleteCommentById(updatedComment.getId()); + + comments = facade.listCommentsByRequirementId(testRequirement.getId()); + assertNotNull(comments); + assertEquals(0,comments.size()); + + testComment = Comment.builder() + .message("TestComment") + .requirementId(testRequirement.getId()) + .creator(initUser) + .build(); + + createdComment = facade.createComment(testComment); + + Comment responseComment = Comment.builder() + .message("TestResponse") + .requirementId(testRequirement.getId()) + .replyToComment(createdComment.getId()) + .creator(initUser) + .build(); + + responseComment = facade.createComment(responseComment); + + facade.deleteCommentById(createdComment.getId()); + + Comment deletedComment = facade.getCommentById(createdComment.getId()); + + assertNotNull(deletedComment); + assertTrue(deletedComment.getDeleted()); + } + + /* Doesn't work, searching breaks + public void testModifyProject() throws Exception { + //TODO + } + + public void testListRequirements() throws Exception { + List requirements = facade.listRequirements(ALL_IN_ONE_PAGE); + + assertNotNull(requirements); + assertEquals(3, requirements.size()); + + Requirement requirement = requirements.get(2); + + assertEquals(1,requirement.getId()); + assertEquals(1,requirement.getCreator().getId()); + assertEquals(1,requirement.getLeadDeveloper().getId()); + assertEquals(1,requirement.getProjectId()); + assertEquals("Req1",requirement.getName()); + assertEquals("ReqDesc1",requirement.getDescription()); + + requirements = facade.listRequirements(new PageInfo(1, 2)); + + assertNotNull(requirements); + assertEquals(1, requirements.size()); + assertEquals(1,requirements.get(0).getId()); + + requirements = facade.listRequirements(new PageInfo(0, 1)); + + assertNotNull(requirements); + assertEquals(1, requirements.size()); + assertEquals(3,requirements.get(0).getId()); + } + + public void testListRequirementsByProject() throws Exception { + List requirements = (List) facade.listRequirementsByProject(2, ALL_IN_ONE_PAGE, 1); + + assertNotNull(requirements); + assertEquals(1, requirements.size()); + + Requirement requirement2 = requirements.get(0); + + assertEquals(2,requirement2.getId()); + assertEquals(1,requirement2.getCreator().getId()); + assertEquals(1,requirement2.getLeadDeveloper().getId()); + assertEquals(2,requirement2.getProjectId()); + assertEquals("Req2",requirement2.getName()); + assertEquals("ReqDesc2",requirement2.getDescription()); + + + } + + public void testGetRequirementById() throws Exception { + Requirement requirement = facade.getRequirementById(2, 1); + + assertEquals(2, requirement.getId()); + + assertEquals(initUser, requirement.getCreator()); + assertEquals(initUser,requirement.getCreator()); + assertEquals(initUser.getFirstName(),requirement.getCreator().getFirstName()); + + assertEquals(initUser,requirement.getLeadDeveloper()); + assertEquals(1,requirement.getLeadDeveloper().getId()); + assertEquals("Elek",requirement.getLeadDeveloper().getFirstName()); + + assertEquals(2,requirement.getProjectId()); + assertEquals("Req2",requirement.getName()); + assertEquals("ReqDesc2",requirement.getDescription()); + + List attachments = requirement.getAttachments(); + assertNotNull(attachments); + assertEquals(1, attachments.size()); + assertEquals(2, attachments.get(0).getCreator().getId()); + + List components = requirement.getCategories(); + assertNotNull(components); + assertEquals(1,components.size()); + assertEquals(1, components.get(0).getId()); + assertEquals("Comp1",components.get(0).getName()); + } + + public void testCreateRequirement() throws Exception { + int createdRequirementId = 9; + try { + Requirement requirement = Requirement.getBuilder("AddedReq1").id(createdRequirementId).description("Test addition").creator(initUser).leadDeveloper(initUser).projectId(3).build(); + + facade.createRequirement(requirement, initUser.getId()); + + Requirement requirementById = facade.getRequirementById(createdRequirementId, 1); + + assertEquals(requirement.getId(), requirementById.getId()); + assertEquals(requirement.getName(), requirementById.getName()); + assertEquals(requirement.getDescription(), requirementById.getDescription()); + assertEquals(requirement.getCreator(), requirementById.getCreator()); + assertEquals(requirement.getLeadDeveloper(), requirementById.getLeadDeveloper()); + assertEquals(requirement.getProjectId(), requirementById.getProjectId()); + } catch (Exception e) { + e.printStackTrace(); + Assert.fail(e.toString()); + } + } + + public void testModifyRequirement() throws Exception { + //TODO + } + + public void testDeleteRequirementById() throws Exception { + Requirement requirement = Requirement.getBuilder("AddedReq1").id(9).description("Test addition").creator(initUser).leadDeveloper(initUser).projectId(3).build(); + + facade.createRequirement(requirement, initUser.getId()); + + facade.deleteRequirementById(9, initUser.getId()); + + try { + Requirement requirementById = facade.getRequirementById(9, 1); + } + catch (Exception ex){ + assertEquals("No class de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementsRecord found with id: 9", ex.getMessage()); + } + } + + public void testListComponentsByProjectId() throws Exception { + List components = (List) facade.listCategoriesByProjectId(2, ALL_IN_ONE_PAGE, 1); + + assertNotNull(components); + assertEquals(1,components.size()); + assertEquals(1,components.get(0).getId()); + } + + public void testModifyComponent() throws Exception { + //TODO + } + + public void testDeleteComponentById() throws Exception { + //TODO + } + + public void testVoteAndUnvote() throws Exception { + boolean hasUserVotedForRequirement = facade.hasUserVotedForRequirement(3, 1); + + assertFalse(hasUserVotedForRequirement); + + facade.vote(3,1,true); + hasUserVotedForRequirement = facade.hasUserVotedForRequirement(3, 1); + + assertTrue(hasUserVotedForRequirement); + + facade.unVote(3,1); + hasUserVotedForRequirement = facade.hasUserVotedForRequirement(3, 1); + + assertFalse(hasUserVotedForRequirement); + } + */ +} diff --git a/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/helpers/SetupData.java b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/helpers/SetupData.java new file mode 100644 index 00000000..3e2f63d5 --- /dev/null +++ b/reqbaz/src/test/java/de/rwth/dbis/acis/bazaar/service/helpers/SetupData.java @@ -0,0 +1,101 @@ +package de.rwth.dbis.acis.bazaar.service.helpers; + +import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; +import de.rwth.dbis.acis.bazaar.service.dal.DALFacadeImpl; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Project; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Requirement; +import de.rwth.dbis.acis.bazaar.service.dal.entities.Tag; +import de.rwth.dbis.acis.bazaar.service.dal.entities.User; +import de.rwth.dbis.acis.bazaar.service.internalization.Localization; +import org.apache.commons.dbcp2.BasicDataSource; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.junit.After; +import org.junit.Before; + +import javax.sql.DataSource; +import java.util.List; +import java.util.Locale; +import java.util.ResourceBundle; + +public abstract class SetupData { + public DALFacade facade; + public DALFacadeImpl dalImpl; + public DSLContext jooq; + public User initUser; + public Project testProject; + public Requirement testRequirement; + // las2peer id of eve (defined in the testing components of las2peer) + public String eveId = "799dea0f00e126dc3493f362bddbddbc55bdfbb918fce3b12f68e1340a8ea7de7aaaa8a7af900b6ee7f849a524b18649d4ae80cb406959568f405a487f085ac7"; + + private static DataSource setupDataSource(String dbUrl, String dbUserName, String dbPassword) { + BasicDataSource dataSource = new BasicDataSource(); + // Deprecated according to jooq + // dataSource.setDriverClassName("com.mysql.jdbc.Driver"); + dataSource.setUrl(dbUrl); + dataSource.setUsername(dbUserName); + dataSource.setPassword(dbPassword); + dataSource.setValidationQuery("SELECT 1;"); + dataSource.setTestOnBorrow(true); // test each connection when borrowing from the pool with the validation query + dataSource.setMaxConnLifetimeMillis(1000 * 60 * 60); // max connection life time 1h. mysql drops connection after 8h. + return dataSource; + } + + @Before + public void setUp() throws Exception { + String url = "jdbc:postgresql://localhost:5432/reqbaz"; + + DataSource dataSource = setupDataSource(url, "reqbaz", "reqbaz"); + + dalImpl = new DALFacadeImpl(dataSource, SQLDialect.POSTGRES); + facade = dalImpl; + jooq = dalImpl.getDslContext(); + + Locale locale = new Locale("en", "us"); + Localization.getInstance().setResourceBundle(ResourceBundle.getBundle("i18n.Translation", locale)); + + try { + initUser = facade.getUserById(facade.getUserIdByLAS2PeerId(eveId)); + } catch (Exception e) { + initUser = User.builder() + .eMail("test@test.hu") + .firstName("Elek") + .lastName("Test") + .userName("TestElek") + .las2peerId(eveId) + .build(); + + facade.createUser(initUser); + initUser = facade.getUserById(facade.getUserIdByLAS2PeerId(eveId)); + facade.addUserToRole(initUser.getId(), "SystemAdmin", null); + } + try { + testProject = facade.getProjectById(0, initUser.getId()); + testRequirement = facade.getRequirementById(0, initUser.getId()); + } catch (Exception e) { + testProject = Project.builder().name("ProjectTest").description("ProjDesc").leader(initUser).visibility(true).build(); + testProject = facade.createProject(testProject, initUser.getId()); + + + facade.createTag(Tag.builder() + .name("Bug") + .colour("#FF0000") + .projectId(testProject.getId()) + .build()); + + testRequirement = Requirement.builder() + .name("Test") + .description("Test") + .categories(List.of(testProject.getDefaultCategoryId())) + .projectId(testProject.getId()) + .creator(initUser) + .build(); + testRequirement = facade.createRequirement(testRequirement, initUser.getId()); + } + } + + @After + public void tearDown() { + jooq.delete(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project.PROJECT).where(de.rwth.dbis.acis.bazaar.dal.jooq.tables.Project.PROJECT.ID.eq(testProject.getId())).execute(); + } +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 00000000..c7169383 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,11 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * + * Detailed information about configuring a multi-project build in Gradle can be found + * in the user manual at https://docs.gradle.org/6.7/userguide/multi_project_builds.html + */ + +rootProject.name = 'Requirements Bazaar' +include('reqbaz') diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/AttachmentsResource.java b/src/main/de/rwth/dbis/acis/bazaar/service/AttachmentsResource.java deleted file mode 100644 index 41689dc1..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/AttachmentsResource.java +++ /dev/null @@ -1,310 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service; - -import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; -import de.rwth.dbis.acis.bazaar.service.dal.entities.*; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; -import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; -import de.rwth.dbis.acis.bazaar.service.internalization.Localization; -import de.rwth.dbis.acis.bazaar.service.security.AuthorizationManager; -import i5.las2peer.api.Context; -import i5.las2peer.api.logging.MonitoringEvent; -import i5.las2peer.api.security.Agent; -import i5.las2peer.logging.L2pLogger; -import io.swagger.annotations.*; -import jodd.vtor.Vtor; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.net.HttpURLConnection; -import java.util.*; - - -@Api(value = "attachments", description = "Attachments resource") -@SwaggerDefinition( - info = @Info( - title = "Requirements Bazaar", - version = "0.6", - description = "Requirements Bazaar project", - termsOfService = "http://requirements-bazaar.org", - contact = @Contact( - name = "Requirements Bazaar Dev Team", - url = "http://requirements-bazaar.org", - email = "info@requirements-bazaar.org" - ), - license = @License( - name = "Apache2", - url = "http://requirements-bazaar.org/license" - ) - ), - schemes = SwaggerDefinition.Scheme.HTTPS -) -@Path("/attachments") -public class AttachmentsResource { - - private final L2pLogger logger = L2pLogger.getInstance(AttachmentsResource.class.getName()); - private BazaarService bazaarService; - - public AttachmentsResource() throws Exception { - bazaarService = (BazaarService) Context.getCurrent().getService(); - } - - /** - * This method returns the list of attachments for a specific requirement. - * - * @param requirementId id of the requirement - * @param page page number - * @param perPage number of projects by page - * @return Response with comments as a JSON array. - */ - public Response getAttachmentsForRequirement(int requirementId, int page, int perPage) { - DALFacade dalFacade = null; - try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } - PageInfo pageInfo = new PageInfo(page, perPage); - Vtor vtor = bazaarService.getValidators(); - vtor.validate(pageInfo); - if (vtor.hasViolations()) ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - dalFacade = bazaarService.getDBConnection(); - //Todo use requirement's projectId for security context, not the one sent from client - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Requirement requirement = dalFacade.getRequirementById(requirementId, internalUserId); - Project project = dalFacade.getProjectById(requirement.getProjectId(), internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE_CHILD, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_44, - requirement.getId(), Activity.DataType.REQUIREMENT, internalUserId); - if (dalFacade.isRequirementPublic(requirementId)) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_COMMENT, String.valueOf(project.getId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_COMMENT, String.valueOf(project.getId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.comment.read")); - } - } - PaginationResult attachmentsResult = dalFacade.listAttachmentsByRequirementId(requirementId, pageInfo); - - Map> parameter = new HashMap<>(); - parameter.put("page", new ArrayList() {{ - add(String.valueOf(page)); - }}); - parameter.put("per_page", new ArrayList() {{ - add(String.valueOf(perPage)); - }}); - - Response.ResponseBuilder responseBuilder = Response.ok(); - responseBuilder = responseBuilder.entity(attachmentsResult.toJSON()); - responseBuilder = bazaarService.paginationLinks(responseBuilder, attachmentsResult, "requirements/" + String.valueOf(requirementId) + "/attachments", parameter); - responseBuilder = bazaarService.xHeaderFields(responseBuilder, attachmentsResult); - - return responseBuilder.build(); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get attachments for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } - } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get attachments for requirement " + requirementId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } finally { - bazaarService.closeDBConnection(dalFacade); - } - } - - /** - * This method allows to retrieve a certain attachment. - * - * @param attachmentId id of the attachment - * @return Response with attachment as a JSON object. - */ - @GET - @Path("/{attachmentId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to retrieve a certain attachment") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain attachment", response = Attachment.class), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public Response getAttachment(@PathParam("attachmentId") int attachmentId) { - DALFacade dalFacade = null; - try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Attachment attachment = dalFacade.getAttachmentById(attachmentId); - Requirement requirement = dalFacade.getRequirementById(attachment.getRequirementId(), internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_49, - attachment.getId(), Activity.DataType.ATTACHMENT, internalUserId); - if (dalFacade.isProjectPublic(requirement.getProjectId())) { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_PUBLIC_ATTACHMENT, String.valueOf(requirement.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.anonymous")); - } - } else { - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Read_ATTACHMENT, String.valueOf(requirement.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.attachment.read")); - } - } - return Response.ok(attachment.toJSON()).build(); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get attachment " + attachmentId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } - } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get attachment " + attachmentId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } finally { - bazaarService.closeDBConnection(dalFacade); - } - } - - /** - * This method allows to create a new attachment. - * - * @param attachmentToCreate as JSON object - * @return Response with the created attachment as JSON object. - */ - @POST - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to create a new attachment.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "Returns the created attachment", response = Attachment.class), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public Response createAttachment(@ApiParam(value = "Attachment entity as JSON", required = true) Attachment attachmentToCreate) { - DALFacade dalFacade = null; - try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } - Vtor vtor = bazaarService.getValidators(); - vtor.useProfiles("create"); - vtor.validate(attachmentToCreate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Requirement requirement = dalFacade.getRequirementById(attachmentToCreate.getRequirementId(), internalUserId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Create_ATTACHMENT, String.valueOf(requirement.getProjectId()), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.attachment.create")); - } - attachmentToCreate.setCreator(dalFacade.getUserById(internalUserId)); - Attachment createdAttachment = dalFacade.createAttachment(attachmentToCreate); - bazaarService.getNotificationDispatcher().dispatchNotification(createdAttachment.getCreationDate(), Activity.ActivityAction.CREATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_50, - createdAttachment.getId(), Activity.DataType.ATTACHMENT, internalUserId); - return Response.status(Response.Status.CREATED).entity(createdAttachment.toJSON()).build(); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - L2pLogger.logEvent(MonitoringEvent.SERVICE_CUSTOM_MESSAGE_50, Context.getCurrent().getMainAgent(), "Create attachment"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } - } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - L2pLogger.logEvent(MonitoringEvent.SERVICE_CUSTOM_MESSAGE_50, Context.getCurrent().getMainAgent(), "Create attachment"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } finally { - bazaarService.closeDBConnection(dalFacade); - } - } - - /** - * This method deletes a specific attachment. - * - * @param attachmentId id of the attachment, which should be deleted - * @return Response with the deleted attachment as a JSON object. - */ - @DELETE - @Path("/{attachmentId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method deletes a specific attachment.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the deleted attachment", response = Attachment.class), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public Response deleteAttachment(@PathParam("attachmentId") int attachmentId) { - DALFacade dalFacade = null; - try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - Requirement requirement = dalFacade.getRequirementById(attachmentId, internalUserId); - boolean authorized = new AuthorizationManager().isAuthorized(internalUserId, PrivilegeEnum.Modify_ATTACHMENT, Arrays.asList(String.valueOf(attachmentId), String.valueOf(requirement.getProjectId())), dalFacade); - if (!authorized) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, Localization.getInstance().getResourceBundle().getString("error.authorization.attachment.modify")); - } - Attachment deletedAttachment = dalFacade.deleteAttachmentById(attachmentId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.DELETE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_52, - deletedAttachment.getId(), Activity.DataType.ATTACHMENT, internalUserId); - return Response.ok(deletedAttachment.toJSON()).build(); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete attachment " + attachmentId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } - } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Delete attachment " + attachmentId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } finally { - bazaarService.closeDBConnection(dalFacade); - } - } -} \ No newline at end of file diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/UsersResource.java b/src/main/de/rwth/dbis/acis/bazaar/service/UsersResource.java deleted file mode 100644 index 484f66fc..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/UsersResource.java +++ /dev/null @@ -1,218 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service; - -import de.rwth.dbis.acis.bazaar.service.dal.DALFacade; -import de.rwth.dbis.acis.bazaar.service.dal.entities.Activity; -import de.rwth.dbis.acis.bazaar.service.dal.entities.User; -import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; -import i5.las2peer.api.Context; -import i5.las2peer.api.logging.MonitoringEvent; -import i5.las2peer.api.security.Agent; -import i5.las2peer.logging.L2pLogger; -import io.swagger.annotations.*; -import jodd.vtor.Vtor; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.net.HttpURLConnection; -import java.util.Date; -import java.util.EnumSet; - - -@Api(value = "users", description = "Users resource") -@SwaggerDefinition( - info = @Info( - title = "Requirements Bazaar", - version = "0.6", - description = "Requirements Bazaar project", - termsOfService = "http://requirements-bazaar.org", - contact = @Contact( - name = "Requirements Bazaar Dev Team", - url = "http://requirements-bazaar.org", - email = "info@requirements-bazaar.org" - ), - license = @License( - name = "Apache2", - url = "http://requirements-bazaar.org/license" - ) - ), - schemes = SwaggerDefinition.Scheme.HTTPS -) -@Path("/users") -public class UsersResource { - - private BazaarService bazaarService; - - private final L2pLogger logger = L2pLogger.getInstance(UsersResource.class.getName()); - - public UsersResource() throws Exception { - bazaarService = (BazaarService) Context.getCurrent().getService(); - } - - /** - * This method allows to retrieve a certain user. - * - * @param userId the id of the user to be returned - * @return Response with user as a JSON object. - */ - @GET - @Path("/{userId}") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to retrieve a certain user.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns a certain user", response = User.class), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public Response getUser(@PathParam("userId") int userId) { - DALFacade dalFacade = null; - try { - // TODO: check whether the current user may request this project - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } - dalFacade = bazaarService.getDBConnection(); - User user = dalFacade.getUserById(userId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_53, - userId, Activity.DataType.USER, userId); - - return Response.ok(user.toJSON()).build(); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get user " + userId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } - } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get user " + userId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } finally { - bazaarService.closeDBConnection(dalFacade); - } - } - - /** - * This method allows to retrieve the active user. - * - * @return Response with active user as a JSON object. - */ - @GET - @Path("/me") - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to retrieve the active user.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the active user", response = User.class), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public Response getActiveUser() { - DALFacade dalFacade = null; - try { - Agent agent = Context.getCurrent().getMainAgent(); - String userId = agent.getIdentifier(); - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(userId); - User user = dalFacade.getUserById(internalUserId); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.RETRIEVE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_54, - internalUserId, Activity.DataType.USER, internalUserId); - - return Response.ok(user.toJSON()).build(); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get active user"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } - } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Get active user"); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } finally { - bazaarService.closeDBConnection(dalFacade); - } - } - - /** - * Allows to update a certain user. - * - * @param userId id of the user to update - * @param userToUpdate updated user as a JSON object - * @return Response with the updated user as a JSON object. - */ - @PUT - @Path("/{userId}") - @Consumes(MediaType.APPLICATION_JSON) - @Produces(MediaType.APPLICATION_JSON) - @ApiOperation(value = "This method allows to update the user profile.") - @ApiResponses(value = { - @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Returns the updated user", response = User.class), - @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"), - @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Not found"), - @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Internal server problems") - }) - public Response updateUser(@PathParam("userId") int userId, - @ApiParam(value = "User entity as JSON", required = true) User userToUpdate) { - DALFacade dalFacade = null; - try { - String registrarErrors = bazaarService.notifyRegistrars(EnumSet.of(BazaarFunction.VALIDATION, BazaarFunction.USER_FIRST_LOGIN_HANDLING)); - if (registrarErrors != null) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, registrarErrors); - } - Agent agent = Context.getCurrent().getMainAgent(); - - Vtor vtor = bazaarService.getValidators(); - vtor.validate(userToUpdate); - if (vtor.hasViolations()) { - ExceptionHandler.getInstance().handleViolations(vtor.getViolations()); - } - dalFacade = bazaarService.getDBConnection(); - Integer internalUserId = dalFacade.getUserIdByLAS2PeerId(agent.getIdentifier()); - if (!internalUserId.equals(userId)) { - ExceptionHandler.getInstance().throwException(ExceptionLocation.BAZAARSERVICE, ErrorCode.AUTHORIZATION, - "UserId is not identical with user sending this request."); - } - User updatedUser = dalFacade.modifyUser(userToUpdate); - bazaarService.getNotificationDispatcher().dispatchNotification(new Date(), Activity.ActivityAction.UPDATE, MonitoringEvent.SERVICE_CUSTOM_MESSAGE_56, - userId, Activity.DataType.USER, internalUserId); - return Response.ok(updatedUser.toJSON()).build(); - } catch (BazaarException bex) { - if (bex.getErrorCode() == ErrorCode.AUTHORIZATION) { - return Response.status(Response.Status.UNAUTHORIZED).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else if (bex.getErrorCode() == ErrorCode.NOT_FOUND) { - return Response.status(Response.Status.NOT_FOUND).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } else { - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update user " + userId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } - } catch (Exception ex) { - BazaarException bex = ExceptionHandler.getInstance().convert(ex, ExceptionLocation.BAZAARSERVICE, ErrorCode.UNKNOWN, ex.getMessage()); - logger.warning(bex.getMessage()); - Context.get().monitorEvent(MonitoringEvent.SERVICE_ERROR, "Update user " + userId); - return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ExceptionHandler.getInstance().toJSON(bex)).build(); - } finally { - bazaarService.closeDBConnection(dalFacade); - } - } -} \ No newline at end of file diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Activity.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Activity.java deleted file mode 100644 index a678e2b8..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Activity.java +++ /dev/null @@ -1,223 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -import com.fasterxml.jackson.annotation.JsonFilter; -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.Date; - -public class Activity extends EntityBase { - - private final transient int id; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private final Date creationDate; - private final ActivityAction activityAction; - private final String dataUrl; - private final DataType dataType; - private final String dataFrontendUrl; - private final String parentDataUrl; - private final DataType parentDataType; - private final String userUrl; - private final String origin; - - private AdditionalObject additionalObject; - - private Activity(Builder builder) { - this.id = builder.id; - this.creationDate = builder.creationDate; - this.activityAction = builder.activityAction; - this.dataUrl = builder.dataUrl; - this.dataType = builder.dataType; - this.dataFrontendUrl = builder.dataFrontendUrl; - this.parentDataUrl = builder.parentDataUrl; - this.parentDataType = builder.parentDataType; - this.userUrl = builder.userUrl; - this.origin = builder.origin; - this.additionalObject = builder.additionalObject; - } - - public static Builder getBuilder() { - return new Builder(); - } - - @Override - @JsonIgnore - public int getId() { - return id; - } - - public Date getCreationDate() { - return creationDate; - } - - public ActivityAction getActivityAction() { - return activityAction; - } - - public String getDataUrl() { - return dataUrl; - } - - public DataType getDataType() { - return dataType; - } - - public String getDataFrontendUrl() { - return dataFrontendUrl; - } - - public String getParentDataUrl() { - return parentDataUrl; - } - - public DataType getParentDataType() { - return parentDataType; - } - - public String getUserUrl() { - return userUrl; - } - - public String getOrigin() { - return origin; - } - - public AdditionalObject getAdditionalObject() { - return additionalObject; - } - - public enum DataType { - STATISTIC, - PROJECT, - CATEGORY, - REQUIREMENT, - COMMENT, - ATTACHMENT, - USER - } - - public enum ActivityAction { - RETRIEVE, - RETRIEVE_CHILD, - CREATE, - UPDATE, - DELETE, - REALIZE, - UNREALIZE, - VOTE, - UNVOTE, - DEVELOP, - UNDEVELOP, - FOLLOW, - UNFOLLOW, - LEADDEVELOP, - UNLEADDEVELOP - } - - public static class Builder { - - protected int id; - protected Date creationDate; - protected ActivityAction activityAction; - protected String dataUrl; - protected DataType dataType; - protected String dataFrontendUrl; - protected String parentDataUrl; - protected DataType parentDataType; - protected String userUrl; - protected String origin; - protected AdditionalObject additionalObject; - - public Builder creationDate(Date creationDate) { - this.creationDate = creationDate; - return this; - } - - public Builder activityAction(ActivityAction activityAction) { - this.activityAction = activityAction; - return this; - } - - public Builder dataUrl(String dataUrl) { - this.dataUrl = dataUrl; - return this; - } - - public Builder dataType(DataType dataType) { - this.dataType = dataType; - return this; - } - - public Builder dataFrontendUrl(String dataFrontendUrl) { - this.dataFrontendUrl = dataFrontendUrl; - return this; - } - - public Builder parentDataUrl(String parentDataUrl) { - this.parentDataUrl = parentDataUrl; - return this; - } - - public Builder parentDataType(DataType parentDataType) { - this.parentDataType = parentDataType; - return this; - } - - public Builder userUrl(String userUrl) { - this.userUrl = userUrl; - return this; - } - - public Builder origin(String origin) { - this.origin = origin; - return this; - } - - public Builder addititionalObject(AdditionalObject additionalObject) { - this.additionalObject = additionalObject; - return this; - } - - public Activity build() { - return new Activity(this); - } - } - - public static class AdditionalObject { - @JsonFilter("ActivityFilter") - private Project project; - - @JsonFilter("ActivityFilter") - private Category category; - - @JsonFilter("ActivityFilter") - private Requirement requirement; - - @JsonFilter("ActivityFilter") - private User user; - - public Project getProject() { - return project; - } - - public Category getCategory() { - return category; - } - - public Requirement getRequirement() { - return requirement; - } - - public User getUser() { - return user; - } - - public AdditionalObject(Project project, Category category, Requirement requirement, User user) { - this.project = project; - this.category = category; - this.requirement = requirement; - this.user = user; - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Attachment.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Attachment.java deleted file mode 100644 index 64aafb5b..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Attachment.java +++ /dev/null @@ -1,210 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -import com.fasterxml.jackson.annotation.JsonFormat; -import jodd.vtor.constraint.MaxLength; -import jodd.vtor.constraint.Min; -import jodd.vtor.constraint.NotBlank; -import jodd.vtor.constraint.NotNull; - -import java.util.Date; - -public class Attachment extends EntityBase { - - private int id; - - @NotNull(profiles = {"create"}) - @NotBlank(profiles = {"*"}) - @MaxLength(value = 50, profiles = {"*"}) - private String name; - - private String description; - - @NotNull(profiles = {"create"}) - @NotBlank(profiles = {"*"}) - @MaxLength(value = 1000, profiles = {"*"}) - private String mimeType; - - @NotNull(profiles = {"create"}) - @NotBlank(profiles = {"*"}) - @MaxLength(value = 1000, profiles = {"*"}) - private String identifier; - - @NotNull(profiles = {"create"}) - @NotBlank(profiles = {"*"}) - @MaxLength(value = 1000, profiles = {"*"}) - private String fileUrl; - - @Min(value = 0, profiles = {"create"}) - private int requirementId; - - private User creator; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date creationDate; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date lastUpdatedDate; - - public Attachment() { - } - - public Attachment(Builder builder) { - this.id = builder.id; - this.name = builder.name; - this.description = builder.description; - this.mimeType = builder.mimeType; - this.identifier = builder.identifier; - this.fileUrl = builder.fileUrl; - this.creationDate = builder.creationDate; - this.creator = builder.creator; - this.requirementId = builder.requirementId; - this.lastUpdatedDate = builder.lastUpdatedDate; - } - - public int getId() { - return id; - } - - public int getRequirementId() { - return requirementId; - } - - public void setRequirementId(int requirementId) { - this.requirementId = requirementId; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getMimeType() { - return mimeType; - } - - public String getIdentifier() { - return identifier; - } - - public String getFileUrl() { - return fileUrl; - } - - public Date getCreationDate() { - return creationDate; - } - - public Date getLastUpdatedDate() { - return lastUpdatedDate; - } - - public User getCreator() { - return creator; - } - - public void setCreator(User creator) { - this.creator = creator; - } - - public static Builder getBuilder() { - return new Builder(); - } - - public static class Builder { - private int id; - private int requirementId; - private String name; - private String description; - private String mimeType; - private String identifier; - private String fileUrl; - private Date creationDate; - private Date lastUpdatedDate; - User creator; - - public Builder id(int id) { - this.id = id; - return this; - } - - public Builder requirementId(int requirementId) { - this.requirementId = requirementId; - return this; - } - - public Builder name(String name) { - this.name = name; - return this; - } - - public Builder description(String description) { - this.description = description; - return this; - } - - public Builder mimeType(String mimeType) { - this.mimeType = mimeType; - return this; - } - - public Builder identifier(String identifier) { - this.identifier = identifier; - return this; - } - - public Builder fileUrl(String fileUrl) { - this.fileUrl = fileUrl; - return this; - } - - public Builder creationDate(Date creationDate) { - this.creationDate = creationDate; - return this; - } - - public Builder lastUpdatedDate(Date lastUpdatedDate) { - this.lastUpdatedDate = lastUpdatedDate; - return this; - } - - public Builder creator(User creator) { - this.creator = creator; - return this; - } - - public Attachment build() { - return new Attachment(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Category.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Category.java deleted file mode 100644 index 638d6fd7..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Category.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.entities; - - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonProperty; -import jodd.vtor.constraint.MaxLength; -import jodd.vtor.constraint.Min; -import jodd.vtor.constraint.NotBlank; -import jodd.vtor.constraint.NotNull; - -import java.util.Date; - -/** - * @author Adam Gavronek - * @since 6/9/2014 - */ -public class Category extends EntityBase { - - private int id; - - @NotBlank(profiles = {"*"}) - @NotNull(profiles = {"create"}) - @MaxLength(value = 50, profiles = {"*"}) - private String name; - - @NotBlank(profiles = {"*"}) - @NotNull(profiles = {"create"}) - private String description; - - @Min(value = 0, profiles = {"create"}) - private int projectId; - - private User leader; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date creationDate; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date lastUpdatedDate; - - private Integer numberOfRequirements; - private Integer numberOfFollowers; - private Boolean isFollower; - - public Category() { - } - - /** - * Private constructor, should be called from its builder only. - * - * @param builder - */ - private Category(Builder builder) { - this.id = builder.id; - this.name = builder.name; - this.description = builder.description; - this.projectId = builder.projectId; - this.leader = builder.leader; - this.creationDate = builder.creationDate; - this.lastUpdatedDate = builder.lastUpdatedDate; - this.isFollower = builder.isFollower; - } - - /** - * Builder to easily build Category objects - * - * @param name Name field will be initialized using the passed value - * @return a builder with name returned - */ - public static Builder getBuilder(String name) { - return new Builder(name); - } - - public int getId() { - return id; - } - - public int getProjectId() { - return projectId; - } - - public Date getCreationDate() { - return creationDate; - } - - public Date getLastUpdatedDate() { - return lastUpdatedDate; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public User getLeader() { - return leader; - } - - public void setLeader(User leader) { - this.leader = leader; - } - - public void setFollower(Boolean follower) { - isFollower = follower; - } - - public Integer getNumberOfRequirements() { - return numberOfRequirements; - } - - public void setNumberOfRequirements(Integer numberOfRequirements) { - this.numberOfRequirements = numberOfRequirements; - } - - public Integer getNumberOfFollowers() { - return numberOfFollowers; - } - - public void setNumberOfFollowers(Integer numberOfFollowers) { - this.numberOfFollowers = numberOfFollowers; - } - - @JsonProperty("isFollower") - public Boolean isFollower() { - return isFollower; - } - - public static class Builder { - - User leader; - private int id; - private String description; - private String name; - private Date creationDate; - private Date lastUpdatedDate; - private int projectId; - private Boolean isFollower; - - public Builder(String name) { - this.name = name; - } - - public Builder description(String description) { - this.description = description; - return this; - } - - public Builder id(int id) { - this.id = id; - return this; - } - - public Builder leader(User leader) { - this.leader = leader; - return this; - } - - public Builder isFollower(Boolean isFollower) { - this.isFollower = isFollower; - return this; - } - - public Builder projectId(int projectId) { - this.projectId = projectId; - return this; - } - - public Builder creationDate(Date creationDate) { - this.creationDate = creationDate; - return this; - } - - public Builder lastUpdatedDate(Date lastUpdatedDate) { - this.lastUpdatedDate = lastUpdatedDate; - return this; - } - - /** - * Call this to create a Category object with the values previously set in the builder. - * - * @return initialized Category object - */ - public Category build() { - Category created = new Category(this); - - String name = created.getName(); - - if (name == null || name.length() == 0) { - throw new IllegalStateException("name cannot be null or empty"); - } - - return created; - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryContributors.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryContributors.java deleted file mode 100644 index 55646449..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryContributors.java +++ /dev/null @@ -1,109 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.List; - -/** - * Created by Martin on 15.06.2017. - */ -public class CategoryContributors extends EntityBase { - - private final int id; - - private User leader; - private List requirementCreator; - private List leadDeveloper; - private List developers; - private List commentCreator; - private List attachmentCreator; - - protected CategoryContributors(Builder builder) { - this.id = builder.id; - this.leader = builder.leader; - this.requirementCreator = builder.requirementCreator; - this.leadDeveloper = builder.leadDeveloper; - this.developers = builder.developers; - this.commentCreator = builder.commentCreator; - this.attachmentCreator = builder.attachmentCreator; - } - - public static Builder getBuilder() { - return new Builder(); - } - - @Override - @JsonIgnore - public int getId() { - return id; - } - - public User getLeader() { - return leader; - } - - public List getRequirementCreator() { - return requirementCreator; - } - - public List getLeadDeveloper() { - return leadDeveloper; - } - - public List getDevelopers() { - return developers; - } - - public List getCommentCreator() { - return commentCreator; - } - - public List getAttachmentCreator() { - return attachmentCreator; - } - - public static class Builder { - - private int id; - private User leader; - private List requirementCreator; - private List leadDeveloper; - private List developers; - private List commentCreator; - private List attachmentCreator; - - public Builder leader(User leader) { - this.leader = leader; - return this; - } - - public Builder requirementCreator(List requirementCreator) { - this.requirementCreator = requirementCreator; - return this; - } - - public Builder leadDeveloper(List leadDeveloper) { - this.leadDeveloper = leadDeveloper; - return this; - } - - public Builder developers(List developers) { - this.developers = developers; - return this; - } - - public Builder commentCreator(List commentCreator) { - this.commentCreator = commentCreator; - return this; - } - - public Builder attachmentCreator(List attachmentCreator) { - this.attachmentCreator = attachmentCreator; - return this; - } - - public CategoryContributors build() { - return new CategoryContributors(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryFollower.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryFollower.java deleted file mode 100644 index f388a881..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/CategoryFollower.java +++ /dev/null @@ -1,54 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -public class CategoryFollower extends EntityBase { - private final int Id; - private final int CategoryId; - private final int UserId; - - private CategoryFollower(Builder builder) { - Id = builder.id; - CategoryId = builder.categoryId; - UserId = builder.userId; - } - - public int getId() { - return Id; - } - - public int getCategoryId() { - return CategoryId; - } - - public int getUserId() { - return UserId; - } - - public static Builder getBuilder() { - return new Builder(); - } - - public static class Builder { - int userId; - int categoryId; - int id; - - public Builder userId(int userId) { - this.userId = userId; - return this; - } - - public Builder categoryId(int categoryId) { - this.categoryId = categoryId; - return this; - } - - public Builder id(int id) { - this.id = id; - return this; - } - - public CategoryFollower build() { - return new CategoryFollower(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Comment.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Comment.java deleted file mode 100644 index 74813768..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Comment.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.entities; - - -import com.fasterxml.jackson.annotation.JsonFormat; -import jodd.vtor.constraint.Min; -import jodd.vtor.constraint.NotBlank; -import jodd.vtor.constraint.NotNull; - -import java.util.Date; - -/** - * @author Adam Gavronek - * @since 6/11/2014 - */ -public class Comment extends EntityBase { - - private int id; - @NotBlank(profiles = {"*"}) - @NotNull(profiles = {"create"}) - private String message; - - @Min(value = 0, profiles = {"create"}) - private Integer replyToComment; - - @Min(value = 0, profiles = {"create"}) - private int requirementId; - - private User creator; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date creationDate; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date lastUpdatedDate; - - public Comment() { - } - - public Comment(Builder builder) { - this.id = builder.id; - this.message = builder.message; - this.replyToComment = builder.replyToComment; - this.requirementId = builder.requirementId; - this.creator = builder.creator; - this.creationDate = builder.creationDate; - this.lastUpdatedDate = builder.lastUpdatedDate; - } - - public int getId() { - return id; - } - - public int getRequirementId() { - return requirementId; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - public Integer getReplyToComment() { - return replyToComment; - } - - public Date getCreationDate() { - return creationDate; - } - - public Date getLastUpdatedDate() { - return lastUpdatedDate; - } - - public User getCreator() { - return creator; - } - - public void setCreator(User creator) { - this.creator = creator; - } - - public static Builder getBuilder(String message) { - return new Builder(message); - } - - public static class Builder { - private int id; - private String message; - private int requirementId; - private Integer replyToComment; - Date creationDate; - Date lastUpdatedDate; - User creator; - - - public Builder(String message) { - message(message); - } - - public Builder id(int id) { - this.id = id; - return this; - } - - public Builder message(String message) { - this.message = message; - return this; - } - - public Builder replyToComment(Integer replyToComment) { - this.replyToComment = replyToComment; - return this; - } - - public Builder creationDate(Date creationDate) { - this.creationDate = creationDate; - return this; - } - - public Builder lastUpdatedDate(Date lastUpdatedDate) { - this.lastUpdatedDate = lastUpdatedDate; - return this; - } - - public Builder requirementId(int requirementId) { - this.requirementId = requirementId; - return this; - } - - public Builder creator(User creator) { - this.creator = creator; - return this; - } - - public Comment build() { - return new Comment(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Email.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Email.java deleted file mode 100644 index 5731eaba..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Email.java +++ /dev/null @@ -1,135 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service.dal.entities; - - -import java.util.Date; -import java.util.Set; - -public class Email extends EntityBase { - - private final transient int id; - - private final Set recipients; - private final String subject; - private final String starting; - private final String message; - private final String closing; - private final String footer; - private final Date creationDate; - - protected Email(Builder builder) { - id = builder.id; - recipients = builder.recipients; - subject = builder.subject; - starting = builder.starting; - message = builder.message; - closing = builder.closing; - footer = builder.footer; - creationDate = builder.creationDate; - } - - public int getId() { - return id; - } - - public Set getRecipients() { - return recipients; - } - - public String getSubject() { - return subject; - } - - public String getStarting() { - return starting; - } - - public String getMessage() { - return message; - } - - public String getClosing() { - return closing; - } - - public String getFooter() { - return footer; - } - - public Date getCreationDate() { - return creationDate; - } - - public void removeRecipient(User user) { - recipients.remove(user); - } - - public static Activity.Builder getBuilder() { - return new Activity.Builder(); - } - - public static class Builder { - - private int id; - private Set recipients; - private String subject; - private String starting; - private String message; - private String closing; - private String footer; - private Date creationDate; - - public Builder() { - - } - - public Builder(Email email) { - this.recipients = email.recipients; - this.subject = email.subject; - this.starting = email.starting; - this.message = email.message; - this.closing = email.closing; - this.footer = email.footer; - this.creationDate = email.creationDate; - } - - public Builder recipients(Set recipients) { - this.recipients = recipients; - return this; - } - - public Builder subject(String subject) { - this.subject = subject; - return this; - } - - public Builder starting(String starting) { - this.starting = starting; - return this; - } - - public Builder message(String message) { - this.message = message; - return this; - } - - public Builder closing(String closing) { - this.closing = closing; - return this; - } - - public Builder footer(String footer) { - this.footer = footer; - return this; - } - - public Builder creationDate(Date creationDate) { - this.creationDate = creationDate; - return this; - } - - public Email build() { - Email created = new Email(this); - return created; - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Privilege.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Privilege.java deleted file mode 100644 index bf09ebc6..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Privilege.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * - * Copyright (c) 2015, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -/** - * @author Adam Gavronek - * @since 2/17/2015 - */ -public class Privilege extends EntityBase { - - private final int Id; - - private final PrivilegeEnum name; - - private Privilege(Builder builder) { - Id = builder.id; - this.name = builder.name; - } - - @Override - public int getId() { - return Id; - } - - public PrivilegeEnum getName() { - return name; - } - - public static Builder getBuilder(PrivilegeEnum privilege) { - return new Builder(privilege); - } - - public static class Builder { - private int id; - private PrivilegeEnum name; - - public Builder(PrivilegeEnum privilege) { - this.name = privilege; - } - - public Builder id(int id) { - this.id = id; - return this; - } - - public Builder name(PrivilegeEnum name) { - this.name = name; - return this; - } - - public Privilege build() { - return new Privilege(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Project.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Project.java deleted file mode 100644 index a792942b..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Project.java +++ /dev/null @@ -1,249 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonProperty; -import jodd.vtor.constraint.MaxLength; -import jodd.vtor.constraint.NotBlank; -import jodd.vtor.constraint.NotNull; - -import java.util.Date; - -/** - * @author Adam Gavronek - * @since 6/9/2014 - */ -public class Project extends EntityBase { - - private int id; - - @NotBlank(profiles = {"*"}) - @NotNull(profiles = {"create"}) - @MaxLength(value = 50, profiles = {"*"}) - private String name; - - @NotBlank(profiles = {"*"}) - @NotNull(profiles = {"create"}) - private String description; - - private Boolean visibility; - - private Integer defaultCategoryId; - - private User leader; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date creationDate; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date lastUpdatedDate; - - private Integer numberOfCategories; - private Integer numberOfRequirements; - private Integer numberOfFollowers; - private Boolean isFollower; - - public Project() { - } - - /** - * Private constructor, should be called from its builder only. - * - * @param builder - */ - private Project(Builder builder) { - this.id = builder.id; - this.name = builder.name; - this.description = builder.description; - this.visibility = builder.visibility; - this.defaultCategoryId = builder.defaultCategoryId; - this.leader = builder.leader; - this.isFollower = builder.isFollower; - this.creationDate = builder.creationDate; - this.lastUpdatedDate = builder.lastUpdatedDate; - } - - /** - * Builder to easily build Category objects - * - * @param name Name field will be initialized using the passed value - * @return a builder with name returned - */ - public static Builder getBuilder(String name) { - return new Builder(name); - } - - public int getId() { - return id; - } - - public Date getCreationDate() { - return creationDate; - } - - public Date getLastUpdatedDate() { - return lastUpdatedDate; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public User getLeader() { - return leader; - } - - public void setLeader(User leader) { - this.leader = leader; - } - - public Integer getDefaultCategoryId() { - return defaultCategoryId; - } - - public void setDefaultCategoryId(Integer defaultCategoryId) { - this.defaultCategoryId = defaultCategoryId; - } - - public Boolean getVisibility() { - return visibility; - } - - public Integer getNumberOfCategories() { - return numberOfCategories; - } - - public void setNumberOfCategories(Integer numberOfCategories) { - this.numberOfCategories = numberOfCategories; - } - - public Integer getNumberOfRequirements() { - return numberOfRequirements; - } - - public void setNumberOfRequirements(Integer numberOfRequirements) { - this.numberOfRequirements = numberOfRequirements; - } - - public Integer getNumberOfFollowers() { - return numberOfFollowers; - } - - public void setNumberOfFollowers(Integer numberOfFollowers) { - this.numberOfFollowers = numberOfFollowers; - } - - public void setFollower(Boolean isFollower) { - this.isFollower = isFollower; - } - - @JsonProperty("isFollower") - public Boolean isFollower() { - return isFollower; - } - - public static class Builder { - - private int id; - private String description; - private String name; - private Boolean visibility; - private User leader; - private Date creationDate; - private Date lastUpdatedDate; - private Integer defaultCategoryId; - private Boolean isFollower; - - public Builder(String name) { - this.name = name; - } - - public Builder description(String description) { - this.description = description; - return this; - } - - public Builder id(int id) { - this.id = id; - return this; - } - - public Builder visibility(Boolean visibility) { - this.visibility = visibility; - return this; - } - - public Builder leader(User leader) { - this.leader = leader; - return this; - } - - public Builder defaultCategoryId(Integer defaultCategoryId) { - this.defaultCategoryId = defaultCategoryId; - return this; - } - - public Builder isFollower(Boolean isFollower) { - this.isFollower = isFollower; - return this; - } - - public Builder creationDate(Date creationDate) { - this.creationDate = creationDate; - return this; - } - - public Builder lastUpdatedDate(Date lastUpdatedDate) { - this.lastUpdatedDate = lastUpdatedDate; - return this; - } - - /** - * Call this to create a Project object with the values previously set in the builder. - * - * @return initialized Project object - */ - public Project build() { - Project created = new Project(this); - - String name = created.getName(); - - if (name == null || name.length() == 0) { - throw new IllegalStateException("name cannot be null or empty"); - } - - return created; - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectContributors.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectContributors.java deleted file mode 100644 index 68a3489b..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectContributors.java +++ /dev/null @@ -1,121 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.List; - -/** - * Created by Martin on 15.06.2017. - */ -public class ProjectContributors extends EntityBase { - - private final int id; - - private User leader; - private List categoryLeader; - private List requirementCreator; - private List leadDeveloper; - private List developers; - private List commentCreator; - private List attachmentCreator; - - protected ProjectContributors(Builder builder) { - this.id = builder.id; - this.leader = builder.leader; - this.categoryLeader = builder.categoryLeader; - this.requirementCreator = builder.requirementCreator; - this.leadDeveloper = builder.leadDeveloper; - this.developers = builder.developers; - this.commentCreator = builder.commentCreator; - this.attachmentCreator = builder.attachmentCreator; - } - - public static Builder getBuilder() { - return new Builder(); - } - - @Override - @JsonIgnore - public int getId() { - return id; - } - - public User getLeader() { - return leader; - } - - public List getCategoryLeader() { - return categoryLeader; - } - - public List getRequirementCreator() { - return requirementCreator; - } - - public List getLeadDeveloper() { - return leadDeveloper; - } - - public List getDevelopers() { - return developers; - } - - public List getCommentCreator() { - return commentCreator; - } - - public List getAttachmentCreator() { - return attachmentCreator; - } - - public static class Builder { - - private int id; - private User leader; - private List categoryLeader; - private List requirementCreator; - private List leadDeveloper; - private List developers; - private List commentCreator; - private List attachmentCreator; - - public Builder leader(User leader) { - this.leader = leader; - return this; - } - - public Builder categoryLeader(List categoryLeader) { - this.categoryLeader = categoryLeader; - return this; - } - - public Builder requirementCreator(List requirementCreator) { - this.requirementCreator = requirementCreator; - return this; - } - - public Builder leadDeveloper(List leadDeveloper) { - this.leadDeveloper = leadDeveloper; - return this; - } - - public Builder developers(List developers) { - this.developers = developers; - return this; - } - - public Builder commentCreator(List commentCreator) { - this.commentCreator = commentCreator; - return this; - } - - public Builder attachmentCreator(List attachmentCreator) { - this.attachmentCreator = attachmentCreator; - return this; - } - - public ProjectContributors build() { - return new ProjectContributors(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectFollower.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectFollower.java deleted file mode 100644 index d8afbb9a..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/ProjectFollower.java +++ /dev/null @@ -1,55 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -public class ProjectFollower extends EntityBase { - private final int Id; - private final int ProjectId; - private final int UserId; - - private ProjectFollower(Builder builder) { - Id = builder.id; - ProjectId = builder.projectId; - UserId = builder.userId; - } - - public int getId() { - return Id; - } - - public int getProjectId() { - return ProjectId; - } - - public int getUserId() { - return UserId; - } - - public static Builder getBuilder() { - return new Builder(); - } - - public static class Builder { - int userId; - int projectId; - int id; - - public Builder userId(int userId) { - this.userId = userId; - return this; - } - - public Builder projectId(int projectId) { - this.projectId = projectId; - return this; - } - - public Builder id(int id) { - this.id = id; - return this; - } - - public ProjectFollower build() { - return new ProjectFollower(this); - } - } -} - diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Requirement.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Requirement.java deleted file mode 100644 index c0b64fe0..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Requirement.java +++ /dev/null @@ -1,329 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service.dal.entities; - - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonProperty; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.UserVote; -import jodd.vtor.constraint.*; - -import java.util.Date; -import java.util.List; - -/** - * Requirement entity - */ -public class Requirement extends EntityBase { - - private int id; - - @NotBlank(profiles = {"*"}) - @NotNull(profiles = {"create"}) - @MaxLength(value = 50, profiles = {"*"}) - private String name; - - @NotBlank(profiles = {"*"}) - @NotNull(profiles = {"create"}) - private String description; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date realized; - - @Min(value = 0, profiles = {"create"}) - private int projectId; - - private User creator; - private User leadDeveloper; - - @NotNull(profiles = {"create"}) - @Size(min = 1, profiles = {"create"}) - private List categories; - - // This field is not filled because attachments should be not included in requirements response. - // But the API still allows to create a requirement with attachments at the same time. - private List attachments; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date creationDate; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date lastUpdatedDate; - - private Integer numberOfComments; - private Integer numberOfAttachments; - private Integer numberOfFollowers; - - private int upVotes; - private int downVotes; - private UserVote userVoted; - - private Boolean isFollower; - private Boolean isDeveloper; - private Boolean isContributor; - - public Requirement() { - } - - protected Requirement(Builder builder) { - this.id = builder.id; - this.name = builder.name; - this.description = builder.description; - this.realized = builder.realized; - this.projectId = builder.projectId; - this.creator = builder.creator; - this.leadDeveloper = builder.leadDeveloper; - this.creationDate = builder.creationDate; - this.lastUpdatedDate = builder.lastUpdatedDate; - this.upVotes = builder.upVotes; - this.downVotes = builder.downVotes; - this.userVoted = builder.userVoted; - this.isFollower = builder.isFollower; - this.isDeveloper = builder.isDeveloper; - this.isContributor = builder.isContributor; - } - - /** - * Builder to easily build Requirement objects - * - * @param name Name field will be initialized using the passed value - * @return a builder with name returned - */ - public static Builder getBuilder(String name) { - return new Builder(name); - } - - public Date getRealized() { - return realized; - } - - public Date getCreationDate() { - return creationDate; - } - - public Date getLastUpdatedDate() { - return lastUpdatedDate; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public List getCategories() { - return categories; - } - - public void setCategories(List categories) { - this.categories = categories; - } - - public List getAttachments() { - return attachments; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getId() { - return id; - } - - public int getProjectId() { - return projectId; - } - - public void setProjectId(int projectId) { - this.projectId = projectId; - } - - public User getCreator() { - return creator; - } - - public void setCreator(User creator) { - this.creator = creator; - } - - public User getLeadDeveloper() { - return leadDeveloper; - } - - public void setFollower(Boolean follower) { - isFollower = follower; - } - - public void setDeveloper(Boolean developer) { - isDeveloper = developer; - } - - public void setContributor(Boolean contributor) { - isContributor = contributor; - } - - public Integer getNumberOfComments() { - return numberOfComments; - } - - public void setNumberOfComments(Integer numberOfComments) { - this.numberOfComments = numberOfComments; - } - - public Integer getNumberOfAttachments() { - return numberOfAttachments; - } - - public void setNumberOfAttachments(Integer numberOfAttachments) { - this.numberOfAttachments = numberOfAttachments; - } - - public Integer getNumberOfFollowers() { - return numberOfFollowers; - } - - public void setNumberOfFollowers(Integer numberOfFollowers) { - this.numberOfFollowers = numberOfFollowers; - } - - public int getUpVotes() { - return upVotes; - } - - public int getDownVotes() { - return downVotes; - } - - public UserVote getUserVoted() { - return userVoted; - } - - @JsonProperty("isFollower") - public Boolean isFollower() { - return isFollower; - } - - @JsonProperty("isDeveloper") - public Boolean isDeveloper() { - return isDeveloper; - } - - @JsonProperty("isContributor") - public Boolean isContributor() { - return isContributor; - } - - public static class Builder { - private int id; - private String description; - private String name; - private Date realized; - private int projectId; - private Date creationDate; - private Date lastUpdatedDate; - private int upVotes; - private int downVotes; - private UserVote userVoted; - private User creator; - private User leadDeveloper; - private Boolean isFollower; - private Boolean isDeveloper; - private Boolean isContributor; - - public Builder(String name) { - this.name = name; - } - - public Builder description(String description) { - this.description = description; - return this; - } - - public Builder id(int id) { - this.id = id; - return this; - } - - /** - * Call this to create a Requirement object with the values previously set in the builder. - * - * @return initialized Requirement object - */ - public Requirement build() { - Requirement created = new Requirement(this); - - String name = created.getName(); - - if (name == null || name.length() == 0) { - throw new IllegalStateException("name cannot be null or empty"); - } - - return created; - } - - public Builder projectId(int projectId) { - this.projectId = projectId; - return this; - } - - public Builder realized(Date realized) { - this.realized = realized; - return this; - } - - public Builder creationDate(Date creationDate) { - this.creationDate = creationDate; - return this; - } - - public Builder lastUpdatedDate(Date lastUpdatedDate) { - this.lastUpdatedDate = lastUpdatedDate; - return this; - } - - public Builder upVotes(int upVotes) { - this.upVotes = upVotes; - return this; - } - - public Builder downVotes(int downVotes) { - this.downVotes = downVotes; - return this; - } - - public Builder userVoted(UserVote userVoted) { - this.userVoted = userVoted; - return this; - } - - public Requirement.Builder creator(User creator) { - this.creator = creator; - return this; - } - - public Requirement.Builder leadDeveloper(User leadDeveloper) { - this.leadDeveloper = leadDeveloper; - return this; - } - - public Requirement.Builder isFollower(Boolean isFollower) { - this.isFollower = isFollower; - return this; - } - - public Requirement.Builder isDeveloper(Boolean isDeveloper) { - this.isDeveloper = isDeveloper; - return this; - } - - public Requirement.Builder isContributor(Boolean isContributor) { - this.isContributor = isContributor; - return this; - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementCategory.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementCategory.java deleted file mode 100644 index 3ec139d4..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementCategory.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -/** - * @author Adam Gavronek - * @since 6/11/2014 - */ -public class RequirementCategory extends EntityBase { - - private final int id; - private final int categoryId; - private final int requirementId; - - private RequirementCategory(Builder builder) { - this.id = builder.id; - this.categoryId = builder.categoryId; - this.requirementId = builder.requirementId; - } - - public int getId() { - return id; - } - - public int getCategoryId() { - return categoryId; - } - - public int getRequirementId() { - return requirementId; - } - - public static Builder getBuilder(int category_id) { - return new Builder(category_id); - } - - public static class Builder { - private int id; - private int categoryId; - private int requirementId; - - public Builder(int category_id) { - this.categoryId = category_id; - } - - public Builder id(int id) { - this.id = id; - return this; - } - - public Builder categoryId(int categoryId) { - this.categoryId = categoryId; - return this; - } - - public Builder requirementId(int requirementId) { - this.requirementId = requirementId; - return this; - } - - public RequirementCategory build() { - return new RequirementCategory(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementContributors.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementContributors.java deleted file mode 100644 index 8e7fbb6f..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementContributors.java +++ /dev/null @@ -1,102 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import java.util.List; - -// import javax.ws.rs.core.Link; - -/** - * Created by Martin on 12.06.2017. - */ -public class RequirementContributors extends EntityBase { - - private final int id; - - private User creator; - private User leadDeveloper; - private List developers; - //private Link developersLink; // TODO: Skip after 10 elements and add HATEOAS link - private List commentCreator; - //private Link commentCreatorLink; - private List attachmentCreator; - //private Link attachmentCreatorLink; - - protected RequirementContributors(Builder builder) { - this.id = builder.id; - this.creator = builder.creator; - this.leadDeveloper = builder.leadDeveloper; - this.developers = builder.developers; - this.commentCreator = builder.commentCreator; - this.attachmentCreator = builder.attachmentCreator; - } - - public static Builder getBuilder() { - return new Builder(); - } - - @Override - @JsonIgnore - public int getId() { - return id; - } - - public User getCreator() { - return creator; - } - - public User getLeadDeveloper() { - return leadDeveloper; - } - - public List getDevelopers() { - return developers; - } - - public List getCommentCreator() { - return commentCreator; - } - - public List getAttachmentCreator() { - return attachmentCreator; - } - - public static class Builder { - - private int id; - private User creator; - private User leadDeveloper; - private List developers; - private List commentCreator; - private List attachmentCreator; - - public Builder creator(User creator) { - this.creator = creator; - return this; - } - - public Builder leadDeveloper(User leadDeveloper) { - this.leadDeveloper = leadDeveloper; - return this; - } - - public Builder developers(List developers) { - this.developers = developers; - return this; - } - - public Builder commentCreator(List commentCreator) { - this.commentCreator = commentCreator; - return this; - } - - public Builder attachmentCreator(List attachmentCreator) { - this.attachmentCreator = attachmentCreator; - return this; - } - - public RequirementContributors build() { - return new RequirementContributors(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementDeveloper.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementDeveloper.java deleted file mode 100644 index 19de9333..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementDeveloper.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -/** - * @author Adam Gavronek - * @since 6/11/2014 - */ -public class RequirementDeveloper extends EntityBase { - private final int Id; - private final int RequirementId; - private final int UserId; - - private RequirementDeveloper(Builder builder) { - Id = builder.id; - RequirementId = builder.requirementId; - UserId = builder.userId; - } - - public int getId() { - return Id; - } - - public int getRequirementId() { - return RequirementId; - } - - public int getUserId() { - return UserId; - } - - public static Builder getBuilder() { - return new Builder(); - } - - public static class Builder { - int userId; - int requirementId; - int id; - - public Builder userId(int userId) { - this.userId = userId; - return this; - } - - public Builder requirementId(int requirementId) { - this.requirementId = requirementId; - return this; - } - - public Builder id(int id) { - this.id = id; - return this; - } - - public RequirementDeveloper build() { - return new RequirementDeveloper(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementFollower.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementFollower.java deleted file mode 100644 index 0fc5f162..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/RequirementFollower.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -/** - * @author Adam Gavronek - * @since 6/11/2014 - */ -public class RequirementFollower extends EntityBase { - private final int Id; - private final int RequirementId; - private final int UserId; - - private RequirementFollower(Builder builder) { - Id = builder.id; - RequirementId = builder.requirementId; - UserId = builder.userId; - } - - public int getId() { - return Id; - } - - public int getRequirementId() { - return RequirementId; - } - - public int getUserId() { - return UserId; - } - - public static Builder getBuilder() { - return new Builder(); - } - - public static class Builder { - int userId; - int requirementId; - int id; - - public Builder userId(int userId) { - this.userId = userId; - return this; - } - - public Builder requirementId(int requirementId) { - this.requirementId = requirementId; - return this; - } - - public Builder id(int id) { - this.id = id; - return this; - } - - public RequirementFollower build() { - return new RequirementFollower(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Statistic.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Statistic.java deleted file mode 100644 index 44c6409b..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Statistic.java +++ /dev/null @@ -1,129 +0,0 @@ -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * Created by hugif on 26.12.2016. - */ -public class Statistic { - - private int numberOfProjects; - private int numberOfCategories; - private int numberOfRequirements; - private int numberOfComments; - private int numberOfAttachments; - private int numberOfVotes; - - - protected Statistic(Builder builder) { - this.numberOfProjects = builder.numberOfProjects; - this.numberOfCategories = builder.numberOfCategories; - this.numberOfRequirements = builder.numberOfRequirements; - this.numberOfComments = builder.numberOfComments; - this.numberOfAttachments = builder.numberOfAttachments; - this.numberOfVotes = builder.numberOfVotes; - } - - public int getNumberOfProjects() { - return numberOfProjects; - } - - public void setNumberOfProjects(int numberOfProjects) { - this.numberOfProjects = numberOfProjects; - } - - public int getNumberOfCategories() { - return numberOfCategories; - } - - public void setNumberOfCategories(int numberOfCategories) { - this.numberOfCategories = numberOfCategories; - } - - public int getNumberOfRequirements() { - return numberOfRequirements; - } - - public void setNumberOfRequirements(int numberOfRequirements) { - this.numberOfRequirements = numberOfRequirements; - } - - public int getNumberOfComments() { - return numberOfComments; - } - - public void setNumberOfComments(int numberOfComments) { - this.numberOfComments = numberOfComments; - } - - public int getNumberOfAttachments() { - return numberOfAttachments; - } - - public void setNumberOfAttachments(int numberOfAttachments) { - this.numberOfAttachments = numberOfAttachments; - } - - public int getNumberOfVotes() { - return numberOfVotes; - } - - public void setNumberOfVotes(int numberOfVotes) { - this.numberOfVotes = numberOfVotes; - } - - public String toJSON() throws JsonProcessingException { - return new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL).writeValueAsString(this); - } - - public static Builder getBuilder() { - return new Builder(); - } - - public static class Builder { - - protected int numberOfProjects; - protected int numberOfCategories; - protected int numberOfRequirements; - protected int numberOfComments; - protected int numberOfAttachments; - protected int numberOfVotes; - - public Builder numberOfProjects(int numberOfProjects) { - this.numberOfProjects = numberOfProjects; - return this; - } - - public Builder numberOfCategories(int numberOfCategories) { - this.numberOfCategories = numberOfCategories; - return this; - } - - public Builder numberOfRequirements(int numberOfRequirements) { - this.numberOfRequirements = numberOfRequirements; - return this; - } - - public Builder numberOfComments(int numberOfComments) { - this.numberOfComments = numberOfComments; - return this; - } - - public Builder numberOfAttachments(int numberOfAttachments) { - this.numberOfAttachments = numberOfAttachments; - return this; - } - - public Builder numberOfVotes(int numberOfVotes) { - this.numberOfVotes = numberOfVotes; - return this; - } - - public Statistic build() { - return new Statistic(this); - } - } - -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/User.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/User.java deleted file mode 100644 index fe763b78..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/User.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.entities; - - -import com.fasterxml.jackson.annotation.JsonFormat; -import com.fasterxml.jackson.annotation.JsonIgnore; -import jodd.vtor.constraint.MaxLength; -import jodd.vtor.constraint.Min; -import jodd.vtor.constraint.NotBlank; -import jodd.vtor.constraint.NotNull; - -import java.util.Date; - -public class User extends EntityBase { - - private int id; - - @NotBlank(profiles = {"*"}) - @NotNull(profiles = {"create"}) - @MaxLength(value = 1000, profiles = {"*"}) - private String userName; - - @MaxLength(value = 1000, profiles = {"*"}) - private String firstName; - - @MaxLength(value = 1000, profiles = {"*"}) - private String lastName; - - @NotBlank(profiles = {"*"}) - @NotNull(profiles = {"create"}) - @MaxLength(value = 1000, profiles = {"*"}) - private transient String eMail; - - private Boolean admin; - - @Min(value = 1, profiles = {"create"}) - private String las2peerId; - - private String profileImage; - - private Boolean emailLeadSubscription; - - private Boolean emailFollowSubscription; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date creationDate; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date lastUpdatedDate; - - @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ") - private Date lastLoginDate; - - public User() { - } - - public User(Builder builder) { - this.id = builder.id; - this.userName = builder.userName; - this.firstName = builder.firstName; - this.lastName = builder.lastName; - this.eMail = builder.eMail; - this.admin = builder.admin; - this.las2peerId = builder.las2peerId; - this.profileImage = builder.profileImage; - this.emailLeadSubscription = builder.emailLeadSubscription; - this.emailFollowSubscription = builder.emailFollowSubscription; - this.creationDate = builder.creationDate; - this.lastUpdatedDate = builder.lastUpdatedDate; - this.lastLoginDate = builder.lastLoginDate; - } - - public int getId() { - return id; - } - - public String getFirstName() { - return firstName; - } - - public String getLastName() { - return lastName; - } - - @JsonIgnore - public String getEMail() { - return eMail; - } - - public Boolean isAdmin() { - return admin; - } - - public String getLas2peerId() { - return las2peerId; - } - - public String getUserName() { - return userName; - } - - public String getProfileImage() { - return profileImage; - } - - public Boolean isEmailLeadSubscription() { - return emailLeadSubscription; - } - - public Boolean isEmailFollowSubscription() { - return emailFollowSubscription; - } - - public Date getCreationDate() { - return creationDate; - } - - public Date getLastUpdatedDate() { - return lastUpdatedDate; - } - - public Date getLastLoginDate() { - return lastLoginDate; - } - - public static Builder geBuilder(String eMail) { - return new Builder(eMail); - } - - public boolean getAdmin() { - return admin; - } - - public static class Builder { - private int id; - private String firstName; - private String lastName; - private String eMail; - private Boolean admin; - private String las2peerId; - private String userName; - private String profileImage; - private Boolean emailLeadSubscription; - private Boolean emailFollowSubscription; - private Date creationDate; - private Date lastUpdatedDate; - private Date lastLoginDate; - - public Builder(String eMail) { - this.eMail = eMail; - } - - public Builder id(int id) { - this.id = id; - return this; - } - - public Builder firstName(String firstName) { - this.firstName = firstName; - return this; - } - - public Builder lastName(String lastName) { - this.lastName = lastName; - return this; - } - - public Builder eMail(String eMail) { - this.eMail = eMail; - return this; - } - - public Builder admin(Boolean admin) { - this.admin = admin; - return this; - } - - public Builder las2peerId(String userId) { - this.las2peerId = userId; - return this; - } - - public Builder userName(String userName) { - this.userName = userName; - return this; - } - - public Builder profileImage(String profileImage) { - this.profileImage = profileImage; - return this; - } - - public Builder emailLeadSubscription(Boolean emailLeadSubscription) { - this.emailLeadSubscription = emailLeadSubscription; - return this; - } - - public Builder emailFollowSubscription(Boolean emailFollowSubscription) { - this.emailFollowSubscription = emailFollowSubscription; - return this; - } - - public Builder creationDate(Date creationDate) { - this.creationDate = creationDate; - return this; - } - - public Builder lastUpdatedDate(Date lastUpdatedDate) { - this.lastUpdatedDate = lastUpdatedDate; - return this; - } - - public Builder lastLoginDate(Date lastLoginDate) { - this.lastLoginDate = lastLoginDate; - return this; - } - - public User build() { - return new User(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Vote.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Vote.java deleted file mode 100644 index f41a6b70..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/entities/Vote.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.entities; - -/** - * @author Adam Gavronek - * @since 6/11/2014 - */ -public class Vote extends EntityBase { - - private final int Id; - private final boolean isUpvote; - private final int RequirementId; - private final int UserId; - - private Vote(Builder builder) { - Id = builder.id; - this.isUpvote = builder.isUpvote; - RequirementId = builder.requirementId; - UserId = builder.userId; - } - - public int getId() { - return Id; - } - - public boolean isUpvote() { - return isUpvote; - } - - public int getRequirementId() { - return RequirementId; - } - - public int getUserId() { - return UserId; - } - - public static Builder getBuilder() { - return new Builder(); - } - - public static class Builder { - private int id; - private boolean isUpvote; - private int requirementId; - private int userId; - - public Builder id(int id) { - this.id = id; - return this; - } - - public Builder isUpvote(boolean isUpvote) { - this.isUpvote = isUpvote; - return this; - } - - public Builder requirementId(int requirementId) { - this.requirementId = requirementId; - return this; - } - - public Builder userId(int userId) { - this.userId = userId; - return this; - } - - public Vote build() { - return new Vote(this); - } - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/DefaultCatalog.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/DefaultCatalog.java deleted file mode 100644 index 37fa34c8..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/DefaultCatalog.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq; - - -import org.jooq.Schema; -import org.jooq.impl.CatalogImpl; - -import javax.annotation.Generated; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class DefaultCatalog extends CatalogImpl { - - private static final long serialVersionUID = 617773064; - - /** - * The reference instance of - */ - public static final DefaultCatalog DEFAULT_CATALOG = new DefaultCatalog(); - - /** - * The schema reqbaz. - */ - public final Reqbaz REQBAZ = de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz.REQBAZ; - - /** - * No further instances allowed - */ - private DefaultCatalog() { - super(""); - } - - @Override - public final List getSchemas() { - List result = new ArrayList(); - result.addAll(getSchemas0()); - return result; - } - - private final List getSchemas0() { - return Arrays.asList( - Reqbaz.REQBAZ); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/Keys.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/Keys.java deleted file mode 100644 index db732abd..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/Keys.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.*; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.*; -import org.jooq.ForeignKey; -import org.jooq.Identity; -import org.jooq.UniqueKey; -import org.jooq.impl.AbstractKeys; - -import javax.annotation.Generated; - - -/** - * A class modelling foreign key relationships between tables of the reqbaz - * schema - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class Keys { - - // ------------------------------------------------------------------------- - // IDENTITY definitions - // ------------------------------------------------------------------------- - - public static final Identity IDENTITY_ATTACHMENT = Identities0.IDENTITY_ATTACHMENT; - public static final Identity IDENTITY_CATEGORY = Identities0.IDENTITY_CATEGORY; - public static final Identity IDENTITY_CATEGORY_FOLLOWER_MAP = Identities0.IDENTITY_CATEGORY_FOLLOWER_MAP; - public static final Identity IDENTITY_COMMENT = Identities0.IDENTITY_COMMENT; - public static final Identity IDENTITY_PRIVILEGE = Identities0.IDENTITY_PRIVILEGE; - public static final Identity IDENTITY_PROJECT = Identities0.IDENTITY_PROJECT; - public static final Identity IDENTITY_PROJECT_FOLLOWER_MAP = Identities0.IDENTITY_PROJECT_FOLLOWER_MAP; - public static final Identity IDENTITY_REQUIREMENT = Identities0.IDENTITY_REQUIREMENT; - public static final Identity IDENTITY_REQUIREMENT_CATEGORY_MAP = Identities0.IDENTITY_REQUIREMENT_CATEGORY_MAP; - public static final Identity IDENTITY_REQUIREMENT_DEVELOPER_MAP = Identities0.IDENTITY_REQUIREMENT_DEVELOPER_MAP; - public static final Identity IDENTITY_REQUIREMENT_FOLLOWER_MAP = Identities0.IDENTITY_REQUIREMENT_FOLLOWER_MAP; - public static final Identity IDENTITY_ROLE = Identities0.IDENTITY_ROLE; - public static final Identity IDENTITY_ROLE_PRIVILEGE_MAP = Identities0.IDENTITY_ROLE_PRIVILEGE_MAP; - public static final Identity IDENTITY_ROLE_ROLE_MAP = Identities0.IDENTITY_ROLE_ROLE_MAP; - public static final Identity IDENTITY_USER = Identities0.IDENTITY_USER; - public static final Identity IDENTITY_USER_ROLE_MAP = Identities0.IDENTITY_USER_ROLE_MAP; - public static final Identity IDENTITY_VOTE = Identities0.IDENTITY_VOTE; - - // ------------------------------------------------------------------------- - // UNIQUE and PRIMARY KEY definitions - // ------------------------------------------------------------------------- - - public static final UniqueKey KEY_ATTACHMENT_PRIMARY = UniqueKeys0.KEY_ATTACHMENT_PRIMARY; - public static final UniqueKey KEY_CATEGORY_PRIMARY = UniqueKeys0.KEY_CATEGORY_PRIMARY; - public static final UniqueKey KEY_CATEGORY_FOLLOWER_MAP_PRIMARY = UniqueKeys0.KEY_CATEGORY_FOLLOWER_MAP_PRIMARY; - public static final UniqueKey KEY_COMMENT_PRIMARY = UniqueKeys0.KEY_COMMENT_PRIMARY; - public static final UniqueKey KEY_PRIVILEGE_PRIMARY = UniqueKeys0.KEY_PRIVILEGE_PRIMARY; - public static final UniqueKey KEY_PROJECT_PRIMARY = UniqueKeys0.KEY_PROJECT_PRIMARY; - public static final UniqueKey KEY_PROJECT_FOLLOWER_MAP_PRIMARY = UniqueKeys0.KEY_PROJECT_FOLLOWER_MAP_PRIMARY; - public static final UniqueKey KEY_REQUIREMENT_PRIMARY = UniqueKeys0.KEY_REQUIREMENT_PRIMARY; - public static final UniqueKey KEY_REQUIREMENT_CATEGORY_MAP_PRIMARY = UniqueKeys0.KEY_REQUIREMENT_CATEGORY_MAP_PRIMARY; - public static final UniqueKey KEY_REQUIREMENT_DEVELOPER_MAP_PRIMARY = UniqueKeys0.KEY_REQUIREMENT_DEVELOPER_MAP_PRIMARY; - public static final UniqueKey KEY_REQUIREMENT_FOLLOWER_MAP_PRIMARY = UniqueKeys0.KEY_REQUIREMENT_FOLLOWER_MAP_PRIMARY; - public static final UniqueKey KEY_ROLE_PRIMARY = UniqueKeys0.KEY_ROLE_PRIMARY; - public static final UniqueKey KEY_ROLE_ROLE_IDX_1 = UniqueKeys0.KEY_ROLE_ROLE_IDX_1; - public static final UniqueKey KEY_ROLE_PRIVILEGE_MAP_PRIMARY = UniqueKeys0.KEY_ROLE_PRIVILEGE_MAP_PRIMARY; - public static final UniqueKey KEY_ROLE_ROLE_MAP_PRIMARY = UniqueKeys0.KEY_ROLE_ROLE_MAP_PRIMARY; - public static final UniqueKey KEY_SCHEMA_VERSION_PRIMARY = UniqueKeys0.KEY_SCHEMA_VERSION_PRIMARY; - public static final UniqueKey KEY_USER_PRIMARY = UniqueKeys0.KEY_USER_PRIMARY; - public static final UniqueKey KEY_USER_LAS2PEER_IDX = UniqueKeys0.KEY_USER_LAS2PEER_IDX; - public static final UniqueKey KEY_USER_ROLE_MAP_PRIMARY = UniqueKeys0.KEY_USER_ROLE_MAP_PRIMARY; - public static final UniqueKey KEY_VOTE_PRIMARY = UniqueKeys0.KEY_VOTE_PRIMARY; - - // ------------------------------------------------------------------------- - // FOREIGN KEY definitions - // ------------------------------------------------------------------------- - - public static final ForeignKey ATTACHMENT_REQUIREMENT = ForeignKeys0.ATTACHMENT_REQUIREMENT; - public static final ForeignKey ATTACHMENT_USER = ForeignKeys0.ATTACHMENT_USER; - public static final ForeignKey CATEGORY_PROJECT = ForeignKeys0.CATEGORY_PROJECT; - public static final ForeignKey CATEGORY_USER = ForeignKeys0.CATEGORY_USER; - public static final ForeignKey CATEGORY_FOLLOWER_MAP_CATEGORY = ForeignKeys0.CATEGORY_FOLLOWER_MAP_CATEGORY; - public static final ForeignKey CATEGORY_FOLLOWER_MAP_USER = ForeignKeys0.CATEGORY_FOLLOWER_MAP_USER; - public static final ForeignKey COMMENT_REQUIREMENT = ForeignKeys0.COMMENT_REQUIREMENT; - public static final ForeignKey COMMENT_USER = ForeignKeys0.COMMENT_USER; - public static final ForeignKey REPLY_COMMENT = ForeignKeys0.REPLY_COMMENT; - public static final ForeignKey PROJECT_USER = ForeignKeys0.PROJECT_USER; - public static final ForeignKey PROJECT_CATEGORY = ForeignKeys0.PROJECT_CATEGORY; - public static final ForeignKey PROJECT_FOLLOWER_MAP_PROJECT = ForeignKeys0.PROJECT_FOLLOWER_MAP_PROJECT; - public static final ForeignKey PROJECT_FOLLOWER_MAP_USER = ForeignKeys0.PROJECT_FOLLOWER_MAP_USER; - public static final ForeignKey LEAD_DEVELOPER = ForeignKeys0.LEAD_DEVELOPER; - public static final ForeignKey CREATOR = ForeignKeys0.CREATOR; - public static final ForeignKey REQUIREMENT_PROJECT = ForeignKeys0.REQUIREMENT_PROJECT; - public static final ForeignKey REQUIREMENT_CATEGORY_MAP_CATEGORY = ForeignKeys0.REQUIREMENT_CATEGORY_MAP_CATEGORY; - public static final ForeignKey REQUIREMENT_CATEGORY_MAP_REQUIREMENT = ForeignKeys0.REQUIREMENT_CATEGORY_MAP_REQUIREMENT; - public static final ForeignKey REQUIREMENT_DEVELOPER_MAP_REQUIREMENT = ForeignKeys0.REQUIREMENT_DEVELOPER_MAP_REQUIREMENT; - public static final ForeignKey REQUIREMENT_DEVELOPER_MAP_USER = ForeignKeys0.REQUIREMENT_DEVELOPER_MAP_USER; - public static final ForeignKey REQUIREMENT_FOLLOWER_MAP_REQUIREMENT = ForeignKeys0.REQUIREMENT_FOLLOWER_MAP_REQUIREMENT; - public static final ForeignKey REQUIREMENT_FOLLOWER_MAP_USER = ForeignKeys0.REQUIREMENT_FOLLOWER_MAP_USER; - public static final ForeignKey ROLE_PRIVILEGE_MAP_ROLE = ForeignKeys0.ROLE_PRIVILEGE_MAP_ROLE; - public static final ForeignKey ROLE_PRIVILEGE_MAP_PRIVILEGE = ForeignKeys0.ROLE_PRIVILEGE_MAP_PRIVILEGE; - public static final ForeignKey ROLE_ROLE_MAP_CHILD = ForeignKeys0.ROLE_ROLE_MAP_CHILD; - public static final ForeignKey ROLE_ROLE_MAP_PARENT = ForeignKeys0.ROLE_ROLE_MAP_PARENT; - public static final ForeignKey USER_ROLE_MAP_ROLE = ForeignKeys0.USER_ROLE_MAP_ROLE; - public static final ForeignKey USER_ROLE_MAP_USER = ForeignKeys0.USER_ROLE_MAP_USER; - public static final ForeignKey VOTE_REQUIREMENT = ForeignKeys0.VOTE_REQUIREMENT; - public static final ForeignKey VOTE_USER = ForeignKeys0.VOTE_USER; - - // ------------------------------------------------------------------------- - // [#1459] distribute members to avoid static initialisers > 64kb - // ------------------------------------------------------------------------- - - private static class Identities0 extends AbstractKeys { - public static Identity IDENTITY_ATTACHMENT = createIdentity(Attachment.ATTACHMENT, Attachment.ATTACHMENT.ID); - public static Identity IDENTITY_CATEGORY = createIdentity(Category.CATEGORY, Category.CATEGORY.ID); - public static Identity IDENTITY_CATEGORY_FOLLOWER_MAP = createIdentity(CategoryFollowerMap.CATEGORY_FOLLOWER_MAP, CategoryFollowerMap.CATEGORY_FOLLOWER_MAP.ID); - public static Identity IDENTITY_COMMENT = createIdentity(Comment.COMMENT, Comment.COMMENT.ID); - public static Identity IDENTITY_PRIVILEGE = createIdentity(Privilege.PRIVILEGE, Privilege.PRIVILEGE.ID); - public static Identity IDENTITY_PROJECT = createIdentity(Project.PROJECT, Project.PROJECT.ID); - public static Identity IDENTITY_PROJECT_FOLLOWER_MAP = createIdentity(ProjectFollowerMap.PROJECT_FOLLOWER_MAP, ProjectFollowerMap.PROJECT_FOLLOWER_MAP.ID); - public static Identity IDENTITY_REQUIREMENT = createIdentity(Requirement.REQUIREMENT, Requirement.REQUIREMENT.ID); - public static Identity IDENTITY_REQUIREMENT_CATEGORY_MAP = createIdentity(RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP, RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP.ID); - public static Identity IDENTITY_REQUIREMENT_DEVELOPER_MAP = createIdentity(RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP, RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP.ID); - public static Identity IDENTITY_REQUIREMENT_FOLLOWER_MAP = createIdentity(RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP, RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP.ID); - public static Identity IDENTITY_ROLE = createIdentity(Role.ROLE, Role.ROLE.ID); - public static Identity IDENTITY_ROLE_PRIVILEGE_MAP = createIdentity(RolePrivilegeMap.ROLE_PRIVILEGE_MAP, RolePrivilegeMap.ROLE_PRIVILEGE_MAP.ID); - public static Identity IDENTITY_ROLE_ROLE_MAP = createIdentity(RoleRoleMap.ROLE_ROLE_MAP, RoleRoleMap.ROLE_ROLE_MAP.ID); - public static Identity IDENTITY_USER = createIdentity(User.USER, User.USER.ID); - public static Identity IDENTITY_USER_ROLE_MAP = createIdentity(UserRoleMap.USER_ROLE_MAP, UserRoleMap.USER_ROLE_MAP.ID); - public static Identity IDENTITY_VOTE = createIdentity(Vote.VOTE, Vote.VOTE.ID); - } - - private static class UniqueKeys0 extends AbstractKeys { - public static final UniqueKey KEY_ATTACHMENT_PRIMARY = createUniqueKey(Attachment.ATTACHMENT, "KEY_attachment_PRIMARY", Attachment.ATTACHMENT.ID); - public static final UniqueKey KEY_CATEGORY_PRIMARY = createUniqueKey(Category.CATEGORY, "KEY_category_PRIMARY", Category.CATEGORY.ID); - public static final UniqueKey KEY_CATEGORY_FOLLOWER_MAP_PRIMARY = createUniqueKey(CategoryFollowerMap.CATEGORY_FOLLOWER_MAP, "KEY_category_follower_map_PRIMARY", CategoryFollowerMap.CATEGORY_FOLLOWER_MAP.ID); - public static final UniqueKey KEY_COMMENT_PRIMARY = createUniqueKey(Comment.COMMENT, "KEY_comment_PRIMARY", Comment.COMMENT.ID); - public static final UniqueKey KEY_PRIVILEGE_PRIMARY = createUniqueKey(Privilege.PRIVILEGE, "KEY_privilege_PRIMARY", Privilege.PRIVILEGE.ID); - public static final UniqueKey KEY_PROJECT_PRIMARY = createUniqueKey(Project.PROJECT, "KEY_project_PRIMARY", Project.PROJECT.ID); - public static final UniqueKey KEY_PROJECT_FOLLOWER_MAP_PRIMARY = createUniqueKey(ProjectFollowerMap.PROJECT_FOLLOWER_MAP, "KEY_project_follower_map_PRIMARY", ProjectFollowerMap.PROJECT_FOLLOWER_MAP.ID); - public static final UniqueKey KEY_REQUIREMENT_PRIMARY = createUniqueKey(Requirement.REQUIREMENT, "KEY_requirement_PRIMARY", Requirement.REQUIREMENT.ID); - public static final UniqueKey KEY_REQUIREMENT_CATEGORY_MAP_PRIMARY = createUniqueKey(RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP, "KEY_requirement_category_map_PRIMARY", RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP.ID); - public static final UniqueKey KEY_REQUIREMENT_DEVELOPER_MAP_PRIMARY = createUniqueKey(RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP, "KEY_requirement_developer_map_PRIMARY", RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP.ID); - public static final UniqueKey KEY_REQUIREMENT_FOLLOWER_MAP_PRIMARY = createUniqueKey(RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP, "KEY_requirement_follower_map_PRIMARY", RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP.ID); - public static final UniqueKey KEY_ROLE_PRIMARY = createUniqueKey(Role.ROLE, "KEY_role_PRIMARY", Role.ROLE.ID); - public static final UniqueKey KEY_ROLE_ROLE_IDX_1 = createUniqueKey(Role.ROLE, "KEY_role_role_idx_1", Role.ROLE.NAME); - public static final UniqueKey KEY_ROLE_PRIVILEGE_MAP_PRIMARY = createUniqueKey(RolePrivilegeMap.ROLE_PRIVILEGE_MAP, "KEY_role_privilege_map_PRIMARY", RolePrivilegeMap.ROLE_PRIVILEGE_MAP.ID); - public static final UniqueKey KEY_ROLE_ROLE_MAP_PRIMARY = createUniqueKey(RoleRoleMap.ROLE_ROLE_MAP, "KEY_role_role_map_PRIMARY", RoleRoleMap.ROLE_ROLE_MAP.ID); - public static final UniqueKey KEY_SCHEMA_VERSION_PRIMARY = createUniqueKey(SchemaVersion.SCHEMA_VERSION, "KEY_schema_version_PRIMARY", SchemaVersion.SCHEMA_VERSION.INSTALLED_RANK); - public static final UniqueKey KEY_USER_PRIMARY = createUniqueKey(User.USER, "KEY_user_PRIMARY", User.USER.ID); - public static final UniqueKey KEY_USER_LAS2PEER_IDX = createUniqueKey(User.USER, "KEY_user_las2peer_idx", User.USER.LAS2PEER_ID); - public static final UniqueKey KEY_USER_ROLE_MAP_PRIMARY = createUniqueKey(UserRoleMap.USER_ROLE_MAP, "KEY_user_role_map_PRIMARY", UserRoleMap.USER_ROLE_MAP.ID); - public static final UniqueKey KEY_VOTE_PRIMARY = createUniqueKey(Vote.VOTE, "KEY_vote_PRIMARY", Vote.VOTE.ID); - } - - private static class ForeignKeys0 extends AbstractKeys { - public static final ForeignKey ATTACHMENT_REQUIREMENT = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_REQUIREMENT_PRIMARY, Attachment.ATTACHMENT, "attachment_requirement", Attachment.ATTACHMENT.REQUIREMENT_ID); - public static final ForeignKey ATTACHMENT_USER = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, Attachment.ATTACHMENT, "attachment_user", Attachment.ATTACHMENT.USER_ID); - public static final ForeignKey CATEGORY_PROJECT = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_PROJECT_PRIMARY, Category.CATEGORY, "category_project", Category.CATEGORY.PROJECT_ID); - public static final ForeignKey CATEGORY_USER = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, Category.CATEGORY, "category_user", Category.CATEGORY.LEADER_ID); - public static final ForeignKey CATEGORY_FOLLOWER_MAP_CATEGORY = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_CATEGORY_PRIMARY, CategoryFollowerMap.CATEGORY_FOLLOWER_MAP, "category_follower_map_category", CategoryFollowerMap.CATEGORY_FOLLOWER_MAP.CATEGORY_ID); - public static final ForeignKey CATEGORY_FOLLOWER_MAP_USER = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, CategoryFollowerMap.CATEGORY_FOLLOWER_MAP, "category_follower_map_user", CategoryFollowerMap.CATEGORY_FOLLOWER_MAP.USER_ID); - public static final ForeignKey COMMENT_REQUIREMENT = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_REQUIREMENT_PRIMARY, Comment.COMMENT, "comment_requirement", Comment.COMMENT.REQUIREMENT_ID); - public static final ForeignKey COMMENT_USER = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, Comment.COMMENT, "comment_user", Comment.COMMENT.USER_ID); - public static final ForeignKey REPLY_COMMENT = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_COMMENT_PRIMARY, Comment.COMMENT, "reply_comment", Comment.COMMENT.REPLY_TO_COMMENT_ID); - public static final ForeignKey PROJECT_USER = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, Project.PROJECT, "project_user", Project.PROJECT.LEADER_ID); - public static final ForeignKey PROJECT_CATEGORY = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_CATEGORY_PRIMARY, Project.PROJECT, "project_category", Project.PROJECT.DEFAULT_CATEGORY_ID); - public static final ForeignKey PROJECT_FOLLOWER_MAP_PROJECT = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_PROJECT_PRIMARY, ProjectFollowerMap.PROJECT_FOLLOWER_MAP, "project_follower_map_project", ProjectFollowerMap.PROJECT_FOLLOWER_MAP.PROJECT_ID); - public static final ForeignKey PROJECT_FOLLOWER_MAP_USER = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, ProjectFollowerMap.PROJECT_FOLLOWER_MAP, "project_follower_map_user", ProjectFollowerMap.PROJECT_FOLLOWER_MAP.USER_ID); - public static final ForeignKey LEAD_DEVELOPER = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, Requirement.REQUIREMENT, "lead_developer", Requirement.REQUIREMENT.LEAD_DEVELOPER_ID); - public static final ForeignKey CREATOR = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, Requirement.REQUIREMENT, "creator", Requirement.REQUIREMENT.CREATOR_ID); - public static final ForeignKey REQUIREMENT_PROJECT = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_PROJECT_PRIMARY, Requirement.REQUIREMENT, "requirement_project", Requirement.REQUIREMENT.PROJECT_ID); - public static final ForeignKey REQUIREMENT_CATEGORY_MAP_CATEGORY = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_CATEGORY_PRIMARY, RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP, "requirement_category_map_category", RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP.CATEGORY_ID); - public static final ForeignKey REQUIREMENT_CATEGORY_MAP_REQUIREMENT = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_REQUIREMENT_PRIMARY, RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP, "requirement_category_map_requirement", RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID); - public static final ForeignKey REQUIREMENT_DEVELOPER_MAP_REQUIREMENT = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_REQUIREMENT_PRIMARY, RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP, "requirement_developer_map_requirement", RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP.REQUIREMENT_ID); - public static final ForeignKey REQUIREMENT_DEVELOPER_MAP_USER = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP, "requirement_developer_map_user", RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP.USER_ID); - public static final ForeignKey REQUIREMENT_FOLLOWER_MAP_REQUIREMENT = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_REQUIREMENT_PRIMARY, RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP, "requirement_follower_map_requirement", RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID); - public static final ForeignKey REQUIREMENT_FOLLOWER_MAP_USER = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP, "requirement_follower_map_user", RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP.USER_ID); - public static final ForeignKey ROLE_PRIVILEGE_MAP_ROLE = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_ROLE_PRIMARY, RolePrivilegeMap.ROLE_PRIVILEGE_MAP, "role_privilege_map_role", RolePrivilegeMap.ROLE_PRIVILEGE_MAP.ROLE_ID); - public static final ForeignKey ROLE_PRIVILEGE_MAP_PRIVILEGE = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_PRIVILEGE_PRIMARY, RolePrivilegeMap.ROLE_PRIVILEGE_MAP, "role_privilege_map_privilege", RolePrivilegeMap.ROLE_PRIVILEGE_MAP.PRIVILEGE_ID); - public static final ForeignKey ROLE_ROLE_MAP_CHILD = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_ROLE_PRIMARY, RoleRoleMap.ROLE_ROLE_MAP, "role_role_map_child", RoleRoleMap.ROLE_ROLE_MAP.CHILD_ID); - public static final ForeignKey ROLE_ROLE_MAP_PARENT = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_ROLE_PRIMARY, RoleRoleMap.ROLE_ROLE_MAP, "role_role_map_parent", RoleRoleMap.ROLE_ROLE_MAP.PARENT_ID); - public static final ForeignKey USER_ROLE_MAP_ROLE = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_ROLE_PRIMARY, UserRoleMap.USER_ROLE_MAP, "user_role_map_role", UserRoleMap.USER_ROLE_MAP.ROLE_ID); - public static final ForeignKey USER_ROLE_MAP_USER = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, UserRoleMap.USER_ROLE_MAP, "user_role_map_user", UserRoleMap.USER_ROLE_MAP.USER_ID); - public static final ForeignKey VOTE_REQUIREMENT = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_REQUIREMENT_PRIMARY, Vote.VOTE, "vote_requirement", Vote.VOTE.REQUIREMENT_ID); - public static final ForeignKey VOTE_USER = createForeignKey(de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys.KEY_USER_PRIMARY, Vote.VOTE, "vote_user", Vote.VOTE.USER_ID); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/Reqbaz.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/Reqbaz.java deleted file mode 100644 index 5ee813d6..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/Reqbaz.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.*; -import org.jooq.Catalog; -import org.jooq.Table; -import org.jooq.impl.SchemaImpl; - -import javax.annotation.Generated; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class Reqbaz extends SchemaImpl { - - private static final long serialVersionUID = 1551044375; - - /** - * The reference instance of reqbaz - */ - public static final Reqbaz REQBAZ = new Reqbaz(); - - /** - * The table reqbaz.attachment. - */ - public final Attachment ATTACHMENT = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Attachment.ATTACHMENT; - - /** - * The table reqbaz.category. - */ - public final Category CATEGORY = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Category.CATEGORY; - - /** - * The table reqbaz.category_follower_map. - */ - public final CategoryFollowerMap CATEGORY_FOLLOWER_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.CategoryFollowerMap.CATEGORY_FOLLOWER_MAP; - - /** - * The table reqbaz.comment. - */ - public final Comment COMMENT = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Comment.COMMENT; - - /** - * The table reqbaz.privilege. - */ - public final Privilege PRIVILEGE = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Privilege.PRIVILEGE; - - /** - * The table reqbaz.project. - */ - public final Project PROJECT = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Project.PROJECT; - - /** - * The table reqbaz.project_follower_map. - */ - public final ProjectFollowerMap PROJECT_FOLLOWER_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.ProjectFollowerMap.PROJECT_FOLLOWER_MAP; - - /** - * The table reqbaz.requirement. - */ - public final Requirement REQUIREMENT = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Requirement.REQUIREMENT; - - /** - * The table reqbaz.requirement_category_map. - */ - public final RequirementCategoryMap REQUIREMENT_CATEGORY_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP; - - /** - * The table reqbaz.requirement_developer_map. - */ - public final RequirementDeveloperMap REQUIREMENT_DEVELOPER_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP; - - /** - * The table reqbaz.requirement_follower_map. - */ - public final RequirementFollowerMap REQUIREMENT_FOLLOWER_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP; - - /** - * The table reqbaz.role. - */ - public final Role ROLE = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Role.ROLE; - - /** - * The table reqbaz.role_privilege_map. - */ - public final RolePrivilegeMap ROLE_PRIVILEGE_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RolePrivilegeMap.ROLE_PRIVILEGE_MAP; - - /** - * The table reqbaz.role_role_map. - */ - public final RoleRoleMap ROLE_ROLE_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RoleRoleMap.ROLE_ROLE_MAP; - - /** - * The table reqbaz.schema_version. - */ - public final SchemaVersion SCHEMA_VERSION = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.SchemaVersion.SCHEMA_VERSION; - - /** - * The table reqbaz.user. - */ - public final User USER = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User.USER; - - /** - * The table reqbaz.user_role_map. - */ - public final UserRoleMap USER_ROLE_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.UserRoleMap.USER_ROLE_MAP; - - /** - * The table reqbaz.vote. - */ - public final Vote VOTE = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Vote.VOTE; - - /** - * No further instances allowed - */ - private Reqbaz() { - super("reqbaz", null); - } - - - /** - * {@inheritDoc} - */ - @Override - public Catalog getCatalog() { - return DefaultCatalog.DEFAULT_CATALOG; - } - - @Override - public final List> getTables() { - List result = new ArrayList(); - result.addAll(getTables0()); - return result; - } - - private final List> getTables0() { - return Arrays.>asList( - Attachment.ATTACHMENT, - Category.CATEGORY, - CategoryFollowerMap.CATEGORY_FOLLOWER_MAP, - Comment.COMMENT, - Privilege.PRIVILEGE, - Project.PROJECT, - ProjectFollowerMap.PROJECT_FOLLOWER_MAP, - Requirement.REQUIREMENT, - RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP, - RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP, - RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP, - Role.ROLE, - RolePrivilegeMap.ROLE_PRIVILEGE_MAP, - RoleRoleMap.ROLE_ROLE_MAP, - SchemaVersion.SCHEMA_VERSION, - User.USER, - UserRoleMap.USER_ROLE_MAP, - Vote.VOTE); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/Tables.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/Tables.java deleted file mode 100644 index c17346e3..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/Tables.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.*; - -import javax.annotation.Generated; - - -/** - * Convenience access to all tables in reqbaz - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class Tables { - - /** - * The table reqbaz.attachment. - */ - public static final Attachment ATTACHMENT = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Attachment.ATTACHMENT; - - /** - * The table reqbaz.category. - */ - public static final Category CATEGORY = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Category.CATEGORY; - - /** - * The table reqbaz.category_follower_map. - */ - public static final CategoryFollowerMap CATEGORY_FOLLOWER_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.CategoryFollowerMap.CATEGORY_FOLLOWER_MAP; - - /** - * The table reqbaz.comment. - */ - public static final Comment COMMENT = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Comment.COMMENT; - - /** - * The table reqbaz.privilege. - */ - public static final Privilege PRIVILEGE = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Privilege.PRIVILEGE; - - /** - * The table reqbaz.project. - */ - public static final Project PROJECT = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Project.PROJECT; - - /** - * The table reqbaz.project_follower_map. - */ - public static final ProjectFollowerMap PROJECT_FOLLOWER_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.ProjectFollowerMap.PROJECT_FOLLOWER_MAP; - - /** - * The table reqbaz.requirement. - */ - public static final Requirement REQUIREMENT = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Requirement.REQUIREMENT; - - /** - * The table reqbaz.requirement_category_map. - */ - public static final RequirementCategoryMap REQUIREMENT_CATEGORY_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP; - - /** - * The table reqbaz.requirement_developer_map. - */ - public static final RequirementDeveloperMap REQUIREMENT_DEVELOPER_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP; - - /** - * The table reqbaz.requirement_follower_map. - */ - public static final RequirementFollowerMap REQUIREMENT_FOLLOWER_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP; - - /** - * The table reqbaz.role. - */ - public static final Role ROLE = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Role.ROLE; - - /** - * The table reqbaz.role_privilege_map. - */ - public static final RolePrivilegeMap ROLE_PRIVILEGE_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RolePrivilegeMap.ROLE_PRIVILEGE_MAP; - - /** - * The table reqbaz.role_role_map. - */ - public static final RoleRoleMap ROLE_ROLE_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RoleRoleMap.ROLE_ROLE_MAP; - - /** - * The table reqbaz.schema_version. - */ - public static final SchemaVersion SCHEMA_VERSION = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.SchemaVersion.SCHEMA_VERSION; - - /** - * The table reqbaz.user. - */ - public static final User USER = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User.USER; - - /** - * The table reqbaz.user_role_map. - */ - public static final UserRoleMap USER_ROLE_MAP = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.UserRoleMap.USER_ROLE_MAP; - - /** - * The table reqbaz.vote. - */ - public static final Vote VOTE = de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Vote.VOTE; -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Attachment.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Attachment.java deleted file mode 100644 index dfcf5e42..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Attachment.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.AttachmentRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class Attachment extends TableImpl { - - private static final long serialVersionUID = -1603866374; - - /** - * The reference instance of reqbaz.attachment - */ - public static final Attachment ATTACHMENT = new Attachment(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return AttachmentRecord.class; - } - - /** - * The column reqbaz.attachment.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.attachment.creation_date. - */ - public final TableField CREATION_DATE = createField("creation_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * The column reqbaz.attachment.last_updated_date. - */ - public final TableField LAST_UPDATED_DATE = createField("last_updated_date", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); - - /** - * The column reqbaz.attachment.requirement_id. - */ - public final TableField REQUIREMENT_ID = createField("requirement_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.attachment.user_id. - */ - public final TableField USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.attachment.name. - */ - public final TableField NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); - - /** - * The column reqbaz.attachment.description. - */ - public final TableField DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.CLOB, this, ""); - - /** - * The column reqbaz.attachment.mime_type. - */ - public final TableField MIME_TYPE = createField("mime_type", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); - - /** - * The column reqbaz.attachment.identifier. - */ - public final TableField IDENTIFIER = createField("identifier", org.jooq.impl.SQLDataType.VARCHAR.length(900).nullable(false), this, ""); - - /** - * The column reqbaz.attachment.file_url. - */ - public final TableField FILE_URL = createField("file_url", org.jooq.impl.SQLDataType.VARCHAR.length(1000).nullable(false), this, ""); - - /** - * Create a reqbaz.attachment table reference - */ - public Attachment() { - this("attachment", null); - } - - /** - * Create an aliased reqbaz.attachment table reference - */ - public Attachment(String alias) { - this(alias, ATTACHMENT); - } - - private Attachment(String alias, Table aliased) { - this(alias, aliased, null); - } - - private Attachment(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_ATTACHMENT; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_ATTACHMENT_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_ATTACHMENT_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.ATTACHMENT_REQUIREMENT, Keys.ATTACHMENT_USER); - } - - /** - * {@inheritDoc} - */ - @Override - public Attachment as(String alias) { - return new Attachment(alias, this); - } - - /** - * Rename this table - */ - @Override - public Attachment rename(String name) { - return new Attachment(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Category.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Category.java deleted file mode 100644 index 3b914e86..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Category.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.CategoryRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class Category extends TableImpl { - - private static final long serialVersionUID = 1856403820; - - /** - * The reference instance of reqbaz.category - */ - public static final Category CATEGORY = new Category(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return CategoryRecord.class; - } - - /** - * The column reqbaz.category.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.category.name. - */ - public final TableField NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); - - /** - * The column reqbaz.category.description. - */ - public final TableField DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, ""); - - /** - * The column reqbaz.category.creation_date. - */ - public final TableField CREATION_DATE = createField("creation_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * The column reqbaz.category.last_updated_date. - */ - public final TableField LAST_UPDATED_DATE = createField("last_updated_date", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); - - /** - * The column reqbaz.category.project_id. - */ - public final TableField PROJECT_ID = createField("project_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.category.leader_id. - */ - public final TableField LEADER_ID = createField("leader_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * Create a reqbaz.category table reference - */ - public Category() { - this("category", null); - } - - /** - * Create an aliased reqbaz.category table reference - */ - public Category(String alias) { - this(alias, CATEGORY); - } - - private Category(String alias, Table aliased) { - this(alias, aliased, null); - } - - private Category(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_CATEGORY; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_CATEGORY_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_CATEGORY_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.CATEGORY_PROJECT, Keys.CATEGORY_USER); - } - - /** - * {@inheritDoc} - */ - @Override - public Category as(String alias) { - return new Category(alias, this); - } - - /** - * Rename this table - */ - @Override - public Category rename(String name) { - return new Category(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/CategoryFollowerMap.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/CategoryFollowerMap.java deleted file mode 100644 index 6b2ae008..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/CategoryFollowerMap.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.CategoryFollowerMapRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class CategoryFollowerMap extends TableImpl { - - private static final long serialVersionUID = -1568253073; - - /** - * The reference instance of reqbaz.category_follower_map - */ - public static final CategoryFollowerMap CATEGORY_FOLLOWER_MAP = new CategoryFollowerMap(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return CategoryFollowerMapRecord.class; - } - - /** - * The column reqbaz.category_follower_map.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.category_follower_map.category_id. - */ - public final TableField CATEGORY_ID = createField("category_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.category_follower_map.user_id. - */ - public final TableField USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.category_follower_map.creation_date. - */ - public final TableField CREATION_DATE = createField("creation_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * Create a reqbaz.category_follower_map table reference - */ - public CategoryFollowerMap() { - this("category_follower_map", null); - } - - /** - * Create an aliased reqbaz.category_follower_map table reference - */ - public CategoryFollowerMap(String alias) { - this(alias, CATEGORY_FOLLOWER_MAP); - } - - private CategoryFollowerMap(String alias, Table aliased) { - this(alias, aliased, null); - } - - private CategoryFollowerMap(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_CATEGORY_FOLLOWER_MAP; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_CATEGORY_FOLLOWER_MAP_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_CATEGORY_FOLLOWER_MAP_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.CATEGORY_FOLLOWER_MAP_CATEGORY, Keys.CATEGORY_FOLLOWER_MAP_USER); - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryFollowerMap as(String alias) { - return new CategoryFollowerMap(alias, this); - } - - /** - * Rename this table - */ - @Override - public CategoryFollowerMap rename(String name) { - return new CategoryFollowerMap(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Comment.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Comment.java deleted file mode 100644 index 5cd00d29..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Comment.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.CommentRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class Comment extends TableImpl { - - private static final long serialVersionUID = -348339124; - - /** - * The reference instance of reqbaz.comment - */ - public static final Comment COMMENT = new Comment(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return CommentRecord.class; - } - - /** - * The column reqbaz.comment.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.comment.message. - */ - public final TableField MESSAGE = createField("message", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, ""); - - /** - * The column reqbaz.comment.creation_date. - */ - public final TableField CREATION_DATE = createField("creation_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * The column reqbaz.comment.last_updated_date. - */ - public final TableField LAST_UPDATED_DATE = createField("last_updated_date", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); - - /** - * The column reqbaz.comment.requirement_id. - */ - public final TableField REQUIREMENT_ID = createField("requirement_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.comment.user_id. - */ - public final TableField USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.comment.reply_to_comment_id. - */ - public final TableField REPLY_TO_COMMENT_ID = createField("reply_to_comment_id", org.jooq.impl.SQLDataType.INTEGER, this, ""); - - /** - * Create a reqbaz.comment table reference - */ - public Comment() { - this("comment", null); - } - - /** - * Create an aliased reqbaz.comment table reference - */ - public Comment(String alias) { - this(alias, COMMENT); - } - - private Comment(String alias, Table aliased) { - this(alias, aliased, null); - } - - private Comment(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_COMMENT; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_COMMENT_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_COMMENT_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.COMMENT_REQUIREMENT, Keys.COMMENT_USER, Keys.REPLY_COMMENT); - } - - /** - * {@inheritDoc} - */ - @Override - public Comment as(String alias) { - return new Comment(alias, this); - } - - /** - * Rename this table - */ - @Override - public Comment rename(String name) { - return new Comment(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Privilege.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Privilege.java deleted file mode 100644 index ccdb2a8c..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Privilege.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.PrivilegeRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class Privilege extends TableImpl { - - private static final long serialVersionUID = 799298701; - - /** - * The reference instance of reqbaz.privilege - */ - public static final Privilege PRIVILEGE = new Privilege(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return PrivilegeRecord.class; - } - - /** - * The column reqbaz.privilege.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.privilege.name. - */ - public final TableField NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(100).nullable(false), this, ""); - - /** - * Create a reqbaz.privilege table reference - */ - public Privilege() { - this("privilege", null); - } - - /** - * Create an aliased reqbaz.privilege table reference - */ - public Privilege(String alias) { - this(alias, PRIVILEGE); - } - - private Privilege(String alias, Table aliased) { - this(alias, aliased, null); - } - - private Privilege(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_PRIVILEGE; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_PRIVILEGE_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_PRIVILEGE_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public Privilege as(String alias) { - return new Privilege(alias, this); - } - - /** - * Rename this table - */ - @Override - public Privilege rename(String name) { - return new Privilege(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Project.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Project.java deleted file mode 100644 index d688c1a8..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Project.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.ProjectRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class Project extends TableImpl { - - private static final long serialVersionUID = 1235446294; - - /** - * The reference instance of reqbaz.project - */ - public static final Project PROJECT = new Project(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return ProjectRecord.class; - } - - /** - * The column reqbaz.project.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.project.name. - */ - public final TableField NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); - - /** - * The column reqbaz.project.description. - */ - public final TableField DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.CLOB.nullable(false), this, ""); - - /** - * The column reqbaz.project.visibility. - */ - public final TableField VISIBILITY = createField("visibility", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, ""); - - /** - * The column reqbaz.project.creation_date. - */ - public final TableField CREATION_DATE = createField("creation_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * The column reqbaz.project.last_updated_date. - */ - public final TableField LAST_UPDATED_DATE = createField("last_updated_date", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); - - /** - * The column reqbaz.project.leader_id. - */ - public final TableField LEADER_ID = createField("leader_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.project.default_category_id. - */ - public final TableField DEFAULT_CATEGORY_ID = createField("default_category_id", org.jooq.impl.SQLDataType.INTEGER, this, ""); - - /** - * Create a reqbaz.project table reference - */ - public Project() { - this("project", null); - } - - /** - * Create an aliased reqbaz.project table reference - */ - public Project(String alias) { - this(alias, PROJECT); - } - - private Project(String alias, Table aliased) { - this(alias, aliased, null); - } - - private Project(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_PROJECT; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_PROJECT_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_PROJECT_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.PROJECT_USER, Keys.PROJECT_CATEGORY); - } - - /** - * {@inheritDoc} - */ - @Override - public Project as(String alias) { - return new Project(alias, this); - } - - /** - * Rename this table - */ - @Override - public Project rename(String name) { - return new Project(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/ProjectFollowerMap.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/ProjectFollowerMap.java deleted file mode 100644 index 14a67863..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/ProjectFollowerMap.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.ProjectFollowerMapRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class ProjectFollowerMap extends TableImpl { - - private static final long serialVersionUID = -1701261507; - - /** - * The reference instance of reqbaz.project_follower_map - */ - public static final ProjectFollowerMap PROJECT_FOLLOWER_MAP = new ProjectFollowerMap(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return ProjectFollowerMapRecord.class; - } - - /** - * The column reqbaz.project_follower_map.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.project_follower_map.project_id. - */ - public final TableField PROJECT_ID = createField("project_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.project_follower_map.user_id. - */ - public final TableField USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.project_follower_map.creation_date. - */ - public final TableField CREATION_DATE = createField("creation_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * Create a reqbaz.project_follower_map table reference - */ - public ProjectFollowerMap() { - this("project_follower_map", null); - } - - /** - * Create an aliased reqbaz.project_follower_map table reference - */ - public ProjectFollowerMap(String alias) { - this(alias, PROJECT_FOLLOWER_MAP); - } - - private ProjectFollowerMap(String alias, Table aliased) { - this(alias, aliased, null); - } - - private ProjectFollowerMap(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_PROJECT_FOLLOWER_MAP; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_PROJECT_FOLLOWER_MAP_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_PROJECT_FOLLOWER_MAP_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.PROJECT_FOLLOWER_MAP_PROJECT, Keys.PROJECT_FOLLOWER_MAP_USER); - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectFollowerMap as(String alias) { - return new ProjectFollowerMap(alias, this); - } - - /** - * Rename this table - */ - @Override - public ProjectFollowerMap rename(String name) { - return new ProjectFollowerMap(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Requirement.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Requirement.java deleted file mode 100644 index adf3908b..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Requirement.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class Requirement extends TableImpl { - - private static final long serialVersionUID = 507661299; - - /** - * The reference instance of reqbaz.requirement - */ - public static final Requirement REQUIREMENT = new Requirement(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return RequirementRecord.class; - } - - /** - * The column reqbaz.requirement.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.requirement.name. - */ - public final TableField NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); - - /** - * The column reqbaz.requirement.description. - */ - public final TableField DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.CLOB, this, ""); - - /** - * The column reqbaz.requirement.realized. - */ - public final TableField REALIZED = createField("realized", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); - - /** - * The column reqbaz.requirement.creation_date. - */ - public final TableField CREATION_DATE = createField("creation_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * The column reqbaz.requirement.last_updated_date. - */ - public final TableField LAST_UPDATED_DATE = createField("last_updated_date", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); - - /** - * The column reqbaz.requirement.lead_developer_id. - */ - public final TableField LEAD_DEVELOPER_ID = createField("lead_developer_id", org.jooq.impl.SQLDataType.INTEGER, this, ""); - - /** - * The column reqbaz.requirement.creator_id. - */ - public final TableField CREATOR_ID = createField("creator_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.requirement.project_id. - */ - public final TableField PROJECT_ID = createField("project_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * Create a reqbaz.requirement table reference - */ - public Requirement() { - this("requirement", null); - } - - /** - * Create an aliased reqbaz.requirement table reference - */ - public Requirement(String alias) { - this(alias, REQUIREMENT); - } - - private Requirement(String alias, Table aliased) { - this(alias, aliased, null); - } - - private Requirement(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_REQUIREMENT; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_REQUIREMENT_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_REQUIREMENT_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.LEAD_DEVELOPER, Keys.CREATOR, Keys.REQUIREMENT_PROJECT); - } - - /** - * {@inheritDoc} - */ - @Override - public Requirement as(String alias) { - return new Requirement(alias, this); - } - - /** - * Rename this table - */ - @Override - public Requirement rename(String name) { - return new Requirement(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RequirementCategoryMap.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RequirementCategoryMap.java deleted file mode 100644 index 78b805da..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RequirementCategoryMap.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementCategoryMapRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class RequirementCategoryMap extends TableImpl { - - private static final long serialVersionUID = -1083456567; - - /** - * The reference instance of reqbaz.requirement_category_map - */ - public static final RequirementCategoryMap REQUIREMENT_CATEGORY_MAP = new RequirementCategoryMap(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return RequirementCategoryMapRecord.class; - } - - /** - * The column reqbaz.requirement_category_map.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.requirement_category_map.category_id. - */ - public final TableField CATEGORY_ID = createField("category_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.requirement_category_map.requirement_id. - */ - public final TableField REQUIREMENT_ID = createField("requirement_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * Create a reqbaz.requirement_category_map table reference - */ - public RequirementCategoryMap() { - this("requirement_category_map", null); - } - - /** - * Create an aliased reqbaz.requirement_category_map table reference - */ - public RequirementCategoryMap(String alias) { - this(alias, REQUIREMENT_CATEGORY_MAP); - } - - private RequirementCategoryMap(String alias, Table aliased) { - this(alias, aliased, null); - } - - private RequirementCategoryMap(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_REQUIREMENT_CATEGORY_MAP; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_REQUIREMENT_CATEGORY_MAP_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_REQUIREMENT_CATEGORY_MAP_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.REQUIREMENT_CATEGORY_MAP_CATEGORY, Keys.REQUIREMENT_CATEGORY_MAP_REQUIREMENT); - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementCategoryMap as(String alias) { - return new RequirementCategoryMap(alias, this); - } - - /** - * Rename this table - */ - @Override - public RequirementCategoryMap rename(String name) { - return new RequirementCategoryMap(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RequirementDeveloperMap.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RequirementDeveloperMap.java deleted file mode 100644 index c1f9721a..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RequirementDeveloperMap.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementDeveloperMapRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class RequirementDeveloperMap extends TableImpl { - - private static final long serialVersionUID = 559012393; - - /** - * The reference instance of reqbaz.requirement_developer_map - */ - public static final RequirementDeveloperMap REQUIREMENT_DEVELOPER_MAP = new RequirementDeveloperMap(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return RequirementDeveloperMapRecord.class; - } - - /** - * The column reqbaz.requirement_developer_map.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.requirement_developer_map.requirement_id. - */ - public final TableField REQUIREMENT_ID = createField("requirement_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.requirement_developer_map.user_id. - */ - public final TableField USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.requirement_developer_map.creation_date. - */ - public final TableField CREATION_DATE = createField("creation_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * Create a reqbaz.requirement_developer_map table reference - */ - public RequirementDeveloperMap() { - this("requirement_developer_map", null); - } - - /** - * Create an aliased reqbaz.requirement_developer_map table reference - */ - public RequirementDeveloperMap(String alias) { - this(alias, REQUIREMENT_DEVELOPER_MAP); - } - - private RequirementDeveloperMap(String alias, Table aliased) { - this(alias, aliased, null); - } - - private RequirementDeveloperMap(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_REQUIREMENT_DEVELOPER_MAP; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_REQUIREMENT_DEVELOPER_MAP_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_REQUIREMENT_DEVELOPER_MAP_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.REQUIREMENT_DEVELOPER_MAP_REQUIREMENT, Keys.REQUIREMENT_DEVELOPER_MAP_USER); - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementDeveloperMap as(String alias) { - return new RequirementDeveloperMap(alias, this); - } - - /** - * Rename this table - */ - @Override - public RequirementDeveloperMap rename(String name) { - return new RequirementDeveloperMap(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RequirementFollowerMap.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RequirementFollowerMap.java deleted file mode 100644 index a46897dd..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RequirementFollowerMap.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementFollowerMapRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class RequirementFollowerMap extends TableImpl { - - private static final long serialVersionUID = -1236442855; - - /** - * The reference instance of reqbaz.requirement_follower_map - */ - public static final RequirementFollowerMap REQUIREMENT_FOLLOWER_MAP = new RequirementFollowerMap(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return RequirementFollowerMapRecord.class; - } - - /** - * The column reqbaz.requirement_follower_map.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.requirement_follower_map.requirement_id. - */ - public final TableField REQUIREMENT_ID = createField("requirement_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.requirement_follower_map.user_id. - */ - public final TableField USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.requirement_follower_map.creation_date. - */ - public final TableField CREATION_DATE = createField("creation_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * Create a reqbaz.requirement_follower_map table reference - */ - public RequirementFollowerMap() { - this("requirement_follower_map", null); - } - - /** - * Create an aliased reqbaz.requirement_follower_map table reference - */ - public RequirementFollowerMap(String alias) { - this(alias, REQUIREMENT_FOLLOWER_MAP); - } - - private RequirementFollowerMap(String alias, Table aliased) { - this(alias, aliased, null); - } - - private RequirementFollowerMap(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_REQUIREMENT_FOLLOWER_MAP; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_REQUIREMENT_FOLLOWER_MAP_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_REQUIREMENT_FOLLOWER_MAP_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.REQUIREMENT_FOLLOWER_MAP_REQUIREMENT, Keys.REQUIREMENT_FOLLOWER_MAP_USER); - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementFollowerMap as(String alias) { - return new RequirementFollowerMap(alias, this); - } - - /** - * Rename this table - */ - @Override - public RequirementFollowerMap rename(String name) { - return new RequirementFollowerMap(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Role.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Role.java deleted file mode 100644 index be7c541e..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Role.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RoleRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class Role extends TableImpl { - - private static final long serialVersionUID = 2020251099; - - /** - * The reference instance of reqbaz.role - */ - public static final Role ROLE = new Role(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return RoleRecord.class; - } - - /** - * The column reqbaz.role.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.role.name. - */ - public final TableField NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR.length(50), this, ""); - - /** - * Create a reqbaz.role table reference - */ - public Role() { - this("role", null); - } - - /** - * Create an aliased reqbaz.role table reference - */ - public Role(String alias) { - this(alias, ROLE); - } - - private Role(String alias, Table aliased) { - this(alias, aliased, null); - } - - private Role(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_ROLE; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_ROLE_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_ROLE_PRIMARY, Keys.KEY_ROLE_ROLE_IDX_1); - } - - /** - * {@inheritDoc} - */ - @Override - public Role as(String alias) { - return new Role(alias, this); - } - - /** - * Rename this table - */ - @Override - public Role rename(String name) { - return new Role(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RolePrivilegeMap.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RolePrivilegeMap.java deleted file mode 100644 index af859b3c..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RolePrivilegeMap.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RolePrivilegeMapRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class RolePrivilegeMap extends TableImpl { - - private static final long serialVersionUID = 288946433; - - /** - * The reference instance of reqbaz.role_privilege_map - */ - public static final RolePrivilegeMap ROLE_PRIVILEGE_MAP = new RolePrivilegeMap(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return RolePrivilegeMapRecord.class; - } - - /** - * The column reqbaz.role_privilege_map.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.role_privilege_map.role_id. - */ - public final TableField ROLE_ID = createField("role_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.role_privilege_map.privilege_id. - */ - public final TableField PRIVILEGE_ID = createField("privilege_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * Create a reqbaz.role_privilege_map table reference - */ - public RolePrivilegeMap() { - this("role_privilege_map", null); - } - - /** - * Create an aliased reqbaz.role_privilege_map table reference - */ - public RolePrivilegeMap(String alias) { - this(alias, ROLE_PRIVILEGE_MAP); - } - - private RolePrivilegeMap(String alias, Table aliased) { - this(alias, aliased, null); - } - - private RolePrivilegeMap(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_ROLE_PRIVILEGE_MAP; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_ROLE_PRIVILEGE_MAP_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_ROLE_PRIVILEGE_MAP_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.ROLE_PRIVILEGE_MAP_ROLE, Keys.ROLE_PRIVILEGE_MAP_PRIVILEGE); - } - - /** - * {@inheritDoc} - */ - @Override - public RolePrivilegeMap as(String alias) { - return new RolePrivilegeMap(alias, this); - } - - /** - * Rename this table - */ - @Override - public RolePrivilegeMap rename(String name) { - return new RolePrivilegeMap(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RoleRoleMap.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RoleRoleMap.java deleted file mode 100644 index 10f6961a..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/RoleRoleMap.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RoleRoleMapRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class RoleRoleMap extends TableImpl { - - private static final long serialVersionUID = 308433545; - - /** - * The reference instance of reqbaz.role_role_map - */ - public static final RoleRoleMap ROLE_ROLE_MAP = new RoleRoleMap(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return RoleRoleMapRecord.class; - } - - /** - * The column reqbaz.role_role_map.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.role_role_map.child_id. - */ - public final TableField CHILD_ID = createField("child_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.role_role_map.parent_id. - */ - public final TableField PARENT_ID = createField("parent_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * Create a reqbaz.role_role_map table reference - */ - public RoleRoleMap() { - this("role_role_map", null); - } - - /** - * Create an aliased reqbaz.role_role_map table reference - */ - public RoleRoleMap(String alias) { - this(alias, ROLE_ROLE_MAP); - } - - private RoleRoleMap(String alias, Table aliased) { - this(alias, aliased, null); - } - - private RoleRoleMap(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_ROLE_ROLE_MAP; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_ROLE_ROLE_MAP_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_ROLE_ROLE_MAP_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.ROLE_ROLE_MAP_CHILD, Keys.ROLE_ROLE_MAP_PARENT); - } - - /** - * {@inheritDoc} - */ - @Override - public RoleRoleMap as(String alias) { - return new RoleRoleMap(alias, this); - } - - /** - * Rename this table - */ - @Override - public RoleRoleMap rename(String name) { - return new RoleRoleMap(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/SchemaVersion.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/SchemaVersion.java deleted file mode 100644 index cd056048..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/SchemaVersion.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.SchemaVersionRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class SchemaVersion extends TableImpl { - - private static final long serialVersionUID = -1750837905; - - /** - * The reference instance of reqbaz.schema_version - */ - public static final SchemaVersion SCHEMA_VERSION = new SchemaVersion(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return SchemaVersionRecord.class; - } - - /** - * The column reqbaz.schema_version.installed_rank. - */ - public final TableField INSTALLED_RANK = createField("installed_rank", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.schema_version.version. - */ - public final TableField VERSION = createField("version", org.jooq.impl.SQLDataType.VARCHAR.length(50), this, ""); - - /** - * The column reqbaz.schema_version.description. - */ - public final TableField DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.VARCHAR.length(200).nullable(false), this, ""); - - /** - * The column reqbaz.schema_version.type. - */ - public final TableField TYPE = createField("type", org.jooq.impl.SQLDataType.VARCHAR.length(20).nullable(false), this, ""); - - /** - * The column reqbaz.schema_version.script. - */ - public final TableField SCRIPT = createField("script", org.jooq.impl.SQLDataType.VARCHAR.length(1000).nullable(false), this, ""); - - /** - * The column reqbaz.schema_version.checksum. - */ - public final TableField CHECKSUM = createField("checksum", org.jooq.impl.SQLDataType.INTEGER, this, ""); - - /** - * The column reqbaz.schema_version.installed_by. - */ - public final TableField INSTALLED_BY = createField("installed_by", org.jooq.impl.SQLDataType.VARCHAR.length(100).nullable(false), this, ""); - - /** - * The column reqbaz.schema_version.installed_on. - */ - public final TableField INSTALLED_ON = createField("installed_on", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * The column reqbaz.schema_version.execution_time. - */ - public final TableField EXECUTION_TIME = createField("execution_time", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.schema_version.success. - */ - public final TableField SUCCESS = createField("success", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, ""); - - /** - * Create a reqbaz.schema_version table reference - */ - public SchemaVersion() { - this("schema_version", null); - } - - /** - * Create an aliased reqbaz.schema_version table reference - */ - public SchemaVersion(String alias) { - this(alias, SCHEMA_VERSION); - } - - private SchemaVersion(String alias, Table aliased) { - this(alias, aliased, null); - } - - private SchemaVersion(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_SCHEMA_VERSION_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_SCHEMA_VERSION_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersion as(String alias) { - return new SchemaVersion(alias, this); - } - - /** - * Rename this table - */ - @Override - public SchemaVersion rename(String name) { - return new SchemaVersion(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/User.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/User.java deleted file mode 100644 index 9216ae31..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/User.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.UserRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class User extends TableImpl { - - private static final long serialVersionUID = 1439298886; - - /** - * The reference instance of reqbaz.user - */ - public static final User USER = new User(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return UserRecord.class; - } - - /** - * The column reqbaz.user.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.user.first_name. - */ - public final TableField FIRST_NAME = createField("first_name", org.jooq.impl.SQLDataType.VARCHAR.length(150), this, ""); - - /** - * The column reqbaz.user.last_name. - */ - public final TableField LAST_NAME = createField("last_name", org.jooq.impl.SQLDataType.VARCHAR.length(150), this, ""); - - /** - * The column reqbaz.user.email. - */ - public final TableField EMAIL = createField("email", org.jooq.impl.SQLDataType.VARCHAR.length(255).nullable(false), this, ""); - - /** - * The column reqbaz.user.admin. - */ - public final TableField ADMIN = createField("admin", org.jooq.impl.SQLDataType.BOOLEAN.nullable(false), this, ""); - - /** - * The column reqbaz.user.las2peer_id. - */ - public final TableField LAS2PEER_ID = createField("las2peer_id", org.jooq.impl.SQLDataType.VARCHAR.length(128), this, ""); - - /** - * The column reqbaz.user.user_name. - */ - public final TableField USER_NAME = createField("user_name", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); - - /** - * The column reqbaz.user.profile_image. - */ - public final TableField PROFILE_IMAGE = createField("profile_image", org.jooq.impl.SQLDataType.CLOB, this, ""); - - /** - * The column reqbaz.user.email_lead_subscription. - */ - public final TableField EMAIL_LEAD_SUBSCRIPTION = createField("email_lead_subscription", org.jooq.impl.SQLDataType.TINYINT.nullable(false).defaultValue(org.jooq.impl.DSL.inline("1", org.jooq.impl.SQLDataType.TINYINT)), this, ""); - - /** - * The column reqbaz.user.email_follow_subscription. - */ - public final TableField EMAIL_FOLLOW_SUBSCRIPTION = createField("email_follow_subscription", org.jooq.impl.SQLDataType.TINYINT.nullable(false).defaultValue(org.jooq.impl.DSL.inline("1", org.jooq.impl.SQLDataType.TINYINT)), this, ""); - - /** - * The column reqbaz.user.creation_date. - */ - public final TableField CREATION_DATE = createField("creation_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * The column reqbaz.user.last_updated_date. - */ - public final TableField LAST_UPDATED_DATE = createField("last_updated_date", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); - - /** - * The column reqbaz.user.last_login_date. - */ - public final TableField LAST_LOGIN_DATE = createField("last_login_date", org.jooq.impl.SQLDataType.TIMESTAMP, this, ""); - - /** - * Create a reqbaz.user table reference - */ - public User() { - this("user", null); - } - - /** - * Create an aliased reqbaz.user table reference - */ - public User(String alias) { - this(alias, USER); - } - - private User(String alias, Table aliased) { - this(alias, aliased, null); - } - - private User(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_USER; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_USER_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_USER_PRIMARY, Keys.KEY_USER_LAS2PEER_IDX); - } - - /** - * {@inheritDoc} - */ - @Override - public User as(String alias) { - return new User(alias, this); - } - - /** - * Rename this table - */ - @Override - public User rename(String name) { - return new User(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/UserRoleMap.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/UserRoleMap.java deleted file mode 100644 index d071b095..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/UserRoleMap.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.UserRoleMapRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class UserRoleMap extends TableImpl { - - private static final long serialVersionUID = 902266899; - - /** - * The reference instance of reqbaz.user_role_map - */ - public static final UserRoleMap USER_ROLE_MAP = new UserRoleMap(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return UserRoleMapRecord.class; - } - - /** - * The column reqbaz.user_role_map.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.user_role_map.role_id. - */ - public final TableField ROLE_ID = createField("role_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.user_role_map.user_id. - */ - public final TableField USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.user_role_map.context_info. - */ - public final TableField CONTEXT_INFO = createField("context_info", org.jooq.impl.SQLDataType.VARCHAR.length(255), this, ""); - - /** - * Create a reqbaz.user_role_map table reference - */ - public UserRoleMap() { - this("user_role_map", null); - } - - /** - * Create an aliased reqbaz.user_role_map table reference - */ - public UserRoleMap(String alias) { - this(alias, USER_ROLE_MAP); - } - - private UserRoleMap(String alias, Table aliased) { - this(alias, aliased, null); - } - - private UserRoleMap(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_USER_ROLE_MAP; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_USER_ROLE_MAP_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_USER_ROLE_MAP_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.USER_ROLE_MAP_ROLE, Keys.USER_ROLE_MAP_USER); - } - - /** - * {@inheritDoc} - */ - @Override - public UserRoleMap as(String alias) { - return new UserRoleMap(alias, this); - } - - /** - * Rename this table - */ - @Override - public UserRoleMap rename(String name) { - return new UserRoleMap(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Vote.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Vote.java deleted file mode 100644 index eaa6610e..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/Vote.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Keys; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.Reqbaz; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.VoteRecord; -import org.jooq.*; -import org.jooq.impl.TableImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; -import java.util.Arrays; -import java.util.List; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class Vote extends TableImpl { - - private static final long serialVersionUID = 1104351894; - - /** - * The reference instance of reqbaz.vote - */ - public static final Vote VOTE = new Vote(); - - /** - * The class holding records for this type - */ - @Override - public Class getRecordType() { - return VoteRecord.class; - } - - /** - * The column reqbaz.vote.id. - */ - public final TableField ID = createField("id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.vote.is_upvote. - */ - public final TableField IS_UPVOTE = createField("is_upvote", org.jooq.impl.SQLDataType.TINYINT.nullable(false), this, ""); - - /** - * The column reqbaz.vote.requirement_id. - */ - public final TableField REQUIREMENT_ID = createField("requirement_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.vote.user_id. - */ - public final TableField USER_ID = createField("user_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); - - /** - * The column reqbaz.vote.creation_date. - */ - public final TableField CREATION_DATE = createField("creation_date", org.jooq.impl.SQLDataType.TIMESTAMP.nullable(false).defaultValue(org.jooq.impl.DSL.inline("CURRENT_TIMESTAMP", org.jooq.impl.SQLDataType.TIMESTAMP)), this, ""); - - /** - * Create a reqbaz.vote table reference - */ - public Vote() { - this("vote", null); - } - - /** - * Create an aliased reqbaz.vote table reference - */ - public Vote(String alias) { - this(alias, VOTE); - } - - private Vote(String alias, Table aliased) { - this(alias, aliased, null); - } - - private Vote(String alias, Table aliased, Field[] parameters) { - super(alias, null, aliased, parameters, ""); - } - - /** - * {@inheritDoc} - */ - @Override - public Schema getSchema() { - return Reqbaz.REQBAZ; - } - - /** - * {@inheritDoc} - */ - @Override - public Identity getIdentity() { - return Keys.IDENTITY_VOTE; - } - - /** - * {@inheritDoc} - */ - @Override - public UniqueKey getPrimaryKey() { - return Keys.KEY_VOTE_PRIMARY; - } - - /** - * {@inheritDoc} - */ - @Override - public List> getKeys() { - return Arrays.>asList(Keys.KEY_VOTE_PRIMARY); - } - - /** - * {@inheritDoc} - */ - @Override - public List> getReferences() { - return Arrays.>asList(Keys.VOTE_REQUIREMENT, Keys.VOTE_USER); - } - - /** - * {@inheritDoc} - */ - @Override - public Vote as(String alias) { - return new Vote(alias, this); - } - - /** - * Rename this table - */ - @Override - public Vote rename(String name) { - return new Vote(name, null); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/AttachmentRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/AttachmentRecord.java deleted file mode 100644 index 028a2ee6..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/AttachmentRecord.java +++ /dev/null @@ -1,501 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Attachment; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record10; -import org.jooq.Row10; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class AttachmentRecord extends UpdatableRecordImpl implements Record10 { - - private static final long serialVersionUID = 888863633; - - /** - * Setter for reqbaz.attachment.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.attachment.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.attachment.creation_date. - */ - public void setCreationDate(Timestamp value) { - set(1, value); - } - - /** - * Getter for reqbaz.attachment.creation_date. - */ - public Timestamp getCreationDate() { - return (Timestamp) get(1); - } - - /** - * Setter for reqbaz.attachment.last_updated_date. - */ - public void setLastUpdatedDate(Timestamp value) { - set(2, value); - } - - /** - * Getter for reqbaz.attachment.last_updated_date. - */ - public Timestamp getLastUpdatedDate() { - return (Timestamp) get(2); - } - - /** - * Setter for reqbaz.attachment.requirement_id. - */ - public void setRequirementId(Integer value) { - set(3, value); - } - - /** - * Getter for reqbaz.attachment.requirement_id. - */ - public Integer getRequirementId() { - return (Integer) get(3); - } - - /** - * Setter for reqbaz.attachment.user_id. - */ - public void setUserId(Integer value) { - set(4, value); - } - - /** - * Getter for reqbaz.attachment.user_id. - */ - public Integer getUserId() { - return (Integer) get(4); - } - - /** - * Setter for reqbaz.attachment.name. - */ - public void setName(String value) { - set(5, value); - } - - /** - * Getter for reqbaz.attachment.name. - */ - public String getName() { - return (String) get(5); - } - - /** - * Setter for reqbaz.attachment.description. - */ - public void setDescription(String value) { - set(6, value); - } - - /** - * Getter for reqbaz.attachment.description. - */ - public String getDescription() { - return (String) get(6); - } - - /** - * Setter for reqbaz.attachment.mime_type. - */ - public void setMimeType(String value) { - set(7, value); - } - - /** - * Getter for reqbaz.attachment.mime_type. - */ - public String getMimeType() { - return (String) get(7); - } - - /** - * Setter for reqbaz.attachment.identifier. - */ - public void setIdentifier(String value) { - set(8, value); - } - - /** - * Getter for reqbaz.attachment.identifier. - */ - public String getIdentifier() { - return (String) get(8); - } - - /** - * Setter for reqbaz.attachment.file_url. - */ - public void setFileUrl(String value) { - set(9, value); - } - - /** - * Getter for reqbaz.attachment.file_url. - */ - public String getFileUrl() { - return (String) get(9); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record10 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row10 fieldsRow() { - return (Row10) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row10 valuesRow() { - return (Row10) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return Attachment.ATTACHMENT.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return Attachment.ATTACHMENT.CREATION_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return Attachment.ATTACHMENT.LAST_UPDATED_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return Attachment.ATTACHMENT.REQUIREMENT_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field5() { - return Attachment.ATTACHMENT.USER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field6() { - return Attachment.ATTACHMENT.NAME; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field7() { - return Attachment.ATTACHMENT.DESCRIPTION; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field8() { - return Attachment.ATTACHMENT.MIME_TYPE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field9() { - return Attachment.ATTACHMENT.IDENTIFIER; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field10() { - return Attachment.ATTACHMENT.FILE_URL; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value2() { - return getCreationDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value3() { - return getLastUpdatedDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value4() { - return getRequirementId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value5() { - return getUserId(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value6() { - return getName(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value7() { - return getDescription(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value8() { - return getMimeType(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value9() { - return getIdentifier(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value10() { - return getFileUrl(); - } - - /** - * {@inheritDoc} - */ - @Override - public AttachmentRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public AttachmentRecord value2(Timestamp value) { - setCreationDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public AttachmentRecord value3(Timestamp value) { - setLastUpdatedDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public AttachmentRecord value4(Integer value) { - setRequirementId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public AttachmentRecord value5(Integer value) { - setUserId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public AttachmentRecord value6(String value) { - setName(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public AttachmentRecord value7(String value) { - setDescription(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public AttachmentRecord value8(String value) { - setMimeType(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public AttachmentRecord value9(String value) { - setIdentifier(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public AttachmentRecord value10(String value) { - setFileUrl(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public AttachmentRecord values(Integer value1, Timestamp value2, Timestamp value3, Integer value4, Integer value5, String value6, String value7, String value8, String value9, String value10) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - value5(value5); - value6(value6); - value7(value7); - value8(value8); - value9(value9); - value10(value10); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached AttachmentRecord - */ - public AttachmentRecord() { - super(Attachment.ATTACHMENT); - } - - /** - * Create a detached, initialised AttachmentRecord - */ - public AttachmentRecord(Integer id, Timestamp creationDate, Timestamp lastUpdatedDate, Integer requirementId, Integer userId, String name, String description, String mimeType, String identifier, String fileUrl) { - super(Attachment.ATTACHMENT); - - set(0, id); - set(1, creationDate); - set(2, lastUpdatedDate); - set(3, requirementId); - set(4, userId); - set(5, name); - set(6, description); - set(7, mimeType); - set(8, identifier); - set(9, fileUrl); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/CategoryFollowerMapRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/CategoryFollowerMapRecord.java deleted file mode 100644 index d4c1bbea..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/CategoryFollowerMapRecord.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * This file is generated by jOOQ. -*/ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.CategoryFollowerMap; - -import java.sql.Timestamp; - -import javax.annotation.Generated; - -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record4; -import org.jooq.Row4; -import org.jooq.impl.UpdatableRecordImpl; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({ "all", "unchecked", "rawtypes" }) -public class CategoryFollowerMapRecord extends UpdatableRecordImpl implements Record4 { - - private static final long serialVersionUID = 725392326; - - /** - * Setter for reqbaz.category_follower_map.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.category_follower_map.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.category_follower_map.category_id. - */ - public void setCategoryId(Integer value) { - set(1, value); - } - - /** - * Getter for reqbaz.category_follower_map.category_id. - */ - public Integer getCategoryId() { - return (Integer) get(1); - } - - /** - * Setter for reqbaz.category_follower_map.user_id. - */ - public void setUserId(Integer value) { - set(2, value); - } - - /** - * Getter for reqbaz.category_follower_map.user_id. - */ - public Integer getUserId() { - return (Integer) get(2); - } - - /** - * Setter for reqbaz.category_follower_map.creation_date. - */ - public void setCreationDate(Timestamp value) { - set(3, value); - } - - /** - * Getter for reqbaz.category_follower_map.creation_date. - */ - public Timestamp getCreationDate() { - return (Timestamp) get(3); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record4 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row4 fieldsRow() { - return (Row4) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row4 valuesRow() { - return (Row4) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return CategoryFollowerMap.CATEGORY_FOLLOWER_MAP.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return CategoryFollowerMap.CATEGORY_FOLLOWER_MAP.CATEGORY_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return CategoryFollowerMap.CATEGORY_FOLLOWER_MAP.USER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return CategoryFollowerMap.CATEGORY_FOLLOWER_MAP.CREATION_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value2() { - return getCategoryId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value3() { - return getUserId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value4() { - return getCreationDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryFollowerMapRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryFollowerMapRecord value2(Integer value) { - setCategoryId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryFollowerMapRecord value3(Integer value) { - setUserId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryFollowerMapRecord value4(Timestamp value) { - setCreationDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryFollowerMapRecord values(Integer value1, Integer value2, Integer value3, Timestamp value4) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached CategoryFollowerMapRecord - */ - public CategoryFollowerMapRecord() { - super(CategoryFollowerMap.CATEGORY_FOLLOWER_MAP); - } - - /** - * Create a detached, initialised CategoryFollowerMapRecord - */ - public CategoryFollowerMapRecord(Integer id, Integer categoryId, Integer userId, Timestamp creationDate) { - super(CategoryFollowerMap.CATEGORY_FOLLOWER_MAP); - - set(0, id); - set(1, categoryId); - set(2, userId); - set(3, creationDate); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/CategoryRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/CategoryRecord.java deleted file mode 100644 index ca63da4b..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/CategoryRecord.java +++ /dev/null @@ -1,378 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Category; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record7; -import org.jooq.Row7; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class CategoryRecord extends UpdatableRecordImpl implements Record7 { - - private static final long serialVersionUID = 1461191440; - - /** - * Setter for reqbaz.category.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.category.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.category.name. - */ - public void setName(String value) { - set(1, value); - } - - /** - * Getter for reqbaz.category.name. - */ - public String getName() { - return (String) get(1); - } - - /** - * Setter for reqbaz.category.description. - */ - public void setDescription(String value) { - set(2, value); - } - - /** - * Getter for reqbaz.category.description. - */ - public String getDescription() { - return (String) get(2); - } - - /** - * Setter for reqbaz.category.creation_date. - */ - public void setCreationDate(Timestamp value) { - set(3, value); - } - - /** - * Getter for reqbaz.category.creation_date. - */ - public Timestamp getCreationDate() { - return (Timestamp) get(3); - } - - /** - * Setter for reqbaz.category.last_updated_date. - */ - public void setLastUpdatedDate(Timestamp value) { - set(4, value); - } - - /** - * Getter for reqbaz.category.last_updated_date. - */ - public Timestamp getLastUpdatedDate() { - return (Timestamp) get(4); - } - - /** - * Setter for reqbaz.category.project_id. - */ - public void setProjectId(Integer value) { - set(5, value); - } - - /** - * Getter for reqbaz.category.project_id. - */ - public Integer getProjectId() { - return (Integer) get(5); - } - - /** - * Setter for reqbaz.category.leader_id. - */ - public void setLeaderId(Integer value) { - set(6, value); - } - - /** - * Getter for reqbaz.category.leader_id. - */ - public Integer getLeaderId() { - return (Integer) get(6); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record7 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row7 fieldsRow() { - return (Row7) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row7 valuesRow() { - return (Row7) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return Category.CATEGORY.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return Category.CATEGORY.NAME; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return Category.CATEGORY.DESCRIPTION; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return Category.CATEGORY.CREATION_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field5() { - return Category.CATEGORY.LAST_UPDATED_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field6() { - return Category.CATEGORY.PROJECT_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field7() { - return Category.CATEGORY.LEADER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value2() { - return getName(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value3() { - return getDescription(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value4() { - return getCreationDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value5() { - return getLastUpdatedDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value6() { - return getProjectId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value7() { - return getLeaderId(); - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryRecord value2(String value) { - setName(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryRecord value3(String value) { - setDescription(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryRecord value4(Timestamp value) { - setCreationDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryRecord value5(Timestamp value) { - setLastUpdatedDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryRecord value6(Integer value) { - setProjectId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryRecord value7(Integer value) { - setLeaderId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CategoryRecord values(Integer value1, String value2, String value3, Timestamp value4, Timestamp value5, Integer value6, Integer value7) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - value5(value5); - value6(value6); - value7(value7); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached CategoryRecord - */ - public CategoryRecord() { - super(Category.CATEGORY); - } - - /** - * Create a detached, initialised CategoryRecord - */ - public CategoryRecord(Integer id, String name, String description, Timestamp creationDate, Timestamp lastUpdatedDate, Integer projectId, Integer leaderId) { - super(Category.CATEGORY); - - set(0, id); - set(1, name); - set(2, description); - set(3, creationDate); - set(4, lastUpdatedDate); - set(5, projectId); - set(6, leaderId); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/CommentRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/CommentRecord.java deleted file mode 100644 index 4c9d11cb..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/CommentRecord.java +++ /dev/null @@ -1,378 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Comment; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record7; -import org.jooq.Row7; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class CommentRecord extends UpdatableRecordImpl implements Record7 { - - private static final long serialVersionUID = 191217760; - - /** - * Setter for reqbaz.comment.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.comment.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.comment.message. - */ - public void setMessage(String value) { - set(1, value); - } - - /** - * Getter for reqbaz.comment.message. - */ - public String getMessage() { - return (String) get(1); - } - - /** - * Setter for reqbaz.comment.creation_date. - */ - public void setCreationDate(Timestamp value) { - set(2, value); - } - - /** - * Getter for reqbaz.comment.creation_date. - */ - public Timestamp getCreationDate() { - return (Timestamp) get(2); - } - - /** - * Setter for reqbaz.comment.last_updated_date. - */ - public void setLastUpdatedDate(Timestamp value) { - set(3, value); - } - - /** - * Getter for reqbaz.comment.last_updated_date. - */ - public Timestamp getLastUpdatedDate() { - return (Timestamp) get(3); - } - - /** - * Setter for reqbaz.comment.requirement_id. - */ - public void setRequirementId(Integer value) { - set(4, value); - } - - /** - * Getter for reqbaz.comment.requirement_id. - */ - public Integer getRequirementId() { - return (Integer) get(4); - } - - /** - * Setter for reqbaz.comment.user_id. - */ - public void setUserId(Integer value) { - set(5, value); - } - - /** - * Getter for reqbaz.comment.user_id. - */ - public Integer getUserId() { - return (Integer) get(5); - } - - /** - * Setter for reqbaz.comment.reply_to_comment_id. - */ - public void setReplyToCommentId(Integer value) { - set(6, value); - } - - /** - * Getter for reqbaz.comment.reply_to_comment_id. - */ - public Integer getReplyToCommentId() { - return (Integer) get(6); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record7 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row7 fieldsRow() { - return (Row7) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row7 valuesRow() { - return (Row7) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return Comment.COMMENT.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return Comment.COMMENT.MESSAGE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return Comment.COMMENT.CREATION_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return Comment.COMMENT.LAST_UPDATED_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field5() { - return Comment.COMMENT.REQUIREMENT_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field6() { - return Comment.COMMENT.USER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field7() { - return Comment.COMMENT.REPLY_TO_COMMENT_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value2() { - return getMessage(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value3() { - return getCreationDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value4() { - return getLastUpdatedDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value5() { - return getRequirementId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value6() { - return getUserId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value7() { - return getReplyToCommentId(); - } - - /** - * {@inheritDoc} - */ - @Override - public CommentRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CommentRecord value2(String value) { - setMessage(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CommentRecord value3(Timestamp value) { - setCreationDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CommentRecord value4(Timestamp value) { - setLastUpdatedDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CommentRecord value5(Integer value) { - setRequirementId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CommentRecord value6(Integer value) { - setUserId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CommentRecord value7(Integer value) { - setReplyToCommentId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public CommentRecord values(Integer value1, String value2, Timestamp value3, Timestamp value4, Integer value5, Integer value6, Integer value7) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - value5(value5); - value6(value6); - value7(value7); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached CommentRecord - */ - public CommentRecord() { - super(Comment.COMMENT); - } - - /** - * Create a detached, initialised CommentRecord - */ - public CommentRecord(Integer id, String message, Timestamp creationDate, Timestamp lastUpdatedDate, Integer requirementId, Integer userId, Integer replyToCommentId) { - super(Comment.COMMENT); - - set(0, id); - set(1, message); - set(2, creationDate); - set(3, lastUpdatedDate); - set(4, requirementId); - set(5, userId); - set(6, replyToCommentId); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/PrivilegeRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/PrivilegeRecord.java deleted file mode 100644 index 4db24236..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/PrivilegeRecord.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Privilege; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record2; -import org.jooq.Row2; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class PrivilegeRecord extends UpdatableRecordImpl implements Record2 { - - private static final long serialVersionUID = -324005622; - - /** - * Setter for reqbaz.privilege.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.privilege.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.privilege.name. - */ - public void setName(String value) { - set(1, value); - } - - /** - * Getter for reqbaz.privilege.name. - */ - public String getName() { - return (String) get(1); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record2 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row2 fieldsRow() { - return (Row2) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row2 valuesRow() { - return (Row2) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return Privilege.PRIVILEGE.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return Privilege.PRIVILEGE.NAME; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value2() { - return getName(); - } - - /** - * {@inheritDoc} - */ - @Override - public PrivilegeRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public PrivilegeRecord value2(String value) { - setName(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public PrivilegeRecord values(Integer value1, String value2) { - value1(value1); - value2(value2); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached PrivilegeRecord - */ - public PrivilegeRecord() { - super(Privilege.PRIVILEGE); - } - - /** - * Create a detached, initialised PrivilegeRecord - */ - public PrivilegeRecord(Integer id, String name) { - super(Privilege.PRIVILEGE); - - set(0, id); - set(1, name); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/ProjectFollowerMapRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/ProjectFollowerMapRecord.java deleted file mode 100644 index 8fa81dc4..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/ProjectFollowerMapRecord.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * This file is generated by jOOQ. -*/ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.ProjectFollowerMap; - -import java.sql.Timestamp; - -import javax.annotation.Generated; - -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record4; -import org.jooq.Row4; -import org.jooq.impl.UpdatableRecordImpl; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({ "all", "unchecked", "rawtypes" }) -public class ProjectFollowerMapRecord extends UpdatableRecordImpl implements Record4 { - - private static final long serialVersionUID = 327516215; - - /** - * Setter for reqbaz.project_follower_map.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.project_follower_map.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.project_follower_map.project_id. - */ - public void setProjectId(Integer value) { - set(1, value); - } - - /** - * Getter for reqbaz.project_follower_map.project_id. - */ - public Integer getProjectId() { - return (Integer) get(1); - } - - /** - * Setter for reqbaz.project_follower_map.user_id. - */ - public void setUserId(Integer value) { - set(2, value); - } - - /** - * Getter for reqbaz.project_follower_map.user_id. - */ - public Integer getUserId() { - return (Integer) get(2); - } - - /** - * Setter for reqbaz.project_follower_map.creation_date. - */ - public void setCreationDate(Timestamp value) { - set(3, value); - } - - /** - * Getter for reqbaz.project_follower_map.creation_date. - */ - public Timestamp getCreationDate() { - return (Timestamp) get(3); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record4 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row4 fieldsRow() { - return (Row4) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row4 valuesRow() { - return (Row4) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return ProjectFollowerMap.PROJECT_FOLLOWER_MAP.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return ProjectFollowerMap.PROJECT_FOLLOWER_MAP.PROJECT_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return ProjectFollowerMap.PROJECT_FOLLOWER_MAP.USER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return ProjectFollowerMap.PROJECT_FOLLOWER_MAP.CREATION_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value2() { - return getProjectId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value3() { - return getUserId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value4() { - return getCreationDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectFollowerMapRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectFollowerMapRecord value2(Integer value) { - setProjectId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectFollowerMapRecord value3(Integer value) { - setUserId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectFollowerMapRecord value4(Timestamp value) { - setCreationDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectFollowerMapRecord values(Integer value1, Integer value2, Integer value3, Timestamp value4) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached ProjectFollowerMapRecord - */ - public ProjectFollowerMapRecord() { - super(ProjectFollowerMap.PROJECT_FOLLOWER_MAP); - } - - /** - * Create a detached, initialised ProjectFollowerMapRecord - */ - public ProjectFollowerMapRecord(Integer id, Integer projectId, Integer userId, Timestamp creationDate) { - super(ProjectFollowerMap.PROJECT_FOLLOWER_MAP); - - set(0, id); - set(1, projectId); - set(2, userId); - set(3, creationDate); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/ProjectRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/ProjectRecord.java deleted file mode 100644 index a27513b8..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/ProjectRecord.java +++ /dev/null @@ -1,419 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Project; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record8; -import org.jooq.Row8; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class ProjectRecord extends UpdatableRecordImpl implements Record8 { - - private static final long serialVersionUID = 416723320; - - /** - * Setter for reqbaz.project.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.project.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.project.name. - */ - public void setName(String value) { - set(1, value); - } - - /** - * Getter for reqbaz.project.name. - */ - public String getName() { - return (String) get(1); - } - - /** - * Setter for reqbaz.project.description. - */ - public void setDescription(String value) { - set(2, value); - } - - /** - * Getter for reqbaz.project.description. - */ - public String getDescription() { - return (String) get(2); - } - - /** - * Setter for reqbaz.project.visibility. - */ - public void setVisibility(Byte value) { - set(3, value); - } - - /** - * Getter for reqbaz.project.visibility. - */ - public Byte getVisibility() { - return (Byte) get(3); - } - - /** - * Setter for reqbaz.project.creation_date. - */ - public void setCreationDate(Timestamp value) { - set(4, value); - } - - /** - * Getter for reqbaz.project.creation_date. - */ - public Timestamp getCreationDate() { - return (Timestamp) get(4); - } - - /** - * Setter for reqbaz.project.last_updated_date. - */ - public void setLastUpdatedDate(Timestamp value) { - set(5, value); - } - - /** - * Getter for reqbaz.project.last_updated_date. - */ - public Timestamp getLastUpdatedDate() { - return (Timestamp) get(5); - } - - /** - * Setter for reqbaz.project.leader_id. - */ - public void setLeaderId(Integer value) { - set(6, value); - } - - /** - * Getter for reqbaz.project.leader_id. - */ - public Integer getLeaderId() { - return (Integer) get(6); - } - - /** - * Setter for reqbaz.project.default_category_id. - */ - public void setDefaultCategoryId(Integer value) { - set(7, value); - } - - /** - * Getter for reqbaz.project.default_category_id. - */ - public Integer getDefaultCategoryId() { - return (Integer) get(7); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record8 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row8 fieldsRow() { - return (Row8) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row8 valuesRow() { - return (Row8) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return Project.PROJECT.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return Project.PROJECT.NAME; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return Project.PROJECT.DESCRIPTION; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return Project.PROJECT.VISIBILITY; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field5() { - return Project.PROJECT.CREATION_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field6() { - return Project.PROJECT.LAST_UPDATED_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field7() { - return Project.PROJECT.LEADER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field8() { - return Project.PROJECT.DEFAULT_CATEGORY_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value2() { - return getName(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value3() { - return getDescription(); - } - - /** - * {@inheritDoc} - */ - @Override - public Byte value4() { - return getVisibility(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value5() { - return getCreationDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value6() { - return getLastUpdatedDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value7() { - return getLeaderId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value8() { - return getDefaultCategoryId(); - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectRecord value2(String value) { - setName(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectRecord value3(String value) { - setDescription(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectRecord value4(Byte value) { - setVisibility(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectRecord value5(Timestamp value) { - setCreationDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectRecord value6(Timestamp value) { - setLastUpdatedDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectRecord value7(Integer value) { - setLeaderId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectRecord value8(Integer value) { - setDefaultCategoryId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public ProjectRecord values(Integer value1, String value2, String value3, Byte value4, Timestamp value5, Timestamp value6, Integer value7, Integer value8) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - value5(value5); - value6(value6); - value7(value7); - value8(value8); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached ProjectRecord - */ - public ProjectRecord() { - super(Project.PROJECT); - } - - /** - * Create a detached, initialised ProjectRecord - */ - public ProjectRecord(Integer id, String name, String description, Byte visibility, Timestamp creationDate, Timestamp lastUpdatedDate, Integer leaderId, Integer defaultCategoryId) { - super(Project.PROJECT); - - set(0, id); - set(1, name); - set(2, description); - set(3, visibility); - set(4, creationDate); - set(5, lastUpdatedDate); - set(6, leaderId); - set(7, defaultCategoryId); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementCategoryMapRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementCategoryMapRecord.java deleted file mode 100644 index 1919dadb..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementCategoryMapRecord.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * This file is generated by jOOQ. -*/ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RequirementCategoryMap; - -import javax.annotation.Generated; - -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record3; -import org.jooq.Row3; -import org.jooq.impl.UpdatableRecordImpl; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({ "all", "unchecked", "rawtypes" }) -public class RequirementCategoryMapRecord extends UpdatableRecordImpl implements Record3 { - - private static final long serialVersionUID = -1847480760; - - /** - * Setter for reqbaz.requirement_category_map.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.requirement_category_map.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.requirement_category_map.category_id. - */ - public void setCategoryId(Integer value) { - set(1, value); - } - - /** - * Getter for reqbaz.requirement_category_map.category_id. - */ - public Integer getCategoryId() { - return (Integer) get(1); - } - - /** - * Setter for reqbaz.requirement_category_map.requirement_id. - */ - public void setRequirementId(Integer value) { - set(2, value); - } - - /** - * Getter for reqbaz.requirement_category_map.requirement_id. - */ - public Integer getRequirementId() { - return (Integer) get(2); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record3 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row3 fieldsRow() { - return (Row3) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row3 valuesRow() { - return (Row3) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP.CATEGORY_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value2() { - return getCategoryId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value3() { - return getRequirementId(); - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementCategoryMapRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementCategoryMapRecord value2(Integer value) { - setCategoryId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementCategoryMapRecord value3(Integer value) { - setRequirementId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementCategoryMapRecord values(Integer value1, Integer value2, Integer value3) { - value1(value1); - value2(value2); - value3(value3); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached RequirementCategoryMapRecord - */ - public RequirementCategoryMapRecord() { - super(RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP); - } - - /** - * Create a detached, initialised RequirementCategoryMapRecord - */ - public RequirementCategoryMapRecord(Integer id, Integer categoryId, Integer requirementId) { - super(RequirementCategoryMap.REQUIREMENT_CATEGORY_MAP); - - set(0, id); - set(1, categoryId); - set(2, requirementId); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementDeveloperMapRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementDeveloperMapRecord.java deleted file mode 100644 index 4732385e..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementDeveloperMapRecord.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * This file is generated by jOOQ. -*/ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RequirementDeveloperMap; - -import java.sql.Timestamp; - -import javax.annotation.Generated; - -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record4; -import org.jooq.Row4; -import org.jooq.impl.UpdatableRecordImpl; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({ "all", "unchecked", "rawtypes" }) -public class RequirementDeveloperMapRecord extends UpdatableRecordImpl implements Record4 { - - private static final long serialVersionUID = -738697457; - - /** - * Setter for reqbaz.requirement_developer_map.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.requirement_developer_map.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.requirement_developer_map.requirement_id. - */ - public void setRequirementId(Integer value) { - set(1, value); - } - - /** - * Getter for reqbaz.requirement_developer_map.requirement_id. - */ - public Integer getRequirementId() { - return (Integer) get(1); - } - - /** - * Setter for reqbaz.requirement_developer_map.user_id. - */ - public void setUserId(Integer value) { - set(2, value); - } - - /** - * Getter for reqbaz.requirement_developer_map.user_id. - */ - public Integer getUserId() { - return (Integer) get(2); - } - - /** - * Setter for reqbaz.requirement_developer_map.creation_date. - */ - public void setCreationDate(Timestamp value) { - set(3, value); - } - - /** - * Getter for reqbaz.requirement_developer_map.creation_date. - */ - public Timestamp getCreationDate() { - return (Timestamp) get(3); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record4 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row4 fieldsRow() { - return (Row4) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row4 valuesRow() { - return (Row4) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP.REQUIREMENT_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP.USER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP.CREATION_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value2() { - return getRequirementId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value3() { - return getUserId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value4() { - return getCreationDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementDeveloperMapRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementDeveloperMapRecord value2(Integer value) { - setRequirementId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementDeveloperMapRecord value3(Integer value) { - setUserId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementDeveloperMapRecord value4(Timestamp value) { - setCreationDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementDeveloperMapRecord values(Integer value1, Integer value2, Integer value3, Timestamp value4) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached RequirementDeveloperMapRecord - */ - public RequirementDeveloperMapRecord() { - super(RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP); - } - - /** - * Create a detached, initialised RequirementDeveloperMapRecord - */ - public RequirementDeveloperMapRecord(Integer id, Integer requirementId, Integer userId, Timestamp creationDate) { - super(RequirementDeveloperMap.REQUIREMENT_DEVELOPER_MAP); - - set(0, id); - set(1, requirementId); - set(2, userId); - set(3, creationDate); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementFollowerMapRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementFollowerMapRecord.java deleted file mode 100644 index 7063172d..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementFollowerMapRecord.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * This file is generated by jOOQ. -*/ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RequirementFollowerMap; - -import java.sql.Timestamp; - -import javax.annotation.Generated; - -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record4; -import org.jooq.Row4; -import org.jooq.impl.UpdatableRecordImpl; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({ "all", "unchecked", "rawtypes" }) -public class RequirementFollowerMapRecord extends UpdatableRecordImpl implements Record4 { - - private static final long serialVersionUID = -1293871707; - - /** - * Setter for reqbaz.requirement_follower_map.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.requirement_follower_map.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.requirement_follower_map.requirement_id. - */ - public void setRequirementId(Integer value) { - set(1, value); - } - - /** - * Getter for reqbaz.requirement_follower_map.requirement_id. - */ - public Integer getRequirementId() { - return (Integer) get(1); - } - - /** - * Setter for reqbaz.requirement_follower_map.user_id. - */ - public void setUserId(Integer value) { - set(2, value); - } - - /** - * Getter for reqbaz.requirement_follower_map.user_id. - */ - public Integer getUserId() { - return (Integer) get(2); - } - - /** - * Setter for reqbaz.requirement_follower_map.creation_date. - */ - public void setCreationDate(Timestamp value) { - set(3, value); - } - - /** - * Getter for reqbaz.requirement_follower_map.creation_date. - */ - public Timestamp getCreationDate() { - return (Timestamp) get(3); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record4 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row4 fieldsRow() { - return (Row4) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row4 valuesRow() { - return (Row4) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP.USER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP.CREATION_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value2() { - return getRequirementId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value3() { - return getUserId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value4() { - return getCreationDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementFollowerMapRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementFollowerMapRecord value2(Integer value) { - setRequirementId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementFollowerMapRecord value3(Integer value) { - setUserId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementFollowerMapRecord value4(Timestamp value) { - setCreationDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementFollowerMapRecord values(Integer value1, Integer value2, Integer value3, Timestamp value4) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached RequirementFollowerMapRecord - */ - public RequirementFollowerMapRecord() { - super(RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP); - } - - /** - * Create a detached, initialised RequirementFollowerMapRecord - */ - public RequirementFollowerMapRecord(Integer id, Integer requirementId, Integer userId, Timestamp creationDate) { - super(RequirementFollowerMap.REQUIREMENT_FOLLOWER_MAP); - - set(0, id); - set(1, requirementId); - set(2, userId); - set(3, creationDate); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementRecord.java deleted file mode 100644 index 4b877b60..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RequirementRecord.java +++ /dev/null @@ -1,460 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Requirement; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record9; -import org.jooq.Row9; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class RequirementRecord extends UpdatableRecordImpl implements Record9 { - - private static final long serialVersionUID = 340315030; - - /** - * Setter for reqbaz.requirement.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.requirement.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.requirement.name. - */ - public void setName(String value) { - set(1, value); - } - - /** - * Getter for reqbaz.requirement.name. - */ - public String getName() { - return (String) get(1); - } - - /** - * Setter for reqbaz.requirement.description. - */ - public void setDescription(String value) { - set(2, value); - } - - /** - * Getter for reqbaz.requirement.description. - */ - public String getDescription() { - return (String) get(2); - } - - /** - * Setter for reqbaz.requirement.realized. - */ - public void setRealized(Timestamp value) { - set(3, value); - } - - /** - * Getter for reqbaz.requirement.realized. - */ - public Timestamp getRealized() { - return (Timestamp) get(3); - } - - /** - * Setter for reqbaz.requirement.creation_date. - */ - public void setCreationDate(Timestamp value) { - set(4, value); - } - - /** - * Getter for reqbaz.requirement.creation_date. - */ - public Timestamp getCreationDate() { - return (Timestamp) get(4); - } - - /** - * Setter for reqbaz.requirement.last_updated_date. - */ - public void setLastUpdatedDate(Timestamp value) { - set(5, value); - } - - /** - * Getter for reqbaz.requirement.last_updated_date. - */ - public Timestamp getLastUpdatedDate() { - return (Timestamp) get(5); - } - - /** - * Setter for reqbaz.requirement.lead_developer_id. - */ - public void setLeadDeveloperId(Integer value) { - set(6, value); - } - - /** - * Getter for reqbaz.requirement.lead_developer_id. - */ - public Integer getLeadDeveloperId() { - return (Integer) get(6); - } - - /** - * Setter for reqbaz.requirement.creator_id. - */ - public void setCreatorId(Integer value) { - set(7, value); - } - - /** - * Getter for reqbaz.requirement.creator_id. - */ - public Integer getCreatorId() { - return (Integer) get(7); - } - - /** - * Setter for reqbaz.requirement.project_id. - */ - public void setProjectId(Integer value) { - set(8, value); - } - - /** - * Getter for reqbaz.requirement.project_id. - */ - public Integer getProjectId() { - return (Integer) get(8); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record9 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row9 fieldsRow() { - return (Row9) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row9 valuesRow() { - return (Row9) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return Requirement.REQUIREMENT.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return Requirement.REQUIREMENT.NAME; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return Requirement.REQUIREMENT.DESCRIPTION; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return Requirement.REQUIREMENT.REALIZED; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field5() { - return Requirement.REQUIREMENT.CREATION_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field6() { - return Requirement.REQUIREMENT.LAST_UPDATED_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field7() { - return Requirement.REQUIREMENT.LEAD_DEVELOPER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field8() { - return Requirement.REQUIREMENT.CREATOR_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field9() { - return Requirement.REQUIREMENT.PROJECT_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value2() { - return getName(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value3() { - return getDescription(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value4() { - return getRealized(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value5() { - return getCreationDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value6() { - return getLastUpdatedDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value7() { - return getLeadDeveloperId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value8() { - return getCreatorId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value9() { - return getProjectId(); - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementRecord value2(String value) { - setName(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementRecord value3(String value) { - setDescription(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementRecord value4(Timestamp value) { - setRealized(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementRecord value5(Timestamp value) { - setCreationDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementRecord value6(Timestamp value) { - setLastUpdatedDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementRecord value7(Integer value) { - setLeadDeveloperId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementRecord value8(Integer value) { - setCreatorId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementRecord value9(Integer value) { - setProjectId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RequirementRecord values(Integer value1, String value2, String value3, Timestamp value4, Timestamp value5, Timestamp value6, Integer value7, Integer value8, Integer value9) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - value5(value5); - value6(value6); - value7(value7); - value8(value8); - value9(value9); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached RequirementRecord - */ - public RequirementRecord() { - super(Requirement.REQUIREMENT); - } - - /** - * Create a detached, initialised RequirementRecord - */ - public RequirementRecord(Integer id, String name, String description, Timestamp realized, Timestamp creationDate, Timestamp lastUpdatedDate, Integer leadDeveloperId, Integer creatorId, Integer projectId) { - super(Requirement.REQUIREMENT); - - set(0, id); - set(1, name); - set(2, description); - set(3, realized); - set(4, creationDate); - set(5, lastUpdatedDate); - set(6, leadDeveloperId); - set(7, creatorId); - set(8, projectId); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RolePrivilegeMapRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RolePrivilegeMapRecord.java deleted file mode 100644 index a2bbf83a..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RolePrivilegeMapRecord.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RolePrivilegeMap; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record3; -import org.jooq.Row3; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class RolePrivilegeMapRecord extends UpdatableRecordImpl implements Record3 { - - private static final long serialVersionUID = -308748188; - - /** - * Setter for reqbaz.role_privilege_map.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.role_privilege_map.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.role_privilege_map.role_id. - */ - public void setRoleId(Integer value) { - set(1, value); - } - - /** - * Getter for reqbaz.role_privilege_map.role_id. - */ - public Integer getRoleId() { - return (Integer) get(1); - } - - /** - * Setter for reqbaz.role_privilege_map.privilege_id. - */ - public void setPrivilegeId(Integer value) { - set(2, value); - } - - /** - * Getter for reqbaz.role_privilege_map.privilege_id. - */ - public Integer getPrivilegeId() { - return (Integer) get(2); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record3 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row3 fieldsRow() { - return (Row3) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row3 valuesRow() { - return (Row3) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return RolePrivilegeMap.ROLE_PRIVILEGE_MAP.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return RolePrivilegeMap.ROLE_PRIVILEGE_MAP.ROLE_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return RolePrivilegeMap.ROLE_PRIVILEGE_MAP.PRIVILEGE_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value2() { - return getRoleId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value3() { - return getPrivilegeId(); - } - - /** - * {@inheritDoc} - */ - @Override - public RolePrivilegeMapRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RolePrivilegeMapRecord value2(Integer value) { - setRoleId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RolePrivilegeMapRecord value3(Integer value) { - setPrivilegeId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RolePrivilegeMapRecord values(Integer value1, Integer value2, Integer value3) { - value1(value1); - value2(value2); - value3(value3); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached RolePrivilegeMapRecord - */ - public RolePrivilegeMapRecord() { - super(RolePrivilegeMap.ROLE_PRIVILEGE_MAP); - } - - /** - * Create a detached, initialised RolePrivilegeMapRecord - */ - public RolePrivilegeMapRecord(Integer id, Integer roleId, Integer privilegeId) { - super(RolePrivilegeMap.ROLE_PRIVILEGE_MAP); - - set(0, id); - set(1, roleId); - set(2, privilegeId); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RoleRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RoleRecord.java deleted file mode 100644 index 82f2fd50..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RoleRecord.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Role; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record2; -import org.jooq.Row2; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class RoleRecord extends UpdatableRecordImpl implements Record2 { - - private static final long serialVersionUID = 854316714; - - /** - * Setter for reqbaz.role.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.role.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.role.name. - */ - public void setName(String value) { - set(1, value); - } - - /** - * Getter for reqbaz.role.name. - */ - public String getName() { - return (String) get(1); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record2 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row2 fieldsRow() { - return (Row2) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row2 valuesRow() { - return (Row2) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return Role.ROLE.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return Role.ROLE.NAME; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value2() { - return getName(); - } - - /** - * {@inheritDoc} - */ - @Override - public RoleRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RoleRecord value2(String value) { - setName(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RoleRecord values(Integer value1, String value2) { - value1(value1); - value2(value2); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached RoleRecord - */ - public RoleRecord() { - super(Role.ROLE); - } - - /** - * Create a detached, initialised RoleRecord - */ - public RoleRecord(Integer id, String name) { - super(Role.ROLE); - - set(0, id); - set(1, name); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RoleRoleMapRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RoleRoleMapRecord.java deleted file mode 100644 index 791d8544..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/RoleRoleMapRecord.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.RoleRoleMap; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record3; -import org.jooq.Row3; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class RoleRoleMapRecord extends UpdatableRecordImpl implements Record3 { - - private static final long serialVersionUID = 1477419030; - - /** - * Setter for reqbaz.role_role_map.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.role_role_map.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.role_role_map.child_id. - */ - public void setChildId(Integer value) { - set(1, value); - } - - /** - * Getter for reqbaz.role_role_map.child_id. - */ - public Integer getChildId() { - return (Integer) get(1); - } - - /** - * Setter for reqbaz.role_role_map.parent_id. - */ - public void setParentId(Integer value) { - set(2, value); - } - - /** - * Getter for reqbaz.role_role_map.parent_id. - */ - public Integer getParentId() { - return (Integer) get(2); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record3 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row3 fieldsRow() { - return (Row3) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row3 valuesRow() { - return (Row3) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return RoleRoleMap.ROLE_ROLE_MAP.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return RoleRoleMap.ROLE_ROLE_MAP.CHILD_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return RoleRoleMap.ROLE_ROLE_MAP.PARENT_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value2() { - return getChildId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value3() { - return getParentId(); - } - - /** - * {@inheritDoc} - */ - @Override - public RoleRoleMapRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RoleRoleMapRecord value2(Integer value) { - setChildId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RoleRoleMapRecord value3(Integer value) { - setParentId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public RoleRoleMapRecord values(Integer value1, Integer value2, Integer value3) { - value1(value1); - value2(value2); - value3(value3); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached RoleRoleMapRecord - */ - public RoleRoleMapRecord() { - super(RoleRoleMap.ROLE_ROLE_MAP); - } - - /** - * Create a detached, initialised RoleRoleMapRecord - */ - public RoleRoleMapRecord(Integer id, Integer childId, Integer parentId) { - super(RoleRoleMap.ROLE_ROLE_MAP); - - set(0, id); - set(1, childId); - set(2, parentId); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/SchemaVersionRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/SchemaVersionRecord.java deleted file mode 100644 index b7c77d44..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/SchemaVersionRecord.java +++ /dev/null @@ -1,501 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.SchemaVersion; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record10; -import org.jooq.Row10; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class SchemaVersionRecord extends UpdatableRecordImpl implements Record10 { - - private static final long serialVersionUID = -1022760374; - - /** - * Setter for reqbaz.schema_version.installed_rank. - */ - public void setInstalledRank(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.schema_version.installed_rank. - */ - public Integer getInstalledRank() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.schema_version.version. - */ - public void setVersion(String value) { - set(1, value); - } - - /** - * Getter for reqbaz.schema_version.version. - */ - public String getVersion() { - return (String) get(1); - } - - /** - * Setter for reqbaz.schema_version.description. - */ - public void setDescription(String value) { - set(2, value); - } - - /** - * Getter for reqbaz.schema_version.description. - */ - public String getDescription() { - return (String) get(2); - } - - /** - * Setter for reqbaz.schema_version.type. - */ - public void setType(String value) { - set(3, value); - } - - /** - * Getter for reqbaz.schema_version.type. - */ - public String getType() { - return (String) get(3); - } - - /** - * Setter for reqbaz.schema_version.script. - */ - public void setScript(String value) { - set(4, value); - } - - /** - * Getter for reqbaz.schema_version.script. - */ - public String getScript() { - return (String) get(4); - } - - /** - * Setter for reqbaz.schema_version.checksum. - */ - public void setChecksum(Integer value) { - set(5, value); - } - - /** - * Getter for reqbaz.schema_version.checksum. - */ - public Integer getChecksum() { - return (Integer) get(5); - } - - /** - * Setter for reqbaz.schema_version.installed_by. - */ - public void setInstalledBy(String value) { - set(6, value); - } - - /** - * Getter for reqbaz.schema_version.installed_by. - */ - public String getInstalledBy() { - return (String) get(6); - } - - /** - * Setter for reqbaz.schema_version.installed_on. - */ - public void setInstalledOn(Timestamp value) { - set(7, value); - } - - /** - * Getter for reqbaz.schema_version.installed_on. - */ - public Timestamp getInstalledOn() { - return (Timestamp) get(7); - } - - /** - * Setter for reqbaz.schema_version.execution_time. - */ - public void setExecutionTime(Integer value) { - set(8, value); - } - - /** - * Getter for reqbaz.schema_version.execution_time. - */ - public Integer getExecutionTime() { - return (Integer) get(8); - } - - /** - * Setter for reqbaz.schema_version.success. - */ - public void setSuccess(Byte value) { - set(9, value); - } - - /** - * Getter for reqbaz.schema_version.success. - */ - public Byte getSuccess() { - return (Byte) get(9); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record10 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row10 fieldsRow() { - return (Row10) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row10 valuesRow() { - return (Row10) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return SchemaVersion.SCHEMA_VERSION.INSTALLED_RANK; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return SchemaVersion.SCHEMA_VERSION.VERSION; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return SchemaVersion.SCHEMA_VERSION.DESCRIPTION; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return SchemaVersion.SCHEMA_VERSION.TYPE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field5() { - return SchemaVersion.SCHEMA_VERSION.SCRIPT; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field6() { - return SchemaVersion.SCHEMA_VERSION.CHECKSUM; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field7() { - return SchemaVersion.SCHEMA_VERSION.INSTALLED_BY; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field8() { - return SchemaVersion.SCHEMA_VERSION.INSTALLED_ON; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field9() { - return SchemaVersion.SCHEMA_VERSION.EXECUTION_TIME; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field10() { - return SchemaVersion.SCHEMA_VERSION.SUCCESS; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getInstalledRank(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value2() { - return getVersion(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value3() { - return getDescription(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value4() { - return getType(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value5() { - return getScript(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value6() { - return getChecksum(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value7() { - return getInstalledBy(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value8() { - return getInstalledOn(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value9() { - return getExecutionTime(); - } - - /** - * {@inheritDoc} - */ - @Override - public Byte value10() { - return getSuccess(); - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersionRecord value1(Integer value) { - setInstalledRank(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersionRecord value2(String value) { - setVersion(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersionRecord value3(String value) { - setDescription(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersionRecord value4(String value) { - setType(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersionRecord value5(String value) { - setScript(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersionRecord value6(Integer value) { - setChecksum(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersionRecord value7(String value) { - setInstalledBy(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersionRecord value8(Timestamp value) { - setInstalledOn(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersionRecord value9(Integer value) { - setExecutionTime(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersionRecord value10(Byte value) { - setSuccess(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public SchemaVersionRecord values(Integer value1, String value2, String value3, String value4, String value5, Integer value6, String value7, Timestamp value8, Integer value9, Byte value10) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - value5(value5); - value6(value6); - value7(value7); - value8(value8); - value9(value9); - value10(value10); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached SchemaVersionRecord - */ - public SchemaVersionRecord() { - super(SchemaVersion.SCHEMA_VERSION); - } - - /** - * Create a detached, initialised SchemaVersionRecord - */ - public SchemaVersionRecord(Integer installedRank, String version, String description, String type, String script, Integer checksum, String installedBy, Timestamp installedOn, Integer executionTime, Byte success) { - super(SchemaVersion.SCHEMA_VERSION); - - set(0, installedRank); - set(1, version); - set(2, description); - set(3, type); - set(4, script); - set(5, checksum); - set(6, installedBy); - set(7, installedOn); - set(8, executionTime); - set(9, success); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/UserRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/UserRecord.java deleted file mode 100644 index a8385d87..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/UserRecord.java +++ /dev/null @@ -1,624 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record13; -import org.jooq.Row13; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class UserRecord extends UpdatableRecordImpl implements Record13 { - - private static final long serialVersionUID = 131097065; - - /** - * Setter for reqbaz.user.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.user.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.user.first_name. - */ - public void setFirstName(String value) { - set(1, value); - } - - /** - * Getter for reqbaz.user.first_name. - */ - public String getFirstName() { - return (String) get(1); - } - - /** - * Setter for reqbaz.user.last_name. - */ - public void setLastName(String value) { - set(2, value); - } - - /** - * Getter for reqbaz.user.last_name. - */ - public String getLastName() { - return (String) get(2); - } - - /** - * Setter for reqbaz.user.email. - */ - public void setEmail(String value) { - set(3, value); - } - - /** - * Getter for reqbaz.user.email. - */ - public String getEmail() { - return (String) get(3); - } - - /** - * Setter for reqbaz.user.admin. - */ - public void setAdmin(Boolean value) { - set(4, value); - } - - /** - * Getter for reqbaz.user.admin. - */ - public Boolean getAdmin() { - return (Boolean) get(4); - } - - /** - * Setter for reqbaz.user.las2peer_id. - */ - public void setLas2peerId(String value) { - set(5, value); - } - - /** - * Getter for reqbaz.user.las2peer_id. - */ - public String getLas2peerId() { - return (String) get(5); - } - - /** - * Setter for reqbaz.user.user_name. - */ - public void setUserName(String value) { - set(6, value); - } - - /** - * Getter for reqbaz.user.user_name. - */ - public String getUserName() { - return (String) get(6); - } - - /** - * Setter for reqbaz.user.profile_image. - */ - public void setProfileImage(String value) { - set(7, value); - } - - /** - * Getter for reqbaz.user.profile_image. - */ - public String getProfileImage() { - return (String) get(7); - } - - /** - * Setter for reqbaz.user.email_lead_subscription. - */ - public void setEmailLeadSubscription(Byte value) { - set(8, value); - } - - /** - * Getter for reqbaz.user.email_lead_subscription. - */ - public Byte getEmailLeadSubscription() { - return (Byte) get(8); - } - - /** - * Setter for reqbaz.user.email_follow_subscription. - */ - public void setEmailFollowSubscription(Byte value) { - set(9, value); - } - - /** - * Getter for reqbaz.user.email_follow_subscription. - */ - public Byte getEmailFollowSubscription() { - return (Byte) get(9); - } - - /** - * Setter for reqbaz.user.creation_date. - */ - public void setCreationDate(Timestamp value) { - set(10, value); - } - - /** - * Getter for reqbaz.user.creation_date. - */ - public Timestamp getCreationDate() { - return (Timestamp) get(10); - } - - /** - * Setter for reqbaz.user.last_updated_date. - */ - public void setLastUpdatedDate(Timestamp value) { - set(11, value); - } - - /** - * Getter for reqbaz.user.last_updated_date. - */ - public Timestamp getLastUpdatedDate() { - return (Timestamp) get(11); - } - - /** - * Setter for reqbaz.user.last_login_date. - */ - public void setLastLoginDate(Timestamp value) { - set(12, value); - } - - /** - * Getter for reqbaz.user.last_login_date. - */ - public Timestamp getLastLoginDate() { - return (Timestamp) get(12); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record13 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row13 fieldsRow() { - return (Row13) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row13 valuesRow() { - return (Row13) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return User.USER.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return User.USER.FIRST_NAME; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return User.USER.LAST_NAME; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return User.USER.EMAIL; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field5() { - return User.USER.ADMIN; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field6() { - return User.USER.LAS2PEER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field7() { - return User.USER.USER_NAME; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field8() { - return User.USER.PROFILE_IMAGE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field9() { - return User.USER.EMAIL_LEAD_SUBSCRIPTION; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field10() { - return User.USER.EMAIL_FOLLOW_SUBSCRIPTION; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field11() { - return User.USER.CREATION_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field12() { - return User.USER.LAST_UPDATED_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field13() { - return User.USER.LAST_LOGIN_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value2() { - return getFirstName(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value3() { - return getLastName(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value4() { - return getEmail(); - } - - /** - * {@inheritDoc} - */ - @Override - public Boolean value5() { - return getAdmin(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value6() { - return getLas2peerId(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value7() { - return getUserName(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value8() { - return getProfileImage(); - } - - /** - * {@inheritDoc} - */ - @Override - public Byte value9() { - return getEmailLeadSubscription(); - } - - /** - * {@inheritDoc} - */ - @Override - public Byte value10() { - return getEmailFollowSubscription(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value11() { - return getCreationDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value12() { - return getLastUpdatedDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value13() { - return getLastLoginDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value2(String value) { - setFirstName(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value3(String value) { - setLastName(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value4(String value) { - setEmail(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value5(Boolean value) { - setAdmin(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value6(String value) { - setLas2peerId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value7(String value) { - setUserName(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value8(String value) { - setProfileImage(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value9(Byte value) { - setEmailLeadSubscription(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value10(Byte value) { - setEmailFollowSubscription(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value11(Timestamp value) { - setCreationDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value12(Timestamp value) { - setLastUpdatedDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord value13(Timestamp value) { - setLastLoginDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRecord values(Integer value1, String value2, String value3, String value4, Boolean value5, String value6, String value7, String value8, Byte value9, Byte value10, Timestamp value11, Timestamp value12, Timestamp value13) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - value5(value5); - value6(value6); - value7(value7); - value8(value8); - value9(value9); - value10(value10); - value11(value11); - value12(value12); - value13(value13); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached UserRecord - */ - public UserRecord() { - super(User.USER); - } - - /** - * Create a detached, initialised UserRecord - */ - public UserRecord(Integer id, String firstName, String lastName, String email, Boolean admin, String las2peerId, String userName, String profileImage, Byte emailLeadSubscription, Byte emailFollowSubscription, Timestamp creationDate, Timestamp lastUpdatedDate, Timestamp lastLoginDate) { - super(User.USER); - - set(0, id); - set(1, firstName); - set(2, lastName); - set(3, email); - set(4, admin); - set(5, las2peerId); - set(6, userName); - set(7, profileImage); - set(8, emailLeadSubscription); - set(9, emailFollowSubscription); - set(10, creationDate); - set(11, lastUpdatedDate); - set(12, lastLoginDate); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/UserRoleMapRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/UserRoleMapRecord.java deleted file mode 100644 index a1bcd3f7..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/UserRoleMapRecord.java +++ /dev/null @@ -1,254 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.UserRoleMap; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record4; -import org.jooq.Row4; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class UserRoleMapRecord extends UpdatableRecordImpl implements Record4 { - - private static final long serialVersionUID = -247032073; - - /** - * Setter for reqbaz.user_role_map.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.user_role_map.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.user_role_map.role_id. - */ - public void setRoleId(Integer value) { - set(1, value); - } - - /** - * Getter for reqbaz.user_role_map.role_id. - */ - public Integer getRoleId() { - return (Integer) get(1); - } - - /** - * Setter for reqbaz.user_role_map.user_id. - */ - public void setUserId(Integer value) { - set(2, value); - } - - /** - * Getter for reqbaz.user_role_map.user_id. - */ - public Integer getUserId() { - return (Integer) get(2); - } - - /** - * Setter for reqbaz.user_role_map.context_info. - */ - public void setContextInfo(String value) { - set(3, value); - } - - /** - * Getter for reqbaz.user_role_map.context_info. - */ - public String getContextInfo() { - return (String) get(3); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record4 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row4 fieldsRow() { - return (Row4) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row4 valuesRow() { - return (Row4) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return UserRoleMap.USER_ROLE_MAP.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return UserRoleMap.USER_ROLE_MAP.ROLE_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return UserRoleMap.USER_ROLE_MAP.USER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return UserRoleMap.USER_ROLE_MAP.CONTEXT_INFO; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value2() { - return getRoleId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value3() { - return getUserId(); - } - - /** - * {@inheritDoc} - */ - @Override - public String value4() { - return getContextInfo(); - } - - /** - * {@inheritDoc} - */ - @Override - public UserRoleMapRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRoleMapRecord value2(Integer value) { - setRoleId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRoleMapRecord value3(Integer value) { - setUserId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRoleMapRecord value4(String value) { - setContextInfo(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public UserRoleMapRecord values(Integer value1, Integer value2, Integer value3, String value4) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached UserRoleMapRecord - */ - public UserRoleMapRecord() { - super(UserRoleMap.USER_ROLE_MAP); - } - - /** - * Create a detached, initialised UserRoleMapRecord - */ - public UserRoleMapRecord(Integer id, Integer roleId, Integer userId, String contextInfo) { - super(UserRoleMap.USER_ROLE_MAP); - - set(0, id); - set(1, roleId); - set(2, userId); - set(3, contextInfo); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/VoteRecord.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/VoteRecord.java deleted file mode 100644 index 6fb983e9..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/jooq/tables/records/VoteRecord.java +++ /dev/null @@ -1,296 +0,0 @@ -/* - * This file is generated by jOOQ. - */ -package de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records; - - -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Vote; -import org.jooq.Field; -import org.jooq.Record1; -import org.jooq.Record5; -import org.jooq.Row5; -import org.jooq.impl.UpdatableRecordImpl; - -import javax.annotation.Generated; -import java.sql.Timestamp; - - -/** - * This class is generated by jOOQ. - */ -@Generated( - value = { - "http://www.jooq.org", - "jOOQ version:3.9.1" - }, - comments = "This class is generated by jOOQ" -) -@SuppressWarnings({"all", "unchecked", "rawtypes"}) -public class VoteRecord extends UpdatableRecordImpl implements Record5 { - - private static final long serialVersionUID = 1481873125; - - /** - * Setter for reqbaz.vote.id. - */ - public void setId(Integer value) { - set(0, value); - } - - /** - * Getter for reqbaz.vote.id. - */ - public Integer getId() { - return (Integer) get(0); - } - - /** - * Setter for reqbaz.vote.is_upvote. - */ - public void setIsUpvote(Byte value) { - set(1, value); - } - - /** - * Getter for reqbaz.vote.is_upvote. - */ - public Byte getIsUpvote() { - return (Byte) get(1); - } - - /** - * Setter for reqbaz.vote.requirement_id. - */ - public void setRequirementId(Integer value) { - set(2, value); - } - - /** - * Getter for reqbaz.vote.requirement_id. - */ - public Integer getRequirementId() { - return (Integer) get(2); - } - - /** - * Setter for reqbaz.vote.user_id. - */ - public void setUserId(Integer value) { - set(3, value); - } - - /** - * Getter for reqbaz.vote.user_id. - */ - public Integer getUserId() { - return (Integer) get(3); - } - - /** - * Setter for reqbaz.vote.creation_date. - */ - public void setCreationDate(Timestamp value) { - set(4, value); - } - - /** - * Getter for reqbaz.vote.creation_date. - */ - public Timestamp getCreationDate() { - return (Timestamp) get(4); - } - - // ------------------------------------------------------------------------- - // Primary key information - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Record1 key() { - return (Record1) super.key(); - } - - // ------------------------------------------------------------------------- - // Record5 type implementation - // ------------------------------------------------------------------------- - - /** - * {@inheritDoc} - */ - @Override - public Row5 fieldsRow() { - return (Row5) super.fieldsRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Row5 valuesRow() { - return (Row5) super.valuesRow(); - } - - /** - * {@inheritDoc} - */ - @Override - public Field field1() { - return Vote.VOTE.ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field2() { - return Vote.VOTE.IS_UPVOTE; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field3() { - return Vote.VOTE.REQUIREMENT_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field4() { - return Vote.VOTE.USER_ID; - } - - /** - * {@inheritDoc} - */ - @Override - public Field field5() { - return Vote.VOTE.CREATION_DATE; - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value1() { - return getId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Byte value2() { - return getIsUpvote(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value3() { - return getRequirementId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Integer value4() { - return getUserId(); - } - - /** - * {@inheritDoc} - */ - @Override - public Timestamp value5() { - return getCreationDate(); - } - - /** - * {@inheritDoc} - */ - @Override - public VoteRecord value1(Integer value) { - setId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public VoteRecord value2(Byte value) { - setIsUpvote(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public VoteRecord value3(Integer value) { - setRequirementId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public VoteRecord value4(Integer value) { - setUserId(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public VoteRecord value5(Timestamp value) { - setCreationDate(value); - return this; - } - - /** - * {@inheritDoc} - */ - @Override - public VoteRecord values(Integer value1, Byte value2, Integer value3, Integer value4, Timestamp value5) { - value1(value1); - value2(value2); - value3(value3); - value4(value4); - value5(value5); - return this; - } - - // ------------------------------------------------------------------------- - // Constructors - // ------------------------------------------------------------------------- - - /** - * Create a detached VoteRecord - */ - public VoteRecord() { - super(Vote.VOTE); - } - - /** - * Create a detached, initialised VoteRecord - */ - public VoteRecord(Integer id, Byte isUpvote, Integer requirementId, Integer userId, Timestamp creationDate) { - super(Vote.VOTE); - - set(0, id); - set(1, isUpvote); - set(2, requirementId); - set(3, userId); - set(4, creationDate); - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepositoryImpl.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepositoryImpl.java deleted file mode 100644 index dae0d33d..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/CommentRepositoryImpl.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.repositories; - -import de.rwth.dbis.acis.bazaar.service.dal.entities.Comment; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.CommentRecord; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.UserRecord; -import de.rwth.dbis.acis.bazaar.service.dal.transform.CommentTransformer; -import de.rwth.dbis.acis.bazaar.service.dal.transform.UserTransformer; -import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; -import org.jooq.DSLContext; -import org.jooq.Field; -import org.jooq.Record; -import org.jooq.exception.DataAccessException; - -import java.util.ArrayList; -import java.util.List; - -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.*; - -public class CommentRepositoryImpl extends RepositoryImpl implements CommentRepository { - - /** - * @param jooq DSLContext for JOOQ connection - */ - public CommentRepositoryImpl(DSLContext jooq) { - super(jooq, new CommentTransformer()); - } - - @Override - public PaginationResult findAllByRequirementId(int requirementId, Pageable pageable) throws BazaarException { - PaginationResult result = null; - List comments; - try { - comments = new ArrayList<>(); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User creatorUser = USER.as("creatorUser"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Comment childComment = COMMENT.as("childComment"); - User childCommentCreatorUser = USER.as("childCommentCreatorUser"); - - Field idCount = jooq.selectCount() - .from(COMMENT) - .where(COMMENT.REQUIREMENT_ID.equal(requirementId)) - .asField("idCount"); - - List queryResults = jooq.select(COMMENT.fields()) - .select(childComment.fields()).select(creatorUser.fields()).select(childCommentCreatorUser.fields()).select(idCount) - .from(COMMENT) - .leftJoin(childComment).on(childComment.REPLY_TO_COMMENT_ID.equal(COMMENT.ID)) - .leftJoin(childCommentCreatorUser).on(childCommentCreatorUser.ID.equal(childComment.USER_ID)) - .join(creatorUser).on(creatorUser.ID.equal(COMMENT.USER_ID)) - .where(COMMENT.REQUIREMENT_ID.equal(requirementId).and(COMMENT.REPLY_TO_COMMENT_ID.isNull())) - .orderBy(transformer.getSortFields(pageable.getSorts())) - .limit(pageable.getPageSize()) - .offset(pageable.getOffset()) - .fetch(); - - Comment entry = null; - for (Record record : queryResults) { - if (entry == null || transformer.getEntityFromTableRecord(record.into(CommentRecord.class)).getId() != entry.getId()) { - entry = convertToCommentWithUser(record, creatorUser); - comments.add(entry); - } - CommentRecord childRecord = record.into(childComment); - if (childRecord.getId() != null) { - Comment childEntry = convertToCommentWithUser(record, childComment, childCommentCreatorUser); - comments.add(childEntry); - } - } - int total = queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount")); - result = new PaginationResult<>(total, pageable, comments); - } catch (DataAccessException e) { - ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); - } - - return result; - } - - private Comment convertToCommentWithUser(Record record, de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User creatorUser) { - CommentRecord commentRecord = record.into(CommentRecord.class); - Comment entry = transformer.getEntityFromTableRecord(commentRecord); - UserTransformer userTransformer = new UserTransformer(); - UserRecord userRecord = record.into(creatorUser); - entry.setCreator(userTransformer.getEntityFromTableRecord(userRecord)); - return entry; - } - - private Comment convertToCommentWithUser(Record record, de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Comment comment, de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User creatorUser) { - CommentRecord commentRecord = record.into(comment); - Comment entry = transformer.getEntityFromTableRecord(commentRecord); - UserTransformer userTransformer = new UserTransformer(); - UserRecord userRecord = record.into(creatorUser); - entry.setCreator(userTransformer.getEntityFromTableRecord(userRecord)); - return entry; - } - - @Override - public de.rwth.dbis.acis.bazaar.service.dal.entities.Comment findById(int id) throws Exception { - Comment returnComment = null; - try { - User creatorUser = USER.as("creatorUser"); - Record record = jooq.selectFrom(COMMENT - .join(creatorUser).on(creatorUser.ID.equal(COMMENT.USER_ID))) - .where(transformer.getTableId().equal(id)) - .fetchOne(); - returnComment = convertToCommentWithUser(record, creatorUser); - } catch (DataAccessException e) { - ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); - } catch (NullPointerException e) { - ExceptionHandler.getInstance().convertAndThrowException( - new Exception("No " + transformer.getRecordClass() + " found with id: " + id), - ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); - } - return returnComment; - } - - @Override - public boolean belongsToPublicProject(int id) throws BazaarException { - try { - Integer countOfPublicProjects = jooq.selectCount() - .from(transformer.getTable()) - .join(REQUIREMENT).on(REQUIREMENT.ID.eq(COMMENT.REQUIREMENT_ID)) - .join(PROJECT).on(PROJECT.ID.eq(REQUIREMENT.PROJECT_ID)) - .where(transformer.getTableId().eq(id).and(PROJECT.VISIBILITY.isTrue())) - .fetchOne(0, int.class); - - return (countOfPublicProjects == 1); - } catch (DataAccessException e) { - ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); - } - return false; - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepositoryImpl.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepositoryImpl.java deleted file mode 100644 index a9e1e00a..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/repositories/RequirementRepositoryImpl.java +++ /dev/null @@ -1,458 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.repositories; - -import de.rwth.dbis.acis.bazaar.service.dal.entities.Category; -import de.rwth.dbis.acis.bazaar.service.dal.entities.Requirement; -import de.rwth.dbis.acis.bazaar.service.dal.entities.Statistic; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.PaginationResult; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.UserVote; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementRecord; -import de.rwth.dbis.acis.bazaar.service.dal.transform.RequirementTransformer; -import de.rwth.dbis.acis.bazaar.service.dal.transform.UserTransformer; -import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -import de.rwth.dbis.acis.bazaar.service.exception.ErrorCode; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionHandler; -import de.rwth.dbis.acis.bazaar.service.exception.ExceptionLocation; -import org.jooq.*; -import org.jooq.exception.DataAccessException; -import org.jooq.impl.DSL; - -import java.math.BigDecimal; -import java.sql.Timestamp; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; -import java.util.Map; - -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.*; -import static org.jooq.impl.DSL.*; - -public class RequirementRepositoryImpl extends RepositoryImpl implements RequirementRepository { - - // derived table for activities inside requirement - public static final Table ACTIVITY = table( - select(REQUIREMENT.ID, REQUIREMENT.CREATION_DATE) - .from(REQUIREMENT) - .unionAll( - select(REQUIREMENT.ID, REQUIREMENT.LAST_UPDATED_DATE) - .from(REQUIREMENT)) - .unionAll( - select(COMMENT.REQUIREMENT_ID, COMMENT.CREATION_DATE) - .from(COMMENT)) - .unionAll( - select(COMMENT.REQUIREMENT_ID, COMMENT.LAST_UPDATED_DATE) - .from(COMMENT)) - .unionAll( - select(ATTACHMENT.REQUIREMENT_ID, ATTACHMENT.CREATION_DATE) - .from(ATTACHMENT)) - .unionAll( - select(ATTACHMENT.REQUIREMENT_ID, ATTACHMENT.LAST_UPDATED_DATE) - .from(ATTACHMENT)) - ).as("ACTIVITY"); - - // derived table for last activity inside requirement - public static final Table LAST_ACTIVITY = table( - select( - ACTIVITY.field(REQUIREMENT.ID), - max(ACTIVITY.field(REQUIREMENT.CREATION_DATE)).as("last_activity")) - .from(ACTIVITY) - .groupBy(ACTIVITY.field(REQUIREMENT.ID))) - .as("last_activity"); - - public static final Field VOTE_COUNT = select(DSL.count(DSL.nullif(VOTE.IS_UPVOTE, 0))) - .from(VOTE) - .where(VOTE.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .asField("voteCount"); - - public static final Field COMMENT_COUNT = select(DSL.count()) - .from(COMMENT) - .where(COMMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .asField("commentCount"); - - public static final Field ATTACHMENT_COUNT = select(DSL.count()) - .from(ATTACHMENT) - .where(ATTACHMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .asField("attachmentCount"); - - public static final Field FOLLOWER_COUNT = select(DSL.count()) - .from(REQUIREMENT_FOLLOWER_MAP) - .where(REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .asField("followerCount"); - - /** - * @param jooq DSLContext object to initialize JOOQ connection. For more see JOOQ documentation. - */ - public RequirementRepositoryImpl(DSLContext jooq) { - super(jooq, new RequirementTransformer()); - } - - @Override - public PaginationResult findAllByProject(int projectId, Pageable pageable, int userId) throws BazaarException { - PaginationResult result = null; - List requirements; - try { - requirements = new ArrayList<>(); - - Field idCount = jooq.selectCount() - .from(REQUIREMENT) - .where(transformer.getFilterConditions(pageable.getFilters())) - .and(transformer.getSearchCondition(pageable.getSearch())) - .and(REQUIREMENT.PROJECT_ID.eq(projectId)) - .asField("idCount"); - - List queryResults = jooq.select(REQUIREMENT.fields()) - .select(idCount) - .select(VOTE_COUNT) - .select(COMMENT_COUNT) - .select(FOLLOWER_COUNT) - .from(REQUIREMENT) - .leftOuterJoin(LAST_ACTIVITY).on(REQUIREMENT.ID.eq(LAST_ACTIVITY.field(REQUIREMENT.ID))) - .where(transformer.getFilterConditions(pageable.getFilters())) - .and(transformer.getSearchCondition(pageable.getSearch())) - .and(REQUIREMENT.PROJECT_ID.eq(projectId)) - .groupBy(REQUIREMENT.ID) - .orderBy(transformer.getSortFields(pageable.getSorts())) - .limit(pageable.getPageSize()) - .offset(pageable.getOffset()) - .fetch(); - - for (Record queryResult : queryResults) { - RequirementRecord requirementRecord = queryResult.into(REQUIREMENT); - Requirement requirement = transformer.getEntityFromTableRecord(requirementRecord); - requirements.add(findById(requirement.getId(), userId)); // TODO: Remove the getId call and create the objects themself here - } - int total = queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount")); - result = new PaginationResult<>(total, pageable, requirements); - } catch (DataAccessException e) { - ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); - } catch (Exception e) { - ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); - } - return result; - } - - private UserVote transformToUserVoted(Integer userVotedInt) { - UserVote userVoted; - if (userVotedInt == null) - return UserVote.NO_VOTE; - switch (userVotedInt) { - case 0: - userVoted = UserVote.DOWN_VOTE; - break; - case 1: - userVoted = UserVote.UP_VOTE; - break; - default: - userVoted = UserVote.NO_VOTE; - } - return userVoted; - } - - @Override - public PaginationResult findAllByCategory(int categoryId, Pageable pageable, int userId) throws BazaarException { - PaginationResult result = null; - List requirements; - try { - requirements = new ArrayList<>(); - - Field idCount = jooq.selectCount() - .from(REQUIREMENT) - .join(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID.eq(REQUIREMENT.ID)) - .where(transformer.getFilterConditions(pageable.getFilters())) - .and(transformer.getSearchCondition(pageable.getSearch())) - .and(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID.eq(categoryId)) - .asField("idCount"); - - Field voteCount = jooq.select(DSL.count(DSL.nullif(VOTE.IS_UPVOTE, 0))) - .from(VOTE) - .where(VOTE.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .asField("voteCount"); - - Field commentCount = jooq.select(DSL.count()) - .from(COMMENT) - .where(COMMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .asField("commentCount"); - - Field followerCount = jooq.select(DSL.count()) - .from(REQUIREMENT_FOLLOWER_MAP) - .where(REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .asField("followerCount"); - - List queryResults = jooq.select(REQUIREMENT.fields()) - .select(idCount) - .select(VOTE_COUNT) - .select(COMMENT_COUNT) - .select(FOLLOWER_COUNT) - .from(REQUIREMENT) - .leftOuterJoin(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID.eq(REQUIREMENT.ID)) - .leftOuterJoin(LAST_ACTIVITY).on(REQUIREMENT.ID.eq(LAST_ACTIVITY.field(REQUIREMENT.ID))) - .where(transformer.getFilterConditions(pageable.getFilters())) - .and(transformer.getSearchCondition(pageable.getSearch())) - .and(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID.eq(categoryId)) - .groupBy(REQUIREMENT.ID) - .orderBy(transformer.getSortFields(pageable.getSorts())) - .limit(pageable.getPageSize()) - .offset(pageable.getOffset()) - .fetch(); - - for (Record queryResult : queryResults) { - RequirementRecord requirementRecord = queryResult.into(RequirementRecord.class); - requirements.add(findById(requirementRecord.getId(), userId)); // TODO: Remove the getId call and create the objects themself here - } - int total = queryResults.isEmpty() ? 0 : ((Integer) queryResults.get(0).get("idCount")); - result = new PaginationResult<>(total, pageable, requirements); - } catch (Exception e) { - ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); - } - return result; - } - - @Override - public boolean belongsToPublicProject(int id) throws BazaarException { - try { - Integer countOfPublicProjects = jooq.selectCount() - .from(transformer.getTable()) - .join(PROJECT).on(PROJECT.ID.eq(REQUIREMENT.PROJECT_ID)) - .where(transformer.getTableId().eq(id).and(PROJECT.VISIBILITY.isTrue())) - .fetchOne(0, int.class); - return (countOfPublicProjects == 1); - } catch (DataAccessException e) { - ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); - } - return false; - } - - @Override - public Requirement findById(int id, int userId) throws Exception { - Requirement requirement = null; - try { - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User creatorUser = USER.as("creatorUser"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.User leadDeveloperUser = USER.as("leadDeveloperUser"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Vote vote = VOTE.as("vote"); - de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Vote userVote = VOTE.as("userVote"); - - Field isFollower = DSL.select(DSL.count()) - .from(REQUIREMENT_FOLLOWER_MAP) - .where(REQUIREMENT_FOLLOWER_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID).and(REQUIREMENT_FOLLOWER_MAP.USER_ID.equal(userId))) - .asField("isFollower"); - - Field isDeveloper = DSL.select(DSL.count()) - .from(REQUIREMENT_DEVELOPER_MAP) - .where(REQUIREMENT_DEVELOPER_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID).and(REQUIREMENT_DEVELOPER_MAP.USER_ID.equal(userId))) - .asField("isDeveloper"); - - // Contributors = {Creator, Lead Developer, Developers, Comments creators, Attachments creators} - // This code could be improved so that not only "1" or "0" will return but how much contributions an user made - // I tried this for 2-3 hours. SQL ... yeah ... I leave this to someone else. :-> - // TODO: Try the first idea from here: http://stackoverflow.com/questions/43717672/sum-over-multiple-count-field/43721212?noredirect=1#comment74498115_43721212 - Field isContributor = select(sum(choose() - .when(REQUIREMENT.CREATOR_ID.eq(userId), inline(1)) - .when(REQUIREMENT.LEAD_DEVELOPER_ID.eq(userId), inline(1)) - .when(REQUIREMENT_DEVELOPER_MAP.USER_ID.eq(userId), inline(1)) - .when(COMMENT.USER_ID.eq(userId), inline(1)) - .when(ATTACHMENT.USER_ID.eq(userId), inline(1)) - .otherwise(inline(0)) - )) - .from(REQUIREMENT) - .leftOuterJoin(REQUIREMENT_DEVELOPER_MAP).on(REQUIREMENT_DEVELOPER_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .leftOuterJoin(COMMENT).on(COMMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .leftOuterJoin(ATTACHMENT).on(ATTACHMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .where(REQUIREMENT.ID.equal(id)) - .asField("isContributor"); - - Result queryResult = jooq.select(REQUIREMENT.fields()) - .select(COMMENT_COUNT) - .select(ATTACHMENT_COUNT) - .select(FOLLOWER_COUNT) - .select(isFollower) - .select(isDeveloper) - .select(isContributor) - .select(creatorUser.fields()) - .select(leadDeveloperUser.fields()) - .select(CATEGORY.fields()) - .from(REQUIREMENT) - .join(creatorUser).on(creatorUser.ID.equal(REQUIREMENT.CREATOR_ID)) - .leftOuterJoin(leadDeveloperUser).on(leadDeveloperUser.ID.equal(REQUIREMENT.LEAD_DEVELOPER_ID)) - .leftOuterJoin(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .leftOuterJoin(CATEGORY).on(CATEGORY.ID.equal(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID)) - .where(transformer.getTableId().equal(id)) - .fetch(); - - if (queryResult == null || queryResult.size() == 0) { - ExceptionHandler.getInstance().convertAndThrowException( - new Exception("No " + transformer.getRecordClass() + " found with id: " + id), - ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); - } - - //Filling up Requirement fields - Requirement.Builder builder = Requirement.getBuilder(queryResult.getValues(REQUIREMENT.NAME).get(0)); - builder.id(queryResult.getValues(REQUIREMENT.ID).get(0)) - .description(queryResult.getValues(REQUIREMENT.DESCRIPTION).get(0)) - .realized(queryResult.getValues(REQUIREMENT.REALIZED).get(0)) - .creationDate(queryResult.getValues(REQUIREMENT.CREATION_DATE).get(0)) - .lastUpdatedDate(queryResult.getValues(REQUIREMENT.LAST_UPDATED_DATE).get(0)) - .projectId(queryResult.getValues(REQUIREMENT.PROJECT_ID).get(0)); - - UserTransformer userTransformer = new UserTransformer(); - //Filling up Creator - builder.creator( - userTransformer.getEntityFromQueryResult(creatorUser, queryResult) - ); - - //Filling up LeadDeveloper - if (queryResult.getValues(leadDeveloperUser.ID).get(0) != null) { - builder.leadDeveloper( - userTransformer.getEntityFromQueryResult(leadDeveloperUser, queryResult) - ); - } - - //Filling up votes - Result voteQueryResult = jooq.select(DSL.count(DSL.nullif(vote.IS_UPVOTE, 0)).as("upVotes")) - .select(DSL.count(DSL.nullif(vote.IS_UPVOTE, 1)).as("downVotes")) - .select(userVote.IS_UPVOTE.as("userVoted")) - .from(REQUIREMENT) - .leftOuterJoin(vote).on(vote.REQUIREMENT_ID.eq(REQUIREMENT.ID)) - .leftOuterJoin(userVote).on(userVote.REQUIREMENT_ID.eq(REQUIREMENT.ID).and(userVote.USER_ID.eq(userId))) - .where(transformer.getTableId().equal(id)) - .groupBy(userVote.IS_UPVOTE) - .fetch(); - - builder.upVotes(voteQueryResult.get(0).getValue("upVotes", Integer.class)); - builder.downVotes(voteQueryResult.get(0).getValue("downVotes", Integer.class)); - builder.userVoted(transformToUserVoted(voteQueryResult.get(0).getValue("userVoted", Integer.class))); - - requirement = builder.build(); - - //Filling up categories - List categories = new ArrayList<>(); - - for (Map.Entry> entry : queryResult.intoGroups(CATEGORY.ID).entrySet()) { - if (entry.getKey() == null) continue; - Result records = entry.getValue(); - categories.add( - Category.getBuilder(records.getValues(CATEGORY.NAME).get(0)) - .projectId(records.getValues(CATEGORY.PROJECT_ID).get(0)) - .id(records.getValues(CATEGORY.ID).get(0)) - .description(records.getValues(CATEGORY.DESCRIPTION).get(0)) - .build() - ); - } - requirement.setCategories(categories); - - //Filling up additional information - requirement.setNumberOfComments((Integer) queryResult.getValues(COMMENT_COUNT).get(0)); - requirement.setNumberOfAttachments((Integer) queryResult.getValues(ATTACHMENT_COUNT).get(0)); - requirement.setNumberOfFollowers((Integer) queryResult.getValues(FOLLOWER_COUNT).get(0)); - if (userId != 1) { - requirement.setFollower((Integer) queryResult.getValues(isFollower).get(0) == 0 ? false : true); - requirement.setDeveloper((Integer) queryResult.getValues(isDeveloper).get(0) == 0 ? false : true); - requirement.setContributor(queryResult.getValues(isContributor).get(0).equals(new BigDecimal(0)) ? false : true); - } - - } catch (BazaarException be) { - ExceptionHandler.getInstance().convertAndThrowException(be); - } catch (Exception e) { - ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); - } - return requirement; - } - - @Override - public void setRealized(int id, Timestamp realized) throws BazaarException { - try { - jooq.update(REQUIREMENT) - .set(REQUIREMENT.REALIZED, realized) - .set(REQUIREMENT.LAST_UPDATED_DATE, new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())) - .where(REQUIREMENT.ID.eq(id)) - .execute(); - } catch (Exception e) { - ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); - } - } - - @Override - public void setLeadDeveloper(int id, Integer userId) throws BazaarException { - try { - jooq.update(REQUIREMENT) - .set(REQUIREMENT.LEAD_DEVELOPER_ID, userId) - .set(REQUIREMENT.LAST_UPDATED_DATE, new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())) - .where(REQUIREMENT.ID.eq(id)) - .execute(); - } catch (Exception e) { - ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.NOT_FOUND); - } - } - - @Override - public Statistic getStatisticsForRequirement(int userId, int requirementId, Timestamp timestamp) throws BazaarException { - Statistic result = null; - try { - // If you want to change something here, please know what you are doing! Its SQL and even worse JOOQ :-| - Record record1 = jooq - .select(DSL.countDistinct(PROJECT.ID).as("numberOfProjects")) - .select(DSL.countDistinct(CATEGORY.ID).as("numberOfCategories")) - .select(DSL.countDistinct(COMMENT.ID).as("numberOfComments")) - .select(DSL.countDistinct(ATTACHMENT.ID).as("numberOfAttachments")) - .select(DSL.countDistinct(VOTE.ID).as("numberOfVotes")) - .from(REQUIREMENT) - .leftJoin(PROJECT).on(PROJECT.CREATION_DATE.greaterOrEqual(timestamp) - .or(PROJECT.LAST_UPDATED_DATE.greaterOrEqual(timestamp)) - .and(PROJECT.ID.equal(REQUIREMENT.PROJECT_ID))) - .leftJoin(REQUIREMENT_CATEGORY_MAP).on(REQUIREMENT_CATEGORY_MAP.REQUIREMENT_ID.equal(REQUIREMENT.ID)) - .leftJoin(CATEGORY).on(CATEGORY.CREATION_DATE.greaterOrEqual(timestamp) - .or(CATEGORY.LAST_UPDATED_DATE.greaterOrEqual(timestamp)) - .and(CATEGORY.ID.equal(REQUIREMENT_CATEGORY_MAP.CATEGORY_ID))) - .leftJoin(COMMENT).on(COMMENT.CREATION_DATE.greaterOrEqual(timestamp) - .or(COMMENT.LAST_UPDATED_DATE.greaterOrEqual(timestamp)) - .and(COMMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID))) - .leftJoin(ATTACHMENT).on(ATTACHMENT.CREATION_DATE.greaterOrEqual(timestamp) - .or(ATTACHMENT.LAST_UPDATED_DATE.greaterOrEqual(timestamp)) - .and(ATTACHMENT.REQUIREMENT_ID.equal(REQUIREMENT.ID))) - .leftJoin(VOTE).on(VOTE.CREATION_DATE.greaterOrEqual(timestamp) - .and(VOTE.REQUIREMENT_ID.equal(REQUIREMENT.ID))) - .where(REQUIREMENT.ID.eq(requirementId)) - .fetchOne(); - - Record record2 = jooq - .select(DSL.countDistinct(REQUIREMENT.ID).as("numberOfRequirements")) - .from(REQUIREMENT) - .where(REQUIREMENT.CREATION_DATE.greaterOrEqual(timestamp) - .or(REQUIREMENT.LAST_UPDATED_DATE.greaterOrEqual(timestamp)) - .and(REQUIREMENT.ID.eq(requirementId))) - .fetchOne(); - - result = Statistic.getBuilder() - .numberOfProjects((Integer) record1.get("numberOfProjects")) - .numberOfCategories((Integer) record1.get("numberOfCategories")) - .numberOfRequirements((Integer) record2.get("numberOfRequirements")) - .numberOfComments((Integer) record1.get("numberOfComments")) - .numberOfAttachments((Integer) record1.get("numberOfAttachments")) - .numberOfVotes((Integer) record1.get("numberOfVotes")) - .build(); - - } catch (DataAccessException e) { - ExceptionHandler.getInstance().convertAndThrowException(e, ExceptionLocation.REPOSITORY, ErrorCode.UNKNOWN); - } - return result; - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/CommentTransformer.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/CommentTransformer.java deleted file mode 100644 index 4407a679..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/CommentTransformer.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.transform; - -import com.vdurmont.emoji.EmojiParser; -import de.rwth.dbis.acis.bazaar.service.dal.entities.Comment; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.CommentRecord; -import org.jooq.*; - -import java.sql.Timestamp; -import java.util.*; - -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.COMMENT; - -/** - * @author Adam Gavronek - * @since 6/23/2014 - */ -public class CommentTransformer implements Transformer { - @Override - public CommentRecord createRecord(Comment entity) { - entity = this.cleanEntity(entity); - - CommentRecord record = new CommentRecord(); - record.setUserId(entity.getCreator().getId()); - record.setMessage(entity.getMessage()); - record.setRequirementId(entity.getRequirementId()); - record.setReplyToCommentId(entity.getReplyToComment()); - record.setCreationDate(new Timestamp(Calendar.getInstance().getTime().getTime())); - return record; - } - - @Override - public Comment getEntityFromTableRecord(CommentRecord record) { - return Comment.getBuilder(record.getMessage()) - .id(record.getId()) - .requirementId(record.getRequirementId()) - .replyToComment(record.getReplyToCommentId()) - .creationDate(record.getCreationDate()) - .lastUpdatedDate(record.getLastUpdatedDate()) - .build(); - } - - @Override - public Table getTable() { - return COMMENT; - } - - @Override - public TableField getTableId() { - return COMMENT.ID; - } - - @Override - public Class getRecordClass() { - return CommentRecord.class; - } - - @Override - public Map getUpdateMap(final Comment entity) { - HashMap updateMap = new HashMap() {{ - put(COMMENT.REQUIREMENT_ID, entity.getRequirementId()); - put(COMMENT.MESSAGE, entity.getMessage()); - }}; - if (!updateMap.isEmpty()) { - updateMap.put(COMMENT.LAST_UPDATED_DATE, new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); - } - return updateMap; - } - - @Override - public Collection> getSortFields(List sorts) { - if (sorts.isEmpty()) { - return Collections.singletonList(COMMENT.CREATION_DATE.asc()); - } - return null; - } - - @Override - public Condition getSearchCondition(String search) throws Exception { - throw new Exception("Search is not supported!"); - } - - @Override - public Collection getFilterConditions(Map filters) throws Exception { - return new ArrayList<>(); - } - - private Comment cleanEntity(Comment comment) { - if (comment.getMessage() != null) { - comment.setMessage(EmojiParser.parseToAliases(comment.getMessage())); - } - return comment; - } -} diff --git a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementTransformer.java b/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementTransformer.java deleted file mode 100644 index 1da52672..00000000 --- a/src/main/de/rwth/dbis/acis/bazaar/service/dal/transform/RequirementTransformer.java +++ /dev/null @@ -1,231 +0,0 @@ -/* - * - * Copyright (c) 2014, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.dal.transform; - -import com.vdurmont.emoji.EmojiParser; -import de.rwth.dbis.acis.bazaar.service.dal.entities.Requirement; -import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementRecord; -import de.rwth.dbis.acis.bazaar.service.dal.repositories.RequirementRepositoryImpl; -import org.jooq.*; -import org.jooq.impl.DSL; - -import java.util.*; - -import static de.rwth.dbis.acis.bazaar.service.dal.jooq.Tables.*; - -public class RequirementTransformer implements Transformer { - @Override - public RequirementRecord createRecord(Requirement entry) { - entry = this.cleanEntity(entry); - - RequirementRecord record = new RequirementRecord(); - record.setDescription(entry.getDescription()); - record.setName(entry.getName()); - record.setCreationDate(new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); - record.setCreatorId(entry.getCreator().getId()); - record.setProjectId(entry.getProjectId()); - return record; - } - - public Requirement.Builder mapToEntityBuilder(RequirementRecord record) { - return Requirement.getBuilder(record.getName()) - .description(record.getDescription()) - .id(record.getId()) - .realized(record.getRealized()) - .creationDate(record.getCreationDate()) - .lastUpdatedDate(record.getLastUpdatedDate()) - .projectId(record.getProjectId()); - } - - @Override - public Requirement getEntityFromTableRecord(RequirementRecord record) { - return mapToEntityBuilder(record) - .build(); - } - - @Override - public Table getTable() { - return REQUIREMENT; - } - - @Override - public TableField getTableId() { - return REQUIREMENT.ID; - } - - @Override - public Class getRecordClass() { - return RequirementRecord.class; - } - - @Override - public Map getUpdateMap(final Requirement entry) { - HashMap updateMap = new HashMap() {{ - if (entry.getDescription() != null) { - put(REQUIREMENT.DESCRIPTION, entry.getDescription()); - } - if (entry.getName() != null) { - put(REQUIREMENT.NAME, entry.getName()); - } - }}; - if (!updateMap.isEmpty()) { - updateMap.put(REQUIREMENT.LAST_UPDATED_DATE, new java.sql.Timestamp(Calendar.getInstance().getTime().getTime())); - } - return updateMap; - } - - @Override - public Collection> getSortFields(List sorts) { - if (sorts.isEmpty()) { - return Collections.singletonList(RequirementRepositoryImpl.LAST_ACTIVITY.field("last_activity").desc()); - } - List> sortFields = new ArrayList<>(); - for (Pageable.SortField sort : sorts) { - switch (sort.getField()) { - case "last_activity": - switch (sort.getSortDirection()) { - case ASC: - sortFields.add(RequirementRepositoryImpl.LAST_ACTIVITY.field("last_activity").asc()); - break; - case DESC: - sortFields.add(RequirementRepositoryImpl.LAST_ACTIVITY.field("last_activity").desc()); - break; - default: - sortFields.add(RequirementRepositoryImpl.LAST_ACTIVITY.field("last_activity").desc()); - break; - } - break; - case "date": - switch (sort.getSortDirection()) { - case ASC: - sortFields.add(REQUIREMENT.CREATION_DATE.asc()); - break; - case DESC: - sortFields.add(REQUIREMENT.CREATION_DATE.desc()); - break; - default: - sortFields.add(REQUIREMENT.CREATION_DATE.desc()); - break; - } - break; - case "name": - switch (sort.getSortDirection()) { - case ASC: - sortFields.add(REQUIREMENT.NAME.asc()); - break; - case DESC: - sortFields.add(REQUIREMENT.NAME.desc()); - break; - default: - sortFields.add(REQUIREMENT.NAME.asc()); - break; - } - break; - case "vote": - switch (sort.getSortDirection()) { - case ASC: - sortFields.add(RequirementRepositoryImpl.VOTE_COUNT.asc()); - break; - case DESC: - sortFields.add(RequirementRepositoryImpl.VOTE_COUNT.desc()); - break; - default: - sortFields.add(RequirementRepositoryImpl.VOTE_COUNT.desc()); - break; - } - break; - case "comment": - switch (sort.getSortDirection()) { - case ASC: - sortFields.add(RequirementRepositoryImpl.COMMENT_COUNT.asc()); - break; - case DESC: - sortFields.add(RequirementRepositoryImpl.COMMENT_COUNT.desc()); - break; - default: - sortFields.add(RequirementRepositoryImpl.COMMENT_COUNT.desc()); - break; - } - break; - case "follower": - switch (sort.getSortDirection()) { - case ASC: - sortFields.add(RequirementRepositoryImpl.FOLLOWER_COUNT.asc()); - break; - case DESC: - sortFields.add(RequirementRepositoryImpl.FOLLOWER_COUNT.desc()); - break; - default: - sortFields.add(RequirementRepositoryImpl.FOLLOWER_COUNT.desc()); - break; - } - break; - case "realized": - switch (sort.getSortDirection()) { - case ASC: - sortFields.add(REQUIREMENT.REALIZED.asc()); - break; - case DESC: - sortFields.add(REQUIREMENT.REALIZED.desc()); - break; - default: - sortFields.add(REQUIREMENT.REALIZED.desc()); - break; - } - break; - } - } - return sortFields; - } - - @Override - public Condition getSearchCondition(String search) throws Exception { - return REQUIREMENT.NAME.likeIgnoreCase("%" + search + "%") - .or(REQUIREMENT.DESCRIPTION.likeIgnoreCase("%" + search + "%")); - } - - @Override - public Collection getFilterConditions(Map filters) throws Exception { - List conditions = new ArrayList<>(); - for (Map.Entry filterEntry : filters.entrySet()) { - if (filterEntry.getKey().equals("realized")) { - if (filterEntry.getValue().equals("realized")) { - conditions.add(REQUIREMENT.REALIZED.isNotNull()); - } - if (filterEntry.getValue().equals("open")) { - conditions.add(REQUIREMENT.REALIZED.isNull()); - } - } - } - return conditions; - } - - private Requirement cleanEntity(Requirement requirement) { - if (requirement.getName() != null) { - requirement.setName(EmojiParser.parseToAliases(requirement.getName())); - } - if (requirement.getDescription() != null) { - requirement.setDescription(EmojiParser.parseToAliases(requirement.getDescription())); - } - return requirement; - } -} diff --git a/src/test/de/rwth/dbis/acis/bazaar/service/BazaarRequestParams.java b/src/test/de/rwth/dbis/acis/bazaar/service/BazaarRequestParams.java deleted file mode 100644 index 528a0170..00000000 --- a/src/test/de/rwth/dbis/acis/bazaar/service/BazaarRequestParams.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * - * Copyright (c) 2015, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Adam Gavronek - * @since 2/22/2015 - */ -public class BazaarRequestParams { - private Map queryParams; - private String contentParam; - - public Map getQueryParams() { - if (queryParams == null) - queryParams = new HashMap<>(); - return queryParams; - } - - public void setQueryParams(Map queryParams) { - this.queryParams = queryParams; - } - - public String getContentParam() { - if (contentParam == null) - return ""; - return contentParam; - } - - public void setContentParam(String contentParam) { - this.contentParam = contentParam; - } -} diff --git a/src/test/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeMockImpl.java b/src/test/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeMockImpl.java deleted file mode 100644 index 2a7ef4b1..00000000 --- a/src/test/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeMockImpl.java +++ /dev/null @@ -1,574 +0,0 @@ -///* -// * -// * Copyright (c) 2014, RWTH Aachen University. -// * For a list of contributors see the AUTHORS file at the top-level directory -// * of this distribution. -// * -// * 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 -// * -// * http://www.apache.org/licenses/LICENSE-2.0 -// * -// * Unless required by applicable law or agreed to in writing, software -// * distributed under the License is distributed on an "AS IS" BASIS, -// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// * See the License for the specific language governing permissions and -// * limitations under the License. -// * / -// */ -// -//package de.rwth.dbis.acis.bazaar.service.dal; -// -//import de.rwth.dbis.acis.bazaar.service.dal.entities.*; -//import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; -//import de.rwth.dbis.acis.bazaar.service.dal.helpers.Pageable; -//import de.rwth.dbis.acis.bazaar.service.exception.BazaarException; -// -//import java.sql.Connection; -//import java.util.ArrayList; -//import java.util.Iterator; -//import java.util.List; -//import java.util.Random; -// -///** -// * @author Adam Gavronek -// * @since 6/14/2014 -// */ -//public class DALFacadeMockImpl implements DALFacade { -// -// //region Fields -// -// List userList = new ArrayList(); -// List projectList = new ArrayList(); -// List componentList = new ArrayList(); -// List requirementList = new ArrayList(); -// List commentList = new ArrayList(); -// List attachmentList = new ArrayList(); -// List voteList = new ArrayList(); -// List tagList = new ArrayList(); -// List developerList = new ArrayList(); -// List followerList = new ArrayList(); -// -// //endregion -// -// //region Private helper methods -// -// private int calcPaginationFrom(Pageable pageable){ -// -// return Math.max(0,pageable.getOffset() + pageable.getPageNumber()* pageable.getPageSize()); -// -// } -// private int calcPaginationTo(Pageable pageable, int listSize){ -// return Math.min(listSize,(pageable.getPageNumber()+1)*pageable.getPageSize()); -// } -// -// private List getCategories(int requirementId) { -// List components = new ArrayList(); -// -// for (RequirementCategory tag : tagList) { -// if (tag.getRequirementId() == requirementId) { -// for (Category component : componentList) { -// if (component.getId() == tag.getComponentId()) -// components.add(component); -// } -// -// } -// } -// return components; -// } -// -// private List getContributors(List attachments) { -// List users = new ArrayList(); -// List userIdList = new ArrayList(); -// -// for (Attachment attachment : attachments) { -// userIdList.add(attachment.getCreatorId()); -// } -// -// for (User user : userList) { -// if (userIdList.contains(user.getId())) -// users.add(user); -// } -// -// return users; -// } -// -// private List getFollowers(int requirementId) { -// List users = new ArrayList(); -// -// for (RequirementFollower follower : followerList) { -// if (follower.getRequirementId() == requirementId) { -// for (User user : userList) { -// if (user.getId() == follower.getUserId()) -// users.add(user); -// } -// -// } -// } -// return users; -// -// } -// -// private List getDevelopers(int requirementId) { -// List users = new ArrayList(); -// -// for (RequirementDeveloper developer : developerList) { -// if (developer.getRequirementId() == requirementId) { -// for (User user : userList) { -// if (user.getId() == developer.getUserId()) -// users.add(user); -// } -// -// } -// } -// return users; -// -// } -// -// private List getAttachments(int requirementId) { -// List attachments = new ArrayList(); -// -// for (Attachment attachment : attachmentList) { -// if (attachment.getRequirementId() == requirementId) -// attachments.add(attachment); -// } -// -// return attachments; -// } -// //endregion -// -// @Override -// public Connection getConnection() { -// return null; -// } -// -// @Override -// public int createUser(User user) { -// userList.add(user); -// return 0; -// } -// -// @Override -// public void modifyUser(User modifiedUser) { -// -// } -// -// @Override -// public User getUserById(int userId) { -//// return User.geBuilder("test@test.de") -//// .admin(false) -//// .firstName("Elek") -//// .lastName("Test") -//// .id(userId) -//// .userId(2222) -//// .build(); -// -// for (User user : userList) { -// if (user.getId() == userId) -// return user; -// } -// return null; -// } -// -// @Override -// public Integer getUserIdByLAS2PeerId(long las2PeerId) throws Exception { -// return null; -// } -// -// @Override -// public List listPublicProjects(Pageable pageable) { -// return projectList.subList(calcPaginationFrom(pageable),calcPaginationTo(pageable,projectList.size())); -//// return Arrays.asList( -//// Project.getBuilder("Proj1").description("Test project 1").id(1).visibility(Project.ProjectVisibility.PRIVATE).leaderId(1).build(), -//// Project.getBuilder("Proj2").description("Test project 2 + SEARCHSTR").visibility(Project.ProjectVisibility.PRIVATE).leaderId(1).id(2).build(), -//// Project.getBuilder("Proj3").description("Test project 3 + SEARCHSTR").visibility(Project.ProjectVisibility.PRIVATE).leaderId(1).id(2).build() -//// ); -// } -// -// @Override -// public List listPublicAndAuthorizedProjects(PageInfo pageable, long userId) throws BazaarException { -// return null; -// } -// -// @Override -// public List searchProjects(String searchTerm, Pageable pageable) { -// List toReturn = new ArrayList(); -// for (Project project : projectList) { -// if (project.getDescription().toUpperCase().contains(searchTerm.toUpperCase())) -// toReturn.add(project); -// } -// return toReturn.subList(calcPaginationFrom(pageable),calcPaginationTo(pageable,toReturn.size())); -// } -// -// @Override -// public Project getProjectById(int projectId) { -// -// for (Project project : projectList) { -// if (project.getId() == projectId) -// return project; -// } -// return null; -//// return Project.getBuilder("ProjById").description("Test project").id(projectId).visibility(Project.ProjectVisibility.PRIVATE).leaderId(1).build(); -// } -// -// @Override -// public int createProject(Project project) { -// projectList.add(project); -// return 0; -// } -// -// @Override -// public void modifyProject(Project modifiedProject) { -// -// } -// -// @Override -// public boolean isProjectPublic(int projectId) throws Exception { -// return false; -// } -// -// @Override -// public List listRequirements(Pageable pageable) { -// return requirementList.subList(calcPaginationFrom(pageable),calcPaginationTo(pageable,requirementList.size())); -// -//// return Arrays.asList( -//// Requirement.getBuilder("Req1").id(1).description("Requirement details 1").projectId(1).leadDeveloperId(1).creatorId(2).build(), -//// Requirement.getBuilder("Req2").id(2).description("Requirement details 2").projectId(1).leadDeveloperId(1).creatorId(2).build(), -//// Requirement.getBuilder("Req3").id(3).description("Requirement details 3").projectId(2).leadDeveloperId(1).creatorId(2).build() -//// ); -// } -// -// @Override -// public List listRequirementsByProject(int projectId, Pageable pageable) { -// List toReturn = new ArrayList(); -// for (Requirement req : requirementList) { -// if (req.getProjectId() == projectId) -// toReturn.add(req); -// } -// return toReturn.subList(calcPaginationFrom(pageable),calcPaginationTo(pageable,toReturn.size())); -// -//// return Arrays.asList( -//// Requirement.getBuilder("Req1").id(1).description("Requirement details 1").projectId(projectId).build(), -//// Requirement.getBuilder("Req2").id(2).description("Requirement details 2").projectId(projectId).build() -//// ); -// } -// -// @Override -// public List listRequirementsByComponent(int componentId, Pageable pageable) { -// List requirementIdList = new ArrayList(); -// for (RequirementCategory tag : tagList) { -// if (tag.getComponentId() == componentId) -// requirementIdList.add(tag.getRequirementId()); -// } -// -// List toReturn = new ArrayList(); -// for (Requirement req : requirementList) { -// if (requirementIdList.contains(req.getId())) -// toReturn.add(req); -// } -// return toReturn.subList(calcPaginationFrom(pageable),calcPaginationTo(pageable,toReturn.size())); -// } -// -// @Override -// public List searchRequirements(String searchTerm, Pageable pageable) { -// List toReturn = new ArrayList(); -// for (Requirement req : requirementList) { -// if (req.getDescription().toUpperCase().contains(searchTerm.toUpperCase())) -// toReturn.add(req); -// } -// return toReturn.subList(calcPaginationFrom(pageable),calcPaginationTo(pageable,toReturn.size())); -// } -// -// @Override -// public RequirementEx getRequirementById(int requirementId) { -// Requirement requirement = null; -// -// for (Requirement req : requirementList) { -// if (req.getId() == requirementId) -// requirement = req; -// } -// -// if (requirement != null) { -// List attachments = getAttachments(requirementId); -// List developers = getDevelopers(requirementId); -// List followers = getFollowers(requirementId); -// List contributors = getContributors(attachments); -// List components = getCategories(requirementId); -// -// return RequirementEx.getBuilder(requirement.getName()) -// .id(requirement.getId()) -// .description(requirement.getDescription()) -// .projectId(requirement.getProjectId()) -// .leadDeveloperId(requirement.getLeadDeveloperId()) -// .creatorId(requirement.getCreatorId()) -// .creator(getUserById(requirement.getCreatorId())) -// .leadDeveloper(getUserById(requirement.getLeadDeveloperId())) -// .developers(developers) -// .followers(followers) -// .contributors(contributors) -// .attachments(attachments) -// .components(components) -// .build(); -// } -// -// return null; -// } -// -// -// @Override -// public int createRequirement(Requirement requirement, int componentId) { -// requirementList.add(requirement); -// return 0; -// } -// -// @Override -// public void modifyRequirement(Requirement modifiedRequirement) { -// -// } -// -// @Override -// public void deleteRequirementById(int requirementId) { -// //Delete component tags -// Iterator tagIterator = tagList.iterator(); -// while (tagIterator.hasNext()) { -// RequirementCategory tag = tagIterator.next(); -// -// if (tag.getRequirementId() == requirementId) -// tagIterator.remove(); -// } -// -// //Delete followers -// Iterator followerIterator = followerList.iterator(); -// while (followerIterator.hasNext()) { -// RequirementFollower follower = followerIterator.next(); -// -// if (follower.getRequirementId() == requirementId) -// followerIterator.remove(); -// } -// -// //Delete developers -// Iterator developerIterator = developerList.iterator(); -// while (developerIterator.hasNext()) { -// RequirementDeveloper developer = developerIterator.next(); -// -// if (developer.getRequirementId() == requirementId) -// developerIterator.remove(); -// } -// //Delete attachments -// Iterator attachmentIterator = attachmentList.iterator(); -// while (attachmentIterator.hasNext()) { -// Attachment attachment = attachmentIterator.next(); -// -// if (attachment.getRequirementId() == requirementId) -// attachmentIterator.remove(); -// } -// -// //Delete comments -// Iterator commentIterator = commentList.iterator(); -// while (commentIterator.hasNext()) { -// Comment comment = commentIterator.next(); -// -// if (comment.getRequirementId() == requirementId) -// commentIterator.remove(); -// } -// -// //Delete votes -// Iterator voteIterator = voteList.iterator(); -// while (voteIterator.hasNext()) { -// Vote vote = voteIterator.next(); -// -// if (vote.getRequirementId() == requirementId) -// voteIterator.remove(); -// } -// -// //Delete requirement itself -// Iterator itr = requirementList.iterator(); -// while (itr.hasNext()) { -// Requirement requirement = itr.next(); -// -// if (requirement.getId() == requirementId) -// itr.remove(); -// } -// } -// -// @Override -// public List listComponentsByProjectId(int projectId, Pageable pageable) { -// Category.getBuilder("dd").projectId(2); -// List toReturn = new ArrayList(); -// for (Category component : componentList) { -// if (component.getProjectId() == projectId) -// toReturn.add(component); -// } -// return toReturn.subList(calcPaginationFrom(pageable),calcPaginationTo(pageable,toReturn.size())); -// } -// -// @Override -// public int createComponent(Category component) { -// componentList.add(component); -// return 0; -// } -// -// @Override -// public void modifyComponent(Category component) { -// -// } -// -// @Override -// public void deleteComponentById(int componentId) { -// Integer index = null; -// for (Category comp : componentList) { -// if (comp.getId() == componentId) -// index = componentList.indexOf(comp); -// } -// -// componentList.remove(index); -// } -// -// @Override -// public int createAttachment(Attachment attachment) { -// attachmentList.add(attachment); -// return 0; -// } -// -// @Override -// public void deleteAttachmentById(int attachmentId) { -// Integer index = null; -// for (Attachment attachment : attachmentList) { -// if (attachment.getId() == attachmentId) -// index = attachmentList.indexOf(attachment); -// } -// -// attachmentList.remove(index); -// } -// -// @Override -// public List listCommentsByRequirementId(int requirementId, Pageable pageable) { -// List toReturn = new ArrayList(); -// for (Comment comment : commentList) { -// if (comment.getRequirementId() == requirementId) -// toReturn.add(comment); -// } -// return toReturn.subList(calcPaginationFrom(pageable),calcPaginationTo(pageable,toReturn.size())); -// } -// -// @Override -// public int createComment(Comment comment) { -// commentList.add(comment); -// return 0; -// } -// -// @Override -// public void deleteCommentById(int commentId) { -// Iterator itr = commentList.iterator(); -// while (itr.hasNext()) { -// Comment comment = itr.next(); -// -// if (comment.getId() == commentId) -// itr.remove(); -// } -// } -// -// @Override -// public void follow(int userId, int requirementId) { -// RequirementFollower follower = RequirementFollower.getBuilder().id(new Random().nextInt()).userId(userId).requirementId(requirementId).build(); -// followerList.add(follower); -// } -// -// @Override -// public void unFollowRequirement(int userId, int requirementId) { -// Iterator itr = followerList.iterator(); -// while (itr.hasNext()) { -// RequirementFollower follower = itr.next(); -// -// if (follower.getUserId() == userId && follower.getRequirementId() == requirementId) -// itr.remove(); -// } -// } -// -// @Override -// public void wantToDevelop(int userId, int requirementId) { -// RequirementDeveloper developer = RequirementDeveloper.getBuilder().id(new Random().nextInt()).userId(userId).requirementId(requirementId).build(); -// -// developerList.add(developer); -// } -// -// @Override -// public void notWantToDevelop(int userId, int requirementId) { -// Iterator itr = developerList.iterator(); -// while (itr.hasNext()) { -// RequirementDeveloper developer = itr.next(); -// -// if (developer.getUserId() == userId && developer.getRequirementId() == requirementId) -// itr.remove(); -// } -// } -// -// -// -// @Override -// public void addComponentTag(int requirementId, int componentId) { -// RequirementCategory tag = RequirementCategory.getBuilder(componentId).requirementId(requirementId).id(new Random().nextInt()).build(); -// -// tagList.add(tag); -// } -// -// @Override -// public void deleteComponentTag(int requirementId, int componentId) { -// Iterator itr = tagList.iterator(); -// while (itr.hasNext()) { -// RequirementCategory tag = itr.next(); -// -// if (tag.getRequirementId() == requirementId && tag.getComponentId() == componentId) -// itr.remove(); -// } -// } -// -// @Override -// public void vote(int userId, int requirementId, boolean isUpVote) { -// Vote vote = Vote.getBuilder().id(new Random().nextInt()).requirementId(requirementId).userId(userId).isUpvote(isUpVote).build(); -// -// voteList.add(vote); -// } -// -// @Override -// public void unVote(int userId, int requirementId) { -// Iterator itr = voteList.iterator(); -// while (itr.hasNext()) { -// Vote vote = itr.next(); -// -// if (vote.getRequirementId() == requirementId && vote.getUserId() == userId) -// itr.remove(); -// } -// } -// -// @Override -// public boolean hasUserVotedForRequirement(int userId, int requirementId) { -// for (Vote vote : voteList) { -// if (vote.getRequirementId() == requirementId && vote.getUserId() == userId) -// return true; -// } -// return false; -// } -// -// @Override -// public List getRolesByUserId(int userId) throws BazaarException { -// return null; -// } -// -// @Override -// public List getParentsForRole(int roleId) throws BazaarException { -// return null; -// } -// -// @Override -// public void createPrivilegeIfNotExists(PrivilegeEnum privilege) throws BazaarException { -// -// } -// -// @Override -// public Category getComponentById(int componentId) throws Exception { -// // TODO Auto-generated method stub -// return null; -// } -//} diff --git a/src/test/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java b/src/test/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java deleted file mode 100644 index 0e82d60f..00000000 --- a/src/test/de/rwth/dbis/acis/bazaar/service/dal/DALFacadeTest.java +++ /dev/null @@ -1,607 +0,0 @@ -///* -// * -// * Copyright (c) 2014, RWTH Aachen University. -// * For a list of contributors see the AUTHORS file at the top-level directory -// * of this distribution. -// * -// * 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 -// * -// * http://www.apache.org/licenses/LICENSE-2.0 -// * -// * Unless required by applicable law or agreed to in writing, software -// * distributed under the License is distributed on an "AS IS" BASIS, -// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// * See the License for the specific language governing permissions and -// * limitations under the License. -// * / -// */ -// -//package de.rwth.dbis.acis.bazaar.service.dal; -// -//import de.rwth.dbis.acis.bazaar.service.dal.entities.*; -//import de.rwth.dbis.acis.bazaar.service.dal.helpers.PageInfo; -//import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.*; -//import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.*; -//import junit.framework.TestCase; -//import org.jooq.*; -//import org.jooq.impl.DefaultExecuteListener; -//import org.junit.BeforeClass; -// -//import java.net.URL; -//import java.sql.Connection; -//import java.sql.DriverManager; -//import java.sql.Timestamp; -//import java.util.List; -// -//import static de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Users.USERS; -//import static org.jooq.impl.DSL.count; -// -////TODO Pagination testing -//public class DALFacadeTest extends TestCase { -// -// public static final PageInfo ALL_IN_ONE_PAGE = new PageInfo(0, 100); -// -// DALFacade facade; -// private DALFacadeImpl dalImpl; -// DSLContext jooq; -// -// @BeforeClass -// public void setUp() throws Exception { -// Connection conn = null; -// -// String userName = "root"; -// String password = ""; -// URL db = DALFacadeTest.class.getResource("reqbaz.db"); -// String url = "jdbc:sqlite:" + db.getPath(); -// -// -// Class.forName("org.sqlite.JDBC").newInstance(); -// conn = DriverManager.getConnection(url, userName, password); -// -// -// -// dalImpl = new DALFacadeImpl(conn, SQLDialect.SQLITE); -// facade = dalImpl; -// jooq = dalImpl.getDslContext(); -// jooq.configuration().set(new ExecuteListenerProvider() { -// @Override -// public ExecuteListener provide() { -// return new DefaultExecuteListener() { -// @Override -// public void renderEnd(ExecuteContext ctx) { -// String sql = ctx.sql(); -// String replace = sql.replace("reqbaz.", "main."); -// ctx.sql(replace); -// } -// }; -// } -// }); -// -// jooq.execute("DELETE FROM main.Attachments"); -// jooq.execute("DELETE FROM main.Authorizations"); -// jooq.execute("DELETE FROM main.Comments"); -// jooq.execute("DELETE FROM main.Developers"); -// jooq.execute("DELETE FROM main.Followers"); -// jooq.execute("DELETE FROM main.Votes"); -// jooq.execute("DELETE FROM main.Tags"); -// jooq.execute("DELETE FROM main.Components"); -// jooq.execute("DELETE FROM main.Requirements"); -// jooq.execute("DELETE FROM main.Projects"); -// jooq.execute("DELETE FROM main.Users"); -// -// Field f = count(); -// -// User initUser = getInitUser(); -// if (jooq.selectCount().from(USERS).where(USERS.ID.equal(initUser.getId())).fetchOne(f) != 1) -// jooq.insertInto(USERS).set(new UsersRecord(initUser.getId(), initUser.getFirstName(), initUser.getLastName(), initUser.geteMail(), (byte) (initUser.getAdmin() ? 1 : 0), initUser.getLas2peerId(), initUser.getUserName())).execute(); -// -// if (jooq.selectCount().from(USERS).where(USERS.ID.equal(2)).fetchOne(f) != 1) -// jooq.insertInto(USERS).set(new UsersRecord(2, "Alma", "Barack", "test@test.hu", (byte) 1, 2222, "AlmBar")).execute(); -// -// if (jooq.selectCount().from(USERS).where(USERS.ID.equal(3)).fetchOne(f) != 1) -// jooq.insertInto(USERS).set(new UsersRecord(3, "Citrom", "Datolya", "test@test.hu", (byte) 0, 3333, "CitrDat")).execute(); -// -// if (jooq.selectCount().from(Projects.PROJECTS).where(Projects.PROJECTS.ID.equal(1)).fetchOne(f) != 1) -// jooq.insertInto(Projects.PROJECTS).set(new ProjectsRecord(1, "Project1", "ProjDesc1", "-", 1)).execute(); -// -// if (jooq.selectCount().from(Projects.PROJECTS).where(Projects.PROJECTS.ID.equal(2)).fetchOne(f) != 1) -// jooq.insertInto(Projects.PROJECTS).set(new ProjectsRecord(2, "Project2", "ProjDesc2", "+", 1)).execute(); -// -// if (jooq.selectCount().from(Requirements.REQUIREMENTS).where(Requirements.REQUIREMENTS.ID.equal(1)).fetchOne(f) != 1) -// jooq.insertInto(Requirements.REQUIREMENTS).set(new RequirementsRecord(1, "Req1", "ReqDesc1", Timestamp.valueOf("2005-04-06 09:01:10"), 1, 1, 1)).execute(); -// -// if (jooq.selectCount().from(Requirements.REQUIREMENTS).where(Requirements.REQUIREMENTS.ID.equal(2)).fetchOne(f) != 1) -// jooq.insertInto(Requirements.REQUIREMENTS).set(new RequirementsRecord(2, "Req2", "ReqDesc2", Timestamp.valueOf("2005-05-06 09:01:10"), 1, 1, 2)).execute(); -// -// if (jooq.selectCount().from(Requirements.REQUIREMENTS).where(Requirements.REQUIREMENTS.ID.equal(3)).fetchOne(f) != 1) -// jooq.insertInto(Requirements.REQUIREMENTS).set(new RequirementsRecord(3, "Req3", "ReqDesc3", Timestamp.valueOf("2005-06-06 09:01:10"), 1, 1, 1)).execute(); -// -// if (jooq.selectCount().from(Components.COMPONENTS).where(Components.COMPONENTS.ID.equal(1)).fetchOne(f) != 1) -// jooq.insertInto(Components.COMPONENTS).set(new ComponentsRecord(1, "Comp1", "CompDesc1", 2, 1)).execute(); -// -// if (jooq.selectCount().from(Tags.TAGS).where(Tags.TAGS.ID.equal(1)).fetchOne(f) != 1) -// jooq.insertInto(Tags.TAGS).set(new TagsRecord(1, 1, 2)).execute(); -// -// if (jooq.selectCount().from(Developers.DEVELOPERS).where(Developers.DEVELOPERS.ID.equal(1)).fetchOne(f) != 1) -// jooq.insertInto(Developers.DEVELOPERS).set(new DevelopersRecord(1, 2, 2)).execute(); -// -// if (jooq.selectCount().from(Developers.DEVELOPERS).where(Developers.DEVELOPERS.ID.equal(2)).fetchOne(f) != 1) -// jooq.insertInto(Developers.DEVELOPERS).set(new DevelopersRecord(2, 2, 3)).execute(); -// -// if (jooq.selectCount().from(Followers.FOLLOWERS).where(Followers.FOLLOWERS.ID.equal(1)).fetchOne(f) != 1) -// jooq.insertInto(Followers.FOLLOWERS).set(new FollowersRecord(1, 2, 2)).execute(); -// if (jooq.selectCount().from(Followers.FOLLOWERS).where(Followers.FOLLOWERS.ID.equal(2)).fetchOne(f) != 1) -// jooq.insertInto(Followers.FOLLOWERS).set(new FollowersRecord(2, 2, 3)).execute(); -// -// if (jooq.selectCount().from(Votes.VOTES).where(Votes.VOTES.ID.equal(1)).fetchOne(f) != 1) -// jooq.insertInto(Votes.VOTES).set(new VotesRecord(1, (byte) 1, 2, 1)).execute(); -// if (jooq.selectCount().from(Votes.VOTES).where(Votes.VOTES.ID.equal(2)).fetchOne(f) != 1) -// jooq.insertInto(Votes.VOTES).set(new VotesRecord(2, (byte) 0, 2, 3)).execute(); -// -// if (jooq.selectCount().from(Attachments.ATTACHMENTS).where(Attachments.ATTACHMENTS.ID.equal(1)).fetchOne(f) != 1) -// jooq.insertInto(Attachments.ATTACHMENTS).set(new AttachmentsRecord(1, Timestamp.valueOf("2005-04-06 09:01:10"), 2, 2, "StoryAttachment", "S", null, null, "RequirementStory", null, null, null)).execute(); -// -// -// if (jooq.selectCount().from(Comments.COMMENTS).where(Comments.COMMENTS.ID.equal(1)).fetchOne(f) != 1) -// jooq.insertInto(Comments.COMMENTS).set(new CommentsRecord(1, "Lorem ipsum dolor sit amet", Timestamp.valueOf("2005-04-06 09:01:10"), 2, 2)).execute(); -// if (jooq.selectCount().from(Comments.COMMENTS).where(Comments.COMMENTS.ID.equal(2)).fetchOne(f) != 1) -// jooq.insertInto(Comments.COMMENTS).set(new CommentsRecord(2, "Test message payload", Timestamp.valueOf("2005-04-06 10:01:10"), 2, 3)).execute(); -// -// -// } -// -// private User getInitUser() { -// return User.geBuilder("test@test.hu") -// .id(1) -// .firstName("Elek") -// .lastName("Test") -// .userName("TestElek") -// .admin(true) -// .las2peerId(1111) -// .build(); -// } -// -// public void testCreateUser() throws Exception { -// facade.createUser(User.geBuilder("unittest@test.hu").id(9).firstName("Max").lastName("Zimmermann").admin(false).las2peerId(9999).userName("MaxZim").build()); -// -// User user = facade.getUserById(9); -// -// assertEquals(9, user.getId()); -// assertEquals("unittest@test.hu", user.geteMail()); -// assertEquals("Max", user.getFirstName()); -// assertEquals("Zimmermann", user.getLastName()); -// assertEquals(false, user.isAdmin()); -// assertEquals(9999, user.getLas2peerId()); -// -// -// //Clean -// jooq.delete(USERS).where(USERS.ID.equal(9)).execute(); -// } -// -// public void testModifyUser() throws Exception { -// //TODO -// } -// -// public void testGetUserById() throws Exception { -// User user = facade.getUserById(1); -// -// assertEquals(1, user.getId()); -// assertEquals("test@test.hu", user.geteMail()); -// assertEquals("Elek", user.getFirstName()); -// assertEquals("Test", user.getLastName()); -// assertEquals(true, user.isAdmin()); -// assertEquals(1111, user.getLas2peerId()); -// } -// -// public void testListPublicProjects() throws Exception { -// List projects = facade.listPublicProjects(new PageInfo(0, 1)); -// -// assertNotNull(projects); -// assertEquals(1,projects.size()); -// -// for (Project project : projects) { -// assertEquals(Project.ProjectVisibility.PUBLIC,project.getVisibility()); -// } -// -// Project project = projects.get(0); -// -// assertEquals(2, project.getId()); -// assertEquals("Project2",project.getName()); -// assertEquals("ProjDesc2",project.getDescription()); -// assertEquals(1,project.getLeaderId()); -// assertEquals(Project.ProjectVisibility.PUBLIC, project.getVisibility()); -// } -// -// -// public void testSearchProjects() throws Exception { -// List projects = facade.searchProjects("2", ALL_IN_ONE_PAGE); -// -// assertNotNull(projects); -// assertEquals(1,projects.size()); -// -// Project project = projects.get(0); -// assertEquals(2, project.getId()); -// assertEquals("Project2",project.getName()); -// assertEquals("ProjDesc2",project.getDescription()); -// assertEquals(1,project.getLeaderId()); -// assertEquals(Project.ProjectVisibility.PUBLIC, project.getVisibility()); -// -// projects = facade.searchProjects("ProjD", new PageInfo(0, 100)); -// -// assertNotNull(projects); -// assertEquals(2,projects.size()); -// -// assertEquals(1, projects.get(0).getId()); -// assertEquals("Project1",projects.get(0).getName()); -// assertEquals("ProjDesc1",projects.get(0).getDescription()); -// assertEquals(1,projects.get(0).getLeaderId()); -// assertEquals(Project.ProjectVisibility.PRIVATE, projects.get(0).getVisibility()); -// -// assertEquals(2, projects.get(1).getId()); -// assertEquals("Project2",projects.get(1).getName()); -// assertEquals("ProjDesc2",projects.get(1).getDescription()); -// assertEquals(1,projects.get(1).getLeaderId()); -// assertEquals(Project.ProjectVisibility.PRIVATE, projects.get(1).getVisibility()); -// } -// -// public void testGetProjectById() throws Exception { -// Project project = facade.getProjectById(1); -// -// assertEquals(1, project.getId()); -// assertEquals("Project1",project.getName()); -// assertEquals("ProjDesc1",project.getDescription()); -// assertEquals(1,project.getLeaderId()); -// assertEquals(Project.ProjectVisibility.PRIVATE, project.getVisibility()); -// } -// -// public void testCreateProject() throws Exception { -// int createdProjId = 3; -// Project project = Project.getBuilder("Project3").description("ProjDesc3").leaderId(1).id(createdProjId).visibility(Project.ProjectVisibility.PUBLIC).build(); -// -// facade.createProject(project); -// -// Project projectById = facade.getProjectById(createdProjId); -// -// assertEquals(project.getId(), projectById.getId() ); -// assertEquals(project.getName(), projectById.getName() ); -// assertEquals(project.getDescription(),projectById.getDescription() ); -// assertEquals(project.getLeaderId(), projectById.getLeaderId() ); -// assertEquals(project.getVisibility(), projectById.getVisibility() ); -// -// //Clean -// jooq.delete(Projects.PROJECTS).where(Projects.PROJECTS.ID.equal(createdProjId)).execute(); -// } -// -// public void testModifyProject() throws Exception { -// //TODO -// } -// -// public void testListRequirements() throws Exception { -// List requirements = facade.listRequirements(ALL_IN_ONE_PAGE); -// -// assertNotNull(requirements); -// assertEquals(3, requirements.size()); -// -// Requirement requirement = requirements.get(2); -// -// assertEquals(1,requirement.getId()); -// assertEquals(1,requirement.getCreatorId()); -// assertEquals(1,requirement.getLeadDeveloperId()); -// assertEquals(1,requirement.getProjectId()); -// assertEquals("Req1",requirement.getName()); -// assertEquals("ReqDesc1",requirement.getDescription()); -// -// requirements = facade.listRequirements(new PageInfo(1, 2)); -// -// assertNotNull(requirements); -// assertEquals(1, requirements.size()); -// assertEquals(1,requirements.get(0).getId()); -// -// requirements = facade.listRequirements(new PageInfo(0, 1)); -// -// assertNotNull(requirements); -// assertEquals(1, requirements.size()); -// assertEquals(3,requirements.get(0).getId()); -// -// } -// -// public void testListRequirementsByProject() throws Exception { -// List requirements = facade.listRequirementsByProject(2, ALL_IN_ONE_PAGE); -// -// assertNotNull(requirements); -// assertEquals(1, requirements.size()); -// -// Requirement requirement2 = requirements.get(0); -// -// assertEquals(2,requirement2.getId()); -// assertEquals(1,requirement2.getCreatorId()); -// assertEquals(1,requirement2.getLeadDeveloperId()); -// assertEquals(2,requirement2.getProjectId()); -// assertEquals("Req2",requirement2.getName()); -// assertEquals("ReqDesc2",requirement2.getDescription()); -// -// -// } -// -// public void testListRequirementsByComponent() throws Exception { -// List requirements = facade.listRequirementsByComponent(1, ALL_IN_ONE_PAGE); -// -// assertNotNull(requirements); -// assertEquals(1, requirements.size()); -// -// Requirement requirement2 = requirements.get(0); -// -// assertEquals(2,requirement2.getId()); -// assertEquals(1,requirement2.getCreatorId()); -// assertEquals(1,requirement2.getLeadDeveloperId()); -// assertEquals(2,requirement2.getProjectId()); -// assertEquals("Req2",requirement2.getName()); -// assertEquals("ReqDesc2",requirement2.getDescription()); -// -// } -// -// public void testSearchRequirements() throws Exception { -// List requirements = facade.searchRequirements("desc2", ALL_IN_ONE_PAGE); -// -// assertNotNull(requirements); -// assertEquals(1, requirements.size()); -// -// Requirement requirement2 = requirements.get(0); -// -// assertEquals(2,requirement2.getId()); -// assertEquals(1,requirement2.getCreatorId()); -// assertEquals(1,requirement2.getLeadDeveloperId()); -// assertEquals(2,requirement2.getProjectId()); -// assertEquals("Req2",requirement2.getName()); -// assertEquals("ReqDesc2",requirement2.getDescription()); -// } -// -// public void testGetRequirementById() throws Exception { -// RequirementEx requirement = facade.getRequirementById(2); -// -// assertEquals(2, requirement.getId()); -// -// assertEquals(1, requirement.getCreatorId()); -// assertEquals(1,requirement.getCreator().getId()); -// assertEquals("Elek",requirement.getCreator().getFirstName()); -// -// assertEquals(1,requirement.getLeadDeveloperId()); -// assertEquals(1,requirement.getLeadDeveloper().getId()); -// assertEquals("Elek",requirement.getLeadDeveloper().getFirstName()); -// -// assertEquals(2,requirement.getProjectId()); -// assertEquals("Req2",requirement.getName()); -// assertEquals("ReqDesc2",requirement.getDescription()); -// -// List attachments = requirement.getAttachments(); -// assertNotNull(attachments); -// assertEquals(1, attachments.size()); -// assertEquals(2, attachments.get(0).getCreatorId()); -// -// List components = requirement.getCategories(); -// assertNotNull(components); -// assertEquals(1,components.size()); -// assertEquals(1, components.get(0).getId()); -// assertEquals("Comp1",components.get(0).getName()); -// -// List contributors = requirement.getContributors(); -// assertNotNull(contributors); -// assertEquals(1,contributors.size()); -// assertEquals(2,contributors.get(0).getId()); -// -// List developers = requirement.getDevelopers(); -// assertNotNull(developers); -// assertEquals(2,developers.size()); -// assertEquals(2,developers.get(0).getId()); -// assertEquals(3, developers.get(1).getId()); -// -// List followers = requirement.getFollowers(); -// assertNotNull(followers); -// assertEquals(2,followers.size()); -// assertEquals(2,followers.get(0).getId()); -// assertEquals(3,followers.get(1).getId()); -// -// } -// -// public void testCreateRequirement() throws Exception { -// int createdRequirementId = 9; -// try { -// Requirement requirement = Requirement.getBuilder("AddedReq1").id(createdRequirementId).description("Test addition").creatorId(2).leadDeveloperId(2).projectId(3).creationTime(Timestamp.valueOf("2005-04-06 09:01:10")).build(); -// -// facade.createRequirement(requirement, componentId); -// -// RequirementEx requirementById = facade.getRequirementById(createdRequirementId); -// -// assertEquals(requirement.getId(), requirementById.getId()); -// assertEquals(requirement.getName(), requirementById.getName()); -// assertEquals(requirement.getDescription(), requirementById.getDescription()); -// assertEquals(requirement.getCreatorId(), requirementById.getCreatorId()); -// assertEquals(requirement.getLeadDeveloperId(), requirementById.getLeadDeveloperId()); -// assertEquals(requirement.getProjectId(), requirementById.getProjectId()); -// } -// finally { -// jooq.delete(Requirements.REQUIREMENTS).where(Requirements.REQUIREMENTS.ID.equal(createdRequirementId)).execute(); -// } -// -// } -// -// public void testModifyRequirement() throws Exception { -// //TODO -// } -// -// public void testDeleteRequirementById() throws Exception { -// Requirement requirement = Requirement.getBuilder("AddedReq1").id(9).description("Test addition").creatorId(2).leadDeveloperId(2).projectId(3).build(); -// -// facade.createRequirement(requirement, componentId); -// -// facade.deleteRequirementById(9); -// -// try { -// RequirementEx requirementById = facade.getRequirementById(9); -// } -// catch (Exception ex){ -// assertEquals("No class de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.RequirementsRecord found with id: 9", ex.getMessage()); -// } -// } -// -// public void testListComponentsByProjectId() throws Exception { -// List components = facade.listComponentsByProjectId(2, ALL_IN_ONE_PAGE); -// -// assertNotNull(components); -// assertEquals(1,components.size()); -// assertEquals(1,components.get(0).getId()); -// } -// -// public void testCreateComponent() throws Exception { -// int createdComponentId = 9; -// Category testComp9 = Category.getBuilder("TestComp9").description("Very testing").id(createdComponentId).projectId(1).leaderId(1).build(); -// -// facade.createComponent(testComp9); -// -// List components = facade.listComponentsByProjectId(1, ALL_IN_ONE_PAGE); -// -// assertNotNull(components); -// assertEquals(1,components.size()); -// assertEquals(createdComponentId,components.get(0).getId()); -// -// //Clean -// jooq.delete(Components.COMPONENTS).where(Components.COMPONENTS.ID.equal(createdComponentId)).execute(); -// -// } -// -// public void testModifyComponent() throws Exception { -// //TODO -// } -// -// public void testDeleteComponentById() throws Exception { -// //TODO -// } -// -// public void testListCommentsByRequirementId() throws Exception { -// List comments = facade.listCommentsByRequirementId(2, ALL_IN_ONE_PAGE); -// -// assertNotNull(comments); -// assertEquals(2,comments.size()); -// assertTrue(comments.get(0).getId() == 1 || comments.get(0).getId() == 2); -// assertTrue(comments.get(1).getId() == 1 || comments.get(1).getId() == 2); -// } -// -// public void testCreateComment() throws Exception { -// int createdCommentId = 9; -// Comment testComment = Comment.getBuilder("TestComment").id(createdCommentId).creatorId(1).requirementId(1).build(); -// -// facade.createComment(testComment); -// -// List comments = facade.listCommentsByRequirementId(1, ALL_IN_ONE_PAGE); -// -// assertNotNull(comments); -// assertEquals(1,comments.size()); -// assertEquals(createdCommentId,comments.get(0).getId()); -// -// //CLEAN -// jooq.delete(Comments.COMMENTS).where(Comments.COMMENTS.ID.equal(createdCommentId)).execute(); -// } -// -// public void testDeleteCommentById() throws Exception { -// Comment testComment = Comment.getBuilder("TestComment").id(9).creatorId(1).requirementId(1).build(); -// -// facade.createComment(testComment); -// -// facade.deleteCommentById(9); -// -// List comments = facade.listCommentsByRequirementId(1, ALL_IN_ONE_PAGE); -// assertNotNull(comments); -// assertEquals(0, comments.size()); -// } -// -// public void testFollowUnFollow() throws Exception { -// facade.follow(2, 1); -// -// RequirementEx requirementById = facade.getRequirementById(1); -// List followers = requirementById.getFollowers(); -// -// assertNotNull(followers); -// assertEquals(1, followers.size()); -// assertEquals(2, followers.get(0).getId()); -// -// facade.unFollowRequirement(2, 1); -// -// requirementById = facade.getRequirementById(1); -// followers = requirementById.getFollowers(); -// -// assertEquals(0, followers.size()); -// } -// -// -// public void testWantToDevelopNotWant() throws Exception { -// facade.wantToDevelop(2, 1); -// -// RequirementEx requirementById = facade.getRequirementById(1); -// List developers = requirementById.getDevelopers(); -// -// assertNotNull(developers); -// assertEquals(1, developers.size()); -// assertEquals(2, developers.get(0).getId()); -// -// facade.notWantToDevelop(2, 1); -// -// requirementById = facade.getRequirementById(1); -// developers = requirementById.getDevelopers(); -// -// assertEquals(0, developers.size()); -// } -// -// -// public void testGiveAuthorizationAndRemove() throws Exception { -// -// boolean isAuthorized = facade.isAuthorized(2, 1); -// -// assertEquals(false, isAuthorized); -// -// facade.giveAuthorization(2,1); -// isAuthorized = facade.isAuthorized(2,1); -// -// assertEquals(true, isAuthorized); -// -// facade.removeAuthorization(2, 1); -// isAuthorized = facade.isAuthorized(2,1); -// -// assertEquals(false, isAuthorized); -// } -// -// -// public void testAddComponentTagAndRemove() throws Exception { -// facade.addComponentTag(1,1); -// -// List components = facade.getRequirementById(1).getCategories(); -// assertNotNull(components); -// assertEquals(1,components.size()); -// assertEquals(1, components.get(0).getId()); -// -// facade.deleteComponentTag(1,1); -// -// components = facade.getRequirementById(1).getCategories(); -// assertEquals(0,components.size()); -// } -// -// -// -// public void testVoteandUnvote() throws Exception { -// boolean hasUserVotedForRequirement = facade.hasUserVotedForRequirement(3, 1); -// -// assertEquals(false, hasUserVotedForRequirement); -// -// facade.vote(3,1,true); -// hasUserVotedForRequirement = facade.hasUserVotedForRequirement(3, 1); -// -// assertEquals(true, hasUserVotedForRequirement); -// -// facade.unVote(3,1); -// hasUserVotedForRequirement = facade.hasUserVotedForRequirement(3, 1); -// -// assertEquals(false, hasUserVotedForRequirement); -// } -// -//} \ No newline at end of file diff --git a/src/test/de/rwth/dbis/acis/bazaar/service/dal/RepositoryTest.java b/src/test/de/rwth/dbis/acis/bazaar/service/dal/RepositoryTest.java deleted file mode 100644 index c92d275c..00000000 --- a/src/test/de/rwth/dbis/acis/bazaar/service/dal/RepositoryTest.java +++ /dev/null @@ -1,184 +0,0 @@ -///* -// * -// * Copyright (c) 2014, RWTH Aachen University. -// * For a list of contributors see the AUTHORS file at the top-level directory -// * of this distribution. -// * -// * 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 -// * -// * http://www.apache.org/licenses/LICENSE-2.0 -// * -// * Unless required by applicable law or agreed to in writing, software -// * distributed under the License is distributed on an "AS IS" BASIS, -// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// * See the License for the specific language governing permissions and -// * limitations under the License. -// * / -// */ -// -//package de.rwth.dbis.acis.bazaar.service.dal; -// -//import de.rwth.dbis.acis.bazaar.service.dal.entities.Project; -//import de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.records.ProjectsRecord; -//import de.rwth.dbis.acis.bazaar.service.dal.repositories.ProjectRepository; -//import de.rwth.dbis.acis.bazaar.service.dal.repositories.ProjectRepositoryImpl; -//import static de.rwth.dbis.acis.bazaar.service.dal.jooq.tables.Projects.PROJECTS; -//import static org.junit.Assert.*; -// -//import org.jooq.DSLContext; -//import org.jooq.Result; -//import org.jooq.SQLDialect; -//import org.jooq.impl.DSL; -//import org.jooq.tools.jdbc.MockConnection; -//import org.jooq.tools.jdbc.MockDataProvider; -//import org.jooq.tools.jdbc.MockExecuteContext; -//import org.jooq.tools.jdbc.MockResult; -//import org.junit.BeforeClass; -//import org.junit.Test; -// -//import java.sql.Connection; -//import java.sql.SQLException; -//import java.util.ArrayList; -//import java.util.List; -// -///** -//* @author Adam Gavronek -//* @since 6/9/2014 -//*/ -//public class RepositoryTest { -// -// -// private static ProjectRepository repo; -// -// -// public static final int PROJECT_ID = 1; -// public static final String PROJECT_DESC = "blabla"; -// public static final String PROJECT_NAME = "projRec1"; -// -// private static final Integer PROJECT_ID2 = 2; -// private static final String PROJECT_DESC2 = "Lorem ipsum"; -// private static final String PROJECT_NAME2 = "testProject2"; -// private static MockedProjectDataProvider mockedProjectDataProvider; -// -// @BeforeClass -// public static void setUp(){ -// mockedProjectDataProvider = new MockedProjectDataProvider(); -// Connection connection = new MockConnection(mockedProjectDataProvider); -// DSLContext context = DSL.using(connection, SQLDialect.MYSQL); -// repo = new ProjectRepositoryImpl(context); -// } -// -// @Test -// public void testFindById() throws Exception { -// -// Project project = repo.findById(PROJECT_ID); -// -// assertEquals((long)PROJECT_ID,(long)project.getId()); -// assertEquals(PROJECT_DESC,project.getDescription()); -// assertEquals(PROJECT_NAME,project.getName()); -// } -// -// @Test -// public void testFindAll() throws Exception { -// List projects = repo.findAll(); -// -// assertNotNull(projects); -// assertEquals(2,projects.size()); -// Project project1 = projects.get(0); -// -// assertEquals((long)PROJECT_ID,(long)project1.getId()); -// assertEquals(PROJECT_DESC,project1.getDescription()); -// assertEquals(PROJECT_NAME,project1.getName()); -// -// Project project2 = projects.get(1); -// -// assertEquals((long)PROJECT_ID2,(long)project2.getId()); -// assertEquals(PROJECT_DESC2,project2.getDescription()); -// assertEquals(PROJECT_NAME2,project2.getName()); -// } -// -//// @Test -//// public void testDeleteAddFirst() throws Exception { -//// repo.delete(PROJECT_ID); -//// assertEquals((long)PROJECT_ID,(long)mockedProjectDataProvider.getDeletedIds().get(0)); -//// -//// -//// -//// Project project = repo.findById(PROJECT_ID); -//// assertNull(project); -//// -//// mockedProjectDataProvider.getDeletedIds().clear(); -//// } -// -// -// public static class MockedProjectDataProvider implements MockDataProvider { -// private List records; -// -// public List getDeletedIds() { -// return deletedIds; -// } -// -// private List deletedIds = new ArrayList(); -// private final DSLContext create; -// -// public MockedProjectDataProvider(){ -// create = DSL.using(SQLDialect.MYSQL); -// -// ProjectsRecord record1 = create.newRecord(PROJECTS); -// record1.setValue(PROJECTS.ID, PROJECT_ID); -// record1.setValue(PROJECTS.DESCRIPTION, PROJECT_DESC); -// record1.setValue(PROJECTS.NAME, PROJECT_NAME); -// -// ProjectsRecord record2 = create.newRecord(PROJECTS); -// record2.setValue(PROJECTS.ID, PROJECT_ID2); -// record2.setValue(PROJECTS.DESCRIPTION, PROJECT_DESC2); -// record2.setValue(PROJECTS.NAME, PROJECT_NAME2); -// -// records = new ArrayList(); -// records.add(record1); -// records.add(record2); -// } -// -// @Override -// public MockResult[] execute(MockExecuteContext ctx) throws SQLException { -// -// MockResult[] mock = new MockResult[1]; -// -// String sql = ctx.sql(); -// -// -// // DROP IS NOT SUPPORTED -// if (sql.toUpperCase().startsWith("DROP")) { -// throw new SQLException("Statement not supported: " + sql); -// } -// else if (sql.toUpperCase().startsWith("DELETE")){ -// Integer id = (Integer) ctx.bindings()[0]; -// deletedIds.add(id); -// -// } -// else if (sql.toUpperCase().startsWith("INSERT")){ -// -// } -// // IF SELECT + WHERE, so FindById and we return 1 record -// else if (sql.toUpperCase().startsWith("SELECT") && sql.toUpperCase().contains("WHERE")) -// { -// Result result = create.newResult(PROJECTS); -// Integer id = (Integer) ctx.bindings()[0]; -// if(!deletedIds.contains(id)) -// result.add(records.get(id-1)); -// mock[0] = new MockResult(1, result); -// } -// // IF SELECT ONLY: FindAll so we return more records -// else if (sql.toUpperCase().startsWith("SELECT")) { -// Result result = create.newResult(PROJECTS); -// result.add(records.get(0)); -// result.add(records.get(1)); -// mock[0] = new MockResult(1,result); -// } -// return mock; -// } -// } -//} -// diff --git a/src/test/de/rwth/dbis/acis/bazaar/service/dal/reqbaz.db b/src/test/de/rwth/dbis/acis/bazaar/service/dal/reqbaz.db deleted file mode 100644 index ba12a52a..00000000 Binary files a/src/test/de/rwth/dbis/acis/bazaar/service/dal/reqbaz.db and /dev/null differ diff --git a/src/test/de/rwth/dbis/acis/bazaar/service/security/AnonymUserRightsTest.java b/src/test/de/rwth/dbis/acis/bazaar/service/security/AnonymUserRightsTest.java deleted file mode 100644 index 7c35099e..00000000 --- a/src/test/de/rwth/dbis/acis/bazaar/service/security/AnonymUserRightsTest.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * - * Copyright (c) 2015, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.security; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import de.rwth.dbis.acis.bazaar.service.BazaarRequestParams; -import de.rwth.dbis.acis.bazaar.service.TestBase; -import de.rwth.dbis.acis.bazaar.service.dal.entities.*; -import i5.las2peer.testing.MockAgentFactory; -import i5.las2peer.webConnector.client.ClientResponse; -import i5.las2peer.webConnector.client.MiniClient; - -import org.junit.*; - - -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.List; - -/** - * @author Adam Gavronek - * @since 2/22/2015 - */ -public class AnonymUserRightsTest extends TestBase { - - @BeforeClass - public static void startServer() throws Exception { - //testPass = "evespass"; - testAgent = MockAgentFactory.getAnonymous(); - TestBase.startServer(); - } - - @Override - protected void login(MiniClient c) throws UnsupportedEncodingException { - //super.login(c); - } - - - - @Test - public void test_getProjects() { - ClientResponse response = super.test_getProjects(new BazaarRequestParams()); - assertThat(response, is(notNullValue())); - List projectList = new Gson().fromJson(response.getResponse(), new TypeToken>() { - }.getType()); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(1)))); - assertThat(projectList, not(hasItem(Matchers.hasProperty("id", equalTo(2))))); - } - - @Test - public void test_getPublicProject() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getProject(params); - assertThat(response,is(notNullValue())); - Project project = new Gson().fromJson(response.getResponse(), Project.class); - assertThat(project.getId(), is(1)); - assertThat(project.getName(), is("PublicTestProject")); - } - - @Test - public void test_getPrivateProject(){ - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getProject(params); - assertAccessDenied(response); - } - - @Test - public void test_createComponents( ){ - BazaarRequestParams params = new BazaarRequestParams(); - Category category = Category.getBuilder("TestCreateComponent").id(901).description("hello").projectId(1).build(); - params.setContentParam(new Gson().toJson(category)); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - }}); - ClientResponse response = super.test_createComponent(params); - assertAccessDenied(response); - } - - @Test - public void test_getPublicProjectComponents(){ - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getComponents(params); - assertThat(response, is(notNullValue())); - List projectList = new Gson().fromJson(response.getResponse(), new TypeToken>() {}.getType()); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(1)))); - assertThat(projectList, not(hasItem(Matchers.hasProperty("id", equalTo(2))))); - } - - @Test - public void test_getPrivateProjectComponents() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getComponents(params); - assertAccessDenied(response); - } - - @Test - public void test_deleteComponent() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - put("componentId", String.valueOf(2)); - }}); - ClientResponse response = super.test_deleteComponent(params); - assertAccessDenied(response); - } - - @Test - public void test_createRequirementPublicProject( ){ - BazaarRequestParams params = new BazaarRequestParams(); - Requirement requirement = Requirement.getBuilder("TestCreateReq").id(901).description("hello").projectId(1).build(); - params.setContentParam(new Gson().toJson(requirement)); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - }}); - ClientResponse response = super.test_createRequirement(params); - assertAccessDenied(response); - } - - @Test - public void test_getPublicRequirements() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getRequirementsByProject(params); - assertThat(response, is(notNullValue())); - List projectList = new Gson().fromJson(response.getResponse(), new TypeToken>() {}.getType()); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(1)))); - } - - @Test - public void test_getPrivateRequirements() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getRequirementsByProject(params); - assertAccessDenied(response); - } - - @Test - public void test_getPublicRequirementsByComponent() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getRequirementsByComponent(params); - assertThat(response, is(notNullValue())); - List projectList = new Gson().fromJson(response.getResponse(), new TypeToken>() {}.getType()); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(1)))); - } - - @Test - public void test_getPrivateRequirementsByComponent() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - put("componentId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getRequirementsByComponent(params); - assertAccessDenied(response); - } - - @Test - public void test_getPublicRequirement() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - put("requirementId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getRequirement(params); - assertThat(response,is(notNullValue())); - RequirementEx requirementEx = new Gson().fromJson(response.getResponse(), RequirementEx.class); - assertThat(requirementEx.getId(), is(1)); - assertThat(requirementEx.getName(), is("PublicRequirement")); - } - - @Test - public void test_getPrivateRequirement() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - put("componentId", String.valueOf(2)); - put("requirementId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getRequirement(params); - assertAccessDenied(response); - } - - @Test - public void test_deleteRequirement() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - put("requirementId", String.valueOf(1)); - }}); - ClientResponse response = super.test_deleteRequirement(params); - assertAccessDenied(response); - } - - @Test - public void test_createComment( ){ - BazaarRequestParams params = new BazaarRequestParams(); - Comment comment = Comment.getBuilder("TestCommentText").id(901).requirementId(1).build(); - params.setContentParam(new Gson().toJson(comment)); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - put("requirementId", String.valueOf(1)); - }}); - ClientResponse response = super.test_createComment(params); - assertAccessDenied(response); - } - - @Test - public void test_getPublicComments() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - put("requirementId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getComments(params); - assertThat(response, is(notNullValue())); - List comments = new Gson().fromJson(response.getResponse(), new TypeToken>() {}.getType()); - assertThat(comments, hasItem(Matchers.hasProperty("id", equalTo(1)))); - } - - @Test - public void test_getPrivateComments() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - put("componentId", String.valueOf(2)); - put("requirementId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getComments(params); - assertAccessDenied(response); - } -} diff --git a/src/test/de/rwth/dbis/acis/bazaar/service/security/SysAdminRightsTest.java b/src/test/de/rwth/dbis/acis/bazaar/service/security/SysAdminRightsTest.java deleted file mode 100644 index 6441016d..00000000 --- a/src/test/de/rwth/dbis/acis/bazaar/service/security/SysAdminRightsTest.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * - * Copyright (c) 2015, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.security; - -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.reflect.TypeToken; -import de.rwth.dbis.acis.bazaar.service.BazaarRequestParams; -import de.rwth.dbis.acis.bazaar.service.TestBase; -import de.rwth.dbis.acis.bazaar.service.dal.entities.*; -import i5.las2peer.testing.MockAgentFactory; -import i5.las2peer.webConnector.client.ClientResponse; -import i5.las2peer.webConnector.client.MiniClient; -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.List; - -/** - * @author Adam Gavronek - * @since 2/24/2015 - */ -public class SysAdminRightsTest extends TestBase { - @BeforeClass - public static void startServer() throws Exception { - testPass = "evespass"; - testAgent = MockAgentFactory.getEve(); - TestBase.startServer(); - } - - @Override - protected void login(MiniClient c) throws UnsupportedEncodingException { - super.login(c); - } - - @Test - public void test_getProjects() { - ClientResponse response = super.test_getProjects(new BazaarRequestParams()); - assertThat(response, is(notNullValue())); - List projectList = new Gson().fromJson(response.getResponse(), new TypeToken>() { - }.getType()); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(1)))); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(2)))); - } - - @Test - public void test_getPublicProject() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getProject(params); - assertThat(response,is(notNullValue())); - Project project = new Gson().fromJson(response.getResponse(), Project.class); - assertThat(project.getId(), is(1)); - assertThat(project.getName(), is("PublicTestProject")); - } - - @Test - public void test_getPrivateProject(){ - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getProject(params); - assertThat(response,is(notNullValue())); - Project project = new Gson().fromJson(response.getResponse(), Project.class); - assertThat(project.getId(), is(2)); - assertThat(project.getName(), is("PrivateTestProject")); - } - - @Test - @Ignore - public void test_createAndDeleteComponents( ){ - BazaarRequestParams params = new BazaarRequestParams(); - Category category = Category.getBuilder("TestCreateComponent").id(901).description("hello").projectId(1).build(); - params.setContentParam(new Gson().toJson(category)); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - }}); - ClientResponse response = super.test_createComponent(params); - assertThat(response,is(notNullValue())); - JsonObject userDataJson = new JsonParser().parse(response.getResponse()).getAsJsonObject(); - Integer insertedId= userDataJson.getAsJsonPrimitive("id").getAsInt(); - assertThat(insertedId,is(901)); - - //Delete it - - params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - put("componentId", String.valueOf(901)); - }}); - response = super.test_deleteComponent(params); - assertThat(response,is(notNullValue())); - userDataJson = new JsonParser().parse(response.getResponse()).getAsJsonObject(); - Boolean success = userDataJson.getAsJsonPrimitive("success").getAsBoolean(); - assertThat(success,is(true)); - } - - @Test - public void test_getPublicProjectComponents(){ - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getComponents(params); - assertThat(response, is(notNullValue())); - List projectList = new Gson().fromJson(response.getResponse(), new TypeToken>() {}.getType()); - assertThat(projectList, hasSize(1)); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(1)))); - } - - @Test - public void test_getPrivateProjectComponents() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getComponents(params); - assertThat(response, is(notNullValue())); - List projectList = new Gson().fromJson(response.getResponse(), new TypeToken>() {}.getType()); - assertThat(projectList, hasSize(1)); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(2)))); - } - - @Test - @Ignore - public void test_createRequirementPublicProject( ){ - BazaarRequestParams params = new BazaarRequestParams(); - Requirement requirement = Requirement.getBuilder("TestCreateReq").id(901).description("hello").projectId(1).build(); - params.setContentParam(new Gson().toJson(requirement)); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - }}); - ClientResponse response = super.test_createRequirement(params); - assertAccessDenied(response); - } - - @Test - public void test_getPublicRequirements() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getRequirementsByProject(params); - assertThat(response, is(notNullValue())); - List projectList = new Gson().fromJson(response.getResponse(), new TypeToken>() {}.getType()); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(1)))); - assertThat(projectList, hasSize(1)); - } - - @Test - public void test_getPrivateRequirements() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getRequirementsByProject(params); - assertThat(response, is(notNullValue())); - List projectList = new Gson().fromJson(response.getResponse(), new TypeToken>() {}.getType()); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(2)))); - assertThat(projectList, hasSize(1)); - } - - @Test - public void test_getPublicRequirementsByComponent() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getRequirementsByComponent(params); - assertThat(response, is(notNullValue())); - List projectList = new Gson().fromJson(response.getResponse(), new TypeToken>() {}.getType()); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(1)))); - assertThat(projectList, hasSize(1)); - } - - @Test - public void test_getPrivateRequirementsByComponent() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - put("componentId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getRequirementsByComponent(params); - assertThat(response, is(notNullValue())); - List projectList = new Gson().fromJson(response.getResponse(), new TypeToken>() {}.getType()); - assertThat(projectList, hasItem(Matchers.hasProperty("id", equalTo(2)))); - assertThat(projectList, hasSize(1)); - } - - @Test - public void test_getPublicRequirement() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - put("requirementId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getRequirement(params); - assertThat(response,is(notNullValue())); - RequirementEx requirementEx = new Gson().fromJson(response.getResponse(), RequirementEx.class); - assertThat(requirementEx.getId(), is(1)); - assertThat(requirementEx.getName(), is("PublicRequirement")); - } - - @Test - public void test_getPrivateRequirement() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - put("componentId", String.valueOf(2)); - put("requirementId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getRequirement(params); - assertThat(response,is(notNullValue())); - RequirementEx requirementEx = new Gson().fromJson(response.getResponse(), RequirementEx.class); - assertThat(requirementEx.getId(), is(2)); - assertThat(requirementEx.getName(), is("PrivateRequirement")); - } - - @Test - @Ignore - public void test_deleteRequirement() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - put("requirementId", String.valueOf(1)); - }}); - ClientResponse response = super.test_deleteRequirement(params); - assertAccessDenied(response); - } - - @Test - @Ignore - public void test_createComment( ){ - BazaarRequestParams params = new BazaarRequestParams(); - Comment comment = Comment.getBuilder("TestCommentText").id(901).requirementId(1).build(); - params.setContentParam(new Gson().toJson(comment)); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - put("requirementId", String.valueOf(1)); - }}); - ClientResponse response = super.test_createComment(params); - assertAccessDenied(response); - } - - @Test - public void test_getPublicComments() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(1)); - put("componentId", String.valueOf(1)); - put("requirementId", String.valueOf(1)); - }}); - ClientResponse response = super.test_getComments(params); - assertThat(response, is(notNullValue())); - List comments = new Gson().fromJson(response.getResponse(), new TypeToken>() {}.getType()); - assertThat(comments, hasSize(1)); - assertThat(comments, hasItem(Matchers.hasProperty("id", equalTo(1)))); - } - - @Test - public void test_getPrivateComments() { - BazaarRequestParams params = new BazaarRequestParams(); - params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(2)); - put("componentId", String.valueOf(2)); - put("requirementId", String.valueOf(2)); - }}); - ClientResponse response = super.test_getComments(params); - assertThat(response, is(notNullValue())); - List comments = new Gson().fromJson(response.getResponse(), new TypeToken>() { - }.getType()); - assertThat(comments, hasSize(1)); - assertThat(comments, hasItem(Matchers.hasProperty("id", equalTo(2)))); - } - -} diff --git a/src/test/de/rwth/dbis/acis/bazaar/service/update/UpdateTest.java b/src/test/de/rwth/dbis/acis/bazaar/service/update/UpdateTest.java deleted file mode 100644 index ba68f6aa..00000000 --- a/src/test/de/rwth/dbis/acis/bazaar/service/update/UpdateTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * - * Copyright (c) 2015, RWTH Aachen University. - * For a list of contributors see the AUTHORS file at the top-level directory - * of this distribution. - * - * 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 - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * / - */ - -package de.rwth.dbis.acis.bazaar.service.update; - -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import de.rwth.dbis.acis.bazaar.service.BazaarRequestParams; -import de.rwth.dbis.acis.bazaar.service.TestBase; -import de.rwth.dbis.acis.bazaar.service.dal.entities.Project; -import i5.las2peer.testing.MockAgentFactory; -import i5.las2peer.webConnector.client.ClientResponse; -import i5.las2peer.webConnector.client.MiniClient; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.List; - -/** - * @author Adam Gavronek - * @since 3/13/2015 - */ -public class UpdateTest extends TestBase { - @BeforeClass - public static void startServer() throws Exception { - //testPass = "evespass"; - testAgent = MockAgentFactory.getAnonymous(); - TestBase.startServer(); - } - - @Override - protected void login(MiniClient c) throws UnsupportedEncodingException { - //super.login(c); - } - - @Test - public void test_modifyProjects() { - ClientResponse response = super.test_getProjects(new BazaarRequestParams()); - Gson gson = new Gson(); - List projectList = gson.fromJson(response.getResponse(), new TypeToken>() { - }.getType()); - assertThat(projectList, not(empty())); - final Project project = projectList.get(0); - - String mod_title = "AAAAAAAAA"; - int mod_defaultComponentId = 99; - String mod_Desc = "MOD_DESC"; - Project.ProjectVisibility publicVisibility = Project.ProjectVisibility.PUBLIC; - int mod_leaderId = 88; - final Project modifiedProject = Project.getBuilder(mod_title) - .id(project.getId()) - .defaultComponentId(mod_defaultComponentId) - .description(mod_Desc) - .visibility(publicVisibility) - .leaderId(mod_leaderId) - .build(); - BazaarRequestParams mod_params = new BazaarRequestParams(); - mod_params.setContentParam(gson.toJson(modifiedProject)); - mod_params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(modifiedProject.getId())); - }}); - - ClientResponse modifyResponse = super.test_modifyProject(mod_params); - - BazaarRequestParams mod_test_params = new BazaarRequestParams(); - mod_test_params.setQueryParams(new HashMap() {{ - put("projectId", String.valueOf(project.getId())); - }}); - ClientResponse clientResponse = super.test_getProject(mod_test_params); - Project projectAfterModification = new Gson().fromJson(clientResponse.getResponse(), Project.class); - assertThat(projectAfterModification.getId(), is(project.getId())); - assertThat(projectAfterModification.getName(), is(mod_title)); - assertThat(projectAfterModification.getDefaultComponentId(), is(mod_defaultComponentId)); - assertThat(projectAfterModification.getDescription(), is(mod_Desc)); - assertThat(projectAfterModification.getVisibility(), is(publicVisibility)); - assertThat(projectAfterModification.getLeaderId(), is(mod_leaderId)); - - mod_params.setContentParam(gson.toJson(project)); - super.test_modifyProject(mod_params); - } -}