diff --git a/.gitignore b/.gitignore index d12c3ed9c..745ca3da6 100644 --- a/.gitignore +++ b/.gitignore @@ -252,3 +252,7 @@ dotnet_3/em/embedded/rest/ScsDriver/generated-tests/ /jdk_17_maven/cs/web/spring-petclinic/target/ /jdk_17_maven/em/embedded/web/spring-petclinic/target/ /statistics/table_suts.tex +/jdk_11_gradle/cs/rest/reservations-api/build/ +/jdk_11_gradle/em/embedded/rest/reservations-api/build/ +/jdk_11_gradle/em/external/rest/reservations-api/build/ +/jdk_17_gradle/.gradle/ diff --git a/README.md b/README.md index 02a001abd..1e32a583a 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,10 @@ More details (e.g., #LOCs and used databases) on these APIs can be found [in thi ### REST: Java/Kotlin +* Bibliothek (MIT), [jdk_17_gradle/cs/rest/bibliothek](jdk_17_gradle/cs/rest/bibliothek), from [https://github.com/PaperMC/bibliothek](https://github.com/PaperMC/bibliothek) + +* Reservations API (not-known license), [jdk_11_gradle/cs/rest/reservations-api](jdk_11_gradle/cs/rest/reservations-api), from [https://github.com/cyrilgavala/reservations-api](https://github.com/cyrilgavala/reservations-api) + * Genome Nexus (MIT), [jdk_8_maven/cs/rest-gui/genome-nexus](jdk_8_maven/cs/rest-gui/genome-nexus), from [https://github.com/genome-nexus/genome-nexus](https://github.com/genome-nexus/genome-nexus) * Market (MIT), [jdk_11_maven/cs/rest-gui/market](jdk_11_maven/cs/rest-gui/market), from [https://github.com/aleksey-lukyanets/market](https://github.com/aleksey-lukyanets/market) diff --git a/jdk_11_gradle/build.gradle b/jdk_11_gradle/build.gradle new file mode 100644 index 000000000..c1c05b9f8 --- /dev/null +++ b/jdk_11_gradle/build.gradle @@ -0,0 +1,6 @@ + +allprojects { + ext { + EVOMASTER_VERSION = "1.6.2-SNAPSHOT" + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/Procfile b/jdk_11_gradle/cs/rest/reservations-api/Procfile new file mode 100644 index 000000000..e60585444 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/Procfile @@ -0,0 +1 @@ +web: java -Dserver.port=$PORT $JAVA_OPTS -jar build/libs/reservations-api.jar \ No newline at end of file diff --git a/jdk_11_gradle/cs/rest/reservations-api/README.md b/jdk_11_gradle/cs/rest/reservations-api/README.md new file mode 100644 index 000000000..a7f04ed35 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/README.md @@ -0,0 +1,36 @@ +# Reservations API + +Simple API built with SpringBoot and MongoDB database. + +## Documentation + +Documentation can be found [here](https://cg-reservations-api.herokuapp.com/documentation) + +## How to run + +### Application + +1. Clone the repository by executing commands: + +``` +cd +git clone https://github.com/cyrilgavala/reservations-api.git . +``` + +2. Open the project with your preferable IDE. + If you use IntelliJ IDEA, it will offer you a **SpringBoot** runner configuration. +3. Update the runner by adding environment variable ```DATABASE_URL``` containing + URL to your MongoDB database and ```JWT_SECRET``` with 512-bit secret. +4. Run the runner configuration. + +### Tests + +1. To run tests you need to pass step 2. from previous instructions and run command: + + ```./gradlew test``` + + It will also execute ```jacocoTestReport``` gradle task, which will generate + test report on path ```reservation-api/build/reports/jacoco/test/html/index.html```. +2. To run whether you pass 95% test coverage check, simply run command: + + ```./gradlew jacocoTestCoverageVerification``` diff --git a/jdk_11_gradle/cs/rest/reservations-api/build.gradle b/jdk_11_gradle/cs/rest/reservations-api/build.gradle new file mode 100644 index 000000000..d9b46dcf9 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/build.gradle @@ -0,0 +1,108 @@ +plugins { + id 'org.springframework.boot' version '2.7.0' + id 'io.spring.dependency-management' version '1.0.11.RELEASE' + id 'java' + id 'jacoco' +} + +group = 'sk.cyrilgavala' +sourceCompatibility = '11' + +repositories { + mavenCentral() +} + +dependencies { + /* Annotation processors */ + annotationProcessor group: 'org.projectlombok', name: 'lombok-mapstruct-binding', version: '0.1.0' + annotationProcessor group: 'org.mapstruct', name: 'mapstruct-processor', version: mapStructVersion + annotationProcessor group: 'org.projectlombok', name: 'lombok', version: lombokVersion + + /* Implementation dependencies */ + implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-mongodb', version: springBootVersion + implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: springBootVersion + implementation group: 'org.springframework.boot', name: 'spring-boot-starter-validation', version: springBootVersion + implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: springBootVersion + implementation group: 'io.jsonwebtoken', name: 'jjwt-api', version: jjwtVersion + implementation group: 'io.jsonwebtoken', name: 'jjwt-impl', version: jjwtVersion + implementation group: 'io.jsonwebtoken', name: 'jjwt-jackson', version: jjwtVersion + implementation group: 'org.mapstruct', name: 'mapstruct', version: mapStructVersion + implementation group: 'com.google.code.findbugs', name: 'jsr305', version: '3.0.2' + implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.8' + + /* Compile only dependencies */ + compileOnly group: 'org.projectlombok', name: 'lombok', version: lombokVersion + + /* Test annotation processors */ + testAnnotationProcessor group: 'org.projectlombok', name: 'lombok', version: lombokVersion + testAnnotationProcessor group: 'org.mapstruct', name: 'mapstruct-processor', version: mapStructVersion + + /* Test implementation dependencies */ + testImplementation group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: springBootVersion + testImplementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: springBootVersion + testImplementation group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: springBootVersion + testImplementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-mongodb', version: springBootVersion + testImplementation group: 'org.springframework.security', name: 'spring-security-test', version: springSecurityVersion + + /* Test compile only dependencies */ + testCompileOnly group: 'org.projectlombok', name: 'lombok', version: lombokVersion + +} + +def jacocoExcludePackages = ["**/reservationsApi/ReservationsApi.class", + "**/reservationsApi/config/**", + "**/reservationsApi/exception/*", + "**/reservationsApi/model/*", + "**/reservationsApi/security/*", + "**/reservationsApi/web/advise/*", + "**/reservationsApi/web/interceptor/*", + "**/reservationsApi/web/request/*", + "**/reservationsApi/web/response/*"] + +test { + useJUnitPlatform() + finalizedBy jacocoTestReport +} + +jacoco { + toolVersion "0.8.8" +} + +jacocoTestReport { + dependsOn test + reports { + xml.required = false + csv.required = false + } + afterEvaluate { + classDirectories.setFrom(files(classDirectories.files.collect { + fileTree(dir: it, exclude: jacocoExcludePackages) + })) + } +} + +jacocoTestCoverageVerification { + violationRules { + rule { + limit { + minimum = 0.95 + } + } + } + afterEvaluate { + classDirectories.setFrom(files(classDirectories.files.collect { + fileTree(dir: it, exclude: jacocoExcludePackages) + })) + } +} + +check.dependsOn jacocoTestCoverageVerification + + +tasks.named("bootJar") { + archiveClassifier = 'sut' +} + +tasks.named("jar") { + archiveClassifier = 'plain' +} \ No newline at end of file diff --git a/jdk_11_gradle/cs/rest/reservations-api/gradle.properties b/jdk_11_gradle/cs/rest/reservations-api/gradle.properties new file mode 100644 index 000000000..47bc436da --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/gradle.properties @@ -0,0 +1,6 @@ +springBootVersion=2.7.0 +springSecurityVersion=5.6.3 +lombokVersion=1.18.24 +mapStructVersion=1.4.2.Final +swaggerVersion=3.0.0 +jjwtVersion=0.11.5 \ No newline at end of file diff --git a/jdk_11_gradle/cs/rest/reservations-api/settings.gradle b/jdk_11_gradle/cs/rest/reservations-api/settings.gradle new file mode 100644 index 000000000..df2a6f778 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'reservations-api' \ No newline at end of file diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/ReservationsApi.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/ReservationsApi.java new file mode 100644 index 000000000..5465b4074 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/ReservationsApi.java @@ -0,0 +1,28 @@ +package sk.cyrilgavala.reservationsApi; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.transaction.annotation.EnableTransactionManagement; + +import java.util.TimeZone; + +@SpringBootApplication +@EnableWebSecurity +@EnableMongoRepositories(basePackages = "sk.cyrilgavala.reservationsApi.repository") +@EnableTransactionManagement +@ComponentScan({"sk.cyrilgavala.reservationsApi.config", + "sk.cyrilgavala.reservationsApi.mapper", + "sk.cyrilgavala.reservationsApi.security", + "sk.cyrilgavala.reservationsApi.service", + "sk.cyrilgavala.reservationsApi.web"}) +public class ReservationsApi { + + public static void main(String[] args) { + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + SpringApplication.run(ReservationsApi.class, args); + } + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/DatabaseConfiguration.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/DatabaseConfiguration.java new file mode 100644 index 000000000..064e05457 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/DatabaseConfiguration.java @@ -0,0 +1,39 @@ +package sk.cyrilgavala.reservationsApi.config; + +import com.mongodb.ConnectionString; +import com.mongodb.MongoClientSettings; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.mongodb.MongoDatabaseFactory; +import org.springframework.data.mongodb.MongoTransactionManager; +import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration; + +@Configuration +public class DatabaseConfiguration extends AbstractMongoClientConfiguration { + + @Value("${databaseUrl}") + private String databaseUrl; + + @Bean + MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) { + return new MongoTransactionManager(dbFactory); + } + + @Override + protected String getDatabaseName() { + return "reservations-api"; + } + + @Override + public MongoClient mongoClient() { + ConnectionString connectionString = new ConnectionString(databaseUrl); + MongoClientSettings mongoClientSettings = MongoClientSettings.builder() + .applyConnectionString(connectionString) + .build(); + return MongoClients.create(mongoClientSettings); + } + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/OpenApiConfiguration.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/OpenApiConfiguration.java new file mode 100644 index 000000000..c828cf161 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/OpenApiConfiguration.java @@ -0,0 +1,23 @@ +package sk.cyrilgavala.reservationsApi.config; + +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.security.SecurityScheme; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class OpenApiConfiguration { + + @Bean + public OpenAPI springShopOpenAPI() { + return new OpenAPI() + .components( + new Components().addSecuritySchemes("bearer-key", + new SecurityScheme().type(SecurityScheme.Type.HTTP).scheme("bearer").bearerFormat("JWT"))) + .info(new Info().title("Reservations API") + .description("Simple API for implementing basic reservation system.") + .version("v1.0.0")); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/SecurityConfiguration.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/SecurityConfiguration.java new file mode 100644 index 000000000..d9e09184f --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/SecurityConfiguration.java @@ -0,0 +1,55 @@ +package sk.cyrilgavala.reservationsApi.config; + +import lombok.RequiredArgsConstructor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.HttpStatusEntryPoint; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import sk.cyrilgavala.reservationsApi.security.TokenAuthenticationFilter; + +@RequiredArgsConstructor +@Configuration +public class SecurityConfiguration { + + public static final String ADMIN = "ADMIN"; + public static final String USER = "USER"; + private final TokenAuthenticationFilter tokenAuthenticationFilter; + + @Bean + AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { + return authenticationConfiguration.getAuthenticationManager(); + } + + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(10); + } + + @Bean + SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { + http.authorizeRequests() + .antMatchers(HttpMethod.GET, "/api/reservation/**").hasAnyAuthority(ADMIN, USER) + .antMatchers(HttpMethod.POST, "/api/reservation").hasAnyAuthority(ADMIN, USER) + .antMatchers(HttpMethod.PUT, "/api/reservation").hasAnyAuthority(ADMIN, USER) + .antMatchers(HttpMethod.DELETE, "/api/reservation/**").hasAnyAuthority(ADMIN, USER) + .antMatchers(HttpMethod.GET, "/api/reservation").hasAuthority(ADMIN) + .antMatchers("/api/user/**").permitAll() + .antMatchers("/", "/error", "/documentation", "/swagger-ui.html", "/swagger-ui/**", "/v3/api-docs", "/v3/api-docs/**").permitAll() + .anyRequest().authenticated(); + http.addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); + http.exceptionHandling(e -> e.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))); + http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); + http.cors().and().csrf().disable(); + return http.build(); + } + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/WebConfiguration.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/WebConfiguration.java new file mode 100644 index 000000000..47ce81c6b --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/config/WebConfiguration.java @@ -0,0 +1,31 @@ +package sk.cyrilgavala.reservationsApi.config; + +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; +import java.util.TimeZone; + +@Configuration +public class WebConfiguration implements WebMvcConfigurer { + + @Override + public void configureMessageConverters(List> converters) { + WebMvcConfigurer.super.configureMessageConverters(converters); + + Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder(); + builder.modules(new JavaTimeModule(), new Jdk8Module()); + builder.timeZone(TimeZone.getTimeZone("UTC")); + builder.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + + final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + converter.setObjectMapper(builder.build()); + } + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/exception/DuplicateUserException.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/exception/DuplicateUserException.java new file mode 100644 index 000000000..93a94b039 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/exception/DuplicateUserException.java @@ -0,0 +1,10 @@ +package sk.cyrilgavala.reservationsApi.exception; + +public class DuplicateUserException extends RuntimeException { + + private static final long serialVersionUID = 9197342664218222132L; + + public DuplicateUserException(String message) { + super(message); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/exception/ReservationException.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/exception/ReservationException.java new file mode 100644 index 000000000..d69161ee1 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/exception/ReservationException.java @@ -0,0 +1,10 @@ +package sk.cyrilgavala.reservationsApi.exception; + +public class ReservationException extends RuntimeException { + + private static final long serialVersionUID = 4033799885256608552L; + + public ReservationException(String message) { + super(message); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/mapper/ReservationMapper.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/mapper/ReservationMapper.java new file mode 100644 index 000000000..7169f9c21 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/mapper/ReservationMapper.java @@ -0,0 +1,22 @@ +package sk.cyrilgavala.reservationsApi.mapper; + +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.MappingTarget; +import sk.cyrilgavala.reservationsApi.model.Reservation; +import sk.cyrilgavala.reservationsApi.web.request.CreateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.request.UpdateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.response.ReservationResponse; + +@Mapper(componentModel = "spring") +public interface ReservationMapper { + + @Mapping(target = "uuid", ignore = true) + Reservation createRequestToModel(CreateReservationRequest request); + + @Mapping(target = "createdAt", ignore = true) + Reservation updateRequestToModel(@MappingTarget Reservation model, UpdateReservationRequest request); + + ReservationResponse modelToResponse(Reservation model); + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/mapper/UserMapper.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/mapper/UserMapper.java new file mode 100644 index 000000000..32c2a999b --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/mapper/UserMapper.java @@ -0,0 +1,12 @@ +package sk.cyrilgavala.reservationsApi.mapper; + +import org.mapstruct.Mapper; +import sk.cyrilgavala.reservationsApi.model.User; +import sk.cyrilgavala.reservationsApi.web.response.UserResponse; + +@Mapper(componentModel = "spring") +public interface UserMapper { + + UserResponse modelToResponse(User model); + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/model/Reservation.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/model/Reservation.java new file mode 100644 index 000000000..8d18efb56 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/model/Reservation.java @@ -0,0 +1,30 @@ +package sk.cyrilgavala.reservationsApi.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; +import org.springframework.data.mongodb.core.mapping.FieldType; + +import java.time.LocalDateTime; + +@Document(collection = "reservations") +@NoArgsConstructor +@AllArgsConstructor +@Data +public class Reservation { + + @Id + private String uuid; + @Field(targetType = FieldType.STRING) + private String reservationFor; + @Field(targetType = FieldType.DATE_TIME) + private LocalDateTime reservationFrom; + @Field(targetType = FieldType.DATE_TIME) + private LocalDateTime reservationTo; + @Field(targetType = FieldType.DATE_TIME) + private LocalDateTime createdAt; + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/model/User.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/model/User.java new file mode 100644 index 000000000..3cd39e56a --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/model/User.java @@ -0,0 +1,27 @@ +package sk.cyrilgavala.reservationsApi.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.Field; +import org.springframework.data.mongodb.core.mapping.FieldType; + +@Document(collection = "users") +@Data +@NoArgsConstructor +@AllArgsConstructor +public class User { + + @Id + private String id; + @Field(targetType = FieldType.STRING) + private String username; + @Field(targetType = FieldType.STRING) + private String email; + @Field(targetType = FieldType.STRING) + private String password; + @Field(targetType = FieldType.STRING) + private String role; +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/repository/ReservationRepository.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/repository/ReservationRepository.java new file mode 100644 index 000000000..59b98e9a2 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/repository/ReservationRepository.java @@ -0,0 +1,21 @@ +package sk.cyrilgavala.reservationsApi.repository; + +import org.springframework.data.domain.Sort; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.data.mongodb.repository.Query; +import org.springframework.stereotype.Repository; +import sk.cyrilgavala.reservationsApi.model.Reservation; + +import java.time.LocalDateTime; +import java.util.List; + +@Repository +public interface ReservationRepository extends MongoRepository { + + Reservation findByUuid(String reservationUuid); + + List findAllByReservationFor(String reservationFor, Sort sort); + + @Query("{ $or: [ {$and: [{'reservationFrom': {$lt: ?0}}, {'reservationTo': {$gt: ?0}}]}, {$and: [{'reservationFrom': {$lt: ?1}}, {'reservationTo': {$gt: ?1}}]}] }") + List findAllBetween(LocalDateTime from, LocalDateTime to); +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/repository/UserRepository.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/repository/UserRepository.java new file mode 100644 index 000000000..0cc403787 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/repository/UserRepository.java @@ -0,0 +1,14 @@ +package sk.cyrilgavala.reservationsApi.repository; + +import org.springframework.data.mongodb.repository.MongoRepository; +import sk.cyrilgavala.reservationsApi.model.User; + +import java.util.Optional; + +public interface UserRepository extends MongoRepository { + Optional findByUsername(String username); + + Boolean existsByUsername(String username); + + Boolean existsByEmail(String email); +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/security/TokenAuthenticationFilter.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/security/TokenAuthenticationFilter.java new file mode 100644 index 000000000..dd11dfad4 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/security/TokenAuthenticationFilter.java @@ -0,0 +1,58 @@ +package sk.cyrilgavala.reservationsApi.security; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; + +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.util.Optional; + +@Slf4j +@RequiredArgsConstructor +@Component +public class TokenAuthenticationFilter extends OncePerRequestFilter { + + private static final String TOKEN_HEADER = "Authorization"; + private static final String TOKEN_PREFIX = "Bearer "; + + private final UserDetailsService userDetailsService; + private final TokenProvider tokenProvider; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { + try { + getJwtFromRequest(request) + .flatMap(tokenProvider::validateTokenAndGetJws) + .ifPresent(jws -> { + String username = jws.getBody().getSubject(); + UserDetails userDetails = userDetailsService.loadUserByUsername(username); + UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities()); + authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); + SecurityContextHolder.getContext().setAuthentication(authentication); + }); + } catch (Exception e) { + log.error("Cannot set user authentication", e); + } + chain.doFilter(request, response); + } + + private Optional getJwtFromRequest(HttpServletRequest request) { + String tokenHeader = request.getHeader(TOKEN_HEADER); + if (StringUtils.hasText(tokenHeader) && tokenHeader.startsWith(TOKEN_PREFIX)) { + return Optional.of(tokenHeader.replace(TOKEN_PREFIX, "")); + } + return Optional.empty(); + } + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/security/TokenProvider.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/security/TokenProvider.java new file mode 100644 index 000000000..4cb3cccaa --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/security/TokenProvider.java @@ -0,0 +1,84 @@ +package sk.cyrilgavala.reservationsApi.security; + +import io.jsonwebtoken.Claims; +import io.jsonwebtoken.ExpiredJwtException; +import io.jsonwebtoken.Jws; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.MalformedJwtException; +import io.jsonwebtoken.SignatureAlgorithm; +import io.jsonwebtoken.UnsupportedJwtException; +import io.jsonwebtoken.security.Keys; +import io.jsonwebtoken.security.SignatureException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.stereotype.Component; + +import java.time.ZonedDateTime; +import java.util.Date; +import java.util.Optional; +import java.util.UUID; +import java.util.stream.Collectors; + +@Slf4j +@Component +public class TokenProvider { + + private static final String TOKEN_TYPE = "JWT"; + private static final String TOKEN_ISSUER = "reservations-api"; + private static final String TOKEN_AUDIENCE = "reservations-ui"; + @Value("${app.jwt.secret}") + private String jwtSecret; + @Value("${app.jwt.expiration.minutes}") + private Long jwtExpirationMinutes; + + public String generate(Authentication authentication) { + UserDetails user = (User) authentication.getPrincipal(); + + String roles = user.getAuthorities() + .stream() + .map(GrantedAuthority::getAuthority) + .collect(Collectors.joining(",")); + + byte[] signingKey = jwtSecret.getBytes(); + + return Jwts.builder() + .setHeaderParam("typ", TOKEN_TYPE) + .signWith(Keys.hmacShaKeyFor(signingKey), SignatureAlgorithm.HS512) + .setExpiration(Date.from(ZonedDateTime.now().plusMinutes(jwtExpirationMinutes).toInstant())) + .setIssuedAt(Date.from(ZonedDateTime.now().toInstant())) + .setId(UUID.randomUUID().toString()) + .setIssuer(TOKEN_ISSUER) + .setAudience(TOKEN_AUDIENCE) + .setSubject(user.getUsername()) + .claim("rol", roles) + .compact(); + } + + public Optional> validateTokenAndGetJws(String token) { + try { + byte[] signingKey = jwtSecret.getBytes(); + + Jws jws = Jwts.parserBuilder() + .setSigningKey(signingKey) + .build() + .parseClaimsJws(token); + + return Optional.of(jws); + } catch (ExpiredJwtException exception) { + log.error("Request to parse expired JWT : {} failed : {}", token, exception.getMessage()); + } catch (UnsupportedJwtException exception) { + log.error("Request to parse unsupported JWT : {} failed : {}", token, exception.getMessage()); + } catch (MalformedJwtException exception) { + log.error("Request to parse invalid JWT : {} failed : {}", token, exception.getMessage()); + } catch (SignatureException exception) { + log.error("Request to parse JWT with invalid signature : {} failed : {}", token, exception.getMessage()); + } catch (IllegalArgumentException exception) { + log.error("Request to parse empty or null JWT : {} failed : {}", token, exception.getMessage()); + } + return Optional.empty(); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/ReservationService.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/ReservationService.java new file mode 100644 index 000000000..e77ea5f8d --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/ReservationService.java @@ -0,0 +1,23 @@ +package sk.cyrilgavala.reservationsApi.service; + +import sk.cyrilgavala.reservationsApi.web.request.CreateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.request.UpdateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.response.ReservationResponse; + +import java.util.List; + +/** + * Service for basic operations for reservations. + */ +public interface ReservationService { + + ReservationResponse createReservation(CreateReservationRequest request); + + ReservationResponse updateReservation(UpdateReservationRequest request); + + List getAllReservations(); + + List getAllReservationsForUsername(String username); + + void deleteReservation(String reservationUuid); +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/ReservationServiceImpl.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/ReservationServiceImpl.java new file mode 100644 index 000000000..1ee729339 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/ReservationServiceImpl.java @@ -0,0 +1,89 @@ +package sk.cyrilgavala.reservationsApi.service; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import sk.cyrilgavala.reservationsApi.exception.ReservationException; +import sk.cyrilgavala.reservationsApi.mapper.ReservationMapper; +import sk.cyrilgavala.reservationsApi.model.Reservation; +import sk.cyrilgavala.reservationsApi.repository.ReservationRepository; +import sk.cyrilgavala.reservationsApi.web.request.CreateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.request.UpdateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.response.ReservationResponse; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.stream.Collectors; + +@Slf4j +@Service +@Transactional +@RequiredArgsConstructor +public class ReservationServiceImpl implements ReservationService { + private static final String RESERVATION_UNPROCESSABLE_START_DATE_IS_AFTER_END_DATE = "Reservation unprocessable: start date is after end date"; + private static final String RESERVATION_UNPROCESSABLE_COVERS_ANOTHER_RESERVATION = "Reservation unprocessable: covers another reservation"; + private static final String RESERVATION_UNPROCESSABLE_START_DATE_IN_PAST = "Reservation unprocessable: start date is in past"; + private final ReservationRepository repository; + private final ReservationMapper mapper; + + @Override + public ReservationResponse createReservation(CreateReservationRequest request) { + validateDates(request.getReservationFrom(), request.getReservationTo()); + Reservation mappedReservation = mapper.createRequestToModel(request); + Reservation savedReservation = repository.insert(mappedReservation); + return mapper.modelToResponse(savedReservation); + } + + @Override + public ReservationResponse updateReservation(UpdateReservationRequest request) { + validateDates(request.getReservationFrom(), request.getReservationTo()); + Reservation loadedReservation = repository.findByUuid(request.getUuid()); + Reservation updatedReservation = mapper.updateRequestToModel(loadedReservation, request); + Reservation savedReservation = repository.save(updatedReservation); + return mapper.modelToResponse(savedReservation); + } + + @Override + @Transactional(readOnly = true) + public List getAllReservations() { + return repository.findAll(Sort.by("reservationFrom").descending()) + .stream() + .map(mapper::modelToResponse) + .collect(Collectors.toList()); + } + + @Override + @Transactional(readOnly = true) + public List getAllReservationsForUsername(String username) { + return repository.findAllByReservationFor(username, Sort.by("reservationFrom").descending()) + .stream() + .map(mapper::modelToResponse) + .collect(Collectors.toList()); + } + + @Override + public void deleteReservation(String reservationUuid) { + repository.deleteById(reservationUuid); + } + + private void validateDates(LocalDateTime from, LocalDateTime to) { + if (from.isAfter(to)) { + log.error(RESERVATION_UNPROCESSABLE_START_DATE_IS_AFTER_END_DATE); + throw new ReservationException(RESERVATION_UNPROCESSABLE_START_DATE_IS_AFTER_END_DATE); + } + LocalDateTime now = LocalDateTime.now(); + if (now.isAfter(from)) { + log.error(RESERVATION_UNPROCESSABLE_START_DATE_IN_PAST); + throw new ReservationException(RESERVATION_UNPROCESSABLE_START_DATE_IN_PAST); + } + List reservations = repository.findAllBetween(from, to); + reservations.stream() + .findFirst() + .ifPresent(reservation -> { + log.error(RESERVATION_UNPROCESSABLE_COVERS_ANOTHER_RESERVATION); + throw new ReservationException(RESERVATION_UNPROCESSABLE_COVERS_ANOTHER_RESERVATION); + }); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/UserDetailsServiceImpl.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/UserDetailsServiceImpl.java new file mode 100644 index 000000000..fb9e09f87 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/UserDetailsServiceImpl.java @@ -0,0 +1,32 @@ +package sk.cyrilgavala.reservationsApi.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.User; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import sk.cyrilgavala.reservationsApi.web.response.UserResponse; + +import java.util.Collections; + +@Service +@RequiredArgsConstructor +public class UserDetailsServiceImpl implements UserDetailsService { + + private final UserService userService; + + @Override + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { + UserResponse user = userService.getByUsername(username); + return mapToUserDetails(user); + } + + private UserDetails mapToUserDetails(UserResponse userResponse) { + return new User( + userResponse.getUsername(), + userResponse.getPassword(), + Collections.singletonList(new SimpleGrantedAuthority(userResponse.getRole()))); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/UserService.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/UserService.java new file mode 100644 index 000000000..62141bcd0 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/UserService.java @@ -0,0 +1,15 @@ +package sk.cyrilgavala.reservationsApi.service; + +import sk.cyrilgavala.reservationsApi.model.User; +import sk.cyrilgavala.reservationsApi.web.response.UserResponse; + +public interface UserService { + + UserResponse getByUsername(String username); + + boolean existsByUsername(String username); + + boolean existsByEmail(String email); + + UserResponse saveUser(User user); +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/UserServiceImpl.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/UserServiceImpl.java new file mode 100644 index 000000000..98da8451b --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/service/UserServiceImpl.java @@ -0,0 +1,44 @@ +package sk.cyrilgavala.reservationsApi.service; + +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import sk.cyrilgavala.reservationsApi.mapper.UserMapper; +import sk.cyrilgavala.reservationsApi.model.User; +import sk.cyrilgavala.reservationsApi.repository.UserRepository; +import sk.cyrilgavala.reservationsApi.web.response.UserResponse; + +@Service +@Transactional +@RequiredArgsConstructor +public class UserServiceImpl implements UserService { + + private final UserRepository repository; + private final UserMapper mapper; + + @Override + @Transactional(readOnly = true) + public UserResponse getByUsername(String username) { + return mapper.modelToResponse(repository.findByUsername(username) + .orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + username))); + } + + @Override + @Transactional(readOnly = true) + public boolean existsByUsername(String username) { + return repository.existsByUsername(username); + } + + @Override + @Transactional(readOnly = true) + public boolean existsByEmail(String email) { + return repository.existsByEmail(email); + } + + @Override + public UserResponse saveUser(User user) { + return mapper.modelToResponse(repository.insert(user)); + } + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/DateTimeAware.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/DateTimeAware.java new file mode 100644 index 000000000..be5112615 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/DateTimeAware.java @@ -0,0 +1,5 @@ +package sk.cyrilgavala.reservationsApi.web; + +public interface DateTimeAware { + String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/advise/ReservationExceptionHandler.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/advise/ReservationExceptionHandler.java new file mode 100644 index 000000000..72211a83c --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/advise/ReservationExceptionHandler.java @@ -0,0 +1,44 @@ +package sk.cyrilgavala.reservationsApi.web.advise; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.lang.Nullable; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.context.request.WebRequest; +import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import org.springframework.web.util.WebUtils; +import sk.cyrilgavala.reservationsApi.exception.DuplicateUserException; +import sk.cyrilgavala.reservationsApi.exception.ReservationException; + +import javax.validation.ConstraintViolationException; +import java.util.Objects; + +@ControllerAdvice +public class ReservationExceptionHandler extends ResponseEntityExceptionHandler { + + @ExceptionHandler(value = {ReservationException.class}) + protected ResponseEntity handleReservationException(ReservationException ex, WebRequest request) { + return handleExceptionInternal(ex, null, new HttpHeaders(), HttpStatus.UNPROCESSABLE_ENTITY, request); + } + + @ExceptionHandler(value = {ConstraintViolationException.class}) + protected ResponseEntity handleConstraintViolationException(ConstraintViolationException ex, WebRequest request) { + return handleExceptionInternal(ex, null, new HttpHeaders(), HttpStatus.BAD_REQUEST, request); + } + + @ExceptionHandler(value = {DuplicateUserException.class}) + protected ResponseEntity handleDuplicateUserException(DuplicateUserException ex, WebRequest request) { + return handleExceptionInternal(ex, null, new HttpHeaders(), HttpStatus.CONFLICT, request); + } + + @Override + protected ResponseEntity handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) { + Objects.requireNonNull(ex); + if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) { + request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex, WebRequest.SCOPE_REQUEST); + } + return new ResponseEntity<>(body != null ? body : ex.getMessage(), headers, status); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/controller/ReservationRestController.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/controller/ReservationRestController.java new file mode 100644 index 000000000..1ae279495 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/controller/ReservationRestController.java @@ -0,0 +1,69 @@ +package sk.cyrilgavala.reservationsApi.web.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import sk.cyrilgavala.reservationsApi.service.ReservationService; +import sk.cyrilgavala.reservationsApi.web.request.CreateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.request.UpdateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.response.ReservationResponse; + +import javax.validation.Valid; +import javax.validation.constraints.NotBlank; +import java.util.List; + +@Tag(name = "Reservations") +@RestController +@RequestMapping(value = "/api/reservation", produces = MediaType.APPLICATION_JSON_VALUE) +@Validated +@CrossOrigin +@RequiredArgsConstructor +public class ReservationRestController { + + private final ReservationService service; + + @Operation(summary = "Get reservations for particular user", description = "Get reservations for particular user when correct username provided.", security = {@SecurityRequirement(name = "bearer-key")}) + @GetMapping("/{username}") + public List getAllReservationsForUser(@PathVariable @NotBlank String username) { + return service.getAllReservationsForUsername(username); + } + + @Operation(summary = "Get all reservations", description = "Get all reservations available.", security = {@SecurityRequirement(name = "bearer-key")}) + @GetMapping + public List getAllReservations() { + return service.getAllReservations(); + } + + @Operation(summary = "Create new reservation", description = "Create new reservation when valid information provided.", security = {@SecurityRequirement(name = "bearer-key")}) + @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE) + @ResponseStatus(HttpStatus.CREATED) + public ReservationResponse createReservation(@Valid @RequestBody CreateReservationRequest requestBody) { + return service.createReservation(requestBody); + } + + @Operation(summary = "Update reservation", description = "Update reservation when valid information provided.", security = {@SecurityRequirement(name = "bearer-key")}) + @PutMapping(consumes = MediaType.APPLICATION_JSON_VALUE) + public ReservationResponse updateReservation(@Valid @RequestBody UpdateReservationRequest requestBody) { + return service.updateReservation(requestBody); + } + + @Operation(summary = "Delete reservation", description = "Delete reservation when valid UUID provided.", security = {@SecurityRequirement(name = "bearer-key")}) + @DeleteMapping("/{reservationUuid}") + public void deleteReservation(@PathVariable @NotBlank String reservationUuid) { + service.deleteReservation(reservationUuid); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/controller/UserRestController.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/controller/UserRestController.java new file mode 100644 index 000000000..cf40748f2 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/controller/UserRestController.java @@ -0,0 +1,79 @@ +package sk.cyrilgavala.reservationsApi.web.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import sk.cyrilgavala.reservationsApi.config.SecurityConfiguration; +import sk.cyrilgavala.reservationsApi.exception.DuplicateUserException; +import sk.cyrilgavala.reservationsApi.model.User; +import sk.cyrilgavala.reservationsApi.security.TokenProvider; +import sk.cyrilgavala.reservationsApi.service.UserService; +import sk.cyrilgavala.reservationsApi.web.request.LoginRequest; +import sk.cyrilgavala.reservationsApi.web.request.RegisterRequest; +import sk.cyrilgavala.reservationsApi.web.response.AuthResponse; + +import javax.validation.Valid; +import java.util.Base64; + +@Tag(name = "Users") +@RestController +@RequestMapping("/api/user") +@RequiredArgsConstructor +@CrossOrigin +public class UserRestController { + + private final UserService userService; + private final AuthenticationManager authenticationManager; + private final TokenProvider tokenProvider; + private final PasswordEncoder passwordEncoder; + + @Operation(summary = "Perform user's login to retrieve access token.", description = "Perform user's login to retrieve access token.") + @PostMapping("/login") + public AuthResponse login(@Valid @RequestBody LoginRequest loginRequest) { + String token = authenticateAndGetToken(loginRequest.getUsername(), new String(Base64.getDecoder().decode(loginRequest.getPassword()))); + return new AuthResponse(token); + } + + @Operation(summary = "Perform user's registration to save a user and retrieve access token.", description = "Perform user's registration to save a user and retrieve access token.") + @ResponseStatus(HttpStatus.CREATED) + @PostMapping("/register") + public AuthResponse register(@Valid @RequestBody RegisterRequest registerRequest) { + if (userService.existsByUsername(registerRequest.getUsername())) { + throw new DuplicateUserException(String.format("Username %s already been used", registerRequest.getUsername())); + } + if (userService.existsByEmail(registerRequest.getEmail())) { + throw new DuplicateUserException(String.format("Email %s already been used", registerRequest.getEmail())); + } + + userService.saveUser(mapRegisterRequestToUser(registerRequest)); + + String token = authenticateAndGetToken(registerRequest.getUsername(), new String(Base64.getDecoder().decode(registerRequest.getPassword()))); + return new AuthResponse(token); + } + + private String authenticateAndGetToken(String username, String password) { + Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password)); + return tokenProvider.generate(authentication); + } + + private User mapRegisterRequestToUser(RegisterRequest registerRequest) { + User user = new User(); + user.setUsername(registerRequest.getUsername()); + user.setPassword(passwordEncoder.encode(new String(Base64.getDecoder().decode(registerRequest.getPassword())))); + user.setEmail(registerRequest.getEmail()); + user.setRole(SecurityConfiguration.USER); + return user; + } + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/CreateReservationRequest.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/CreateReservationRequest.java new file mode 100644 index 000000000..034ab4da5 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/CreateReservationRequest.java @@ -0,0 +1,38 @@ +package sk.cyrilgavala.reservationsApi.web.request; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import sk.cyrilgavala.reservationsApi.web.DateTimeAware; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.time.LocalDateTime; + +@JsonInclude(value = JsonInclude.Include.NON_EMPTY) +@NoArgsConstructor +@AllArgsConstructor +@Data +public class CreateReservationRequest implements DateTimeAware, Serializable { + + private static final long serialVersionUID = -44348945472726119L; + + @NotBlank + private String reservationFor; + + @NotNull + @JsonFormat(pattern = DATE_TIME_FORMAT, shape = JsonFormat.Shape.STRING) + private LocalDateTime reservationFrom; + + @NotNull + @JsonFormat(pattern = DATE_TIME_FORMAT, shape = JsonFormat.Shape.STRING) + private LocalDateTime reservationTo; + + @NotNull + @JsonFormat(pattern = DATE_TIME_FORMAT, shape = JsonFormat.Shape.STRING) + private LocalDateTime createdAt; + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/LoginRequest.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/LoginRequest.java new file mode 100644 index 000000000..ae53b68f6 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/LoginRequest.java @@ -0,0 +1,16 @@ +package sk.cyrilgavala.reservationsApi.web.request; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.constraints.NotBlank; + +@Data +@AllArgsConstructor +public class LoginRequest { + + @NotBlank + private String username; + @NotBlank + private String password; +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/RegisterRequest.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/RegisterRequest.java new file mode 100644 index 000000000..0f56a7603 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/RegisterRequest.java @@ -0,0 +1,20 @@ +package sk.cyrilgavala.reservationsApi.web.request; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; + +@Data +@AllArgsConstructor +public class RegisterRequest { + + @NotBlank + private String username; + @NotBlank + @Email + private String email; + @NotBlank + private String password; +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/UpdateReservationRequest.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/UpdateReservationRequest.java new file mode 100644 index 000000000..29da8a3ae --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/request/UpdateReservationRequest.java @@ -0,0 +1,37 @@ +package sk.cyrilgavala.reservationsApi.web.request; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import sk.cyrilgavala.reservationsApi.web.DateTimeAware; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.time.LocalDateTime; + +@JsonInclude(value = JsonInclude.Include.NON_EMPTY) +@NoArgsConstructor +@AllArgsConstructor +@Data +public class UpdateReservationRequest implements DateTimeAware, Serializable { + + private static final long serialVersionUID = 555607903324853344L; + + @NotBlank + private String uuid; + + @NotBlank + private String reservationFor; + + @NotNull + @JsonFormat(pattern = DATE_TIME_FORMAT, shape = JsonFormat.Shape.STRING) + private LocalDateTime reservationFrom; + + @NotNull + @JsonFormat(pattern = DATE_TIME_FORMAT, shape = JsonFormat.Shape.STRING) + private LocalDateTime reservationTo; + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/response/AuthResponse.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/response/AuthResponse.java new file mode 100644 index 000000000..25fed0661 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/response/AuthResponse.java @@ -0,0 +1,11 @@ +package sk.cyrilgavala.reservationsApi.web.response; + +import lombok.AllArgsConstructor; +import lombok.Data; + +@Data +@AllArgsConstructor +public class AuthResponse { + + private String accessToken; +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/response/ReservationResponse.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/response/ReservationResponse.java new file mode 100644 index 000000000..9578f37f1 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/response/ReservationResponse.java @@ -0,0 +1,28 @@ +package sk.cyrilgavala.reservationsApi.web.response; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import sk.cyrilgavala.reservationsApi.web.DateTimeAware; + +import java.io.Serializable; +import java.time.LocalDateTime; + +@NoArgsConstructor +@AllArgsConstructor +@Data +@JsonInclude(JsonInclude.Include.NON_EMPTY) +public class ReservationResponse implements DateTimeAware, Serializable { + + private static final long serialVersionUID = 5714157215793550376L; + + private String uuid; + private String reservationFor; + @JsonFormat(pattern = DATE_TIME_FORMAT, shape = JsonFormat.Shape.STRING) + private LocalDateTime reservationFrom; + @JsonFormat(pattern = DATE_TIME_FORMAT, shape = JsonFormat.Shape.STRING) + private LocalDateTime reservationTo; + +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/response/UserResponse.java b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/response/UserResponse.java new file mode 100644 index 000000000..cf824d790 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/java/sk/cyrilgavala/reservationsApi/web/response/UserResponse.java @@ -0,0 +1,23 @@ +package sk.cyrilgavala.reservationsApi.web.response; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class UserResponse implements Serializable { + + private static final long serialVersionUID = -3333137047634067175L; + + private String id; + private String username; + private String email; + @JsonIgnore + private String password; + private String role; +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/main/resources/application.yaml b/jdk_11_gradle/cs/rest/reservations-api/src/main/resources/application.yaml new file mode 100644 index 000000000..ce6b6147b --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/main/resources/application.yaml @@ -0,0 +1,20 @@ +spring.application.name: 'ReservationAPI' +springdoc: + packagesToScan: 'sk.cyrilgavala.reservationsApi.web' + pathsToMatch: '/api/**' + swagger-ui.path: '/documentation' + +databaseUrl: ${DATABASE_URL:localhost:27017} + +app: + jwt: + secret: ${JWT_SECRET:'jwt_secret'} + expiration: + minutes: 60 + +# logging levels +logging.level: + org.mongodb: WARN + org.springframework: WARN + org.springdoc: WARN + org.apache: WARN \ No newline at end of file diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/config/TestsConfiguration.java b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/config/TestsConfiguration.java new file mode 100644 index 000000000..f4e76d241 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/config/TestsConfiguration.java @@ -0,0 +1,9 @@ +package sk.cyrilgavala.reservationsApi.config; + +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.context.annotation.Import; + +@TestConfiguration +@Import({WebConfiguration.class, SecurityConfiguration.class}) +public class TestsConfiguration { +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/mapper/ReservationMapperTests.java b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/mapper/ReservationMapperTests.java new file mode 100644 index 000000000..360b67ae0 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/mapper/ReservationMapperTests.java @@ -0,0 +1,78 @@ +package sk.cyrilgavala.reservationsApi.mapper; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import sk.cyrilgavala.reservationsApi.model.Reservation; +import sk.cyrilgavala.reservationsApi.web.request.CreateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.request.UpdateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.response.ReservationResponse; + +import java.time.LocalDateTime; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Test cases for {@link ReservationMapper}. + */ +@ExtendWith(MockitoExtension.class) +public class ReservationMapperTests { + + private static final String UUID = "reservationUuid"; + private static final String USERNAME = "username"; + private static final LocalDateTime DATE_15_00 = LocalDateTime.of(2022, 5, 20, 15, 0, 0); + private static final LocalDateTime DATE_16_00 = LocalDateTime.of(2022, 5, 20, 16, 0, 0); + + private final ReservationMapper mapper = new ReservationMapperImpl(); + + @Test + void creteRequestToModel_validRequest() { + CreateReservationRequest request = new CreateReservationRequest(USERNAME, DATE_15_00, DATE_16_00, DATE_15_00); + Reservation result = mapper.createRequestToModel(request); + assertThat(result != null).isTrue(); + assertThat(result.getReservationFor()).isEqualTo(USERNAME); + assertThat(result.getReservationFrom()).isEqualTo(DATE_15_00); + assertThat(result.getReservationTo()).isEqualTo(DATE_16_00); + assertThat(result.getCreatedAt()).isEqualTo(DATE_15_00); + } + + @Test + void updateRequestToModel_null() { + Reservation result = mapper.updateRequestToModel(new Reservation(), null); + assertThat(result).isNull(); + } + + @Test + void updateRequestToModel_validRequest() { + UpdateReservationRequest request = new UpdateReservationRequest(UUID, USERNAME, DATE_15_00, DATE_16_00); + Reservation result = mapper.updateRequestToModel(new Reservation(), request); + assertThat(result != null).isTrue(); + assertThat(result.getReservationFor()).isEqualTo(USERNAME); + assertThat(result.getReservationFrom()).isEqualTo(DATE_15_00); + assertThat(result.getReservationTo()).isEqualTo(DATE_16_00); + assertThat(result.getUuid()).isEqualTo(UUID); + } + + @Test + void createRequestToModel_null() { + Reservation result = mapper.createRequestToModel(null); + assertThat(result).isNull(); + } + + @Test + void modelToResponse_validModel() { + Reservation model = new Reservation(UUID, USERNAME, DATE_15_00, DATE_16_00, DATE_15_00); + ReservationResponse result = mapper.modelToResponse(model); + assertThat(result != null).isTrue(); + assertThat(result.getReservationFor()).isEqualTo(USERNAME); + assertThat(result.getReservationFrom()).isEqualTo(DATE_15_00); + assertThat(result.getReservationTo()).isEqualTo(DATE_16_00); + assertThat(result.getUuid()).isEqualTo(UUID); + } + + @Test + void modelToResponse_null() { + ReservationResponse result = mapper.modelToResponse(null); + assertThat(result).isNull(); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/mapper/UserMapperTests.java b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/mapper/UserMapperTests.java new file mode 100644 index 000000000..cc8e86b24 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/mapper/UserMapperTests.java @@ -0,0 +1,38 @@ +package sk.cyrilgavala.reservationsApi.mapper; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; +import sk.cyrilgavala.reservationsApi.model.User; +import sk.cyrilgavala.reservationsApi.web.response.UserResponse; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * Test cases for {@link UserMapper}. + */ +@ExtendWith(MockitoExtension.class) +public class UserMapperTests { + + private final UserMapper mapper = new UserMapperImpl(); + + @Test + void modelToResponse_validModel() { + User user = new User("userId", "userName", "user@test.com", "userPassword", "USER"); + UserResponse response = mapper.modelToResponse(user); + assertNotNull(response); + assertEquals("userId", response.getId()); + assertEquals("userName", response.getUsername()); + assertEquals("user@test.com", response.getEmail()); + assertEquals("userPassword", response.getPassword()); + assertEquals("USER", response.getRole()); + } + + @Test + void modelToResponse_null() { + UserResponse response = mapper.modelToResponse(null); + assertNull(response); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/service/ReservationServiceImplTests.java b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/service/ReservationServiceImplTests.java new file mode 100644 index 000000000..db4878aed --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/service/ReservationServiceImplTests.java @@ -0,0 +1,204 @@ +package sk.cyrilgavala.reservationsApi.service; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Sort; +import sk.cyrilgavala.reservationsApi.exception.ReservationException; +import sk.cyrilgavala.reservationsApi.mapper.ReservationMapper; +import sk.cyrilgavala.reservationsApi.model.Reservation; +import sk.cyrilgavala.reservationsApi.repository.ReservationRepository; +import sk.cyrilgavala.reservationsApi.web.request.CreateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.request.UpdateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.response.ReservationResponse; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * Test cases for {@link ReservationService}. + */ +@ExtendWith(value = MockitoExtension.class) +public class ReservationServiceImplTests { + + private static final LocalDateTime DATE_15_00 = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS).plusDays(1).withHour(15); + private static final LocalDateTime DATE_16_00 = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS).plusDays(1).withHour(16); + private static final LocalDateTime DATE_17_00 = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS).plusDays(1).withHour(17); + private static final String RESERVATION_UUID = "reservationUuid"; + private static final String USERNAME = "username"; + private static final String REVERTED_DATES_ERROR_MESSAGE = "Reservation unprocessable: start date is after end date"; + private static final String RESERVATION_EXISTS_ERROR_MESSAGE = "Reservation unprocessable: covers another reservation"; + private static final String START_IN_PAST_ERROR_MESSAGE = "Reservation unprocessable: start date is in past"; + private final CreateReservationRequest createRequest = new CreateReservationRequest(); + private final UpdateReservationRequest updateRequest = new UpdateReservationRequest(); + + @Mock + private transient ReservationRepository repository; + @Mock + private ReservationMapper mapper; + @InjectMocks + private ReservationServiceImpl service; + + @Test + void create_invalidDatesFromAfterTo_errorThrown() { + createRequest.setReservationFrom(DATE_17_00); + createRequest.setReservationTo(DATE_15_00); + + try { + service.createReservation(createRequest); + fail("Reservation exception should be thrown"); + } catch (ReservationException exception) { + assertEquals(REVERTED_DATES_ERROR_MESSAGE, exception.getMessage(), "Different message"); + + verifyNoMoreInteractions(repository); + } + } + + @Test + void create_invalidDatesStartInPast_errorThrown() { + createRequest.setReservationFrom(DATE_17_00.minusDays(2)); + createRequest.setReservationTo(DATE_15_00); + + try { + service.createReservation(createRequest); + fail("Reservation exception should be thrown"); + } catch (ReservationException exception) { + assertEquals(START_IN_PAST_ERROR_MESSAGE, exception.getMessage(), "Different message"); + + verifyNoMoreInteractions(repository); + } + } + + @Test + void create_invalidDatesReservationExists_errorThrown() { + createRequest.setReservationFrom(DATE_15_00); + createRequest.setReservationTo(DATE_17_00); + + when(repository.findAllBetween(DATE_15_00, DATE_17_00)).thenReturn(Collections.singletonList(new Reservation())); + + try { + service.createReservation(createRequest); + fail("Reservation exception should be thrown"); + } catch (ReservationException exception) { + assertEquals(RESERVATION_EXISTS_ERROR_MESSAGE, exception.getMessage(), "Different message"); + + verifyNoMoreInteractions(repository); + } + } + + @Test + void create_validRequest_pass() { + Reservation reservationModel = new Reservation("uuid", "username", DATE_15_00, DATE_17_00, DATE_15_00); + createRequest.setReservationFrom(DATE_15_00); + createRequest.setReservationTo(DATE_17_00); + + when(repository.findAllBetween(DATE_15_00, DATE_17_00)).thenReturn(Collections.emptyList()); + when(mapper.createRequestToModel(createRequest)).thenReturn(reservationModel); + when(repository.insert(reservationModel)).thenReturn(reservationModel); + when(mapper.modelToResponse(reservationModel)) + .thenReturn(new ReservationResponse(null, null, DATE_15_00, DATE_17_00)); + + try { + ReservationResponse result = service.createReservation(createRequest); + + assertEquals(DATE_15_00, result.getReservationFrom()); + assertEquals(DATE_17_00, result.getReservationTo()); + + verifyNoMoreInteractions(repository); + } catch (ReservationException exception) { + fail("Reservation exception should not be thrown"); + } + } + + @Test + void update_validRequest_pass() { + updateRequest.setReservationFrom(DATE_16_00); + updateRequest.setReservationTo(DATE_17_00); + updateRequest.setUuid(RESERVATION_UUID); + Reservation reservationToReturn = new Reservation(RESERVATION_UUID, null, DATE_16_00, DATE_17_00, DATE_15_00); + Reservation reservationFromDb = new Reservation(RESERVATION_UUID, null, DATE_15_00, DATE_17_00, DATE_15_00); + + when(repository.findAllBetween(DATE_16_00, DATE_17_00)).thenReturn(Collections.emptyList()); + when(repository.findByUuid(RESERVATION_UUID)).thenReturn(reservationFromDb); + when(repository.save(reservationToReturn)).thenReturn(reservationToReturn); + when(mapper.updateRequestToModel(reservationFromDb, updateRequest)).thenReturn(reservationToReturn); + when(mapper.modelToResponse(reservationToReturn)) + .thenReturn(new ReservationResponse(RESERVATION_UUID, null, DATE_16_00, DATE_17_00)); + + try { + ReservationResponse result = service.updateReservation(updateRequest); + + assertEquals(DATE_16_00, result.getReservationFrom()); + assertEquals(DATE_17_00, result.getReservationTo()); + + verifyNoMoreInteractions(repository); + } catch (ReservationException exception) { + fail("Reservation exception should not be thrown"); + } + } + + @Test + void delete_validUuid_pass() { + service.deleteReservation(RESERVATION_UUID); + verify(repository).deleteById(RESERVATION_UUID); + } + + @Test + void getAllReservations_pass() { + when(repository.findAll(Sort.by("reservationFrom").descending())) + .thenReturn(Arrays.asList( + new Reservation(RESERVATION_UUID + "1", USERNAME, DATE_15_00, DATE_16_00, DATE_15_00), + new Reservation(RESERVATION_UUID + "2", USERNAME, DATE_16_00, DATE_17_00, DATE_16_00))); + when(mapper.modelToResponse(any(Reservation.class))) + .thenReturn( + new ReservationResponse(RESERVATION_UUID + "1", USERNAME, DATE_15_00, DATE_16_00), + new ReservationResponse(RESERVATION_UUID + "2", USERNAME, DATE_16_00, DATE_17_00)); + + List result = service.getAllReservations(); + assertThat(result.size()).isEqualTo(2); + assertThat(result.get(0).getUuid()).isEqualTo(RESERVATION_UUID + "1"); + assertThat(result.get(0).getReservationFor()).isEqualTo(USERNAME); + assertThat(result.get(0).getReservationFrom()).isEqualTo(DATE_15_00); + assertThat(result.get(0).getReservationTo()).isEqualTo(DATE_16_00); + assertThat(result.get(1).getUuid()).isEqualTo(RESERVATION_UUID + "2"); + assertThat(result.get(1).getReservationFor()).isEqualTo(USERNAME); + assertThat(result.get(1).getReservationFrom()).isEqualTo(DATE_16_00); + assertThat(result.get(1).getReservationTo()).isEqualTo(DATE_17_00); + } + + @Test + void getReservationsForUsername_pass() { + when(repository.findAllByReservationFor(USERNAME, Sort.by("reservationFrom").descending())) + .thenReturn(Arrays.asList( + new Reservation(RESERVATION_UUID + "1", USERNAME, DATE_15_00, DATE_16_00, DATE_15_00), + new Reservation(RESERVATION_UUID + "2", USERNAME, DATE_16_00, DATE_17_00, DATE_16_00))); + when(mapper.modelToResponse(any(Reservation.class))) + .thenReturn( + new ReservationResponse(RESERVATION_UUID + "1", USERNAME, DATE_15_00, DATE_16_00), + new ReservationResponse(RESERVATION_UUID + "2", USERNAME, DATE_16_00, DATE_17_00)); + + List result = service.getAllReservationsForUsername(USERNAME); + assertThat(result.size()).isEqualTo(2); + assertThat(result.get(0).getUuid()).isEqualTo(RESERVATION_UUID + "1"); + assertThat(result.get(0).getReservationFor()).isEqualTo(USERNAME); + assertThat(result.get(0).getReservationFrom()).isEqualTo(DATE_15_00); + assertThat(result.get(0).getReservationTo()).isEqualTo(DATE_16_00); + assertThat(result.get(1).getUuid()).isEqualTo(RESERVATION_UUID + "2"); + assertThat(result.get(1).getReservationFor()).isEqualTo(USERNAME); + assertThat(result.get(1).getReservationFrom()).isEqualTo(DATE_16_00); + assertThat(result.get(1).getReservationTo()).isEqualTo(DATE_17_00); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/service/UserDetailsServiceImplTests.java b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/service/UserDetailsServiceImplTests.java new file mode 100644 index 000000000..cb95ab8ed --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/service/UserDetailsServiceImplTests.java @@ -0,0 +1,57 @@ +package sk.cyrilgavala.reservationsApi.service; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import sk.cyrilgavala.reservationsApi.web.response.UserResponse; + +import java.util.Collections; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.when; + +/** + * Test cases for {@link UserDetailsServiceImpl}. + */ +@ExtendWith(MockitoExtension.class) +public class UserDetailsServiceImplTests { + + @Mock + private UserService userService; + @InjectMocks + private UserDetailsServiceImpl userDetailsService; + + @Test + void loadUserByUsername_userFound_pass() { + when(userService.getByUsername("userName")).thenReturn(new UserResponse("userId", "userName", "user@test.com", "userPassword", "USER")); + try { + UserDetails userDetails = userDetailsService.loadUserByUsername("userName"); + assertNotNull(userDetails); + assertEquals("userName", userDetails.getUsername()); + assertEquals("userPassword", userDetails.getPassword()); + assertThat(userDetails.getAuthorities()).hasSize(1).isEqualTo(Collections.unmodifiableSet(Set.of(new SimpleGrantedAuthority("USER")))); + } catch (UsernameNotFoundException ex) { + fail("Error should not be thrown"); + } + } + + @Test + void loadUserByUsername_userNotFound_errorThrown() { + when(userService.getByUsername("userName")).thenThrow(new UsernameNotFoundException("User not found with username: userName")); + try { + userDetailsService.loadUserByUsername("userName"); + fail("Error should be thrown"); + } catch (UsernameNotFoundException ex) { + assertEquals("User not found with username: userName", ex.getMessage()); + } + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/service/UserServiceImplTests.java b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/service/UserServiceImplTests.java new file mode 100644 index 000000000..40a8b4d7c --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/service/UserServiceImplTests.java @@ -0,0 +1,100 @@ +package sk.cyrilgavala.reservationsApi.service; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import sk.cyrilgavala.reservationsApi.mapper.UserMapper; +import sk.cyrilgavala.reservationsApi.model.User; +import sk.cyrilgavala.reservationsApi.repository.UserRepository; +import sk.cyrilgavala.reservationsApi.web.response.UserResponse; + +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static org.mockito.Mockito.when; + +/** + * Test cases for {@link UserServiceImpl}. + */ +@ExtendWith(MockitoExtension.class) +public class UserServiceImplTests { + + private static final String ID = "userId"; + private static final String USERNAME = "username"; + private static final String EMAIL = "user@test.com"; + private static final String PASSWORD = "userPassword"; + private static final String ROLE = "USER"; + + @Mock + private UserRepository repository; + @Mock + private UserMapper mapper; + @InjectMocks + private UserServiceImpl userService; + + @Test + void getByUsername_userFound_pass() { + User user = new User(ID, USERNAME, EMAIL, PASSWORD, ROLE); + UserResponse userResponse = new UserResponse(ID, USERNAME, EMAIL, PASSWORD, ROLE); + when(repository.findByUsername(USERNAME)).thenReturn(Optional.of(user)); + when(mapper.modelToResponse(user)).thenReturn(userResponse); + + try { + UserResponse response = userService.getByUsername(USERNAME); + assertNotNull(response); + assertEquals(ID, response.getId()); + assertEquals(USERNAME, response.getUsername()); + assertEquals(EMAIL, response.getEmail()); + assertEquals(PASSWORD, response.getPassword()); + assertEquals(ROLE, response.getRole()); + } catch (UsernameNotFoundException ex) { + fail("Error should not be thrown"); + } + } + + @Test + void getByUsername_userNotFound_errorThrown() { + when(repository.findByUsername(USERNAME)).thenReturn(Optional.empty()); + + try { + userService.getByUsername(USERNAME); + fail("Error should not be thrown"); + } catch (UsernameNotFoundException ex) { + assertEquals("User not found with username: " + USERNAME, ex.getMessage()); + } + } + + @Test + void existsByUsername() { + when(repository.existsByUsername(USERNAME)).thenReturn(true); + assertTrue(userService.existsByUsername(USERNAME)); + } + + @Test + void existsByEmail() { + when(repository.existsByEmail(EMAIL)).thenReturn(true); + assertTrue(userService.existsByEmail(EMAIL)); + } + + @Test + void saveUser() { + User user = new User(ID, USERNAME, EMAIL, PASSWORD, ROLE); + UserResponse userResponse = new UserResponse(ID, USERNAME, EMAIL, PASSWORD, ROLE); + when(repository.insert(user)).thenReturn(user); + when(mapper.modelToResponse(user)).thenReturn(userResponse); + + UserResponse response = userService.saveUser(user); + assertNotNull(response); + assertEquals(ID, response.getId()); + assertEquals(USERNAME, response.getUsername()); + assertEquals(EMAIL, response.getEmail()); + assertEquals(PASSWORD, response.getPassword()); + assertEquals(ROLE, response.getRole()); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/web/controller/ReservationRestControllerTests.java b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/web/controller/ReservationRestControllerTests.java new file mode 100644 index 000000000..445ac9c25 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/web/controller/ReservationRestControllerTests.java @@ -0,0 +1,199 @@ +package sk.cyrilgavala.reservationsApi.web.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.security.test.context.support.WithMockUser; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import sk.cyrilgavala.reservationsApi.exception.ReservationException; +import sk.cyrilgavala.reservationsApi.service.ReservationService; +import sk.cyrilgavala.reservationsApi.web.request.CreateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.request.UpdateReservationRequest; +import sk.cyrilgavala.reservationsApi.web.response.ReservationResponse; + +import java.time.LocalDateTime; +import java.util.Collections; +import java.util.List; + +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Test cases for {@link ReservationRestController}. + */ +@WebMvcTest +@ActiveProfiles("test") +public class ReservationRestControllerTests { + + private static final String UUID = "uuid"; + private static final String USERNAME = "username"; + private static final String BLANK_USERNAME = " "; + private static final LocalDateTime DATE_15_00 = LocalDateTime.of(2022, 5, 20, 15, 0, 0); + private static final LocalDateTime DATE_16_00 = LocalDateTime.of(2022, 5, 20, 16, 0, 0); + private static final String BLANK_USERNAME_ERROR_MESSAGE_GET = "getAllReservationsForUser.username: must not be blank"; + private static final String BLANK_UUID_ERROR_MESSAGE = "deleteReservation.reservationUuid: must not be blank"; + private static final String BLANK_USERNAME_ERROR_MESSAGE_POST = "Validation failed for argument"; + private static final String RESERVATION_UNPROCESSABLE_START_DATE_IS_AFTER_END_DATE = "Reservation unprocessable: start date is after end date"; + private static final String RESERVATION_UNPROCESSABLE_COVERS_ANOTHER_RESERVATION = "Reservation unprocessable: covers another reservation"; + private final ObjectMapper objectMapper = new ObjectMapper() + .registerModule(new JavaTimeModule()) + .registerModule(new Jdk8Module()) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + @MockBean + private ReservationService service; + @Autowired + private MockMvc mockMvc; + + @Test + @WithMockUser(username = USERNAME, authorities = {"USER"}) + void get_reservationsForUser_pass() throws Exception { + List response = Collections.singletonList( + new ReservationResponse(UUID, USERNAME, DATE_15_00, DATE_16_00)); + when(service.getAllReservationsForUsername(USERNAME)).thenReturn(response); + + mockMvc.perform(get("/api/reservation/" + USERNAME)) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + @WithMockUser(username = USERNAME, authorities = {"USER"}) + void get_reservationsForUser_passEmptyResponse() throws Exception { + List response = Collections.emptyList(); + when(service.getAllReservationsForUsername(USERNAME)).thenReturn(response); + + mockMvc.perform(get("/api/reservation/" + USERNAME)) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + @WithMockUser(username = USERNAME, authorities = {"USER"}) + void get_reservationsForUser_error_400() throws Exception { + List response = Collections.emptyList(); + when(service.getAllReservationsForUsername(USERNAME)).thenReturn(response); + + mockMvc.perform(get("/api/reservation/" + BLANK_USERNAME)) + .andExpect(status().isBadRequest()) + .andExpect(content().string(BLANK_USERNAME_ERROR_MESSAGE_GET)); + } + + @Test + @WithMockUser(username = USERNAME, authorities = {"ADMIN"}) + void get_reservations_pass() throws Exception { + List response = Collections.singletonList(new ReservationResponse(UUID, USERNAME, DATE_15_00, DATE_16_00)); + when(service.getAllReservations()).thenReturn(response); + + mockMvc.perform(get("/api/reservation")) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + @WithMockUser(username = USERNAME, authorities = {"USER"}) + void delete_validUuid_pass() throws Exception { + doNothing().when(service).deleteReservation(UUID); + + mockMvc.perform(delete("/api/reservation/" + UUID)) + .andExpect(status().isOk()) + .andExpect(content().string("")); + } + + @Test + @WithMockUser(username = USERNAME, authorities = {"USER"}) + void delete_blankUuid_error_400() throws Exception { + mockMvc.perform(delete("/api/reservation/" + BLANK_USERNAME)) + .andExpect(status().isBadRequest()) + .andExpect(content().string(BLANK_UUID_ERROR_MESSAGE)); + } + + @Test + @WithMockUser(username = USERNAME, authorities = {"USER"}) + void create_validRequest_pass() throws Exception { + CreateReservationRequest request = new CreateReservationRequest(USERNAME, DATE_15_00, DATE_16_00, DATE_15_00); + ReservationResponse response = new ReservationResponse(UUID, USERNAME, DATE_15_00, DATE_16_00); + when(service.createReservation(request)).thenReturn(response); + + mockMvc.perform(post("/api/reservation") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isCreated()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + @WithMockUser(username = USERNAME, authorities = {"USER"}) + void create_invalidRequest_error_400() throws Exception { + CreateReservationRequest request = new CreateReservationRequest(BLANK_USERNAME, DATE_15_00, DATE_16_00, DATE_15_00); + + boolean validResponseMessage = mockMvc.perform(post("/api/reservation") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isBadRequest()) + .andReturn().getResponse().getContentAsString().startsWith(BLANK_USERNAME_ERROR_MESSAGE_POST); + Assertions.assertTrue(validResponseMessage); + } + + @Test + @WithMockUser(username = USERNAME, authorities = {"USER"}) + void create_invalidRequest_coveringReservationPresent_422() throws Exception { + CreateReservationRequest request = new CreateReservationRequest(USERNAME, DATE_15_00, DATE_16_00, DATE_15_00); + when(service.createReservation(request)).thenThrow(new ReservationException(RESERVATION_UNPROCESSABLE_COVERS_ANOTHER_RESERVATION)); + + mockMvc.perform(post("/api/reservation") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isUnprocessableEntity()) + .andExpect(content().string(RESERVATION_UNPROCESSABLE_COVERS_ANOTHER_RESERVATION)); + } + + @Test + @WithMockUser(username = USERNAME, authorities = {"USER"}) + void create_invalidRequest_startDateAfterEndDate_422() throws Exception { + CreateReservationRequest request = new CreateReservationRequest(USERNAME, DATE_16_00, DATE_15_00, DATE_15_00); + when(service.createReservation(request)).thenThrow(new ReservationException(RESERVATION_UNPROCESSABLE_START_DATE_IS_AFTER_END_DATE)); + + mockMvc.perform(post("/api/reservation") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isUnprocessableEntity()) + .andExpect(content().string(RESERVATION_UNPROCESSABLE_START_DATE_IS_AFTER_END_DATE)); + } + + @Test + @WithMockUser(username = USERNAME, authorities = {"USER"}) + void update_validRequest_pass() throws Exception { + UpdateReservationRequest request = new UpdateReservationRequest(UUID, USERNAME, DATE_15_00, DATE_16_00); + ReservationResponse response = new ReservationResponse(UUID, USERNAME, DATE_15_00, DATE_16_00); + when(service.updateReservation(request)).thenReturn(response); + + mockMvc.perform(put("/api/reservation") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(request))) + .andExpect(status().isOk()) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/web/controller/UserRestControllerTests.java b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/web/controller/UserRestControllerTests.java new file mode 100644 index 000000000..86a11764b --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/test/java/sk/cyrilgavala/reservationsApi/web/controller/UserRestControllerTests.java @@ -0,0 +1,131 @@ +package sk.cyrilgavala.reservationsApi.web.controller; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jdk8.Jdk8Module; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; +import sk.cyrilgavala.reservationsApi.model.User; +import sk.cyrilgavala.reservationsApi.security.TokenProvider; +import sk.cyrilgavala.reservationsApi.service.UserService; +import sk.cyrilgavala.reservationsApi.web.request.LoginRequest; +import sk.cyrilgavala.reservationsApi.web.request.RegisterRequest; +import sk.cyrilgavala.reservationsApi.web.response.AuthResponse; +import sk.cyrilgavala.reservationsApi.web.response.UserResponse; + +import java.util.Base64; + +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +/** + * Test cases for {@link UserRestController}. + */ +@WebMvcTest +@ActiveProfiles("test") +public class UserRestControllerTests { + + private static final String USERNAME = "username"; + private static final String PASSWORD_ENCODED = Base64.getEncoder().encodeToString("password".getBytes()); + private static final String PASSWORD_DECODED = "password"; + private static final String PASSWORD_HASHED = "$2a$10$VmtzKs.GroqLKkd4nzhbZ.F2LS4j3qQsR5afWeiID52GpQTR/vv8S"; + private static final String EMAIL = "user@test.com"; + private static final String ACCESS_TOKEN = "thisIsGeneratedJwtAccessToken"; + private static final String ERROR_CONTENT_TYPE = "text/plain;charset=UTF-8"; + private static final String DUPLICATE_USERNAME_ERROR_MESSAGE = String.format("Username %s already been used", USERNAME); + private static final String DUPLICATE_EMAIL_ERROR_MESSAGE = String.format("Email %s already been used", EMAIL); + + private final LoginRequest loginRequest = new LoginRequest(USERNAME, PASSWORD_ENCODED); + private final RegisterRequest registerRequest = new RegisterRequest(USERNAME, EMAIL, PASSWORD_ENCODED); + + private final ObjectMapper objectMapper = new ObjectMapper() + .registerModule(new JavaTimeModule()) + .registerModule(new Jdk8Module()) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + @MockBean + private UserService userService; + @MockBean + private AuthenticationManager authenticationManager; + @MockBean + private TokenProvider tokenProvider; + @MockBean + private PasswordEncoder passwordEncoder; + @Autowired + private MockMvc mockMvc; + + @Test + void login_validRequest_pass() throws Exception { + Authentication authentication = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD_DECODED); + AuthResponse response = new AuthResponse(ACCESS_TOKEN); + when(authenticationManager.authenticate(authentication)).thenReturn(authentication); + when(tokenProvider.generate(authentication)).thenReturn(ACCESS_TOKEN); + + mockMvc.perform(post("/api/user/login") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(loginRequest))) + .andExpect(status().isOk()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } + + @Test + void register_usernameExists_409() throws Exception { + when(userService.existsByUsername(USERNAME)).thenReturn(true); + + mockMvc.perform(post("/api/user/register") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(registerRequest))) + .andExpect(status().isConflict()) + .andExpect(header().string("Content-Type", ERROR_CONTENT_TYPE)) + .andExpect(content().string(DUPLICATE_USERNAME_ERROR_MESSAGE)); + } + + @Test + void register_emailExists_409() throws Exception { + when(userService.existsByUsername(USERNAME)).thenReturn(false); + when(userService.existsByEmail(EMAIL)).thenReturn(true); + + mockMvc.perform(post("/api/user/register") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(registerRequest))) + .andExpect(status().isConflict()) + .andExpect(header().string("Content-Type", ERROR_CONTENT_TYPE)) + .andExpect(content().string(DUPLICATE_EMAIL_ERROR_MESSAGE)); + } + + @Test + void register_validRequest_pass() throws Exception { + User userToSave = new User(null, USERNAME, EMAIL, PASSWORD_HASHED, "USER"); + Authentication authentication = new UsernamePasswordAuthenticationToken(USERNAME, PASSWORD_DECODED); + AuthResponse response = new AuthResponse(ACCESS_TOKEN); + + when(userService.existsByUsername(USERNAME)).thenReturn(false); + when(userService.existsByEmail(EMAIL)).thenReturn(false); + when(passwordEncoder.encode(PASSWORD_ENCODED)).thenReturn(PASSWORD_HASHED); + when(userService.saveUser(userToSave)).thenReturn(new UserResponse()); + when(authenticationManager.authenticate(authentication)).thenReturn(authentication); + when(tokenProvider.generate(authentication)).thenReturn(ACCESS_TOKEN); + + mockMvc.perform(post("/api/user/register") + .contentType(MediaType.APPLICATION_JSON_VALUE) + .content(objectMapper.writeValueAsString(registerRequest))) + .andExpect(status().isCreated()) + .andExpect(header().string("Content-Type", MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(content().json(objectMapper.writeValueAsString(response))); + } +} diff --git a/jdk_11_gradle/cs/rest/reservations-api/src/test/resources/application-test.yaml b/jdk_11_gradle/cs/rest/reservations-api/src/test/resources/application-test.yaml new file mode 100644 index 000000000..b963833e4 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/src/test/resources/application-test.yaml @@ -0,0 +1,7 @@ +spring.application.name: 'ReservationAPI' +databaseUrl: 'mongodb://localhost:27017' +app: + jwt: + secret: 'jwt_secret' + expiration: + minutes: 60 \ No newline at end of file diff --git a/jdk_11_gradle/cs/rest/reservations-api/system.properties b/jdk_11_gradle/cs/rest/reservations-api/system.properties new file mode 100644 index 000000000..9146af538 --- /dev/null +++ b/jdk_11_gradle/cs/rest/reservations-api/system.properties @@ -0,0 +1 @@ +java.runtime.version=11 diff --git a/jdk_11_gradle/em/embedded/graphql/patio-api/build.gradle.kts b/jdk_11_gradle/em/embedded/graphql/patio-api/build.gradle.kts index 0e4c50e08..94b8a1e09 100644 --- a/jdk_11_gradle/em/embedded/graphql/patio-api/build.gradle.kts +++ b/jdk_11_gradle/em/embedded/graphql/patio-api/build.gradle.kts @@ -29,7 +29,7 @@ dependencyManagement { } } -val EVOMASTER_VERSION = "1.6.2-SNAPSHOT" +val EVOMASTER_VERSION = project.ext.get("EVOMASTER_VERSION") dependencies{ implementation("org.evomaster:evomaster-client-java-controller:$EVOMASTER_VERSION") diff --git a/jdk_11_gradle/em/embedded/rest/reservations-api/build.gradle.kts b/jdk_11_gradle/em/embedded/rest/reservations-api/build.gradle.kts new file mode 100644 index 000000000..6456118ad --- /dev/null +++ b/jdk_11_gradle/em/embedded/rest/reservations-api/build.gradle.kts @@ -0,0 +1,43 @@ + +repositories { + mavenLocal() + mavenCentral() + maven( url ="https://jcenter.bintray.com") +} + + +plugins { + `java-library` + // id("io.spring.dependency-management") version "1.0.6.RELEASE" +} + +configurations { + implementation { + resolutionStrategy.failOnVersionConflict() + } +} + +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 +} + + +//dependencyManagement { +// imports { +// // mavenBom("io.micronaut:micronaut-bom:1.3.4") +// } +//} + +val EVOMASTER_VERSION = project.ext.get("EVOMASTER_VERSION") + +dependencies{ + implementation("org.evomaster:evomaster-client-java-controller:$EVOMASTER_VERSION") + implementation("org.evomaster:evomaster-client-java-dependencies:$EVOMASTER_VERSION") + + api(project(":cs:rest:reservations-api")) + + //Gradle api() is not importing transitive dependencies??? + implementation("org.springframework.boot:spring-boot-starter-web:2.7.0") + implementation("org.mongodb:mongodb-driver-sync:4.4.2") +} \ No newline at end of file diff --git a/jdk_11_gradle/em/embedded/rest/reservations-api/src/main/java/em/embedded/reservationsapi/EmbeddedEvoMasterController.java b/jdk_11_gradle/em/embedded/rest/reservations-api/src/main/java/em/embedded/reservationsapi/EmbeddedEvoMasterController.java new file mode 100644 index 000000000..575ca5ff0 --- /dev/null +++ b/jdk_11_gradle/em/embedded/rest/reservations-api/src/main/java/em/embedded/reservationsapi/EmbeddedEvoMasterController.java @@ -0,0 +1,143 @@ +package em.embedded.reservationsapi; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import org.evomaster.client.java.controller.EmbeddedSutController; +import org.evomaster.client.java.controller.InstrumentedSutStarter; +import org.evomaster.client.java.controller.api.dto.AuthenticationDto; +import org.evomaster.client.java.controller.api.dto.SutInfoDto; +import org.evomaster.client.java.controller.internal.db.DbSpecification; +import org.evomaster.client.java.controller.problem.ProblemInfo; +import org.evomaster.client.java.controller.problem.RestProblem; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.testcontainers.containers.GenericContainer; +import sk.cyrilgavala.reservationsApi.ReservationsApi; + +import java.util.List; +import java.util.Map; + + +/** + * Class used to start/stop the SUT. This will be controller by the EvoMaster process + */ +public class EmbeddedEvoMasterController extends EmbeddedSutController { + + public static void main(String[] args) { + + int port = 40100; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } + + EmbeddedEvoMasterController controller = new EmbeddedEvoMasterController(port); + InstrumentedSutStarter starter = new InstrumentedSutStarter(controller); + + starter.start(); + } + + + private ConfigurableApplicationContext ctx; + + private static final int MONGODB_PORT = 27017; + + //https://www.mongodb.com/docs/drivers/java/sync/current/compatibility/ + private static final String MONGODB_VERSION = "4.4"; + + private static final String MONGODB_DATABASE_NAME = "Reservations"; + + private static final GenericContainer mongodbContainer = new GenericContainer("mongo:" + MONGODB_VERSION) + .withExposedPorts(MONGODB_PORT); + + private String mongoDbUrl; + + private MongoClient mongoClient; + + public EmbeddedEvoMasterController() { + this(0); + } + + public EmbeddedEvoMasterController(int port) { + setControllerPort(port); + } + + + @Override + public String startSut() { + + mongodbContainer.start(); + mongoDbUrl = "mongodb://" + mongodbContainer.getContainerIpAddress() + ":" + mongodbContainer.getMappedPort(MONGODB_PORT) + "/" + MONGODB_DATABASE_NAME; + mongoClient = MongoClients.create(mongoDbUrl); + + + + ctx = SpringApplication.run(ReservationsApi.class, + new String[]{"--server.port=0", + "--databaseUrl="+mongoDbUrl, + "--spring.data.mongodb.uri="+mongoDbUrl, + "--spring.cache.type=NONE" + }); + + return "http://localhost:" + getSutPort(); + } + + protected int getSutPort() { + return (Integer) ((Map) ctx.getEnvironment() + .getPropertySources().get("server.ports").getSource()) + .get("local.server.port"); + } + + + @Override + public boolean isSutRunning() { + return ctx != null && ctx.isRunning(); + } + + @Override + public void stopSut() { + ctx.stop(); + ctx.close(); + + mongodbContainer.stop(); + } + + @Override + public String getPackagePrefixesToCover() { + return "sk.cyrilgavala.reservationsApi."; + } + + @Override + public void resetStateOfSUT() { + mongoClient.getDatabase(MONGODB_DATABASE_NAME).drop(); + } + + @Override + public List getDbSpecifications() { + return null; + } + + + @Override + public List getInfoForAuthentication() { + //TODO might need to setup JWT headers here + return null; + } + + + + + @Override + public ProblemInfo getProblemInfo() { + return new RestProblem( + "http://localhost:" + getSutPort() + "/v3/api-docs", + null + ); + } + + @Override + public SutInfoDto.OutputFormat getPreferredOutputFormat() { + return SutInfoDto.OutputFormat.JAVA_JUNIT_4; + } + + +} diff --git a/jdk_11_gradle/em/external/graphql/patio-api/build.gradle.kts b/jdk_11_gradle/em/external/graphql/patio-api/build.gradle.kts index 97424188c..560619a4d 100644 --- a/jdk_11_gradle/em/external/graphql/patio-api/build.gradle.kts +++ b/jdk_11_gradle/em/external/graphql/patio-api/build.gradle.kts @@ -37,7 +37,7 @@ dependencyManagement { } } -val EVOMASTER_VERSION = "1.6.2-SNAPSHOT" +val EVOMASTER_VERSION = project.ext.get("EVOMASTER_VERSION") dependencies{ implementation("org.evomaster:evomaster-client-java-controller:$EVOMASTER_VERSION") diff --git a/jdk_11_gradle/em/external/rest/reservations-api/build.gradle.kts b/jdk_11_gradle/em/external/rest/reservations-api/build.gradle.kts new file mode 100644 index 000000000..83c2bf02e --- /dev/null +++ b/jdk_11_gradle/em/external/rest/reservations-api/build.gradle.kts @@ -0,0 +1,67 @@ +import org.gradle.jvm.tasks.Jar + + +repositories { + mavenLocal() + mavenCentral() + maven( url ="https://jcenter.bintray.com") +} + + +plugins { + `java-library` + // id("io.spring.dependency-management") version "1.0.6.RELEASE" + application + // id("com.github.johnrengelman.shadow") version "4.0.2" +} + +configurations { + implementation { + resolutionStrategy.failOnVersionConflict() + } +} + +java { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 +} + + +//dependencyManagement { +// imports { +// mavenBom("io.micronaut:micronaut-bom:1.3.4") +// } +//} + +val EVOMASTER_VERSION = project.ext.get("EVOMASTER_VERSION") + +dependencies{ + implementation("org.evomaster:evomaster-client-java-controller:$EVOMASTER_VERSION") + implementation("org.evomaster:evomaster-client-java-instrumentation:$EVOMASTER_VERSION") + implementation("org.evomaster:evomaster-client-java-dependencies:$EVOMASTER_VERSION") + implementation("org.mongodb:mongodb-driver-sync:4.4.2") +} + + + +val fatJar = task("fatJar", type = Jar::class) { + baseName = "${project.name}-evomaster-runner" + isZip64 = true + manifest { + attributes["Implementation-Title"] = "EM" + attributes["Implementation-Version"] = "1.0" + attributes["Main-Class"] = "em.external.reservationsapi.ExternalEvoMasterController" + attributes["Premain-Class"] = "org.evomaster.client.java.instrumentation.InstrumentingAgent" + attributes["Agent-Class"] = "org.evomaster.client.java.instrumentation.InstrumentingAgent" + attributes["Can-Redefine-Classes"] = "true" + attributes["Can-Retransform-Classes"] = "true" + } + from(configurations.runtimeClasspath.get().map{ if (it.isDirectory) it else zipTree(it) }) + with(tasks.jar.get() as CopySpec) +} + +tasks { + "build" { + dependsOn(fatJar) + } +} diff --git a/jdk_11_gradle/em/external/rest/reservations-api/src/main/java/em/external/reservationsapi/ExternalEvoMasterController.java b/jdk_11_gradle/em/external/rest/reservations-api/src/main/java/em/external/reservationsapi/ExternalEvoMasterController.java new file mode 100644 index 000000000..ee333ccf2 --- /dev/null +++ b/jdk_11_gradle/em/external/rest/reservations-api/src/main/java/em/external/reservationsapi/ExternalEvoMasterController.java @@ -0,0 +1,188 @@ +package em.external.reservationsapi; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import org.evomaster.client.java.controller.ExternalSutController; +import org.evomaster.client.java.controller.InstrumentedSutStarter; +import org.evomaster.client.java.controller.api.dto.AuthenticationDto; +import org.evomaster.client.java.controller.api.dto.SutInfoDto; +import org.evomaster.client.java.controller.internal.db.DbSpecification; +import org.evomaster.client.java.controller.problem.ProblemInfo; +import org.evomaster.client.java.controller.problem.RestProblem; +import org.testcontainers.containers.GenericContainer; + +import java.util.List; + +public class ExternalEvoMasterController extends ExternalSutController { + + + public static void main(String[] args) { + + int controllerPort = 40100; + if (args.length > 0) { + controllerPort = Integer.parseInt(args[0]); + } + int sutPort = 12345; + if (args.length > 1) { + sutPort = Integer.parseInt(args[1]); + } + String jarLocation = "cs/rest/reservations-api/build/libs"; + if (args.length > 2) { + jarLocation = args[2]; + } + if(! jarLocation.endsWith(".jar")) { + jarLocation += "/reservations-api-sut.jar"; + } + + int timeoutSeconds = 120; + if(args.length > 3){ + timeoutSeconds = Integer.parseInt(args[3]); + } + String command = "java"; + if(args.length > 4){ + command = args[4]; + } + + + ExternalEvoMasterController controller = + new ExternalEvoMasterController(controllerPort, jarLocation, + sutPort, timeoutSeconds, command); + InstrumentedSutStarter starter = new InstrumentedSutStarter(controller); + + starter.start(); + } + + private final int timeoutSeconds; + private final int sutPort; + private String jarLocation; + private static final int MONGODB_PORT = 27017; + + //https://www.mongodb.com/docs/drivers/java/sync/current/compatibility/ + private static final String MONGODB_VERSION = "4.4"; + + private static final String MONGODB_DATABASE_NAME = "Reservations"; + + private static final GenericContainer mongodbContainer = new GenericContainer("mongo:" + MONGODB_VERSION) + .withExposedPorts(MONGODB_PORT); + + private String mongoDbUrl; + + private MongoClient mongoClient; + + + public ExternalEvoMasterController(){ + this(40100, "../core/target", 12345, 120, "java"); + } + + public ExternalEvoMasterController(String jarLocation) { + this(); + this.jarLocation = jarLocation; + } + + public ExternalEvoMasterController( + int controllerPort, String jarLocation, int sutPort, int timeoutSeconds, String command + ) { + + if(jarLocation==null || jarLocation.isEmpty()){ + throw new IllegalArgumentException("Missing jar location"); + } + + + this.sutPort = sutPort; + this.jarLocation = jarLocation; + this.timeoutSeconds = timeoutSeconds; + setControllerPort(controllerPort); + setJavaCommand(command); + } + + + @Override + public String[] getInputParameters() { + return new String[]{ + "--server.port=" + sutPort, + "--databaseUrl="+mongoDbUrl, + "--spring.data.mongodb.uri="+mongoDbUrl + }; + } + + public String[] getJVMParameters() { + return new String[]{}; + } + + @Override + public String getBaseURL() { + return "http://localhost:" + sutPort; + } + + @Override + public String getPathToExecutableJar() { + return jarLocation; + } + + @Override + public String getLogMessageOfInitializedServer() { + return "Started ReservationsApi in"; + } + + @Override + public long getMaxAwaitForInitializationInSeconds() { + return timeoutSeconds; + } + + @Override + public void preStart() { + mongodbContainer.start(); + mongoDbUrl = "mongodb://" + mongodbContainer.getContainerIpAddress() + ":" + mongodbContainer.getMappedPort(MONGODB_PORT) + "/" + MONGODB_DATABASE_NAME; + mongoClient = MongoClients.create(mongoDbUrl); + } + + @Override + public void postStart() { + } + + @Override + public void resetStateOfSUT() { + mongoClient.getDatabase(MONGODB_DATABASE_NAME).drop(); + } + + @Override + public void preStop() { + } + + @Override + public void postStop() { + mongodbContainer.stop(); + } + + + + @Override + public String getPackagePrefixesToCover() { + return "sk.cyrilgavala.reservationsApi."; + } + + @Override + public ProblemInfo getProblemInfo() { + return new RestProblem( + "http://localhost:" + sutPort + "/v3/api-docs", + null + ); + } + + @Override + public SutInfoDto.OutputFormat getPreferredOutputFormat() { + return SutInfoDto.OutputFormat.JAVA_JUNIT_5; + } + + + + @Override + public List getInfoForAuthentication() { + return null; + } + + @Override + public List getDbSpecifications() { + return null; + } +} diff --git a/jdk_11_gradle/gradle/wrapper/gradle-wrapper.properties b/jdk_11_gradle/gradle/wrapper/gradle-wrapper.properties index be52383ef..da9702f9e 100644 --- a/jdk_11_gradle/gradle/wrapper/gradle-wrapper.properties +++ b/jdk_11_gradle/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/jdk_11_gradle/settings.gradle.kts b/jdk_11_gradle/settings.gradle.kts index 066fb8861..e23021156 100644 --- a/jdk_11_gradle/settings.gradle.kts +++ b/jdk_11_gradle/settings.gradle.kts @@ -2,4 +2,8 @@ rootProject.name = "emb_jdk_11_gradle" include("cs:graphql:patio-api") include("em:embedded:graphql:patio-api") -include("em:external:graphql:patio-api") \ No newline at end of file +include("em:external:graphql:patio-api") + +include("cs:rest:reservations-api") +include("em:embedded:rest:reservations-api") +include("em:external:rest:reservations-api") diff --git a/jdk_17_gradle/build.gradle b/jdk_17_gradle/build.gradle new file mode 100644 index 000000000..c1c05b9f8 --- /dev/null +++ b/jdk_17_gradle/build.gradle @@ -0,0 +1,6 @@ + +allprojects { + ext { + EVOMASTER_VERSION = "1.6.2-SNAPSHOT" + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/.checkstyle/checkstyle.xml b/jdk_17_gradle/cs/rest/bibliothek/.checkstyle/checkstyle.xml new file mode 100644 index 000000000..454e70909 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/.checkstyle/checkstyle.xml @@ -0,0 +1,281 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/jdk_17_gradle/cs/rest/bibliothek/.checkstyle/suppressions.xml b/jdk_17_gradle/cs/rest/bibliothek/.checkstyle/suppressions.xml new file mode 100644 index 000000000..f315cf91e --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/.checkstyle/suppressions.xml @@ -0,0 +1,7 @@ + + + + + + + diff --git a/jdk_17_gradle/cs/rest/bibliothek/.dockerignore b/jdk_17_gradle/cs/rest/bibliothek/.dockerignore new file mode 100644 index 000000000..c9adf3fa6 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/.dockerignore @@ -0,0 +1,10 @@ +# vim: ft=gitignore +# Everything ignored by default +* +# Only whitelist what's needed +!*.gradle.kts +!docker/ +!gradle/ +!gradlew +!license*.txt +!src/ diff --git a/jdk_17_gradle/cs/rest/bibliothek/.spotless/bibliothek.importorder b/jdk_17_gradle/cs/rest/bibliothek/.spotless/bibliothek.importorder new file mode 100644 index 000000000..5019d442a --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/.spotless/bibliothek.importorder @@ -0,0 +1,4 @@ +#Organize Import Order +#Mon Dec 05 23:26:49 PST 2022 +0= +1=\# diff --git a/jdk_17_gradle/cs/rest/bibliothek/Dockerfile b/jdk_17_gradle/cs/rest/bibliothek/Dockerfile new file mode 100644 index 000000000..65bafb395 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/Dockerfile @@ -0,0 +1,34 @@ +ARG JAVA_VERSION=17 +ARG JVM_FLAVOR=hotspot + +FROM openjdk:${JAVA_VERSION}-jdk-slim AS builder +WORKDIR /build + +COPY ./ ./ +RUN ./gradlew clean buildForDocker --no-daemon + + +ARG JAVA_VERSION +ARG JVM_FLAVOR + +FROM openjdk:${JAVA_VERSION}-slim +WORKDIR /app + +RUN groupadd --system bibliothek \ + && useradd --system bibliothek --gid bibliothek \ + && chown -R bibliothek:bibliothek /app +USER bibliothek:bibliothek + +VOLUME /data/storage +EXPOSE 8080 + +# We override default config location search path, +# so that a custom file with defaults can be used +# Normally would use environment variables, +# but they take precedence over config file +# https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/html/boot-features-external-config.html +ENV SPRING_CONFIG_LOCATION="optional:classpath:/,optional:classpath:/config/,file:./default.application.yaml,optional:file:./,optional:file:./config/" +COPY ./docker/default.application.yaml ./default.application.yaml + +COPY --from=builder /build/build/libs/docker/bibliothek.jar ./ +CMD ["java", "-jar", "/app/bibliothek.jar"] diff --git a/jdk_17_gradle/cs/rest/bibliothek/build.gradle.kts b/jdk_17_gradle/cs/rest/bibliothek/build.gradle.kts new file mode 100644 index 000000000..b92d0d787 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/build.gradle.kts @@ -0,0 +1,73 @@ +plugins { + id("java") + + alias(libs.plugins.indra) + //alias(libs.plugins.indra.checkstyle) + alias(libs.plugins.spotless) + alias(libs.plugins.spring.dependency.management) + alias(libs.plugins.spring.boot) +} + +group = "io.papermc" +version = "1.0.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +indra { + javaVersions { + target(17) + } + + github("PaperMC", "bibliothek") + mitLicense() +} + +spotless { + java { + endWithNewline() + importOrderFile(rootProject.file("cs/rest/bibliothek/.spotless/bibliothek.importorder")) + indentWithSpaces(2) + licenseHeaderFile(rootProject.file("cs/rest/bibliothek/license_header.txt")) + trimTrailingWhitespace() + } +} + +dependencies { + annotationProcessor("org.springframework.boot", "spring-boot-configuration-processor") + //checkstyle(libs.stylecheck) + implementation(libs.jetbrains.annotations) + implementation(libs.springdoc.openapi.starter.webmvc.ui) + implementation("org.springframework.boot", "spring-boot-starter-data-mongodb") + implementation("org.springframework.boot", "spring-boot-starter-validation") + implementation("org.springframework.boot", "spring-boot-starter-web") + testImplementation("org.springframework.boot", "spring-boot-starter-test") { + exclude(group = "org.junit.vintage", module = "junit-vintage-engine") + } +} + +tasks { + bootJar { + version = "" + archiveClassifier.set("sut") + launchScript() + } + + jar{ + archiveClassifier.set("plain") + } + + // From StackOverflow: https://stackoverflow.com/a/53087407 + // Licensed under: CC BY-SA 4.0 + // Adapted to Kotlin + register("buildForDocker") { + from(bootJar) + into("build/libs/docker") + rename { fileName -> + // a simple way is to remove the "-$version" from the jar filename + // but you can customize the filename replacement rule as you wish. + fileName.replace("-$version", "") + } + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/docker/default.application.yaml b/jdk_17_gradle/cs/rest/bibliothek/docker/default.application.yaml new file mode 100644 index 000000000..cf0645341 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/docker/default.application.yaml @@ -0,0 +1,8 @@ +--- +app: + # path to volume in Dockerfile - make sure to keep in sync + storagePath: "/data/storage" + apiBaseUrl: "http://localhost/api" +server: + forward-headers-strategy: "framework" + port: 8080 diff --git a/jdk_17_gradle/cs/rest/bibliothek/license.txt b/jdk_17_gradle/cs/rest/bibliothek/license.txt new file mode 100644 index 000000000..12cd1ed6c --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/license.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-2023 PaperMC + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/jdk_17_gradle/cs/rest/bibliothek/license_header.txt b/jdk_17_gradle/cs/rest/bibliothek/license_header.txt new file mode 100644 index 000000000..8c4dc2584 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/license_header.txt @@ -0,0 +1,23 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ diff --git a/jdk_17_gradle/cs/rest/bibliothek/readme.md b/jdk_17_gradle/cs/rest/bibliothek/readme.md new file mode 100644 index 000000000..9df590c5c --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/readme.md @@ -0,0 +1,3 @@ +# bibliothek + +A downloads API. diff --git a/jdk_17_gradle/cs/rest/bibliothek/settings.gradle.kts b/jdk_17_gradle/cs/rest/bibliothek/settings.gradle.kts new file mode 100644 index 000000000..33f528e53 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/settings.gradle.kts @@ -0,0 +1,5 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.5.0" +} + +rootProject.name = "bibliothek" diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/BibliothekApplication.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/BibliothekApplication.java new file mode 100644 index 000000000..1cf670f5f --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/BibliothekApplication.java @@ -0,0 +1,42 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek; + +import io.papermc.bibliothek.configuration.AppConfiguration; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.web.servlet.ServletComponentScan; + +@EnableConfigurationProperties({ + AppConfiguration.class +}) +@SpringBootApplication +@ServletComponentScan +@SuppressWarnings("checkstyle:HideUtilityClassConstructor") +public class BibliothekApplication { + public static void main(final String[] args) { + SpringApplication.run(BibliothekApplication.class, args); + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/AppConfiguration.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/AppConfiguration.java new file mode 100644 index 000000000..075442aa2 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/AppConfiguration.java @@ -0,0 +1,79 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.configuration; + +import jakarta.validation.constraints.NotNull; +import java.net.URL; +import java.nio.file.Path; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.validation.annotation.Validated; + +@ConfigurationProperties(prefix = "app") +@Validated +public class AppConfiguration { + private URL apiBaseUrl; + private String apiTitle; + private String apiVersion; + private @NotNull Path storagePath; + + @SuppressWarnings("checkstyle:MethodName") + public URL getApiBaseUrl() { + return this.apiBaseUrl; + } + + @SuppressWarnings("checkstyle:MethodName") + public void setApiBaseUrl(final URL apiBaseUrl) { + this.apiBaseUrl = apiBaseUrl; + } + + @SuppressWarnings("checkstyle:MethodName") + public String getApiTitle() { + return this.apiTitle; + } + + @SuppressWarnings("checkstyle:MethodName") + public void setApiTitle(final String apiTitle) { + this.apiTitle = apiTitle; + } + + @SuppressWarnings("checkstyle:MethodName") + public String getApiVersion() { + return this.apiVersion; + } + + @SuppressWarnings("checkstyle:MethodName") + public void setApiVersion(final String apiVersion) { + this.apiVersion = apiVersion; + } + + @SuppressWarnings("checkstyle:MethodName") + public Path getStoragePath() { + return this.storagePath; + } + + @SuppressWarnings("checkstyle:MethodName") + public void setStoragePath(final Path storagePath) { + this.storagePath = storagePath; + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/MongoConfiguration.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/MongoConfiguration.java new file mode 100644 index 000000000..b60b767be --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/MongoConfiguration.java @@ -0,0 +1,50 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.mongodb.MongoDatabaseFactory; +import org.springframework.data.mongodb.core.convert.DbRefResolver; +import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; +import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper; +import org.springframework.data.mongodb.core.convert.MappingMongoConverter; +import org.springframework.data.mongodb.core.convert.MongoCustomConversions; +import org.springframework.data.mongodb.core.mapping.MongoMappingContext; + +@Configuration +class MongoConfiguration { + @Bean + MappingMongoConverter mappingMongoConverter( + final MongoDatabaseFactory mongoDatabaseFactory, + final MongoMappingContext context, + final MongoCustomConversions mongoCustomConversions + ) { + final DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDatabaseFactory); + final MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context); + mappingConverter.setCustomConversions(mongoCustomConversions); + mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null)); // to remove _class + return mappingConverter; + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/OpenAPIConfiguration.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/OpenAPIConfiguration.java new file mode 100644 index 000000000..61528619f --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/OpenAPIConfiguration.java @@ -0,0 +1,63 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.configuration; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.servers.Server; +import java.net.URL; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import org.springdoc.core.customizers.OpenApiCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +class OpenAPIConfiguration { + @Bean + OpenAPI openAPI(final AppConfiguration configuration) { + final OpenAPI api = new OpenAPI(); + api.info( + new Info() + .title(configuration.getApiTitle()) + .version(configuration.getApiVersion()) + ); + final URL apiBaseUrl = configuration.getApiBaseUrl(); + if (apiBaseUrl != null) { + api.servers(List.of(new Server().url(apiBaseUrl.toExternalForm()))); + } + return api; + } + + @Bean + @SuppressWarnings("rawtypes") // nothing we can do, the API exposes it raw + OpenApiCustomizer sortSchemasAlphabetically() { + return openApi -> { + final Map schemas = openApi.getComponents().getSchemas(); + openApi.getComponents().setSchemas(new TreeMap<>(schemas)); + }; + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/WebConfiguration.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/WebConfiguration.java new file mode 100644 index 000000000..db2d94f17 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/configuration/WebConfiguration.java @@ -0,0 +1,37 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.configuration; + +import jakarta.servlet.Filter; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.ShallowEtagHeaderFilter; + +@Configuration +class WebConfiguration { + @Bean + Filter shallowETagHeaderFilter() { + return new ShallowEtagHeaderFilter(); + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/RootController.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/RootController.java new file mode 100644 index 000000000..0026c862a --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/RootController.java @@ -0,0 +1,43 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.controller; + +import java.net.URI; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +@Controller +public class RootController { + @GetMapping({ + "/", + "/docs" // without trailing / + }) + public ResponseEntity redirectToDocs() { + return ResponseEntity.status(HttpStatus.FOUND) + .location(URI.create("docs/")) + .build(); + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/DownloadController.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/DownloadController.java new file mode 100644 index 000000000..ebfcddd95 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/DownloadController.java @@ -0,0 +1,168 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.controller.v2; + +import io.papermc.bibliothek.configuration.AppConfiguration; +import io.papermc.bibliothek.database.model.Build; +import io.papermc.bibliothek.database.model.Project; +import io.papermc.bibliothek.database.model.Version; +import io.papermc.bibliothek.database.repository.BuildCollection; +import io.papermc.bibliothek.database.repository.ProjectCollection; +import io.papermc.bibliothek.database.repository.VersionCollection; +import io.papermc.bibliothek.exception.BuildNotFound; +import io.papermc.bibliothek.exception.DownloadFailed; +import io.papermc.bibliothek.exception.DownloadNotFound; +import io.papermc.bibliothek.exception.ProjectNotFound; +import io.papermc.bibliothek.exception.VersionNotFound; +import io.papermc.bibliothek.util.HTTP; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.headers.Header; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import jakarta.validation.constraints.Pattern; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.CacheControl; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) +@SuppressWarnings("checkstyle:FinalClass") +public class DownloadController { + private static final CacheControl CACHE = HTTP.sMaxAgePublicCache(Duration.ofDays(7)); + private final AppConfiguration configuration; + private final ProjectCollection projects; + private final VersionCollection versions; + private final BuildCollection builds; + + @Autowired + private DownloadController( + final AppConfiguration configuration, + final ProjectCollection projects, + final VersionCollection versions, + final BuildCollection builds + ) { + this.configuration = configuration; + this.projects = projects; + this.versions = versions; + this.builds = builds; + } + + @ApiResponse( + responseCode = "200", + headers = { + @Header( + name = "Content-Disposition", + description = "A header indicating that the content is expected to be displayed as an attachment, that is downloaded and saved locally.", + schema = @Schema(type = "string") + ), + @Header( + name = "ETag", + description = "An identifier for a specific version of a resource. It lets caches be more efficient and save bandwidth, as a web server does not need to resend a full response if the content has not changed.", + schema = @Schema(type = "string") + ), + @Header( + name = "Last-Modified", + description = "The date and time at which the origin server believes the resource was last modified.", + schema = @Schema(type = "string") + ) + } + ) + @GetMapping( + value = "/v2/projects/{project:[a-z]+}/versions/{version:" + Version.PATTERN + "}/builds/{build:\\d+}/downloads/{download:" + Build.Download.PATTERN + "}", + produces = { + MediaType.APPLICATION_JSON_VALUE, + HTTP.APPLICATION_JAVA_ARCHIVE_VALUE + } + ) + @Operation(summary = "Downloads the given file from a build's data.") + public ResponseEntity download( + @Parameter(name = "project", description = "The project identifier.", example = "paper") + @PathVariable("project") + @Pattern(regexp = "[a-z]+") // + final String projectName, + @Parameter(description = "A version of the project.") + @PathVariable("version") + @Pattern(regexp = Version.PATTERN) // + final String versionName, + @Parameter(description = "A build of the version.") + @PathVariable("build") + @Pattern(regexp = "\\d+") // + final int buildNumber, + @Parameter(description = "A download of the build.") + @PathVariable("download") + @Pattern(regexp = Build.Download.PATTERN) // + final String downloadName + ) { + final Project project = this.projects.findByName(projectName).orElseThrow(ProjectNotFound::new); + final Version version = this.versions.findByProjectAndName(project._id(), versionName).orElseThrow(VersionNotFound::new); + final Build build = this.builds.findByProjectAndVersionAndNumber(project._id(), version._id(), buildNumber).orElseThrow(BuildNotFound::new); + + for (final Map.Entry download : build.downloads().entrySet()) { + if (download.getValue().name().equals(downloadName)) { + try { + return new JavaArchive( + this.configuration.getStoragePath() + .resolve(project.name()) + .resolve(version.name()) + .resolve(String.valueOf(build.number())) + .resolve(download.getValue().name()), + CACHE + ); + } catch (final IOException e) { + throw new DownloadFailed(e); + } + } + } + throw new DownloadNotFound(); + } + + private static class JavaArchive extends ResponseEntity { + JavaArchive(final Path path, final CacheControl cache) throws IOException { + super(new FileSystemResource(path), headersFor(path, cache), HttpStatus.OK); + } + + private static HttpHeaders headersFor(final Path path, final CacheControl cache) throws IOException { + final HttpHeaders headers = new HttpHeaders(); + headers.setCacheControl(cache); + headers.setContentDisposition(HTTP.attachmentDisposition(path.getFileName())); + headers.setContentType(HTTP.APPLICATION_JAVA_ARCHIVE); + headers.setLastModified(Files.getLastModifiedTime(path).toInstant()); + return headers; + } + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/ProjectController.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/ProjectController.java new file mode 100644 index 000000000..0016f3853 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/ProjectController.java @@ -0,0 +1,111 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.controller.v2; + +import io.papermc.bibliothek.database.model.Project; +import io.papermc.bibliothek.database.model.Version; +import io.papermc.bibliothek.database.model.VersionFamily; +import io.papermc.bibliothek.database.repository.ProjectCollection; +import io.papermc.bibliothek.database.repository.VersionCollection; +import io.papermc.bibliothek.database.repository.VersionFamilyCollection; +import io.papermc.bibliothek.exception.ProjectNotFound; +import io.papermc.bibliothek.util.HTTP; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import jakarta.validation.constraints.Pattern; +import java.time.Duration; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.CacheControl; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) +@SuppressWarnings("checkstyle:FinalClass") +public class ProjectController { + private static final CacheControl CACHE = HTTP.sMaxAgePublicCache(Duration.ofMinutes(30)); + private final ProjectCollection projects; + private final VersionFamilyCollection families; + private final VersionCollection versions; + + @Autowired + private ProjectController( + final ProjectCollection projects, + final VersionFamilyCollection families, + final VersionCollection versions + ) { + this.projects = projects; + this.families = families; + this.versions = versions; + } + + @ApiResponse( + content = @Content( + schema = @Schema(implementation = ProjectResponse.class) + ), + responseCode = "200" + ) + @GetMapping("/v2/projects/{project:[a-z]+}") + @Operation(summary = "Gets information about a project.") + public ResponseEntity project( + @Parameter(name = "project", description = "The project identifier.", example = "paper") + @PathVariable("project") + @Pattern(regexp = "[a-z]+") // + final String projectName + ) { + final Project project = this.projects.findByName(projectName).orElseThrow(ProjectNotFound::new); + final List families = this.families.findAllByProject(project._id()); + final List versions = this.versions.findAllByProject(project._id()); + return HTTP.cachedOk(ProjectResponse.from(project, families, versions), CACHE); + } + + @Schema + private record ProjectResponse( + @Schema(name = "project_id", pattern = "[a-z]+", example = "paper") + String project_id, + @Schema(name = "project_name", example = "Paper") + String project_name, + @Schema(name = "version_groups") + List version_groups, + @Schema(name = "versions") + List versions + ) { + static ProjectResponse from(final Project project, final List families, final List versions) { + return new ProjectResponse( + project.name(), + project.friendlyName(), + families.stream().sorted(VersionFamily.COMPARATOR).map(VersionFamily::name).toList(), + versions.stream().sorted(Version.COMPARATOR).map(Version::name).toList() + ); + } + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/ProjectsController.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/ProjectsController.java new file mode 100644 index 000000000..ab805e7b6 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/ProjectsController.java @@ -0,0 +1,77 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.controller.v2; + +import io.papermc.bibliothek.database.model.Project; +import io.papermc.bibliothek.database.repository.ProjectCollection; +import io.papermc.bibliothek.util.HTTP; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import java.time.Duration; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.CacheControl; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) +@SuppressWarnings("checkstyle:FinalClass") +public class ProjectsController { + private static final CacheControl CACHE = HTTP.sMaxAgePublicCache(Duration.ofDays(7)); + private final ProjectCollection projects; + + @Autowired + private ProjectsController(final ProjectCollection projects) { + this.projects = projects; + } + + @ApiResponse( + content = @Content( + schema = @Schema(implementation = ProjectsResponse.class) + ), + responseCode = "200" + ) + @GetMapping("/v2/projects") + @Operation(summary = "Gets a list of all available projects.") + public ResponseEntity projects() { + final List projects = this.projects.findAll(); + return HTTP.cachedOk(ProjectsResponse.from(projects), CACHE); + } + + @Schema + private record ProjectsResponse( + @Schema(name = "projects") + List projects + ) { + static ProjectsResponse from(final List projects) { + return new ProjectsResponse(projects.stream().map(Project::name).toList()); + } + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionBuildController.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionBuildController.java new file mode 100644 index 000000000..a0ac6eaf0 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionBuildController.java @@ -0,0 +1,138 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.controller.v2; + +import io.papermc.bibliothek.database.model.Build; +import io.papermc.bibliothek.database.model.Project; +import io.papermc.bibliothek.database.model.Version; +import io.papermc.bibliothek.database.repository.BuildCollection; +import io.papermc.bibliothek.database.repository.ProjectCollection; +import io.papermc.bibliothek.database.repository.VersionCollection; +import io.papermc.bibliothek.exception.BuildNotFound; +import io.papermc.bibliothek.exception.ProjectNotFound; +import io.papermc.bibliothek.exception.VersionNotFound; +import io.papermc.bibliothek.util.HTTP; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import jakarta.validation.constraints.Pattern; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.CacheControl; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) +@SuppressWarnings("checkstyle:FinalClass") +public class VersionBuildController { + private static final CacheControl CACHE = HTTP.sMaxAgePublicCache(Duration.ofDays(7)); + private final ProjectCollection projects; + private final VersionCollection versions; + private final BuildCollection builds; + + @Autowired + private VersionBuildController( + final ProjectCollection projects, + final VersionCollection versions, + final BuildCollection builds + ) { + this.projects = projects; + this.versions = versions; + this.builds = builds; + } + + @ApiResponse( + content = @Content( + schema = @Schema(implementation = BuildResponse.class) + ), + responseCode = "200" + ) + @GetMapping("/v2/projects/{project:[a-z]+}/versions/{version:" + Version.PATTERN + "}/builds/{build:\\d+}") + @Operation(summary = "Gets information related to a specific build.") + public ResponseEntity build( + @Parameter(name = "project", description = "The project identifier.", example = "paper") + @PathVariable("project") + @Pattern(regexp = "[a-z]+") // + final String projectName, + @Parameter(description = "A version of the project.") + @PathVariable("version") + @Pattern(regexp = Version.PATTERN) // + final String versionName, + @Parameter(description = "A build of the version.") + @PathVariable("build") + @Pattern(regexp = "\\d+") // + final int buildNumber + ) { + final Project project = this.projects.findByName(projectName).orElseThrow(ProjectNotFound::new); + final Version version = this.versions.findByProjectAndName(project._id(), versionName).orElseThrow(VersionNotFound::new); + final Build build = this.builds.findByProjectAndVersionAndNumber(project._id(), version._id(), buildNumber).orElseThrow(BuildNotFound::new); + return HTTP.cachedOk(BuildResponse.from(project, version, build), CACHE); + } + + @Schema + private record BuildResponse( + @Schema(name = "project_id", pattern = "[a-z]+", example = "paper") + String project_id, + @Schema(name = "project_name", example = "Paper") + String project_name, + @Schema(name = "version", pattern = Version.PATTERN, example = "1.18") + String version, + @Schema(name = "build", pattern = "\\d+", example = "10") + int build, + @Schema(name = "time") + Instant time, + @Schema(name = "channel") + Build.Channel channel, + @Schema(name = "promoted") + boolean promoted, + @Schema(name = "changes") + List changes, + @Schema(name = "downloads") + Map downloads + ) { + static BuildResponse from(final Project project, final Version version, final Build build) { + return new BuildResponse( + project.name(), + project.friendlyName(), + version.name(), + build.number(), + build.time(), + build.channelOrDefault(), + build.promotedOrDefault(), + build.changes(), + build.downloads() + ); + } + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionBuildsController.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionBuildsController.java new file mode 100644 index 000000000..e41327fa0 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionBuildsController.java @@ -0,0 +1,142 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.controller.v2; + +import io.papermc.bibliothek.database.model.Build; +import io.papermc.bibliothek.database.model.Project; +import io.papermc.bibliothek.database.model.Version; +import io.papermc.bibliothek.database.repository.BuildCollection; +import io.papermc.bibliothek.database.repository.ProjectCollection; +import io.papermc.bibliothek.database.repository.VersionCollection; +import io.papermc.bibliothek.exception.ProjectNotFound; +import io.papermc.bibliothek.exception.VersionNotFound; +import io.papermc.bibliothek.util.HTTP; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import jakarta.validation.constraints.Pattern; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.CacheControl; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) +@SuppressWarnings("checkstyle:FinalClass") +public class VersionBuildsController { + private static final CacheControl CACHE = HTTP.sMaxAgePublicCache(Duration.ofMinutes(5)); + private final ProjectCollection projects; + private final VersionCollection versions; + private final BuildCollection builds; + + @Autowired + private VersionBuildsController( + final ProjectCollection projects, + final VersionCollection versions, + final BuildCollection builds + ) { + this.projects = projects; + this.versions = versions; + this.builds = builds; + } + + @ApiResponse( + content = @Content( + schema = @Schema(implementation = BuildsResponse.class) + ), + responseCode = "200" + ) + @GetMapping("/v2/projects/{project:[a-z]+}/versions/{version:" + Version.PATTERN + "}/builds") + @Operation(summary = "Gets all available builds for a project's version.") + public ResponseEntity builds( + @Parameter(name = "project", description = "The project identifier.", example = "paper") + @PathVariable("project") + @Pattern(regexp = "[a-z]+") // + final String projectName, + @Parameter(description = "A version of the project.") + @PathVariable("version") + @Pattern(regexp = Version.PATTERN) // + final String versionName + ) { + final Project project = this.projects.findByName(projectName).orElseThrow(ProjectNotFound::new); + final Version version = this.versions.findByProjectAndName(project._id(), versionName).orElseThrow(VersionNotFound::new); + final List builds = this.builds.findAllByProjectAndVersion(project._id(), version._id()); + return HTTP.cachedOk(BuildsResponse.from(project, version, builds), CACHE); + } + + @Schema + private record BuildsResponse( + @Schema(name = "project_id", pattern = "[a-z]+", example = "paper") + String project_id, + @Schema(name = "project_name", example = "Paper") + String project_name, + @Schema(name = "version", pattern = Version.PATTERN, example = "1.18") + String version, + @Schema(name = "builds") + List builds + ) { + static BuildsResponse from(final Project project, final Version version, final List builds) { + return new BuildsResponse( + project.name(), + project.friendlyName(), + version.name(), + builds.stream().map(build -> new VersionBuild( + build.number(), + build.time(), + build.channelOrDefault(), + build.promotedOrDefault(), + build.changes(), + build.downloads() + )).toList() + ); + } + + @Schema + public record VersionBuild( + @Schema(name = "build", pattern = "\\d+", example = "10") + int build, + @Schema(name = "time") + Instant time, + @Schema(name = "channel") + Build.Channel channel, + @Schema(name = "promoted") + boolean promoted, + @Schema(name = "changes") + List changes, + @Schema(name = "downloads") + Map downloads + ) { + } + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionController.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionController.java new file mode 100644 index 000000000..b1cbb9d97 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionController.java @@ -0,0 +1,116 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.controller.v2; + +import io.papermc.bibliothek.database.model.Build; +import io.papermc.bibliothek.database.model.Project; +import io.papermc.bibliothek.database.model.Version; +import io.papermc.bibliothek.database.repository.BuildCollection; +import io.papermc.bibliothek.database.repository.ProjectCollection; +import io.papermc.bibliothek.database.repository.VersionCollection; +import io.papermc.bibliothek.exception.ProjectNotFound; +import io.papermc.bibliothek.exception.VersionNotFound; +import io.papermc.bibliothek.util.HTTP; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import jakarta.validation.constraints.Pattern; +import java.time.Duration; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.CacheControl; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) +@SuppressWarnings("checkstyle:FinalClass") +public class VersionController { + private static final CacheControl CACHE = HTTP.sMaxAgePublicCache(Duration.ofMinutes(5)); + private final ProjectCollection projects; + private final VersionCollection versions; + private final BuildCollection builds; + + @Autowired + private VersionController( + final ProjectCollection projects, + final VersionCollection versions, + final BuildCollection builds + ) { + this.projects = projects; + this.versions = versions; + this.builds = builds; + } + + @ApiResponse( + content = @Content( + schema = @Schema(implementation = VersionResponse.class) + ), + responseCode = "200" + ) + @GetMapping("/v2/projects/{project:[a-z]+}/versions/{version:" + Version.PATTERN + "}") + @Operation(summary = "Gets information about a version.") + public ResponseEntity version( + @Parameter(name = "project", description = "The project identifier.", example = "paper") + @PathVariable("project") + @Pattern(regexp = "[a-z]+") // + final String projectName, + @Parameter(description = "A version of the project.") + @PathVariable("version") + @Pattern(regexp = Version.PATTERN) // + final String versionName + ) { + final Project project = this.projects.findByName(projectName).orElseThrow(ProjectNotFound::new); + final Version version = this.versions.findByProjectAndName(project._id(), versionName).orElseThrow(VersionNotFound::new); + final List builds = this.builds.findAllByProjectAndVersion(project._id(), version._id()); + return HTTP.cachedOk(VersionResponse.from(project, version, builds), CACHE); + } + + @Schema + private record VersionResponse( + @Schema(name = "project_id", pattern = "[a-z]+", example = "paper") + String project_id, + @Schema(name = "project_name", example = "Paper") + String project_name, + @Schema(name = "version", pattern = Version.PATTERN, example = "1.18") + String version, + @Schema(name = "builds") + List builds + ) { + static VersionResponse from(final Project project, final Version version, final List builds) { + return new VersionResponse( + project.name(), + project.friendlyName(), + version.name(), + builds.stream().map(Build::number).toList() + ); + } + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionFamilyBuildsController.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionFamilyBuildsController.java new file mode 100644 index 000000000..c1d57334f --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionFamilyBuildsController.java @@ -0,0 +1,158 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.controller.v2; + +import io.papermc.bibliothek.database.model.Build; +import io.papermc.bibliothek.database.model.Project; +import io.papermc.bibliothek.database.model.Version; +import io.papermc.bibliothek.database.model.VersionFamily; +import io.papermc.bibliothek.database.repository.BuildCollection; +import io.papermc.bibliothek.database.repository.ProjectCollection; +import io.papermc.bibliothek.database.repository.VersionCollection; +import io.papermc.bibliothek.database.repository.VersionFamilyCollection; +import io.papermc.bibliothek.exception.ProjectNotFound; +import io.papermc.bibliothek.exception.VersionNotFound; +import io.papermc.bibliothek.util.HTTP; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import jakarta.validation.constraints.Pattern; +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; +import org.bson.types.ObjectId; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.CacheControl; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) +@SuppressWarnings("checkstyle:FinalClass") +public class VersionFamilyBuildsController { + private static final CacheControl CACHE = HTTP.sMaxAgePublicCache(Duration.ofMinutes(5)); + private final ProjectCollection projects; + private final VersionFamilyCollection families; + private final VersionCollection versions; + private final BuildCollection builds; + + @Autowired + private VersionFamilyBuildsController( + final ProjectCollection projects, + final VersionFamilyCollection families, + final VersionCollection versions, + final BuildCollection builds + ) { + this.projects = projects; + this.families = families; + this.versions = versions; + this.builds = builds; + } + + @ApiResponse( + content = @Content( + schema = @Schema(implementation = VersionFamilyBuildsResponse.class) + ), + responseCode = "200" + ) + @GetMapping("/v2/projects/{project:[a-z]+}/version_group/{family:" + Version.PATTERN + "}/builds") + @Operation(summary = "Gets all available builds for a project's version group.") + public ResponseEntity familyBuilds( + @Parameter(name = "project", description = "The project identifier.", example = "paper") + @PathVariable("project") + @Pattern(regexp = "[a-z]+") // + final String projectName, + @Parameter(description = "The version group name.") + @PathVariable("family") + @Pattern(regexp = Version.PATTERN) // + final String familyName + ) { + final Project project = this.projects.findByName(projectName).orElseThrow(ProjectNotFound::new); + final VersionFamily family = this.families.findByProjectAndName(project._id(), familyName).orElseThrow(VersionNotFound::new); + final Map versions = this.versions.findAllByProjectAndGroup(project._id(), family._id()).stream() + .collect(Collectors.toMap(Version::_id, Function.identity())); + final List builds = this.builds.findAllByProjectAndVersionIn(project._id(), versions.keySet()); + return HTTP.cachedOk(VersionFamilyBuildsResponse.from(project, family, versions, builds), CACHE); + } + + @Schema + private record VersionFamilyBuildsResponse( + @Schema(name = "project_id", pattern = "[a-z]+", example = "paper") + String project_id, + @Schema(name = "project_name", example = "Paper") + String project_name, + @Schema(name = "version_group", pattern = Version.PATTERN, example = "1.18") + String version_group, + @Schema(name = "versions") + List versions, + @Schema(name = "builds") + List builds + ) { + static VersionFamilyBuildsResponse from(final Project project, final VersionFamily family, final Map versions, final List builds) { + return new VersionFamilyBuildsResponse( + project.name(), + project.friendlyName(), + family.name(), + versions.values().stream().sorted(Version.COMPARATOR).map(Version::name).toList(), + builds.stream().map(build -> new VersionFamilyBuild( + versions.get(build.version()).name(), + build.number(), + build.time(), + build.channelOrDefault(), + build.promotedOrDefault(), + build.changes(), + build.downloads() + )).toList() + ); + } + + @Schema + public static record VersionFamilyBuild( + @Schema(name = "version", pattern = Version.PATTERN, example = "1.18") + String version, + @Schema(name = "build", pattern = "\\d+", example = "10") + int build, + @Schema(name = "time") + Instant time, + @Schema(name = "channel") + Build.Channel channel, + @Schema(name = "promoted") + boolean promoted, + @Schema(name = "changes") + List changes, + @Schema(name = "downloads") + Map downloads + ) { + } + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionFamilyController.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionFamilyController.java new file mode 100644 index 000000000..b84bd882a --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/controller/v2/VersionFamilyController.java @@ -0,0 +1,116 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.controller.v2; + +import io.papermc.bibliothek.database.model.Project; +import io.papermc.bibliothek.database.model.Version; +import io.papermc.bibliothek.database.model.VersionFamily; +import io.papermc.bibliothek.database.repository.ProjectCollection; +import io.papermc.bibliothek.database.repository.VersionCollection; +import io.papermc.bibliothek.database.repository.VersionFamilyCollection; +import io.papermc.bibliothek.exception.ProjectNotFound; +import io.papermc.bibliothek.exception.VersionNotFound; +import io.papermc.bibliothek.util.HTTP; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import jakarta.validation.constraints.Pattern; +import java.time.Duration; +import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.CacheControl; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE) +@SuppressWarnings("checkstyle:FinalClass") +public class VersionFamilyController { + private static final CacheControl CACHE = HTTP.sMaxAgePublicCache(Duration.ofMinutes(5)); + private final ProjectCollection projects; + private final VersionFamilyCollection families; + private final VersionCollection versions; + + @Autowired + private VersionFamilyController( + final ProjectCollection projects, + final VersionFamilyCollection families, + final VersionCollection versions + ) { + this.projects = projects; + this.families = families; + this.versions = versions; + } + + @ApiResponse( + content = @Content( + schema = @Schema(implementation = VersionFamilyResponse.class) + ), + responseCode = "200" + ) + @GetMapping("/v2/projects/{project:[a-z]+}/version_group/{family:" + Version.PATTERN + "}") + @Operation(summary = "Gets information about a project's version group.") + public ResponseEntity family( + @Parameter(name = "project", description = "The project identifier.", example = "paper") + @PathVariable("project") + @Pattern(regexp = "[a-z]+") // + final String projectName, + @Parameter(description = "The version group name.") + @PathVariable("family") + @Pattern(regexp = Version.PATTERN) // + final String familyName + ) { + final Project project = this.projects.findByName(projectName).orElseThrow(ProjectNotFound::new); + final VersionFamily family = this.families.findByProjectAndName(project._id(), familyName).orElseThrow(VersionNotFound::new); + final List versions = this.versions.findAllByProjectAndGroup(project._id(), family._id()); + return HTTP.cachedOk(VersionFamilyResponse.from(project, family, versions), CACHE); + } + + @Schema + private record VersionFamilyResponse( + @Schema(name = "project_id", pattern = "[a-z]+", example = "paper") + String project_id, + @Schema(name = "project_name", example = "Paper") + String project_name, + @Schema(name = "version_group", pattern = Version.PATTERN, example = "1.18") + String version_group, + @Schema(name = "versions") + List versions + ) { + static VersionFamilyResponse from(final Project project, final VersionFamily family, final List versions) { + return new VersionFamilyResponse( + project.name(), + project.friendlyName(), + family.name(), + versions.stream().sorted(Version.COMPARATOR).map(Version::name).toList() + ); + } + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/Build.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/Build.java new file mode 100644 index 000000000..0f7c53fbb --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/Build.java @@ -0,0 +1,93 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.database.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.v3.oas.annotations.media.Schema; +import java.time.Instant; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.bson.types.ObjectId; +import org.intellij.lang.annotations.Language; +import org.jetbrains.annotations.Nullable; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.mapping.Document; + +@CompoundIndex(def = "{'project': 1, 'version': 1}") +@CompoundIndex(def = "{'project': 1, 'version': 1, 'number': 1}") +@Document(collection = "builds") +public record Build( + @Id ObjectId _id, + ObjectId project, + ObjectId version, + int number, + Instant time, + List changes, + Map downloads, + @JsonProperty + @Nullable Channel channel, + @JsonInclude(JsonInclude.Include.NON_NULL) + @Nullable Boolean promoted +) { + public Channel channelOrDefault() { + return Objects.requireNonNullElse(this.channel(), Build.Channel.DEFAULT); + } + + public boolean promotedOrDefault() { + return Objects.requireNonNullElse(this.promoted(), false); + } + + public enum Channel { + @JsonProperty("default") + DEFAULT, + @JsonProperty("experimental") + EXPERIMENTAL; + } + + @Schema + public record Change( + @Schema(name = "commit") + String commit, + @Schema(name = "summary") + String summary, + @Schema(name = "message") + String message + ) { + } + + @Schema + public record Download( + @Schema(name = "name", pattern = "[a-z0-9._-]+", example = "paper-1.18-10.jar") + String name, + @Schema(name = "sha256", pattern = "[a-f0-9]{64}", example = "f065e2d345d9d772d5cf2a1ce5c495c4cc56eb2fcd6820e82856485fa19414c8") + String sha256 + ) { + // NOTE: this pattern cannot contain any capturing groups + @Language("RegExp") + public static final String PATTERN = "[a-zA-Z0-9._-]+"; + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/Project.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/Project.java new file mode 100644 index 000000000..1308c9a91 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/Project.java @@ -0,0 +1,37 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.database.model; + +import org.bson.types.ObjectId; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.Indexed; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document(collection = "projects") +public record Project( + @Id ObjectId _id, + @Indexed String name, + String friendlyName +) { +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/Version.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/Version.java new file mode 100644 index 000000000..fa6d48c85 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/Version.java @@ -0,0 +1,52 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.database.model; + +import io.papermc.bibliothek.util.BringOrderToChaos; +import io.papermc.bibliothek.util.NameSource; +import io.papermc.bibliothek.util.TimeSource; +import java.time.Instant; +import java.util.Comparator; +import org.bson.types.ObjectId; +import org.intellij.lang.annotations.Language; +import org.jetbrains.annotations.Nullable; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.mapping.Document; + +@CompoundIndex(def = "{'project': 1, 'group': 1}") +@CompoundIndex(def = "{'project': 1, 'name': 1}") +@Document(collection = "versions") +public record Version( + @Id ObjectId _id, + ObjectId project, + ObjectId group, + String name, + @Nullable Instant time +) implements NameSource, TimeSource { + // NOTE: this pattern cannot contain any capturing groups + @Language("RegExp") + public static final String PATTERN = "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?"; + public static final Comparator COMPARATOR = BringOrderToChaos.timeOrNameComparator(); +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/VersionFamily.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/VersionFamily.java new file mode 100644 index 000000000..beb0ed600 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/model/VersionFamily.java @@ -0,0 +1,46 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.database.model; + +import io.papermc.bibliothek.util.BringOrderToChaos; +import io.papermc.bibliothek.util.NameSource; +import io.papermc.bibliothek.util.TimeSource; +import java.time.Instant; +import java.util.Comparator; +import org.bson.types.ObjectId; +import org.jetbrains.annotations.Nullable; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.index.CompoundIndex; +import org.springframework.data.mongodb.core.mapping.Document; + +@CompoundIndex(def = "{'project': 1, 'name': 1}") +@Document(collection = "version_groups") +public record VersionFamily( + @Id ObjectId _id, + ObjectId project, + String name, + @Nullable Instant time +) implements NameSource, TimeSource { + public static final Comparator COMPARATOR = BringOrderToChaos.timeOrNameComparator(); +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/BuildCollection.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/BuildCollection.java new file mode 100644 index 000000000..0b82be17f --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/BuildCollection.java @@ -0,0 +1,41 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.database.repository; + +import io.papermc.bibliothek.database.model.Build; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import org.bson.types.ObjectId; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface BuildCollection extends MongoRepository { + List findAllByProjectAndVersion(final ObjectId project, final ObjectId version); + + List findAllByProjectAndVersionIn(final ObjectId project, final Collection version); + + Optional findByProjectAndVersionAndNumber(final ObjectId project, final ObjectId version, final int number); +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/ProjectCollection.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/ProjectCollection.java new file mode 100644 index 000000000..e71bc54c7 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/ProjectCollection.java @@ -0,0 +1,35 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.database.repository; + +import io.papermc.bibliothek.database.model.Project; +import java.util.Optional; +import org.bson.types.ObjectId; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ProjectCollection extends MongoRepository { + Optional findByName(final String name); +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/VersionCollection.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/VersionCollection.java new file mode 100644 index 000000000..f75e46e9e --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/VersionCollection.java @@ -0,0 +1,40 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.database.repository; + +import io.papermc.bibliothek.database.model.Version; +import java.util.List; +import java.util.Optional; +import org.bson.types.ObjectId; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface VersionCollection extends MongoRepository { + List findAllByProject(final ObjectId project); + + List findAllByProjectAndGroup(final ObjectId project, final ObjectId group); + + Optional findByProjectAndName(final ObjectId project, final String name); +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/VersionFamilyCollection.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/VersionFamilyCollection.java new file mode 100644 index 000000000..c598af3b4 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/database/repository/VersionFamilyCollection.java @@ -0,0 +1,38 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.database.repository; + +import io.papermc.bibliothek.database.model.VersionFamily; +import java.util.List; +import java.util.Optional; +import org.bson.types.ObjectId; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface VersionFamilyCollection extends MongoRepository { + List findAllByProject(final ObjectId project); + + Optional findByProjectAndName(final ObjectId project, final String name); +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/Advice.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/Advice.java new file mode 100644 index 000000000..fbf34e842 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/Advice.java @@ -0,0 +1,88 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.exception; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.servlet.NoHandlerFoundException; + +@ControllerAdvice +@SuppressWarnings("checkstyle:FinalClass") +class Advice { + private final ObjectMapper json; + + @Autowired + private Advice(final ObjectMapper json) { + this.json = json; + } + + @ExceptionHandler(BuildNotFound.class) + @ResponseBody + public ResponseEntity buildNotFound(final BuildNotFound exception) { + return this.error(HttpStatus.NOT_FOUND, "Build not found."); + } + + @ExceptionHandler(DownloadFailed.class) + @ResponseBody + public ResponseEntity downloadFailed(final DownloadFailed exception) { + return this.error(HttpStatus.INTERNAL_SERVER_ERROR, "An internal error occurred while serving your download."); + } + + @ExceptionHandler(DownloadNotFound.class) + @ResponseBody + public ResponseEntity downloadNotFound(final DownloadNotFound exception) { + return this.error(HttpStatus.NOT_FOUND, "Download not found."); + } + + @ExceptionHandler(ProjectNotFound.class) + @ResponseBody + public ResponseEntity projectNotFound(final ProjectNotFound exception) { + return this.error(HttpStatus.NOT_FOUND, "Project not found."); + } + + @ExceptionHandler(VersionNotFound.class) + @ResponseBody + public ResponseEntity versionNotFound(final VersionNotFound exception) { + return this.error(HttpStatus.NOT_FOUND, "Version not found."); + } + + @ExceptionHandler(NoHandlerFoundException.class) + @ResponseBody + public ResponseEntity endpointNotFound(final NoHandlerFoundException exception) { + return this.error(HttpStatus.NOT_FOUND, "Endpoint not found."); + } + + private ResponseEntity error(final HttpStatus status, final String error) { + return new ResponseEntity<>( + this.json.createObjectNode() + .put("error", error), + status + ); + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/BuildNotFound.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/BuildNotFound.java new file mode 100644 index 000000000..dd1bc056e --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/BuildNotFound.java @@ -0,0 +1,31 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.exception; + +import java.io.Serial; + +public class BuildNotFound extends RuntimeException { + @Serial + private static final long serialVersionUID = 4345323173317573160L; +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/DownloadFailed.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/DownloadFailed.java new file mode 100644 index 000000000..d25169721 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/DownloadFailed.java @@ -0,0 +1,35 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.exception; + +import java.io.Serial; + +public class DownloadFailed extends RuntimeException { + @Serial + private static final long serialVersionUID = -1573093686056663600L; + + public DownloadFailed(final Throwable cause) { + super(cause); + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/DownloadNotFound.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/DownloadNotFound.java new file mode 100644 index 000000000..272148518 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/DownloadNotFound.java @@ -0,0 +1,31 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.exception; + +import java.io.Serial; + +public class DownloadNotFound extends RuntimeException { + @Serial + private static final long serialVersionUID = -1709491048606353671L; +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/ProjectNotFound.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/ProjectNotFound.java new file mode 100644 index 000000000..05a2ca666 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/ProjectNotFound.java @@ -0,0 +1,31 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.exception; + +import java.io.Serial; + +public class ProjectNotFound extends RuntimeException { + @Serial + private static final long serialVersionUID = 210738408624095602L; +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/VersionNotFound.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/VersionNotFound.java new file mode 100644 index 000000000..7b52785f3 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/exception/VersionNotFound.java @@ -0,0 +1,31 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.exception; + +import java.io.Serial; + +public class VersionNotFound extends RuntimeException { + @Serial + private static final long serialVersionUID = 1716350953824887164L; +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/filter/CorsFilter.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/filter/CorsFilter.java new file mode 100644 index 000000000..bd23d732c --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/filter/CorsFilter.java @@ -0,0 +1,45 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.filter; + +import jakarta.servlet.Filter; +import jakarta.servlet.FilterChain; +import jakarta.servlet.ServletException; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.annotation.WebFilter; +import jakarta.servlet.http.HttpServletResponse; +import java.io.IOException; + +@WebFilter("/*") +public class CorsFilter implements Filter { + + @Override + public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException { + final HttpServletResponse httpServletResponse = (HttpServletResponse) response; + httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); + httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET"); + chain.doFilter(request, response); + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/BringOrderToChaos.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/BringOrderToChaos.java new file mode 100644 index 000000000..e325378fb --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/BringOrderToChaos.java @@ -0,0 +1,49 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.util; + +import java.time.Instant; +import java.util.Comparator; +import java.util.Objects; + +public final class BringOrderToChaos { + private BringOrderToChaos() { + } + + public static Comparator timeOrNameComparator() { + return (o1, o2) -> { + final Instant t1 = o1.time(); + final Instant t2 = o2.time(); + // Both objects are not guaranteed to have a time present, but are guaranteed + // to have a name present - we prefer to compare them by time, but in cases where + // the time is not available on both objects we will compare them using their name + if (t1 != null && t2 != null) { + return t1.compareTo(t2); + } + final String n1 = Objects.requireNonNull(o1.name(), () -> "name of " + o1); + final String n2 = Objects.requireNonNull(o2.name(), () -> "name of " + o2); + return n1.compareTo(n2); + }; + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/HTTP.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/HTTP.java new file mode 100644 index 000000000..de7ec7665 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/HTTP.java @@ -0,0 +1,54 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.util; + +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.time.Duration; +import org.springframework.http.CacheControl; +import org.springframework.http.ContentDisposition; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +public final class HTTP { + public static final String APPLICATION_JAVA_ARCHIVE_VALUE = "application/java-archive"; + public static final MediaType APPLICATION_JAVA_ARCHIVE = new MediaType("application", "java-archive"); + + private HTTP() { + } + + public static ResponseEntity cachedOk(final T response, final CacheControl cache) { + return ResponseEntity.ok().cacheControl(cache).body(response); + } + + public static CacheControl sMaxAgePublicCache(final Duration sMaxAge) { + return CacheControl.empty() + .cachePublic() + .sMaxAge(sMaxAge); + } + + public static ContentDisposition attachmentDisposition(final Path filename) { + return ContentDisposition.attachment().filename(filename.getFileName().toString(), StandardCharsets.UTF_8).build(); + } +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/NameSource.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/NameSource.java new file mode 100644 index 000000000..ea5de4272 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/NameSource.java @@ -0,0 +1,28 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.util; + +public interface NameSource { + String name(); +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/TimeSource.java b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/TimeSource.java new file mode 100644 index 000000000..be35ed7a1 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/java/io/papermc/bibliothek/util/TimeSource.java @@ -0,0 +1,31 @@ +/* + * This file is part of bibliothek, licensed under the MIT License. + * + * Copyright (c) 2019-2023 PaperMC + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package io.papermc.bibliothek.util; + +import java.time.Instant; +import org.jetbrains.annotations.UnknownNullability; + +public interface TimeSource { + @UnknownNullability Instant time(); +} diff --git a/jdk_17_gradle/cs/rest/bibliothek/src/main/resources/application.yaml b/jdk_17_gradle/cs/rest/bibliothek/src/main/resources/application.yaml new file mode 100644 index 000000000..77a5739b5 --- /dev/null +++ b/jdk_17_gradle/cs/rest/bibliothek/src/main/resources/application.yaml @@ -0,0 +1,23 @@ +spring: + data: + mongodb: + # "library" instead of "bibliothek" is intentional here + database: "library" + mvc: + throw-exception-if-no-handler-found: true + web: + resources: + add-mappings: false +springdoc: + api-docs: + path: "/openapi" + show-actuator: false + swagger-ui: + disable-swagger-default-url: true + operations-sorter: "alpha" + path: "/docs/" + show-common-extensions: true +server: + error: + whitelabel: + enabled: false diff --git a/jdk_17_gradle/em/embedded/rest/bibliothek/build.gradle.kts b/jdk_17_gradle/em/embedded/rest/bibliothek/build.gradle.kts new file mode 100644 index 000000000..4c8f54632 --- /dev/null +++ b/jdk_17_gradle/em/embedded/rest/bibliothek/build.gradle.kts @@ -0,0 +1,40 @@ + +repositories { + mavenLocal() + mavenCentral() + maven( url ="https://jcenter.bintray.com") +} + + +plugins { + `java-library` +} + +configurations { + implementation { + resolutionStrategy.failOnVersionConflict() + } +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +val EVOMASTER_VERSION = project.ext.get("EVOMASTER_VERSION") + +dependencies{ + implementation("org.evomaster:evomaster-client-java-controller:$EVOMASTER_VERSION") + implementation("org.evomaster:evomaster-client-java-dependencies:$EVOMASTER_VERSION"){ + exclude("com.github.tomakehurst") + } + + api(project(":cs:rest:bibliothek")) + + //Gradle api() is not importing transitive dependencies??? + implementation("org.springframework.boot:spring-boot-starter-web:3.1.1") + implementation("org.mongodb:mongodb-driver-sync:4.9.1") + + implementation("org.springframework.boot:spring-boot-starter-data-mongodb:3.1.1") + implementation("org.springframework.boot:spring-boot-starter-validation:3.1.1") +} \ No newline at end of file diff --git a/jdk_17_gradle/em/embedded/rest/bibliothek/src/main/java/em/embedded/bibliothek/EmbeddedEvoMasterController.java b/jdk_17_gradle/em/embedded/rest/bibliothek/src/main/java/em/embedded/bibliothek/EmbeddedEvoMasterController.java new file mode 100644 index 000000000..f267ddd01 --- /dev/null +++ b/jdk_17_gradle/em/embedded/rest/bibliothek/src/main/java/em/embedded/bibliothek/EmbeddedEvoMasterController.java @@ -0,0 +1,146 @@ +package em.embedded.bibliothek; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import io.papermc.bibliothek.BibliothekApplication; +import org.evomaster.client.java.controller.EmbeddedSutController; +import org.evomaster.client.java.controller.InstrumentedSutStarter; +import org.evomaster.client.java.controller.api.dto.AuthenticationDto; +import org.evomaster.client.java.controller.api.dto.SutInfoDto; +import org.evomaster.client.java.controller.internal.db.DbSpecification; +import org.evomaster.client.java.controller.problem.ProblemInfo; +import org.evomaster.client.java.controller.problem.RestProblem; +import org.springframework.boot.SpringApplication; +import org.springframework.context.ConfigurableApplicationContext; +import org.testcontainers.containers.GenericContainer; + + +import java.util.List; +import java.util.Map; + + +/** + * Class used to start/stop the SUT. This will be controller by the EvoMaster process + */ +public class EmbeddedEvoMasterController extends EmbeddedSutController { + + public static void main(String[] args) { + + int port = 40100; + if (args.length > 0) { + port = Integer.parseInt(args[0]); + } + + EmbeddedEvoMasterController controller = new EmbeddedEvoMasterController(port); + InstrumentedSutStarter starter = new InstrumentedSutStarter(controller); + + starter.start(); + } + + + private ConfigurableApplicationContext ctx; + + private static final int MONGODB_PORT = 27017; + + //https://www.mongodb.com/docs/drivers/java/sync/current/compatibility/ + + private static final String MONGODB_VERSION = "6.0"; + + private static final String MONGODB_DATABASE_NAME = "library"; + + private static final GenericContainer mongodbContainer = new GenericContainer("mongo:" + MONGODB_VERSION) + .withExposedPorts(MONGODB_PORT); + + private String mongoDbUrl; + + private MongoClient mongoClient; + + public EmbeddedEvoMasterController() { + this(0); + } + + public EmbeddedEvoMasterController(int port) { + setControllerPort(port); + } + + + @Override + public String startSut() { + + mongodbContainer.start(); + mongoDbUrl = "mongodb://" + mongodbContainer.getContainerIpAddress() + ":" + mongodbContainer.getMappedPort(MONGODB_PORT) + "/" + MONGODB_DATABASE_NAME; + mongoClient = MongoClients.create(mongoDbUrl); + + + + ctx = SpringApplication.run(BibliothekApplication.class, + new String[]{"--server.port=0", + "--databaseUrl="+mongoDbUrl, + "--spring.data.mongodb.uri="+mongoDbUrl, + "--spring.cache.type=NONE", + "--app.storagePath=./tmp/bibliothek" + }); + + return "http://localhost:" + getSutPort(); + } + + protected int getSutPort() { + return (Integer) ((Map) ctx.getEnvironment() + .getPropertySources().get("server.ports").getSource()) + .get("local.server.port"); + } + + + @Override + public boolean isSutRunning() { + return ctx != null && ctx.isRunning(); + } + + @Override + public void stopSut() { + ctx.stop(); + ctx.close(); + + mongodbContainer.stop(); + } + + @Override + public String getPackagePrefixesToCover() { + return "io.papermc.bibliothek."; + } + + @Override + public void resetStateOfSUT() { + mongoClient.getDatabase(MONGODB_DATABASE_NAME).drop(); + } + + @Override + public List getDbSpecifications() { + return null; + } + + + @Override + public List getInfoForAuthentication() { + //TODO might need to setup JWT headers here + return null; + } + + + + + @Override + public ProblemInfo getProblemInfo() { + return new RestProblem( + "http://localhost:" + getSutPort() + "/openapi", + null + ); + } + + @Override + public SutInfoDto.OutputFormat getPreferredOutputFormat() { + return SutInfoDto.OutputFormat.JAVA_JUNIT_4; + } + + +} diff --git a/jdk_17_gradle/em/external/rest/bibliothek/build.gradle.kts b/jdk_17_gradle/em/external/rest/bibliothek/build.gradle.kts new file mode 100644 index 000000000..6ee753dc9 --- /dev/null +++ b/jdk_17_gradle/em/external/rest/bibliothek/build.gradle.kts @@ -0,0 +1,60 @@ +import org.gradle.jvm.tasks.Jar + + +repositories { + mavenLocal() + mavenCentral() + maven( url ="https://jcenter.bintray.com") +} + + +plugins { + `java-library` + application +} + +configurations { + implementation { + resolutionStrategy.failOnVersionConflict() + } +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + + +val EVOMASTER_VERSION = project.ext.get("EVOMASTER_VERSION") + +dependencies{ + implementation("org.evomaster:evomaster-client-java-controller:$EVOMASTER_VERSION") + implementation("org.evomaster:evomaster-client-java-instrumentation:$EVOMASTER_VERSION") + implementation("org.evomaster:evomaster-client-java-dependencies:$EVOMASTER_VERSION") + implementation("org.mongodb:mongodb-driver-sync:4.9.1") +} + + + +val fatJar = task("fatJar", type = Jar::class) { + duplicatesStrategy = DuplicatesStrategy.WARN + archiveBaseName.set("${project.name}-evomaster-runner") + isZip64 = true + manifest { + attributes["Implementation-Title"] = "EM" + attributes["Implementation-Version"] = "1.0" + attributes["Main-Class"] = "em.external.bibliothek.ExternalEvoMasterController" + attributes["Premain-Class"] = "org.evomaster.client.java.instrumentation.InstrumentingAgent" + attributes["Agent-Class"] = "org.evomaster.client.java.instrumentation.InstrumentingAgent" + attributes["Can-Redefine-Classes"] = "true" + attributes["Can-Retransform-Classes"] = "true" + } + from(configurations.runtimeClasspath.get().map{ if (it.isDirectory) it else zipTree(it) }) + with(tasks.jar.get() as CopySpec) +} + +tasks { + "build" { + dependsOn(fatJar) + } +} diff --git a/jdk_17_gradle/em/external/rest/bibliothek/src/main/java/em/external/bibliothek/ExternalEvoMasterController.java b/jdk_17_gradle/em/external/rest/bibliothek/src/main/java/em/external/bibliothek/ExternalEvoMasterController.java new file mode 100644 index 000000000..bb8aa6435 --- /dev/null +++ b/jdk_17_gradle/em/external/rest/bibliothek/src/main/java/em/external/bibliothek/ExternalEvoMasterController.java @@ -0,0 +1,189 @@ +package em.external.bibliothek; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import org.evomaster.client.java.controller.ExternalSutController; +import org.evomaster.client.java.controller.InstrumentedSutStarter; +import org.evomaster.client.java.controller.api.dto.AuthenticationDto; +import org.evomaster.client.java.controller.api.dto.SutInfoDto; +import org.evomaster.client.java.controller.internal.db.DbSpecification; +import org.evomaster.client.java.controller.problem.ProblemInfo; +import org.evomaster.client.java.controller.problem.RestProblem; +import org.testcontainers.containers.GenericContainer; + +import java.util.List; + +public class ExternalEvoMasterController extends ExternalSutController { + + + public static void main(String[] args) { + + int controllerPort = 40100; + if (args.length > 0) { + controllerPort = Integer.parseInt(args[0]); + } + int sutPort = 12345; + if (args.length > 1) { + sutPort = Integer.parseInt(args[1]); + } + String jarLocation = "cs/rest/bibliothek/build/libs"; + if (args.length > 2) { + jarLocation = args[2]; + } + if(! jarLocation.endsWith(".jar")) { + jarLocation += "/bibliothek-sut.jar"; + } + + int timeoutSeconds = 120; + if(args.length > 3){ + timeoutSeconds = Integer.parseInt(args[3]); + } + String command = "java"; + if(args.length > 4){ + command = args[4]; + } + + + ExternalEvoMasterController controller = + new ExternalEvoMasterController(controllerPort, jarLocation, + sutPort, timeoutSeconds, command); + InstrumentedSutStarter starter = new InstrumentedSutStarter(controller); + + starter.start(); + } + + private final int timeoutSeconds; + private final int sutPort; + private String jarLocation; + private static final int MONGODB_PORT = 27017; + + //https://www.mongodb.com/docs/drivers/java/sync/current/compatibility/ + private static final String MONGODB_VERSION = "6.0"; + + private static final String MONGODB_DATABASE_NAME = "library"; + + private static final GenericContainer mongodbContainer = new GenericContainer("mongo:" + MONGODB_VERSION) + .withExposedPorts(MONGODB_PORT); + + private String mongoDbUrl; + + private MongoClient mongoClient; + + + public ExternalEvoMasterController(){ + this(40100, "../core/target", 12345, 120, "java"); + } + + public ExternalEvoMasterController(String jarLocation) { + this(); + this.jarLocation = jarLocation; + } + + public ExternalEvoMasterController( + int controllerPort, String jarLocation, int sutPort, int timeoutSeconds, String command + ) { + + if(jarLocation==null || jarLocation.isEmpty()){ + throw new IllegalArgumentException("Missing jar location"); + } + + + this.sutPort = sutPort; + this.jarLocation = jarLocation; + this.timeoutSeconds = timeoutSeconds; + setControllerPort(controllerPort); + setJavaCommand(command); + } + + + @Override + public String[] getInputParameters() { + return new String[]{ + "--server.port=" + sutPort, + "--databaseUrl="+mongoDbUrl, + "--spring.data.mongodb.uri="+mongoDbUrl, + "--app.storagePath=./tmp/bibliothek/" + "p"+sutPort + }; + } + + public String[] getJVMParameters() { + return new String[]{}; + } + + @Override + public String getBaseURL() { + return "http://localhost:" + sutPort; + } + + @Override + public String getPathToExecutableJar() { + return jarLocation; + } + + @Override + public String getLogMessageOfInitializedServer() { + return "Started BibliothekApplication in"; + } + + @Override + public long getMaxAwaitForInitializationInSeconds() { + return timeoutSeconds; + } + + @Override + public void preStart() { + mongodbContainer.start(); + mongoDbUrl = "mongodb://" + mongodbContainer.getContainerIpAddress() + ":" + mongodbContainer.getMappedPort(MONGODB_PORT) + "/" + MONGODB_DATABASE_NAME; + mongoClient = MongoClients.create(mongoDbUrl); + } + + @Override + public void postStart() { + } + + @Override + public void resetStateOfSUT() { + mongoClient.getDatabase(MONGODB_DATABASE_NAME).drop(); + } + + @Override + public void preStop() { + } + + @Override + public void postStop() { + mongodbContainer.stop(); + } + + + + @Override + public String getPackagePrefixesToCover() { + return "io.papermc.bibliothek."; + } + + @Override + public ProblemInfo getProblemInfo() { + return new RestProblem( + "http://localhost:" + sutPort + "/openapi", + null + ); + } + + @Override + public SutInfoDto.OutputFormat getPreferredOutputFormat() { + return SutInfoDto.OutputFormat.JAVA_JUNIT_5; + } + + + + @Override + public List getInfoForAuthentication() { + return null; + } + + @Override + public List getDbSpecifications() { + return null; + } +} diff --git a/jdk_17_gradle/gradle/libs.versions.toml b/jdk_17_gradle/gradle/libs.versions.toml new file mode 100644 index 000000000..b0ae4f337 --- /dev/null +++ b/jdk_17_gradle/gradle/libs.versions.toml @@ -0,0 +1,14 @@ +[versions] +indra = "3.1.1" + +[plugins] +indra = { id = "net.kyori.indra", version.ref = "indra" } +indra-checkstyle = { id = "net.kyori.indra.checkstyle", version.ref = "indra" } +spotless = { id = "com.diffplug.spotless", version = "6.19.0" } +spring-boot = { id = "org.springframework.boot", version = "3.1.1" } +spring-dependency-management = { id = "io.spring.dependency-management", version = "1.1.1" } + +[libraries] +jetbrains-annotations = { group = "org.jetbrains", name = "annotations", version = "24.0.1" } +springdoc-openapi-starter-webmvc-ui = { group = "org.springdoc", name = "springdoc-openapi-starter-webmvc-ui", version = "2.1.0" } +stylecheck = { group = "ca.stellardrift", name = "stylecheck", version = "0.2.1" } diff --git a/jdk_17_gradle/gradle/wrapper/gradle-wrapper.jar b/jdk_17_gradle/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e708b1c02 Binary files /dev/null and b/jdk_17_gradle/gradle/wrapper/gradle-wrapper.jar differ diff --git a/jdk_17_gradle/gradle/wrapper/gradle-wrapper.properties b/jdk_17_gradle/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..fae08049a --- /dev/null +++ b/jdk_17_gradle/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/jdk_17_gradle/gradlew b/jdk_17_gradle/gradlew new file mode 100644 index 000000000..4f906e0c8 --- /dev/null +++ b/jdk_17_gradle/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/jdk_17_gradle/gradlew.bat b/jdk_17_gradle/gradlew.bat new file mode 100644 index 000000000..107acd32c --- /dev/null +++ b/jdk_17_gradle/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/jdk_17_gradle/settings.gradle.kts b/jdk_17_gradle/settings.gradle.kts new file mode 100644 index 000000000..029a97f1f --- /dev/null +++ b/jdk_17_gradle/settings.gradle.kts @@ -0,0 +1,6 @@ +rootProject.name = "emb_jdk_17_gradle" + +include("cs:rest:bibliothek") +include("em:embedded:rest:bibliothek") +include("em:external:rest:bibliothek") + diff --git a/openapi-swagger/bibliothek.json b/openapi-swagger/bibliothek.json new file mode 100644 index 000000000..c1e76c50a --- /dev/null +++ b/openapi-swagger/bibliothek.json @@ -0,0 +1,698 @@ +{ + "openapi": "3.0.1", + "info": {}, + "servers": [ + { + "url": "http://localhost:12080", + "description": "Generated server url" + } + ], + "paths": { + "/v2/projects": { + "get": { + "tags": [ + "projects-controller" + ], + "summary": "Gets a list of all available projects.", + "operationId": "projects", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectsResponse" + } + } + } + } + } + } + }, + "/v2/projects/{project}": { + "get": { + "tags": [ + "project-controller" + ], + "summary": "Gets information about a project.", + "operationId": "project", + "parameters": [ + { + "name": "project", + "in": "path", + "description": "The project identifier.", + "required": true, + "schema": { + "pattern": "[a-z]+", + "type": "string" + }, + "example": "paper" + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ProjectResponse" + } + } + } + } + } + } + }, + "/v2/projects/{project}/versions/{version}": { + "get": { + "tags": [ + "version-controller" + ], + "summary": "Gets information about a version.", + "operationId": "version", + "parameters": [ + { + "name": "project", + "in": "path", + "description": "The project identifier.", + "required": true, + "schema": { + "pattern": "[a-z]+", + "type": "string" + }, + "example": "paper" + }, + { + "name": "version", + "in": "path", + "description": "A version of the project.", + "required": true, + "schema": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VersionResponse" + } + } + } + } + } + } + }, + "/v2/projects/{project}/versions/{version}/builds": { + "get": { + "tags": [ + "version-builds-controller" + ], + "summary": "Gets all available builds for a project's version.", + "operationId": "builds", + "parameters": [ + { + "name": "project", + "in": "path", + "description": "The project identifier.", + "required": true, + "schema": { + "pattern": "[a-z]+", + "type": "string" + }, + "example": "paper" + }, + { + "name": "version", + "in": "path", + "description": "A version of the project.", + "required": true, + "schema": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BuildsResponse" + } + } + } + } + } + } + }, + "/v2/projects/{project}/versions/{version}/builds/{build}": { + "get": { + "tags": [ + "version-build-controller" + ], + "summary": "Gets information related to a specific build.", + "operationId": "build", + "parameters": [ + { + "name": "project", + "in": "path", + "description": "The project identifier.", + "required": true, + "schema": { + "pattern": "[a-z]+", + "type": "string" + }, + "example": "paper" + }, + { + "name": "version", + "in": "path", + "description": "A version of the project.", + "required": true, + "schema": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string" + } + }, + { + "name": "build", + "in": "path", + "description": "A build of the version.", + "required": true, + "schema": { + "pattern": "\\d+", + "type": "integer", + "format": "int32" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/BuildResponse" + } + } + } + } + } + } + }, + "/v2/projects/{project}/versions/{version}/builds/{build}/downloads/{download}": { + "get": { + "tags": [ + "download-controller" + ], + "summary": "Downloads the given file from a build's data.", + "operationId": "download", + "parameters": [ + { + "name": "project", + "in": "path", + "description": "The project identifier.", + "required": true, + "schema": { + "pattern": "[a-z]+", + "type": "string" + }, + "example": "paper" + }, + { + "name": "version", + "in": "path", + "description": "A version of the project.", + "required": true, + "schema": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string" + } + }, + { + "name": "build", + "in": "path", + "description": "A build of the version.", + "required": true, + "schema": { + "pattern": "\\d+", + "type": "integer", + "format": "int32" + } + }, + { + "name": "download", + "in": "path", + "description": "A download of the build.", + "required": true, + "schema": { + "pattern": "[a-zA-Z0-9._-]+", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "headers": { + "ETag": { + "description": "An identifier for a specific version of a resource. It lets caches be more efficient and save bandwidth, as a web server does not need to resend a full response if the content has not changed.", + "style": "simple", + "schema": { + "type": "string" + } + }, + "Content-Disposition": { + "description": "A header indicating that the content is expected to be displayed as an attachment, that is downloaded and saved locally.", + "style": "simple", + "schema": { + "type": "string" + } + }, + "Last-Modified": { + "description": "The date and time at which the origin server believes the resource was last modified.", + "style": "simple", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "type": "object" + } + }, + "application/java-archive": { + "schema": { + "type": "object" + } + } + } + } + } + } + }, + "/v2/projects/{project}/version_group/{family}": { + "get": { + "tags": [ + "version-family-controller" + ], + "summary": "Gets information about a project's version group.", + "operationId": "family", + "parameters": [ + { + "name": "project", + "in": "path", + "description": "The project identifier.", + "required": true, + "schema": { + "pattern": "[a-z]+", + "type": "string" + }, + "example": "paper" + }, + { + "name": "family", + "in": "path", + "description": "The version group name.", + "required": true, + "schema": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VersionFamilyResponse" + } + } + } + } + } + } + }, + "/v2/projects/{project}/version_group/{family}/builds": { + "get": { + "tags": [ + "version-family-builds-controller" + ], + "summary": "Gets all available builds for a project's version group.", + "operationId": "familyBuilds", + "parameters": [ + { + "name": "project", + "in": "path", + "description": "The project identifier.", + "required": true, + "schema": { + "pattern": "[a-z]+", + "type": "string" + }, + "example": "paper" + }, + { + "name": "family", + "in": "path", + "description": "The version group name.", + "required": true, + "schema": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VersionFamilyBuildsResponse" + } + } + } + } + } + } + } + }, + "components": { + "schemas": { + "BuildResponse": { + "type": "object", + "properties": { + "project_id": { + "pattern": "[a-z]+", + "type": "string", + "example": "paper" + }, + "project_name": { + "type": "string", + "example": "Paper" + }, + "version": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string", + "example": "1.18" + }, + "build": { + "pattern": "\\d+", + "type": "integer", + "format": "int32", + "example": 10 + }, + "time": { + "type": "string", + "format": "date-time" + }, + "channel": { + "type": "string", + "enum": [ + "default", + "experimental" + ] + }, + "promoted": { + "type": "boolean" + }, + "changes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Change" + } + }, + "downloads": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Download" + } + } + } + }, + "BuildsResponse": { + "type": "object", + "properties": { + "project_id": { + "pattern": "[a-z]+", + "type": "string", + "example": "paper" + }, + "project_name": { + "type": "string", + "example": "Paper" + }, + "version": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string", + "example": "1.18" + }, + "builds": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VersionBuild" + } + } + } + }, + "Change": { + "type": "object", + "properties": { + "commit": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "message": { + "type": "string" + } + } + }, + "Download": { + "type": "object", + "properties": { + "name": { + "pattern": "[a-z0-9._-]+", + "type": "string", + "example": "paper-1.18-10.jar" + }, + "sha256": { + "pattern": "[a-f0-9]{64}", + "type": "string", + "example": "f065e2d345d9d772d5cf2a1ce5c495c4cc56eb2fcd6820e82856485fa19414c8" + } + } + }, + "ProjectResponse": { + "type": "object", + "properties": { + "project_id": { + "pattern": "[a-z]+", + "type": "string", + "example": "paper" + }, + "project_name": { + "type": "string", + "example": "Paper" + }, + "version_groups": { + "type": "array", + "items": { + "type": "string" + } + }, + "versions": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "ProjectsResponse": { + "type": "object", + "properties": { + "projects": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "VersionBuild": { + "type": "object", + "properties": { + "build": { + "pattern": "\\d+", + "type": "integer", + "format": "int32", + "example": 10 + }, + "time": { + "type": "string", + "format": "date-time" + }, + "channel": { + "type": "string", + "enum": [ + "default", + "experimental" + ] + }, + "promoted": { + "type": "boolean" + }, + "changes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Change" + } + }, + "downloads": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Download" + } + } + } + }, + "VersionFamilyBuild": { + "type": "object", + "properties": { + "version": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string", + "example": "1.18" + }, + "build": { + "pattern": "\\d+", + "type": "integer", + "format": "int32", + "example": 10 + }, + "time": { + "type": "string", + "format": "date-time" + }, + "channel": { + "type": "string", + "enum": [ + "default", + "experimental" + ] + }, + "promoted": { + "type": "boolean" + }, + "changes": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Change" + } + }, + "downloads": { + "type": "object", + "additionalProperties": { + "$ref": "#/components/schemas/Download" + } + } + } + }, + "VersionFamilyBuildsResponse": { + "type": "object", + "properties": { + "project_id": { + "pattern": "[a-z]+", + "type": "string", + "example": "paper" + }, + "project_name": { + "type": "string", + "example": "Paper" + }, + "version_group": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string", + "example": "1.18" + }, + "versions": { + "type": "array", + "items": { + "type": "string" + } + }, + "builds": { + "type": "array", + "items": { + "$ref": "#/components/schemas/VersionFamilyBuild" + } + } + } + }, + "VersionFamilyResponse": { + "type": "object", + "properties": { + "project_id": { + "pattern": "[a-z]+", + "type": "string", + "example": "paper" + }, + "project_name": { + "type": "string", + "example": "Paper" + }, + "version_group": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string", + "example": "1.18" + }, + "versions": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "VersionResponse": { + "type": "object", + "properties": { + "project_id": { + "pattern": "[a-z]+", + "type": "string", + "example": "paper" + }, + "project_name": { + "type": "string", + "example": "Paper" + }, + "version": { + "pattern": "[0-9.]+-?(?:pre|SNAPSHOT)?(?:[0-9.]+)?", + "type": "string", + "example": "1.18" + }, + "builds": { + "type": "array", + "items": { + "type": "integer", + "format": "int32" + } + } + } + } + } + } +} \ No newline at end of file diff --git a/openapi-swagger/reservations-api.json b/openapi-swagger/reservations-api.json new file mode 100644 index 000000000..36a99ddab --- /dev/null +++ b/openapi-swagger/reservations-api.json @@ -0,0 +1,381 @@ +{ + "openapi": "3.0.1", + "info": { + "title": "Reservations API", + "description": "Simple API for implementing basic reservation system.", + "version": "v1.0.0" + }, + "servers": [ + { + "url": "http://localhost:12345", + "description": "Generated server url" + } + ], + "tags": [ + { + "name": "Reservations" + }, + { + "name": "Users" + } + ], + "paths": { + "/api/reservation": { + "get": { + "tags": [ + "Reservations" + ], + "summary": "Get all reservations", + "description": "Get all reservations available.", + "operationId": "getAllReservations", + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ReservationResponse" + } + } + } + } + } + }, + "security": [ + { + "bearer-key": [] + } + ] + }, + "put": { + "tags": [ + "Reservations" + ], + "summary": "Update reservation", + "description": "Update reservation when valid information provided.", + "operationId": "updateReservation", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UpdateReservationRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReservationResponse" + } + } + } + } + }, + "security": [ + { + "bearer-key": [] + } + ] + }, + "post": { + "tags": [ + "Reservations" + ], + "summary": "Create new reservation", + "description": "Create new reservation when valid information provided.", + "operationId": "createReservation", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/CreateReservationRequest" + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReservationResponse" + } + } + } + } + }, + "security": [ + { + "bearer-key": [] + } + ] + } + }, + "/api/user/register": { + "post": { + "tags": [ + "Users" + ], + "summary": "Perform user's registration to save a user and retrieve access token.", + "description": "Perform user's registration to save a user and retrieve access token.", + "operationId": "register", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RegisterRequest" + } + } + }, + "required": true + }, + "responses": { + "201": { + "description": "Created", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/AuthResponse" + } + } + } + } + } + } + }, + "/api/user/login": { + "post": { + "tags": [ + "Users" + ], + "summary": "Perform user's login to retrieve access token.", + "description": "Perform user's login to retrieve access token.", + "operationId": "login", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/LoginRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "OK", + "content": { + "*/*": { + "schema": { + "$ref": "#/components/schemas/AuthResponse" + } + } + } + } + } + } + }, + "/api/reservation/{username}": { + "get": { + "tags": [ + "Reservations" + ], + "summary": "Get reservations for particular user", + "description": "Get reservations for particular user when correct username provided.", + "operationId": "getAllReservationsForUser", + "parameters": [ + { + "name": "username", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/ReservationResponse" + } + } + } + } + } + }, + "security": [ + { + "bearer-key": [] + } + ] + } + }, + "/api/reservation/{reservationUuid}": { + "delete": { + "tags": [ + "Reservations" + ], + "summary": "Delete reservation", + "description": "Delete reservation when valid UUID provided.", + "operationId": "deleteReservation", + "parameters": [ + { + "name": "reservationUuid", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "OK" + } + }, + "security": [ + { + "bearer-key": [] + } + ] + } + } + }, + "components": { + "schemas": { + "UpdateReservationRequest": { + "required": [ + "reservationFor", + "reservationFrom", + "reservationTo", + "uuid" + ], + "type": "object", + "properties": { + "uuid": { + "type": "string" + }, + "reservationFor": { + "type": "string" + }, + "reservationFrom": { + "type": "string", + "format": "date-time" + }, + "reservationTo": { + "type": "string", + "format": "date-time" + } + } + }, + "ReservationResponse": { + "type": "object", + "properties": { + "uuid": { + "type": "string" + }, + "reservationFor": { + "type": "string" + }, + "reservationFrom": { + "type": "string", + "format": "date-time" + }, + "reservationTo": { + "type": "string", + "format": "date-time" + } + } + }, + "RegisterRequest": { + "required": [ + "email", + "password", + "username" + ], + "type": "object", + "properties": { + "username": { + "type": "string" + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + } + } + }, + "AuthResponse": { + "type": "object", + "properties": { + "accessToken": { + "type": "string" + } + } + }, + "LoginRequest": { + "required": [ + "password", + "username" + ], + "type": "object", + "properties": { + "username": { + "type": "string" + }, + "password": { + "type": "string" + } + } + }, + "CreateReservationRequest": { + "required": [ + "createdAt", + "reservationFor", + "reservationFrom", + "reservationTo" + ], + "type": "object", + "properties": { + "reservationFor": { + "type": "string" + }, + "reservationFrom": { + "type": "string", + "format": "date-time" + }, + "reservationTo": { + "type": "string", + "format": "date-time" + }, + "createdAt": { + "type": "string", + "format": "date-time" + } + } + } + }, + "securitySchemes": { + "bearer-key": { + "type": "http", + "scheme": "bearer", + "bearerFormat": "JWT" + } + } + } +} \ No newline at end of file diff --git a/scripts/dist.py b/scripts/dist.py index 628644cee..3deb73ed1 100755 --- a/scripts/dist.py +++ b/scripts/dist.py @@ -225,6 +225,31 @@ def build_jdk_11_gradle(): # Copy JAR files copy(folder + "/cs/graphql/patio-api/build/libs/patio-api-sut.jar", DIST) copy(folder + "/em/external/graphql/patio-api/build/libs/patio-api-evomaster-runner.jar", DIST) + copy(folder + "/cs/rest/reservations-api/build/libs/reservations-api-sut.jar", DIST) + copy(folder + "/em/external/rest/reservations-api/build/libs/reservations-api-evomaster-runner.jar", DIST) + +#################### +def build_jdk_17_gradle(): + env_vars = os.environ.copy() + env_vars["JAVA_HOME"] = JAVA_HOME_17 + folder = "jdk_17_gradle" + + command = "gradlew" + + if platform.system() == "Darwin": + command = "./gradlew" + + gradleres = run([command, "build", "-x", "test"], shell=SHELL, cwd=os.path.join(PROJ_LOCATION, folder), + env=env_vars) + gradleres = gradleres.returncode + + if gradleres != 0: + print("\nERROR: Gradle command failed") + exit(1) + + # Copy JAR files + copy(folder + "/cs/rest/bibliothek/build/libs/bibliothek-sut.jar", DIST) + copy(folder + "/em/external/rest/bibliothek/build/libs/bibliothek-evomaster-runner.jar", DIST) # Building JavaScript projects @@ -318,6 +343,7 @@ def makeZip(): build_jdk_11_maven() build_jdk_17_maven() build_jdk_11_gradle() +build_jdk_17_gradle() ## Those are disabled for now... might support back in the future # build_js_npm() diff --git a/scripts/version.py b/scripts/version.py index 2823141f1..f8a778e63 100755 --- a/scripts/version.py +++ b/scripts/version.py @@ -68,9 +68,9 @@ def replaceInProperty(file): replacement = 'EVOMASTER_VERSION='+version+'\n' replace(file, regex, replacement) -def replaceInKotlinGradle(file): - regex = re.compile(r'.*val.*EVOMASTER_VERSION.*=.*') - replacement = "val EVOMASTER_VERSION = \""+version+"\"\n" +def replaceInGradle(file): + regex = re.compile(r'.*EVOMASTER_VERSION.*=.*') + replacement = " EVOMASTER_VERSION = \""+version+"\"\n" replace(file, regex, replacement) def versionSetMaven(folder, jdk_home): @@ -124,9 +124,8 @@ def replaceInCS(): replaceInPom("jdk_11_maven/pom.xml") replaceInPom("jdk_17_maven/pom.xml") -# is there any easier way for Gradle? -replaceInKotlinGradle("jdk_11_gradle/em/embedded/graphql/patio-api/build.gradle.kts") -replaceInKotlinGradle("jdk_11_gradle/em/external/graphql/patio-api/build.gradle.kts") +replaceInGradle("jdk_17_gradle/build.gradle") +replaceInGradle("jdk_11_gradle/build.gradle") replaceInDist() diff --git a/statistics/data.csv b/statistics/data.csv index a5399d2a7..a9f943fc9 100644 --- a/statistics/data.csv +++ b/statistics/data.csv @@ -1,4 +1,6 @@ EMB,NAME,TYPE,LANGUAGE,RUNTIME,BUILD,FILES,LOCS,DATABASE,LICENSE,ENDPOINTS,URL +TRUE,bibliothek,REST,Java,JDK 17,Gradle,33,2176,MongoDB,MIT,8,https://github.com/PaperMC/bibliothek +TRUE,reservations-api,REST,Java,JDK 11,Gradle,39,1853,MongoDB,UNDEFINED,7,https://github.com/cyrilgavala/reservations-api TRUE,catwatch,REST,Java,JDK 8,Maven,106,9636,H2,Apache,14,https://github.com/zalando-incubator/catwatch TRUE,cwa-verification,REST,Java,JDK 11,Maven,47,3955,H2,Apache,5,https://github.com/corona-warn-app/cwa-verification-server TRUE,features-service,REST,Java,JDK 8,Maven,39,2275,H2,Apache,18,https://github.com/JavierMF/features-service diff --git a/statistics/suts.R b/statistics/suts.R index 0c4514a85..770bca640 100644 --- a/statistics/suts.R +++ b/statistics/suts.R @@ -21,6 +21,8 @@ suts <- function(){ "scout-api", "genome-nexus", "market", + "bibliothek", + "reservations-api", #"petclinic-graphql", #"patio-api", #"timbuctoo", diff --git a/statistics/table_emb.md b/statistics/table_emb.md index 80f06565d..ddf81716b 100644 --- a/statistics/table_emb.md +++ b/statistics/table_emb.md @@ -18,7 +18,9 @@ |__cwa-verification__|REST|3955|47|5|Java|JDK 11|Maven|H2| |__gestaohospital__|REST|3506|33|20|Java|JDK 8|Maven|MongoDB| |__features-service__|REST|2275|39|18|Java|JDK 8|Maven|H2| +|__bibliothek__|REST|2176|33|8|Java|JDK 17|Gradle|MongoDB| |__restcountries__|REST|1977|24|22|Java|JDK 8|Maven|| +|__reservations-api__|REST|1853|39|7|Java|JDK 11|Gradle|MongoDB| |__rest-scs__|REST|862|13|11|Java|JDK 8|Maven|| |__rest-ncs__|REST|605|9|6|Java|JDK 8|Maven|| |__rest-news__|REST|857|11|7|Kotlin|JDK 8|Maven|H2|