From 8aaeda701936541acff6ec6e5602054fdb6358dd Mon Sep 17 00:00:00 2001 From: Adriel Paredes Date: Fri, 30 Sep 2022 14:26:48 -0300 Subject: [PATCH 1/2] Os 67 (#75) * core to quarkus * Se hace upgrade de las dependencias con vulnerabilidades * Se cambian los requestscope a applicationscope y se arregla el startupmanager Co-authored-by: Leandro Beretta --- packages/openscore-core-quarkus/.dockerignore | 5 + packages/openscore-core-quarkus/.gitignore | 40 +++ .../.mvn/wrapper/.gitignore | 1 + .../.mvn/wrapper/MavenWrapperDownloader.java | 142 ++++++++ .../.mvn/wrapper/maven-wrapper.properties | 18 + packages/openscore-core-quarkus/README.md | 1 + packages/openscore-core-quarkus/mvnw | 316 ++++++++++++++++++ packages/openscore-core-quarkus/mvnw.cmd | 188 +++++++++++ packages/openscore-core-quarkus/pom.xml | 258 ++++++++++++++ .../src/main/docker/Dockerfile.jvm | 94 ++++++ .../src/main/docker/Dockerfile.legacy-jar | 90 +++++ .../src/main/docker/Dockerfile.native | 27 ++ .../src/main/docker/Dockerfile.native-micro | 30 ++ .../openscore/core/OpenScoreApplication.java | 9 + .../openscore/core/api/ApiResponse.java | 35 ++ .../openscore/core/api/ImagenApi.java | 32 ++ .../semantic/openscore/core/api/TokenDTO.java | 18 + .../core/api/admin/UsuarioCompletoDTO.java | 87 +++++ .../CrearDefinicionCompeticionDTO.java | 33 ++ .../DefinicionCompeticionDTO.java | 32 ++ .../core/api/equipos/CrearEquipoDTO.java | 41 +++ .../openscore/core/api/equipos/EquipoDTO.java | 52 +++ .../openscore/core/api/grupos/FaseDTO.java | 23 ++ .../openscore/core/api/grupos/GrupoDTO.java | 23 ++ .../core/api/information/Information.java | 35 ++ .../openscore/core/api/paises/PaisDTO.java | 23 ++ .../api/partidos/CrearOUpdatePartidoDTO.java | 70 ++++ .../core/api/partidos/PartidoDTO.java | 101 ++++++ .../core/api/partidos/ResultadoDTO.java | 23 ++ .../openscore/core/api/post/CrearPost.java | 32 ++ .../api/pronosticos/CrearPronosticoDTO.java | 42 +++ .../api/pronosticos/PartidoPronosticoDTO.java | 16 + .../core/api/pronosticos/PronosticoDTO.java | 49 +++ .../openscore/core/api/ranking/Ranking.java | 50 +++ .../core/api/usuarios/CrearUsuarioDTO.java | 100 ++++++ .../core/api/usuarios/LoginUsuarioDTO.java | 23 ++ .../core/api/usuarios/RecoverPassword.java | 60 ++++ .../core/api/usuarios/UpdatePassword.java | 47 +++ .../api/usuarios/UpdateSecretQuestion.java | 42 +++ .../core/api/usuarios/UpdateUsuarioDTO.java | 46 +++ .../core/api/usuarios/UsuarioDTO.java | 69 ++++ .../openscore/core/cache/TokenCache.java | 74 ++++ .../openscore/core/email/FSMailProvider.java | 34 ++ .../openscore/core/email/MailFactory.java | 17 + .../openscore/core/email/MailProvider.java | 6 + .../openscore/core/email/MailServer.java | 30 ++ .../openscore/core/email/MailTemplate.java | 38 +++ .../openscore/core/email/SMTPProvider.java | 34 ++ .../core/email/StdoutMailSender.java | 22 ++ .../core/exceptions/ApplicationException.java | 14 + .../core/exceptions/EmailException.java | 7 + .../exceptions/EntityNotFoundException.java | 8 + .../NoSePuedeLeerInformacionException.java | 8 + .../exceptions/PartidoBloqueadoException.java | 9 + .../core/exceptions/ValidationException.java | 44 +++ .../openscore/core/logging/BaseLogger.java | 24 ++ .../openscore/core/logging/ServiceLogger.java | 14 + .../openscore/core/mapping/EquipoMapper.java | 21 ++ .../openscore/core/mapping/FaseMapper.java | 16 + .../openscore/core/mapping/GrupoMapper.java | 15 + .../openscore/core/mapping/PaisMapper.java | 18 + .../openscore/core/mapping/PartidoMapper.java | 20 ++ .../core/mapping/PronosticoMapper.java | 36 ++ .../openscore/core/mapping/UsuarioMapper.java | 37 ++ .../semantic/openscore/core/model/Equipo.java | 47 +++ .../semantic/openscore/core/model/Fase.java | 42 +++ .../openscore/core/model/Ganador.java | 8 + .../semantic/openscore/core/model/Grupo.java | 36 ++ .../semantic/openscore/core/model/Pais.java | 48 +++ .../openscore/core/model/Partido.java | 132 ++++++++ .../openscore/core/model/PartidoStatus.java | 5 + .../semantic/openscore/core/model/Post.java | 51 +++ .../openscore/core/model/PostStatus.java | 5 + .../openscore/core/model/PreguntaSecreta.java | 28 ++ .../openscore/core/model/Pronostico.java | 91 +++++ .../core/model/RespuestaPreguntaSecreta.java | 29 ++ .../openscore/core/model/Resultado.java | 53 +++ .../io/semantic/openscore/core/model/Rol.java | 7 + .../openscore/core/model/Storable.java | 67 ++++ .../openscore/core/model/Usuario.java | 112 +++++++ .../core/repository/EquiposRepository.java | 41 +++ .../core/repository/FaseRepository.java | 41 +++ .../core/repository/GrupoRepository.java | 41 +++ .../openscore/core/repository/Page.java | 22 ++ .../core/repository/PaisRepository.java | 39 +++ .../core/repository/PartidoRepository.java | 107 ++++++ .../core/repository/PostRepository.java | 30 ++ .../repository/PreguntaSecretaRepository.java | 25 ++ .../core/repository/PronosticoRepository.java | 66 ++++ .../openscore/core/repository/Repository.java | 178 ++++++++++ .../openscore/core/repository/Sort.java | 10 + .../core/repository/UsuarioRepository.java | 53 +++ .../core/repository/startup/PartidoData.java | 68 ++++ .../repository/startup/StartupManager.java | 48 +++ .../core/repository/startup/StartupStep.java | 12 + .../startup/builder/DiaBuilder.java | 10 + .../startup/builder/DiaBuilderImpl.java | 28 ++ .../startup/builder/TestDiaBuilder.java | 25 ++ .../startup/steps/CrearEquipos.java | 67 ++++ .../startup/steps/CrearGruposYFases.java | 77 +++++ .../repository/startup/steps/CrearPaises.java | 61 ++++ .../startup/steps/CrearPartidos.java | 97 ++++++ .../startup/steps/CrearPreguntaSecreta.java | 51 +++ .../startup/steps/CrearUsuarioAdmin.java | 87 +++++ .../startup/steps/FileBasedStartupStep.java | 67 ++++ .../startup/steps/PreguntaSecretaData.java | 27 ++ .../openscore/core/security/Secure.java | 17 + .../openscore/core/security/SecureFilter.java | 75 +++++ .../core/security/TokenGenerator.java | 138 ++++++++ .../openscore/core/services/RestUtil.java | 18 + .../openscore/core/services/UserInfo.java | 28 ++ .../core/services/api/AdminService.java | 16 + .../api/DefinicionCompeticionesService.java | 45 +++ .../core/services/api/EquiposService.java | 19 ++ .../core/services/api/FasesService.java | 15 + .../core/services/api/GetService.java | 16 + .../core/services/api/GruposService.java | 14 + .../core/services/api/InformationService.java | 27 ++ .../core/services/api/PaisesService.java | 16 + .../core/services/api/PartidosService.java | 50 +++ .../core/services/api/PostService.java | 30 ++ .../core/services/api/PronosticosService.java | 66 ++++ .../core/services/api/RankingService.java | 24 ++ .../core/services/api/SearchService.java | 19 ++ .../core/services/api/StandardService.java | 26 ++ .../core/services/api/UsuariosService.java | 62 ++++ .../filters/ApplicationExceptionMapper.java | 38 +++ .../core/services/filters/CorsFilter.java | 35 ++ .../core/services/filters/LoggerFilter.java | 28 ++ .../filters/RuntimeExceptionMapper.java | 25 ++ .../core/services/impl/AdminServiceImpl.java | 41 +++ .../services/impl/EquiposServiceImpl.java | 106 ++++++ .../core/services/impl/FasesServiceImpl.java | 43 +++ .../core/services/impl/GruposServiceImpl.java | 44 +++ .../services/impl/InformationServiceImpl.java | 53 +++ .../core/services/impl/PaisesServiceImpl.java | 40 +++ .../services/impl/PartidosServiceImpl.java | 150 +++++++++ .../core/services/impl/PostServiceImpl.java | 101 ++++++ .../services/impl/PronosticosServiceImpl.java | 228 +++++++++++++ .../services/impl/RankingServiceImpl.java | 97 ++++++ .../services/impl/UsuariosServiceImpl.java | 248 ++++++++++++++ .../core/template/TemplateEngine.java | 35 ++ .../template/TemplateEngineException.java | 9 + .../openscore/core/util/JsonConverter.java | 10 + .../core/validation/ApplicationValidator.java | 41 +++ .../core/validation/annotations/Matches.java | 36 ++ .../core/validation/annotations/Password.java | 26 ++ .../validation/validators/EmailValidator.java | 6 + .../validators/MatchesValidator.java | 47 +++ .../validators/PasswordValidator.java | 37 ++ .../validators/RedHatEmailValidator.java | 9 + .../resources/ValidationMessages.properties | 2 + .../src/main/resources/application.properties | 7 + .../src/main/resources/data/partidos.yml | 141 ++++++++ .../src/main/resources/data/preguntas.yml | 7 + .../src/main/resources/info.properties | 2 + .../src/main/resources/logback.xml | 21 ++ .../src/main/resources/templates/recover.html | 210 ++++++++++++ .../openscore/core/model/UsuarioTest.java | 69 ++++ .../core/repository/PaisRepositoryTest.java | 33 ++ .../core/repository/RepositoryBaseTest.java | 39 +++ .../core/repository/RepositoryTest.java | 120 +++++++ .../openscore/core/repository/TestObject.java | 26 ++ .../core/repository/TestRepository.java | 19 ++ .../repository/UsuarioRepositoryTest.java | 49 +++ .../core/security/GenerateToken.java | 27 ++ .../core/security/TokenGeneratorTest.java | 57 ++++ .../impl/UsuariosServiceImplTest.java | 149 +++++++++ 168 files changed, 8340 insertions(+) create mode 100644 packages/openscore-core-quarkus/.dockerignore create mode 100644 packages/openscore-core-quarkus/.gitignore create mode 100644 packages/openscore-core-quarkus/.mvn/wrapper/.gitignore create mode 100644 packages/openscore-core-quarkus/.mvn/wrapper/MavenWrapperDownloader.java create mode 100644 packages/openscore-core-quarkus/.mvn/wrapper/maven-wrapper.properties create mode 100644 packages/openscore-core-quarkus/README.md create mode 100755 packages/openscore-core-quarkus/mvnw create mode 100644 packages/openscore-core-quarkus/mvnw.cmd create mode 100644 packages/openscore-core-quarkus/pom.xml create mode 100644 packages/openscore-core-quarkus/src/main/docker/Dockerfile.jvm create mode 100644 packages/openscore-core-quarkus/src/main/docker/Dockerfile.legacy-jar create mode 100644 packages/openscore-core-quarkus/src/main/docker/Dockerfile.native create mode 100644 packages/openscore-core-quarkus/src/main/docker/Dockerfile.native-micro create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/OpenScoreApplication.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ApiResponse.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ImagenApi.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/TokenDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/admin/UsuarioCompletoDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/competiciones/CrearDefinicionCompeticionDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/competiciones/DefinicionCompeticionDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/equipos/CrearEquipoDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/equipos/EquipoDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/grupos/FaseDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/grupos/GrupoDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/information/Information.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/paises/PaisDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/CrearOUpdatePartidoDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/PartidoDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/ResultadoDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/post/CrearPost.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/CrearPronosticoDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/PartidoPronosticoDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/PronosticoDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ranking/Ranking.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/CrearUsuarioDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/LoginUsuarioDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/RecoverPassword.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdatePassword.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdateSecretQuestion.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdateUsuarioDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UsuarioDTO.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/cache/TokenCache.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/FSMailProvider.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailFactory.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailProvider.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailServer.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailTemplate.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/SMTPProvider.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/StdoutMailSender.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/ApplicationException.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/EmailException.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/EntityNotFoundException.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/NoSePuedeLeerInformacionException.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/PartidoBloqueadoException.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/ValidationException.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/logging/BaseLogger.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/logging/ServiceLogger.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/EquipoMapper.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/FaseMapper.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/GrupoMapper.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PaisMapper.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PartidoMapper.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PronosticoMapper.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/UsuarioMapper.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Equipo.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Fase.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Ganador.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Grupo.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Pais.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Partido.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PartidoStatus.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Post.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PostStatus.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PreguntaSecreta.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Pronostico.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/RespuestaPreguntaSecreta.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Resultado.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Rol.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Storable.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Usuario.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/EquiposRepository.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/FaseRepository.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/GrupoRepository.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Page.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PaisRepository.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PartidoRepository.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PostRepository.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PreguntaSecretaRepository.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PronosticoRepository.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Repository.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Sort.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/UsuarioRepository.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/PartidoData.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/StartupManager.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/StartupStep.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/DiaBuilder.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/DiaBuilderImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/TestDiaBuilder.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearEquipos.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearGruposYFases.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPaises.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPartidos.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPreguntaSecreta.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearUsuarioAdmin.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/FileBasedStartupStep.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/PreguntaSecretaData.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/Secure.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/SecureFilter.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/TokenGenerator.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/RestUtil.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/UserInfo.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/AdminService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/DefinicionCompeticionesService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/EquiposService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/FasesService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/GetService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/GruposService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/InformationService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PaisesService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PartidosService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PostService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PronosticosService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/RankingService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/SearchService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/StandardService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/UsuariosService.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/ApplicationExceptionMapper.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/CorsFilter.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/LoggerFilter.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/RuntimeExceptionMapper.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/AdminServiceImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/EquiposServiceImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/FasesServiceImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/GruposServiceImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/InformationServiceImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PaisesServiceImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PartidosServiceImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PostServiceImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PronosticosServiceImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/RankingServiceImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/UsuariosServiceImpl.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/template/TemplateEngine.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/template/TemplateEngineException.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/util/JsonConverter.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/ApplicationValidator.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/annotations/Matches.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/annotations/Password.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/EmailValidator.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/MatchesValidator.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/PasswordValidator.java create mode 100644 packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/RedHatEmailValidator.java create mode 100644 packages/openscore-core-quarkus/src/main/resources/ValidationMessages.properties create mode 100644 packages/openscore-core-quarkus/src/main/resources/application.properties create mode 100644 packages/openscore-core-quarkus/src/main/resources/data/partidos.yml create mode 100644 packages/openscore-core-quarkus/src/main/resources/data/preguntas.yml create mode 100644 packages/openscore-core-quarkus/src/main/resources/info.properties create mode 100644 packages/openscore-core-quarkus/src/main/resources/logback.xml create mode 100644 packages/openscore-core-quarkus/src/main/resources/templates/recover.html create mode 100644 packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/model/UsuarioTest.java create mode 100644 packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/PaisRepositoryTest.java create mode 100644 packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/RepositoryBaseTest.java create mode 100644 packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/RepositoryTest.java create mode 100644 packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/TestObject.java create mode 100644 packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/TestRepository.java create mode 100644 packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/UsuarioRepositoryTest.java create mode 100644 packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/security/GenerateToken.java create mode 100644 packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/security/TokenGeneratorTest.java create mode 100644 packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/services/impl/UsuariosServiceImplTest.java diff --git a/packages/openscore-core-quarkus/.dockerignore b/packages/openscore-core-quarkus/.dockerignore new file mode 100644 index 0000000..94810d0 --- /dev/null +++ b/packages/openscore-core-quarkus/.dockerignore @@ -0,0 +1,5 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* +!target/quarkus-app/* \ No newline at end of file diff --git a/packages/openscore-core-quarkus/.gitignore b/packages/openscore-core-quarkus/.gitignore new file mode 100644 index 0000000..693002a --- /dev/null +++ b/packages/openscore-core-quarkus/.gitignore @@ -0,0 +1,40 @@ +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +release.properties +.flattened-pom.xml + +# Eclipse +.project +.classpath +.settings/ +bin/ + +# IntelliJ +.idea +*.ipr +*.iml +*.iws + +# NetBeans +nb-configuration.xml + +# Visual Studio Code +.vscode +.factorypath + +# OSX +.DS_Store + +# Vim +*.swp +*.swo + +# patch +*.orig +*.rej + +# Local environment +.env diff --git a/packages/openscore-core-quarkus/.mvn/wrapper/.gitignore b/packages/openscore-core-quarkus/.mvn/wrapper/.gitignore new file mode 100644 index 0000000..e72f5e8 --- /dev/null +++ b/packages/openscore-core-quarkus/.mvn/wrapper/.gitignore @@ -0,0 +1 @@ +maven-wrapper.jar diff --git a/packages/openscore-core-quarkus/.mvn/wrapper/MavenWrapperDownloader.java b/packages/openscore-core-quarkus/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..1708393 --- /dev/null +++ b/packages/openscore-core-quarkus/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,142 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import java.net.*; +import java.io.*; +import java.nio.channels.*; +import java.util.Properties; + +public class MavenWrapperDownloader +{ + private static final String WRAPPER_VERSION = "3.1.1"; + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = + "https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/" + WRAPPER_VERSION + + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to use instead of the + * default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main( String args[] ) + { + System.out.println( "- Downloader started" ); + File baseDirectory = new File( args[0] ); + System.out.println( "- Using base directory: " + baseDirectory.getAbsolutePath() ); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File( baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH ); + String url = DEFAULT_DOWNLOAD_URL; + if ( mavenWrapperPropertyFile.exists() ) + { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try + { + mavenWrapperPropertyFileInputStream = new FileInputStream( mavenWrapperPropertyFile ); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load( mavenWrapperPropertyFileInputStream ); + url = mavenWrapperProperties.getProperty( PROPERTY_NAME_WRAPPER_URL, url ); + } + catch ( IOException e ) + { + System.out.println( "- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'" ); + } + finally + { + try + { + if ( mavenWrapperPropertyFileInputStream != null ) + { + mavenWrapperPropertyFileInputStream.close(); + } + } + catch ( IOException e ) + { + // Ignore ... + } + } + } + System.out.println( "- Downloading from: " + url ); + + File outputFile = new File( baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH ); + if ( !outputFile.getParentFile().exists() ) + { + if ( !outputFile.getParentFile().mkdirs() ) + { + System.out.println( "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + + "'" ); + } + } + System.out.println( "- Downloading to: " + outputFile.getAbsolutePath() ); + try + { + downloadFileFromURL( url, outputFile ); + System.out.println( "Done" ); + System.exit( 0 ); + } + catch ( Throwable e ) + { + System.out.println( "- Error downloading" ); + e.printStackTrace(); + System.exit( 1 ); + } + } + + private static void downloadFileFromURL( String urlString, File destination ) + throws Exception + { + if ( System.getenv( "MVNW_USERNAME" ) != null && System.getenv( "MVNW_PASSWORD" ) != null ) + { + String username = System.getenv( "MVNW_USERNAME" ); + char[] password = System.getenv( "MVNW_PASSWORD" ).toCharArray(); + Authenticator.setDefault( new Authenticator() + { + @Override + protected PasswordAuthentication getPasswordAuthentication() + { + return new PasswordAuthentication( username, password ); + } + } ); + } + URL website = new URL( urlString ); + ReadableByteChannel rbc; + rbc = Channels.newChannel( website.openStream() ); + FileOutputStream fos = new FileOutputStream( destination ); + fos.getChannel().transferFrom( rbc, 0, Long.MAX_VALUE ); + fos.close(); + rbc.close(); + } + +} diff --git a/packages/openscore-core-quarkus/.mvn/wrapper/maven-wrapper.properties b/packages/openscore-core-quarkus/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..61a2ef1 --- /dev/null +++ b/packages/openscore-core-quarkus/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.6/apache-maven-3.8.6-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar diff --git a/packages/openscore-core-quarkus/README.md b/packages/openscore-core-quarkus/README.md new file mode 100644 index 0000000..53065ae --- /dev/null +++ b/packages/openscore-core-quarkus/README.md @@ -0,0 +1 @@ +docker run --name openscore-db -p 5432:5432 -e POSTGRES_PASSWORD=0p3nsc0r3 -e POSTGRES_USER=postgres -d postgres \ No newline at end of file diff --git a/packages/openscore-core-quarkus/mvnw b/packages/openscore-core-quarkus/mvnw new file mode 100755 index 0000000..eaa3d30 --- /dev/null +++ b/packages/openscore-core-quarkus/mvnw @@ -0,0 +1,316 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`\\unset -f command; \\command -v java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/packages/openscore-core-quarkus/mvnw.cmd b/packages/openscore-core-quarkus/mvnw.cmd new file mode 100644 index 0000000..abb7c32 --- /dev/null +++ b/packages/openscore-core-quarkus/mvnw.cmd @@ -0,0 +1,188 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Maven Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET DOWNLOAD_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/packages/openscore-core-quarkus/pom.xml b/packages/openscore-core-quarkus/pom.xml new file mode 100644 index 0000000..38232dd --- /dev/null +++ b/packages/openscore-core-quarkus/pom.xml @@ -0,0 +1,258 @@ + + + 4.0.0 + io.semantic + openscore-core-quarkus + 1.0.0-SNAPSHOT + + 3.8.1 + 11 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 2.12.1.Final + true + 3.0.0-M7 + + 2.10.0 + 1.2.0.Final + 4.13.1 + 1.7.24 + 1.4.1 + 1.4.1.Final + + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-resteasy + + + io.quarkus + quarkus-resteasy-jsonb + + + io.quarkus + quarkus-junit5 + test + + + io.rest-assured + rest-assured + test + + + + org.slf4j + slf4j-api + ${version.org.slf4j} + + + + ch.qos.logback + logback-classic + ${version.ch.qos.logback} + + + com.google.guava + guava + 23.5-jre + + + commons-beanutils + commons-beanutils + 1.9.4 + + + javax.mail + mail + 1.4.7 + + + io.pebbletemplates + pebble + 3.1.6 + + + + org.jboss.resteasy + resteasy-client + 3.0.14.Final + test + + + com.h2database + h2 + 1.4.196 + test + + + org.apache.commons + commons-text + 1.3 + + + + org.mapstruct + mapstruct + ${org.mapstruct.version} + + + org.mapstruct + mapstruct-processor + ${org.mapstruct.version} + + + javax.el + javax.el-api + 2.2.4 + + + com.nimbusds + nimbus-jose-jwt + 9.25.4 + + + com.google.code.gson + gson + 2.9.0 + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + 2.3.0 + + + com.fasterxml.jackson.core + jackson-databind + 2.13.3 + + + junit + junit + ${version.junit} + + + org.mockito + mockito-core + ${version.org.mockito} + + + + + io.quarkus + quarkus-hibernate-orm + + + + + io.quarkus + quarkus-jdbc-postgresql + + + + io.quarkus + quarkus-hibernate-validator + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + + -parameters + + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + org.jboss.jandex + jandex-maven-plugin + 1.2.3 + + + make-index + + jandex + + + + + + + + + native + + + native + + + + false + native + + + + \ No newline at end of file diff --git a/packages/openscore-core-quarkus/src/main/docker/Dockerfile.jvm b/packages/openscore-core-quarkus/src/main/docker/Dockerfile.jvm new file mode 100644 index 0000000..63d045e --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/docker/Dockerfile.jvm @@ -0,0 +1,94 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.jvm -t quarkus/code-with-quarkus-jvm . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/code-with-quarkus-jvm +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 quarkus/code-with-quarkus-jvm +# +# This image uses the `run-java.sh` script to run the application. +# This scripts computes the command line to execute your Java application, and +# includes memory/GC tuning. +# You can configure the behavior using the following environment properties: +# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") +# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options +# in JAVA_OPTS (example: "-Dsome.property=foo") +# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is +# used to calculate a default maximal heap memory based on a containers restriction. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio +# of the container available memory as set here. The default is `50` which means 50% +# of the available memory is used as an upper boundary. You can skip this mechanism by +# setting this value to `0` in which case no `-Xmx` option is added. +# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This +# is used to calculate a default initial heap memory based on the maximum heap memory. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio +# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx` +# is used as the initial heap size. You can skip this mechanism by setting this value +# to `0` in which case no `-Xms` option is added (example: "25") +# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS. +# This is used to calculate the maximum value of the initial heap memory. If used in +# a container without any memory constraints for the container then this option has +# no effect. If there is a memory constraint then `-Xms` is limited to the value set +# here. The default is 4096MB which means the calculated value of `-Xms` never will +# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096") +# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output +# when things are happening. This option, if set to true, will set +# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true"). +# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example: +# true"). +# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787"). +# - CONTAINER_CORE_LIMIT: A calculated core limit as described in +# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2") +# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024"). +# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion. +# (example: "20") +# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking. +# (example: "40") +# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection. +# (example: "4") +# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus +# previous GC times. (example: "90") +# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20") +# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100") +# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should +# contain the necessary JRE command-line options to specify the required GC, which +# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC). +# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080") +# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080") +# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be +# accessed directly. (example: "foo.example.com,bar.example.com") +# +### +FROM registry.access.redhat.com/ubi8/openjdk-11:1.11 + +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' + + +# We make four distinct layers so if there are application changes the library layers can be re-used +COPY --chown=185 target/quarkus-app/lib/ /deployments/lib/ +COPY --chown=185 target/quarkus-app/*.jar /deployments/ +COPY --chown=185 target/quarkus-app/app/ /deployments/app/ +COPY --chown=185 target/quarkus-app/quarkus/ /deployments/quarkus/ + +EXPOSE 8080 +USER 185 +ENV AB_JOLOKIA_OFF="" +ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" + diff --git a/packages/openscore-core-quarkus/src/main/docker/Dockerfile.legacy-jar b/packages/openscore-core-quarkus/src/main/docker/Dockerfile.legacy-jar new file mode 100644 index 0000000..7169565 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/docker/Dockerfile.legacy-jar @@ -0,0 +1,90 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in JVM mode +# +# Before building the container image run: +# +# ./mvnw package -Dquarkus.package.type=legacy-jar +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.legacy-jar -t quarkus/code-with-quarkus-legacy-jar . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/code-with-quarkus-legacy-jar +# +# If you want to include the debug port into your docker image +# you will have to expose the debug port (default 5005) like this : EXPOSE 8080 5005 +# +# Then run the container using : +# +# docker run -i --rm -p 8080:8080 quarkus/code-with-quarkus-legacy-jar +# +# This image uses the `run-java.sh` script to run the application. +# This scripts computes the command line to execute your Java application, and +# includes memory/GC tuning. +# You can configure the behavior using the following environment properties: +# - JAVA_OPTS: JVM options passed to the `java` command (example: "-verbose:class") +# - JAVA_OPTS_APPEND: User specified Java options to be appended to generated options +# in JAVA_OPTS (example: "-Dsome.property=foo") +# - JAVA_MAX_MEM_RATIO: Is used when no `-Xmx` option is given in JAVA_OPTS. This is +# used to calculate a default maximal heap memory based on a containers restriction. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xmx` is set to a ratio +# of the container available memory as set here. The default is `50` which means 50% +# of the available memory is used as an upper boundary. You can skip this mechanism by +# setting this value to `0` in which case no `-Xmx` option is added. +# - JAVA_INITIAL_MEM_RATIO: Is used when no `-Xms` option is given in JAVA_OPTS. This +# is used to calculate a default initial heap memory based on the maximum heap memory. +# If used in a container without any memory constraints for the container then this +# option has no effect. If there is a memory constraint then `-Xms` is set to a ratio +# of the `-Xmx` memory as set here. The default is `25` which means 25% of the `-Xmx` +# is used as the initial heap size. You can skip this mechanism by setting this value +# to `0` in which case no `-Xms` option is added (example: "25") +# - JAVA_MAX_INITIAL_MEM: Is used when no `-Xms` option is given in JAVA_OPTS. +# This is used to calculate the maximum value of the initial heap memory. If used in +# a container without any memory constraints for the container then this option has +# no effect. If there is a memory constraint then `-Xms` is limited to the value set +# here. The default is 4096MB which means the calculated value of `-Xms` never will +# be greater than 4096MB. The value of this variable is expressed in MB (example: "4096") +# - JAVA_DIAGNOSTICS: Set this to get some diagnostics information to standard output +# when things are happening. This option, if set to true, will set +# `-XX:+UnlockDiagnosticVMOptions`. Disabled by default (example: "true"). +# - JAVA_DEBUG: If set remote debugging will be switched on. Disabled by default (example: +# true"). +# - JAVA_DEBUG_PORT: Port used for remote debugging. Defaults to 5005 (example: "8787"). +# - CONTAINER_CORE_LIMIT: A calculated core limit as described in +# https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt. (example: "2") +# - CONTAINER_MAX_MEMORY: Memory limit given to the container (example: "1024"). +# - GC_MIN_HEAP_FREE_RATIO: Minimum percentage of heap free after GC to avoid expansion. +# (example: "20") +# - GC_MAX_HEAP_FREE_RATIO: Maximum percentage of heap free after GC to avoid shrinking. +# (example: "40") +# - GC_TIME_RATIO: Specifies the ratio of the time spent outside the garbage collection. +# (example: "4") +# - GC_ADAPTIVE_SIZE_POLICY_WEIGHT: The weighting given to the current GC time versus +# previous GC times. (example: "90") +# - GC_METASPACE_SIZE: The initial metaspace size. (example: "20") +# - GC_MAX_METASPACE_SIZE: The maximum metaspace size. (example: "100") +# - GC_CONTAINER_OPTIONS: Specify Java GC to use. The value of this variable should +# contain the necessary JRE command-line options to specify the required GC, which +# will override the default of `-XX:+UseParallelGC` (example: -XX:+UseG1GC). +# - HTTPS_PROXY: The location of the https proxy. (example: "myuser@127.0.0.1:8080") +# - HTTP_PROXY: The location of the http proxy. (example: "myuser@127.0.0.1:8080") +# - NO_PROXY: A comma separated lists of hosts, IP addresses or domains that can be +# accessed directly. (example: "foo.example.com,bar.example.com") +# +### +FROM registry.access.redhat.com/ubi8/openjdk-11:1.11 + +ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' + + +COPY target/lib/* /deployments/lib/ +COPY target/*-runner.jar /deployments/quarkus-run.jar + +EXPOSE 8080 +USER 185 +ENV AB_JOLOKIA_OFF="" +ENV JAVA_OPTS="-Dquarkus.http.host=0.0.0.0 -Djava.util.logging.manager=org.jboss.logmanager.LogManager" +ENV JAVA_APP_JAR="/deployments/quarkus-run.jar" diff --git a/packages/openscore-core-quarkus/src/main/docker/Dockerfile.native b/packages/openscore-core-quarkus/src/main/docker/Dockerfile.native new file mode 100644 index 0000000..b932d86 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/docker/Dockerfile.native @@ -0,0 +1,27 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode. +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native -t quarkus/code-with-quarkus . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/code-with-quarkus +# +### +FROM registry.access.redhat.com/ubi8/ubi-minimal:8.5 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 8080 +USER 1001 + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/packages/openscore-core-quarkus/src/main/docker/Dockerfile.native-micro b/packages/openscore-core-quarkus/src/main/docker/Dockerfile.native-micro new file mode 100644 index 0000000..691cfe3 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/docker/Dockerfile.native-micro @@ -0,0 +1,30 @@ +#### +# This Dockerfile is used in order to build a container that runs the Quarkus application in native (no JVM) mode. +# It uses a micro base image, tuned for Quarkus native executables. +# It reduces the size of the resulting container image. +# Check https://quarkus.io/guides/quarkus-runtime-base-image for further information about this image. +# +# Before building the container image run: +# +# ./mvnw package -Pnative +# +# Then, build the image with: +# +# docker build -f src/main/docker/Dockerfile.native-micro -t quarkus/code-with-quarkus . +# +# Then run the container using: +# +# docker run -i --rm -p 8080:8080 quarkus/code-with-quarkus +# +### +FROM quay.io/quarkus/quarkus-micro-image:1.0 +WORKDIR /work/ +RUN chown 1001 /work \ + && chmod "g+rwX" /work \ + && chown 1001:root /work +COPY --chown=1001:root target/*-runner /work/application + +EXPOSE 8080 +USER 1001 + +CMD ["./application", "-Dquarkus.http.host=0.0.0.0"] diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/OpenScoreApplication.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/OpenScoreApplication.java new file mode 100644 index 0000000..c83d0db --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/OpenScoreApplication.java @@ -0,0 +1,9 @@ +package io.semantic.openscore.core; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("api/rest") +public class OpenScoreApplication extends Application { + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ApiResponse.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ApiResponse.java new file mode 100644 index 0000000..4de138f --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ApiResponse.java @@ -0,0 +1,35 @@ +package io.semantic.openscore.core.api; + +public class ApiResponse { + + private String error; + private String description; + private T data; + + public ApiResponse() { + } + + public ApiResponse(T data) { + this.data = data; + } + + public ApiResponse(String error, + String description, + T data) { + this(data); + this.description = description; + this.error = error; + } + + public String getDescription() { + return description; + } + + public String getError() { + return error; + } + + public T getData() { + return data; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ImagenApi.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ImagenApi.java new file mode 100644 index 0000000..7f4ae17 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ImagenApi.java @@ -0,0 +1,32 @@ +package io.semantic.openscore.core.api; + +public class ImagenApi { + + private long id; + private String nombre; + private byte[] content; + + public byte[] getContent() { + return content; + } + + public void setContent(byte[] content) { + this.content = content; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/TokenDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/TokenDTO.java new file mode 100644 index 0000000..e01be9d --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/TokenDTO.java @@ -0,0 +1,18 @@ +package io.semantic.openscore.core.api; + +public class TokenDTO { + + private String token; + + public TokenDTO(String token) { + this.token = token; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/admin/UsuarioCompletoDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/admin/UsuarioCompletoDTO.java new file mode 100644 index 0000000..d9aa8a9 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/admin/UsuarioCompletoDTO.java @@ -0,0 +1,87 @@ +package io.semantic.openscore.core.api.admin; + +import io.semantic.openscore.core.api.paises.PaisDTO; + +public class UsuarioCompletoDTO { + private long id; + private String nombre; + private String apellido; + private PaisDTO pais; + private String email; + private boolean deleted; + private String creationDate; + private String deletionDate; + private String modificationDate; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getApellido() { + return apellido; + } + + public void setApellido(String apellido) { + this.apellido = apellido; + } + + public PaisDTO getPais() { + return pais; + } + + public void setPais(PaisDTO pais) { + this.pais = pais; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public String getCreationDate() { + return creationDate; + } + + public void setCreationDate(String creationDate) { + this.creationDate = creationDate; + } + + public String getDeletionDate() { + return deletionDate; + } + + public void setDeletionDate(String deletionDate) { + this.deletionDate = deletionDate; + } + + public String getModificationDate() { + return modificationDate; + } + + public void setModificationDate(String modificationDate) { + this.modificationDate = modificationDate; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/competiciones/CrearDefinicionCompeticionDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/competiciones/CrearDefinicionCompeticionDTO.java new file mode 100644 index 0000000..8ba4e0f --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/competiciones/CrearDefinicionCompeticionDTO.java @@ -0,0 +1,33 @@ +package io.semantic.openscore.core.api.competiciones; + +public class CrearDefinicionCompeticionDTO { + + private String nombre; + private String logo; + private String descripcion; + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getLogo() { + return logo; + } + + public void setLogo(String logo) { + this.logo = logo; + } + + public String getDescripcion() { + return descripcion; + } + + public void setDescripcion(String descripcion) { + this.descripcion = descripcion; + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/competiciones/DefinicionCompeticionDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/competiciones/DefinicionCompeticionDTO.java new file mode 100644 index 0000000..42fcb71 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/competiciones/DefinicionCompeticionDTO.java @@ -0,0 +1,32 @@ +package io.semantic.openscore.core.api.competiciones; + +public class DefinicionCompeticionDTO { + + private String nombre; + private String logo; + private String descripcion; + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getLogo() { + return logo; + } + + public void setLogo(String logo) { + this.logo = logo; + } + + public String getDescripcion() { + return descripcion; + } + + public void setDescripcion(String descripcion) { + this.descripcion = descripcion; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/equipos/CrearEquipoDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/equipos/CrearEquipoDTO.java new file mode 100644 index 0000000..19322c0 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/equipos/CrearEquipoDTO.java @@ -0,0 +1,41 @@ +package io.semantic.openscore.core.api.equipos; + +public class CrearEquipoDTO { + + private String nombre; + private String codigo; + private String codigoPais; + private String logo; + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getCodigo() { + return codigo; + } + + public void setCodigo(String codigo) { + this.codigo = codigo; + } + + public String getCodigoPais() { + return codigoPais; + } + + public void setCodigoPais(String codigoPais) { + this.codigoPais = codigoPais; + } + + public String getLogo() { + return logo; + } + + public void setLogo(String logo) { + this.logo = logo; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/equipos/EquipoDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/equipos/EquipoDTO.java new file mode 100644 index 0000000..c69830a --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/equipos/EquipoDTO.java @@ -0,0 +1,52 @@ +package io.semantic.openscore.core.api.equipos; + +import io.semantic.openscore.core.api.paises.PaisDTO; + +public class EquipoDTO { + + private long id; + private String nombre; + private String codigo; + private PaisDTO pais; + private String logo; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getCodigo() { + return codigo; + } + + public void setCodigo(String codigo) { + this.codigo = codigo; + } + + public String getLogo() { + return logo; + } + + public void setLogo(String logo) { + this.logo = logo; + } + + public PaisDTO getPais() { + return pais; + } + + public void setPais(PaisDTO pais) { + this.pais = pais; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/grupos/FaseDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/grupos/FaseDTO.java new file mode 100644 index 0000000..b614846 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/grupos/FaseDTO.java @@ -0,0 +1,23 @@ +package io.semantic.openscore.core.api.grupos; + +public class FaseDTO { + + private String codigo; + private String nombre; + + public String getCodigo() { + return codigo; + } + + public void setCodigo(String codigo) { + this.codigo = codigo; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/grupos/GrupoDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/grupos/GrupoDTO.java new file mode 100644 index 0000000..b867b74 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/grupos/GrupoDTO.java @@ -0,0 +1,23 @@ +package io.semantic.openscore.core.api.grupos; + +public class GrupoDTO { + + private String codigo; + private String nombre; + + public String getCodigo() { + return codigo; + } + + public void setCodigo(String codigo) { + this.codigo = codigo; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/information/Information.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/information/Information.java new file mode 100644 index 0000000..a70eed5 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/information/Information.java @@ -0,0 +1,35 @@ +package io.semantic.openscore.core.api.information; + +import java.util.Map; + +public class Information { + + private String version; + private String environment; + + private Map properties; + + public void setVersion(String version) { + this.version = version; + } + + public String getVersion() { + return version; + } + + public void setEnvironment(String environment) { + this.environment = environment; + } + + public String getEnvironment() { + return environment; + } + + public Map getProperties() { + return properties; + } + + public void setProperties(Map properties) { + this.properties = properties; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/paises/PaisDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/paises/PaisDTO.java new file mode 100644 index 0000000..648a31d --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/paises/PaisDTO.java @@ -0,0 +1,23 @@ +package io.semantic.openscore.core.api.paises; + +public class PaisDTO { + + private String codigo; + private String nombre; + + public String getCodigo() { + return codigo; + } + + public void setCodigo(String codigo) { + this.codigo = codigo; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/CrearOUpdatePartidoDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/CrearOUpdatePartidoDTO.java new file mode 100644 index 0000000..da94583 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/CrearOUpdatePartidoDTO.java @@ -0,0 +1,70 @@ +package io.semantic.openscore.core.api.partidos; + +import java.util.Date; + +public class CrearOUpdatePartidoDTO { + + private String local; + private String visitante; + private Date dia; + private int fecha; + private String lugar; + private String grupo; + private String fase; + + public String getLocal() { + return local; + } + + public void setLocal(String local) { + this.local = local; + } + + public String getVisitante() { + return visitante; + } + + public void setVisitante(String visitante) { + this.visitante = visitante; + } + + public Date getDia() { + return dia; + } + + public void setDia(Date dia) { + this.dia = dia; + } + + public String getLugar() { + return lugar; + } + + public void setLugar(String lugar) { + this.lugar = lugar; + } + + public int getFecha() { + return fecha; + } + + public void setFecha(int fecha) { + this.fecha = fecha; + } + + public String getGrupo() { + return grupo; + } + + public void setGrupo(String grupo) { + this.grupo = grupo; + } + + public String getFase() { + return fase; + } + + public void setFase(String fase) { + this.fase = fase; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/PartidoDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/PartidoDTO.java new file mode 100644 index 0000000..efb89eb --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/PartidoDTO.java @@ -0,0 +1,101 @@ +package io.semantic.openscore.core.api.partidos; + +import io.semantic.openscore.core.api.equipos.EquipoDTO; +import io.semantic.openscore.core.api.grupos.FaseDTO; +import io.semantic.openscore.core.api.grupos.GrupoDTO; + +import java.util.Date; + +public class PartidoDTO { + + private long id; + private EquipoDTO local; + private EquipoDTO visitante; + private Date dia; + private int fecha; + private GrupoDTO grupo; + private FaseDTO fase; + private String lugar; + private String status; + private ResultadoDTO resultado; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public EquipoDTO getLocal() { + return local; + } + + public void setLocal(EquipoDTO local) { + this.local = local; + } + + public EquipoDTO getVisitante() { + return visitante; + } + + public void setVisitante(EquipoDTO visitante) { + this.visitante = visitante; + } + + public Date getDia() { + return dia; + } + + public void setDia(Date dia) { + this.dia = dia; + } + + public String getLugar() { + return lugar; + } + + public void setLugar(String lugar) { + this.lugar = lugar; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public GrupoDTO getGrupo() { + return grupo; + } + + public void setGrupo(GrupoDTO grupo) { + this.grupo = grupo; + } + + public FaseDTO getFase() { + return fase; + } + + public void setFase(FaseDTO fase) { + this.fase = fase; + } + + public int getFecha() { + return fecha; + } + + public void setFecha(int fecha) { + this.fecha = fecha; + } + + public ResultadoDTO getResultado() { + return resultado; + } + + public void setResultado(ResultadoDTO resultado) { + this.resultado = resultado; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/ResultadoDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/ResultadoDTO.java new file mode 100644 index 0000000..dd21c78 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/partidos/ResultadoDTO.java @@ -0,0 +1,23 @@ +package io.semantic.openscore.core.api.partidos; + +public class ResultadoDTO { + + private int local; + private int visitante; + + public int getLocal() { + return local; + } + + public void setLocal(int local) { + this.local = local; + } + + public int getVisitante() { + return visitante; + } + + public void setVisitante(int visitante) { + this.visitante = visitante; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/post/CrearPost.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/post/CrearPost.java new file mode 100644 index 0000000..6f2411a --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/post/CrearPost.java @@ -0,0 +1,32 @@ +package io.semantic.openscore.core.api.post; + +public class CrearPost { + + private String titulo; + private String contenido; + private String autor; + + public String getTitulo() { + return titulo; + } + + public void setTitulo(String titulo) { + this.titulo = titulo; + } + + public String getContenido() { + return contenido; + } + + public void setContenido(String contenido) { + this.contenido = contenido; + } + + public String getAutor() { + return autor; + } + + public void setAutor(String autor) { + this.autor = autor; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/CrearPronosticoDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/CrearPronosticoDTO.java new file mode 100644 index 0000000..f0e0b1c --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/CrearPronosticoDTO.java @@ -0,0 +1,42 @@ +package io.semantic.openscore.core.api.pronosticos; + +public class CrearPronosticoDTO { + + + private boolean local; + private boolean visitante; + private boolean empate; + private long partido; + + public boolean isLocal() { + return local; + } + + public void setLocal(boolean local) { + this.local = local; + } + + public boolean isVisitante() { + return visitante; + } + + public void setVisitante(boolean visitante) { + this.visitante = visitante; + } + + public boolean isEmpate() { + return empate; + } + + public void setEmpate(boolean empate) { + this.empate = empate; + } + + public long getPartido() { + return partido; + } + + public void setPartido(long partido) { + this.partido = partido; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/PartidoPronosticoDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/PartidoPronosticoDTO.java new file mode 100644 index 0000000..0f7408e --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/PartidoPronosticoDTO.java @@ -0,0 +1,16 @@ +package io.semantic.openscore.core.api.pronosticos; + +import io.semantic.openscore.core.api.partidos.PartidoDTO; + +public class PartidoPronosticoDTO extends PartidoDTO { + + private PronosticoDTO pronostico; + + public PronosticoDTO getPronostico() { + return pronostico; + } + + public void setPronostico(PronosticoDTO pronostico) { + this.pronostico = pronostico; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/PronosticoDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/PronosticoDTO.java new file mode 100644 index 0000000..1c397e5 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/pronosticos/PronosticoDTO.java @@ -0,0 +1,49 @@ +package io.semantic.openscore.core.api.pronosticos; + +import io.semantic.openscore.core.model.Usuario; + +import javax.persistence.ManyToOne; + +public class PronosticoDTO { + + private long id; + private boolean local; + private boolean visitante; + private boolean empate; + + @ManyToOne + private Usuario usuario; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public boolean isLocal() { + return local; + } + + public void setLocal(boolean local) { + this.local = local; + } + + public boolean isVisitante() { + return visitante; + } + + public void setVisitante(boolean visitante) { + this.visitante = visitante; + } + + public boolean isEmpate() { + return empate; + } + + public void setEmpate(boolean empate) { + this.empate = empate; + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ranking/Ranking.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ranking/Ranking.java new file mode 100644 index 0000000..4704c0f --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/ranking/Ranking.java @@ -0,0 +1,50 @@ +package io.semantic.openscore.core.api.ranking; + +public class Ranking { + + private int ranking; + private int puntos; + private String nombre; + private String pais; + private long usuario; + + public int getRanking() { + return ranking; + } + + public void setRanking(int ranking) { + this.ranking = ranking; + } + + public int getPuntos() { + return puntos; + } + + public void setPuntos(int puntos) { + this.puntos = puntos; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getPais() { + return pais; + } + + public void setPais(String pais) { + this.pais = pais; + } + + public long getUsuario() { + return usuario; + } + + public void setUsuario(long usuario) { + this.usuario = usuario; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/CrearUsuarioDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/CrearUsuarioDTO.java new file mode 100644 index 0000000..553b124 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/CrearUsuarioDTO.java @@ -0,0 +1,100 @@ +package io.semantic.openscore.core.api.usuarios; + +import io.semantic.openscore.core.validation.annotations.Matches; +import io.semantic.openscore.core.validation.annotations.Password; +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotEmpty; + +import javax.validation.constraints.NotNull; + +@Matches.List({ + @Matches(first = "password", second = "confirmacionPassword"), + @Matches(first = "email", second = "confirmacionEmail")}) +public class CrearUsuarioDTO { + + @NotNull + @Length(min = 2) + private String nombre; + + @NotNull + @Length(min = 2) + private String apellido; + + @NotNull + @NotEmpty + private String pais; + + @NotNull + @Email(regexp = ".*@redhat\\.com") + private String email; + + @NotNull + @Email(regexp = ".*@redhat\\.com") + private String confirmacionEmail; + + @NotNull + @Password + private String password; + + @NotNull + @Password + private String confirmacionPassword; + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getApellido() { + return apellido; + } + + public void setApellido(String apellido) { + this.apellido = apellido; + } + + public String getPais() { + return pais; + } + + public void setPais(String pais) { + this.pais = pais; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getConfirmacionEmail() { + return confirmacionEmail; + } + + public void setConfirmacionEmail(String confirmacionEmail) { + this.confirmacionEmail = confirmacionEmail; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getConfirmacionPassword() { + return confirmacionPassword; + } + + public void setConfirmacionPassword(String confirmacionPassword) { + this.confirmacionPassword = confirmacionPassword; + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/LoginUsuarioDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/LoginUsuarioDTO.java new file mode 100644 index 0000000..1b70131 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/LoginUsuarioDTO.java @@ -0,0 +1,23 @@ +package io.semantic.openscore.core.api.usuarios; + +public class LoginUsuarioDTO { + + private String email; + private String password; + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/RecoverPassword.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/RecoverPassword.java new file mode 100644 index 0000000..1508e42 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/RecoverPassword.java @@ -0,0 +1,60 @@ +package io.semantic.openscore.core.api.usuarios; + +import io.semantic.openscore.core.validation.annotations.Matches; +import io.semantic.openscore.core.validation.annotations.Password; +import org.hibernate.validator.constraints.Email; + +import javax.validation.constraints.NotNull; + +@Matches.List({ + @Matches(first = "password", second = "confirmacionPassword")}) +public class RecoverPassword { + + + @NotNull + @Email(regexp = ".*@redhat\\.com") + private String email; + + @NotNull + private String token; + + @NotNull + @Password + private String password; + + @NotNull + @Password + private String confirmacionPassword; + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getConfirmacionPassword() { + return confirmacionPassword; + } + + public void setConfirmacionPassword(String confirmacionPassword) { + this.confirmacionPassword = confirmacionPassword; + } + + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdatePassword.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdatePassword.java new file mode 100644 index 0000000..854c287 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdatePassword.java @@ -0,0 +1,47 @@ +package io.semantic.openscore.core.api.usuarios; + +import io.semantic.openscore.core.validation.annotations.Matches; +import io.semantic.openscore.core.validation.annotations.Password; +import org.hibernate.validator.constraints.NotEmpty; + +import javax.validation.constraints.NotNull; + +@Matches.List({ + @Matches(first = "password", second = "confirmacionPassword")}) +public class UpdatePassword { + + @NotEmpty + private String oldPassword; + + @NotEmpty + @Password + private String password; + + @NotEmpty + @Password + private String confirmacionPassword; + + public String getOldPassword() { + return oldPassword; + } + + public void setOldPassword(String oldPassword) { + this.oldPassword = oldPassword; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public String getConfirmacionPassword() { + return confirmacionPassword; + } + + public void setConfirmacionPassword(String confirmacionPassword) { + this.confirmacionPassword = confirmacionPassword; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdateSecretQuestion.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdateSecretQuestion.java new file mode 100644 index 0000000..c68f7ed --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdateSecretQuestion.java @@ -0,0 +1,42 @@ +package io.semantic.openscore.core.api.usuarios; + +import io.semantic.openscore.core.validation.annotations.Password; + +import javax.validation.constraints.NotNull; + +public class UpdateSecretQuestion { + + @NotNull + private String preguntaSecreta; + + @NotNull + private String respuestaPreguntaSecreta; + + @NotNull + @Password + private String password; + + public String getPreguntaSecreta() { + return preguntaSecreta; + } + + public void setPreguntaSecreta(String preguntaSecreta) { + this.preguntaSecreta = preguntaSecreta; + } + + public String getRespuestaPreguntaSecreta() { + return respuestaPreguntaSecreta; + } + + public void setRespuestaPreguntaSecreta(String respuestaPreguntaSecreta) { + this.respuestaPreguntaSecreta = respuestaPreguntaSecreta; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdateUsuarioDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdateUsuarioDTO.java new file mode 100644 index 0000000..1bcfcf2 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UpdateUsuarioDTO.java @@ -0,0 +1,46 @@ +package io.semantic.openscore.core.api.usuarios; + +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotEmpty; + +import javax.validation.constraints.NotNull; + +public class UpdateUsuarioDTO { + + @NotNull + @Length(min = 2) + private String nombre; + + @NotNull + @Length(min = 2) + private String apellido; + + @NotNull + @NotEmpty + private String pais; + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getApellido() { + return apellido; + } + + public void setApellido(String apellido) { + this.apellido = apellido; + } + + public String getPais() { + return pais; + } + + public void setPais(String pais) { + this.pais = pais; + } +} + diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UsuarioDTO.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UsuarioDTO.java new file mode 100644 index 0000000..713510c --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/api/usuarios/UsuarioDTO.java @@ -0,0 +1,69 @@ +package io.semantic.openscore.core.api.usuarios; + +import io.semantic.openscore.core.api.paises.PaisDTO; +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.NotEmpty; + +import javax.validation.constraints.NotNull; + +public class UsuarioDTO { + + @NotEmpty + private long id; + + @NotNull + @Length(min = 2) + private String nombre; + + @NotNull + @Length(min = 2) + private String apellido; + + @NotNull + private PaisDTO pais; + + @NotNull + @Email + private String email; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getApellido() { + return apellido; + } + + public void setApellido(String apellido) { + this.apellido = apellido; + } + + public PaisDTO getPais() { + return pais; + } + + public void setPais(PaisDTO pais) { + this.pais = pais; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/cache/TokenCache.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/cache/TokenCache.java new file mode 100644 index 0000000..470b2df --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/cache/TokenCache.java @@ -0,0 +1,74 @@ +package io.semantic.openscore.core.cache; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.cache.CacheBuilder; +import com.google.common.cache.CacheLoader; +import com.google.common.cache.LoadingCache; +import com.google.common.cache.RemovalCause; +import com.google.common.cache.RemovalListener; +import com.google.common.cache.RemovalNotification; + +import javax.annotation.PostConstruct; +import javax.enterprise.context.ApplicationScoped; +import java.io.IOException; +import java.util.Optional; +import java.util.concurrent.ExecutionException; + +@ApplicationScoped +public class TokenCache { + + private Logger logger = LoggerFactory.getLogger(TokenCache.class); + private LoadingCache cache; + + public TokenCache() { + CacheLoader loader; + loader = new CacheLoader() { + @Override + public String load(final String key) { + return key.toUpperCase(); + } + }; + + LoadingCache cache; + cache = CacheBuilder.newBuilder() + .maximumSize(3) + .build(loader); + + } + + public boolean isValid(String email, String token) { + Optional t; + try { + t = Optional.ofNullable(this.cache.get(email)); + return t.map(x -> x.equals(token)).orElse(false); + } catch (ExecutionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return false; + } + + public void remove(String email) { + this.cache.invalidate(email); + logger.info("Entry <{}> removed, new object count: {}", email, this.cache.size()); + } + + public void add(String email, String token) { + this.cache.put(email, token); + logger.info("Entry <{}> added, new object count: {}", email, this.cache.size()); + } + + public Optional getToken(String email) { + String token = null; + try { + token = this.cache.get(email); + } catch (ExecutionException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + logger.info("For key <{}>, value found: <{}>", email, token); + return Optional.ofNullable(token); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/FSMailProvider.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/FSMailProvider.java new file mode 100644 index 0000000..a3c6182 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/FSMailProvider.java @@ -0,0 +1,34 @@ +package io.semantic.openscore.core.email; + +import com.google.common.io.Files; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Alternative; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +@Alternative +@ApplicationScoped +public class FSMailProvider implements MailProvider { + + private Logger logger = LoggerFactory.getLogger(FSMailProvider.class); + + @Override + public void send(String to, String subject, String mail) { + try { + File folder = new File("/tmp/mail"); + if (!folder.exists()) { + folder.mkdirs(); + } + File file = new File(folder, to + "_" + subject + ".html"); + file.createNewFile(); + Files.asCharSink(file, StandardCharsets.UTF_8).write(mail); + logger.info("Email sent"); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailFactory.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailFactory.java new file mode 100644 index 0000000..4255698 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailFactory.java @@ -0,0 +1,17 @@ +package io.semantic.openscore.core.email; + +import java.util.HashMap; +import java.util.Map; + +import javax.enterprise.context.ApplicationScoped; + +@ApplicationScoped +public class MailFactory { + + public MailTemplate getRecoverPasswordEmail(String to, String token) { + Map map = new HashMap<>(); + map.put("email", to); + map.put("token", token); + return new MailTemplate(to, "Recover Password", "recover", map); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailProvider.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailProvider.java new file mode 100644 index 0000000..45cff98 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailProvider.java @@ -0,0 +1,6 @@ +package io.semantic.openscore.core.email; + +public interface MailProvider { + + void send(String to, String subject, String email); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailServer.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailServer.java new file mode 100644 index 0000000..ff41515 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailServer.java @@ -0,0 +1,30 @@ +package io.semantic.openscore.core.email; + +import io.semantic.openscore.core.template.TemplateEngine; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +@ApplicationScoped +public class MailServer { + + private MailProvider provider; + private TemplateEngine templateEngine; + + + public MailServer() { + } + + @Inject + public MailServer(MailProvider provider, + TemplateEngine templateEngine) { + + this.provider = provider; + this.templateEngine = templateEngine; + } + + public void send(MailTemplate template) { + String email = this.templateEngine.evaluate(template.getTemplateName(), template.getParams()); + this.provider.send(template.getTo(), template.getSubject(), email); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailTemplate.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailTemplate.java new file mode 100644 index 0000000..8430fbf --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/MailTemplate.java @@ -0,0 +1,38 @@ +package io.semantic.openscore.core.email; + +import java.util.Map; + +public class MailTemplate { + + private final String to; + private final String subject; + private final String templateName; + private final Map params; + + public MailTemplate(String to, + String subject, + String templateName, + Map params) { + + this.to = to; + this.subject = subject; + this.templateName = templateName; + this.params = params; + } + + public String getTo() { + return to; + } + + public String getSubject() { + return subject; + } + + public String getTemplateName() { + return templateName; + } + + public Map getParams() { + return params; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/SMTPProvider.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/SMTPProvider.java new file mode 100644 index 0000000..8cf837f --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/SMTPProvider.java @@ -0,0 +1,34 @@ +package io.semantic.openscore.core.email; + +import javax.annotation.Resource; +import javax.enterprise.context.ApplicationScoped; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; +import java.util.Date; + +@ApplicationScoped +public class SMTPProvider implements MailProvider { + + @Resource(lookup = "EMailME") + private Session mailSession; + + @Override + public void send(String to, String subject, String email) { + MimeMessage message = new MimeMessage(mailSession); + try { + message.setFrom(new InternetAddress(mailSession.getProperty("mail.from"))); + InternetAddress[] address = {new InternetAddress(to)}; + message.setRecipients(Message.RecipientType.TO, address); + message.setSubject(subject); + message.setSentDate(new Date()); + message.setText(email); + Transport.send(message); + } catch (MessagingException ex) { + ex.printStackTrace(); + } + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/StdoutMailSender.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/StdoutMailSender.java new file mode 100644 index 0000000..8899573 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/email/StdoutMailSender.java @@ -0,0 +1,22 @@ +package io.semantic.openscore.core.email; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Alternative; + +@Alternative +@ApplicationScoped +public class StdoutMailSender implements MailProvider { + + private Logger logger = LoggerFactory.getLogger(StdoutMailSender.class); + + public StdoutMailSender() { + } + + @Override + public void send(String to, String subject, String email) { + logger.info(email); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/ApplicationException.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/ApplicationException.java new file mode 100644 index 0000000..9cb2b95 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/ApplicationException.java @@ -0,0 +1,14 @@ +package io.semantic.openscore.core.exceptions; + +public abstract class ApplicationException extends RuntimeException { + + public ApplicationException(String message) { + super(message); + } + + public ApplicationException(String message, + Throwable cause) { + super(message, + cause); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/EmailException.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/EmailException.java new file mode 100644 index 0000000..a002387 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/EmailException.java @@ -0,0 +1,7 @@ +package io.semantic.openscore.core.exceptions; + +public class EmailException extends ApplicationException { + public EmailException(String message) { + super(message); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/EntityNotFoundException.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/EntityNotFoundException.java new file mode 100644 index 0000000..b4cd72f --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/EntityNotFoundException.java @@ -0,0 +1,8 @@ +package io.semantic.openscore.core.exceptions; + +public class EntityNotFoundException extends ApplicationException { + + public EntityNotFoundException(String message) { + super(message); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/NoSePuedeLeerInformacionException.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/NoSePuedeLeerInformacionException.java new file mode 100644 index 0000000..c3b9402 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/NoSePuedeLeerInformacionException.java @@ -0,0 +1,8 @@ +package io.semantic.openscore.core.exceptions; + +public class NoSePuedeLeerInformacionException extends ApplicationException { + + public NoSePuedeLeerInformacionException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/PartidoBloqueadoException.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/PartidoBloqueadoException.java new file mode 100644 index 0000000..659e1aa --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/PartidoBloqueadoException.java @@ -0,0 +1,9 @@ +package io.semantic.openscore.core.exceptions; + +import java.text.MessageFormat; + +public class PartidoBloqueadoException extends ApplicationException { + public PartidoBloqueadoException(String local, String visitante) { + super(MessageFormat.format("El partido {0} - {1} se encuentra bloqueado", local, visitante)); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/ValidationException.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/ValidationException.java new file mode 100644 index 0000000..b03c606 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/exceptions/ValidationException.java @@ -0,0 +1,44 @@ +package io.semantic.openscore.core.exceptions; + +import javax.validation.ConstraintViolation; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toList; + +public class ValidationException extends ApplicationException { + + private final List data; + + public ValidationException(String message, List data) { + super(message); + this.data = data; + } + + public ValidationException(String message, Throwable e) { + super(message); + this.data = Collections.emptyList(); + } + + public static String generateMessage(Set> errors) { + return ValidationException.generateErrorsList(errors).stream().collect(joining("\n")); + } + + private static String processErrorMessage(ConstraintViolation objectConstraintViolation) { + return objectConstraintViolation.getPropertyPath().toString() + ": " + + objectConstraintViolation.getMessage(); + } + + public static List generateErrorsList(Set> errors) { + return errors.stream() + .map(objectConstraintViolation -> processErrorMessage(objectConstraintViolation)) + .collect(toList()); + } + + public List getData() { + return data; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/logging/BaseLogger.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/logging/BaseLogger.java new file mode 100644 index 0000000..f53ef2f --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/logging/BaseLogger.java @@ -0,0 +1,24 @@ +package io.semantic.openscore.core.logging; + + +import org.slf4j.Logger; + +public abstract class BaseLogger { + + private Logger logger; + + public BaseLogger(Logger logger) { + this.logger = logger; + } + + public boolean isDebugEnabled() { + return this.getLogger().isDebugEnabled(); + } + + + protected Logger getLogger() { + return this.logger; + } + + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/logging/ServiceLogger.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/logging/ServiceLogger.java new file mode 100644 index 0000000..3c89362 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/logging/ServiceLogger.java @@ -0,0 +1,14 @@ +package io.semantic.openscore.core.logging; + +import java.text.MessageFormat; + +import javax.enterprise.context.ApplicationScoped; + +@ApplicationScoped +public class ServiceLogger { + + public String emailInvalido(String email) { + return MessageFormat.format("El email <{0}> es inválido", email); + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/EquipoMapper.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/EquipoMapper.java new file mode 100644 index 0000000..72ae1d9 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/EquipoMapper.java @@ -0,0 +1,21 @@ +package io.semantic.openscore.core.mapping; + +import io.semantic.openscore.core.api.equipos.CrearEquipoDTO; +import io.semantic.openscore.core.api.equipos.EquipoDTO; +import io.semantic.openscore.core.model.Equipo; +import org.mapstruct.Mapper; + +import java.util.List; + +@Mapper(componentModel = "cdi") +public interface EquipoMapper { + + Equipo asEquipo(EquipoDTO equipoDTO); + + Equipo asEquipo(CrearEquipoDTO crearEquipoDTO); + + EquipoDTO asApi(Equipo equipo); + + List asApi(List equipos); + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/FaseMapper.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/FaseMapper.java new file mode 100644 index 0000000..822b7a3 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/FaseMapper.java @@ -0,0 +1,16 @@ +package io.semantic.openscore.core.mapping; + +import io.semantic.openscore.core.api.grupos.FaseDTO; +import io.semantic.openscore.core.model.Fase; +import org.mapstruct.Mapper; + +import java.util.List; + +@Mapper(componentModel = "cdi") +public interface FaseMapper { + + + FaseDTO asApi(Fase fase); + + List asApi(List fase); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/GrupoMapper.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/GrupoMapper.java new file mode 100644 index 0000000..4bde386 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/GrupoMapper.java @@ -0,0 +1,15 @@ +package io.semantic.openscore.core.mapping; + +import io.semantic.openscore.core.api.grupos.GrupoDTO; +import io.semantic.openscore.core.model.Grupo; +import org.mapstruct.Mapper; + +import java.util.List; + +@Mapper(componentModel = "cdi") +public interface GrupoMapper { + + GrupoDTO asApi(Grupo partido); + + List asApi(List partido); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PaisMapper.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PaisMapper.java new file mode 100644 index 0000000..6cc6887 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PaisMapper.java @@ -0,0 +1,18 @@ +package io.semantic.openscore.core.mapping; + +import io.semantic.openscore.core.api.paises.PaisDTO; +import io.semantic.openscore.core.model.Pais; +import org.mapstruct.Mapper; + +import java.util.List; + +@Mapper(componentModel = "cdi") +public interface PaisMapper { + + Pais asPais(PaisDTO paisDTO); + + PaisDTO asApi(Pais pais); + + List asApi(List pais); + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PartidoMapper.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PartidoMapper.java new file mode 100644 index 0000000..7f73bac --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PartidoMapper.java @@ -0,0 +1,20 @@ +package io.semantic.openscore.core.mapping; + +import io.semantic.openscore.core.api.partidos.CrearOUpdatePartidoDTO; +import io.semantic.openscore.core.api.partidos.PartidoDTO; +import io.semantic.openscore.core.api.partidos.ResultadoDTO; +import io.semantic.openscore.core.model.Partido; +import io.semantic.openscore.core.model.Resultado; +import org.mapstruct.Mapper; + +import java.util.List; + +@Mapper(componentModel = "cdi") +public interface PartidoMapper { + + PartidoDTO asApi(Partido partido); + + List asApi(List partido); + + Resultado asResultado(ResultadoDTO resultado); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PronosticoMapper.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PronosticoMapper.java new file mode 100644 index 0000000..a33e405 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/PronosticoMapper.java @@ -0,0 +1,36 @@ +package io.semantic.openscore.core.mapping; + +import io.semantic.openscore.core.api.pronosticos.CrearPronosticoDTO; +import io.semantic.openscore.core.api.pronosticos.PartidoPronosticoDTO; +import io.semantic.openscore.core.api.pronosticos.PronosticoDTO; +import io.semantic.openscore.core.model.Partido; +import io.semantic.openscore.core.model.Pronostico; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.MappingTarget; +import org.mapstruct.Mappings; + +import java.util.List; + +@Mapper(componentModel = "cdi") +public interface PronosticoMapper { + + + PronosticoDTO asApi(Pronostico pronostico); + + List asApi(List pronosticos); + + @Mappings({ + @Mapping(source = "partido", target = "partido", ignore = true) + }) + Pronostico asPronostico(CrearPronosticoDTO crearPronostico); + + PartidoPronosticoDTO asApiPronostico(Partido partido); + + List asApiPronostico(List partido); + + @Mappings({ + @Mapping(source = "partido", target = "partido", ignore = true) + }) + void updatePronostico(CrearPronosticoDTO crearPronostico, @MappingTarget Pronostico pronostico); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/UsuarioMapper.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/UsuarioMapper.java new file mode 100644 index 0000000..be1378c --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/mapping/UsuarioMapper.java @@ -0,0 +1,37 @@ +package io.semantic.openscore.core.mapping; + +import io.semantic.openscore.core.api.admin.UsuarioCompletoDTO; +import io.semantic.openscore.core.api.usuarios.CrearUsuarioDTO; +import io.semantic.openscore.core.api.usuarios.UpdateUsuarioDTO; +import io.semantic.openscore.core.api.usuarios.UsuarioDTO; +import io.semantic.openscore.core.model.Usuario; +import org.mapstruct.Mapper; +import org.mapstruct.Mapping; +import org.mapstruct.MappingTarget; +import org.mapstruct.Mappings; + +import java.util.List; + +@Mapper(componentModel = "cdi") +public interface UsuarioMapper { + + Usuario asUsuario(UsuarioDTO api); + + @Mappings({ + @Mapping(source = "pais", target = "pais", ignore = true) + }) + Usuario asUsuario(CrearUsuarioDTO crearUsuario); + + @Mappings({ + @Mapping(source = "pais", target = "pais", ignore = true), + }) + void updateUsuario(UpdateUsuarioDTO usuarioDTO, @MappingTarget Usuario car); + + UsuarioDTO asApi(Usuario usuario); + + List asApi(List usuario); + + List asCompletoApi(List usuario); + + UsuarioCompletoDTO asCompletoApi(Usuario usuario); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Equipo.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Equipo.java new file mode 100644 index 0000000..9d52a8d --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Equipo.java @@ -0,0 +1,47 @@ +package io.semantic.openscore.core.model; + +import javax.persistence.Entity; +import javax.persistence.ManyToOne; + +@Entity +public class Equipo extends Storable { + + private String nombre; + private String codigo; + private String logo; + + + public Equipo() { + } + + public Equipo(String codigo, String nombre, String logo) { + this.nombre = nombre; + this.codigo = codigo; + this.logo = logo; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getCodigo() { + return codigo; + } + + public void setCodigo(String codigo) { + this.codigo = codigo; + } + + public String getLogo() { + return logo; + } + + public void setLogo(String logo) { + this.logo = logo; + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Fase.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Fase.java new file mode 100644 index 0000000..59eb9ae --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Fase.java @@ -0,0 +1,42 @@ +package io.semantic.openscore.core.model; + +import javax.persistence.Entity; + +@Entity +public class Fase extends Storable { + + public static final String GRUPO = "GRUPO"; + public static final String OCTAVOS = "OCTAVOS"; + public static final String CUARTOS = "CUARTOS"; + public static final String SEMI = "SEMI"; + public static final String FINAL = "FINAL"; + public static final String TERCER = "TERCER"; + + private String codigo; + private String nombre; + private Integer puntos; + + public String getCodigo() { + return codigo; + } + + public void setCodigo(String codigo) { + this.codigo = codigo; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public Integer getPuntos() { + return puntos; + } + + public void setPuntos(Integer puntos) { + this.puntos = puntos; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Ganador.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Ganador.java new file mode 100644 index 0000000..212b3df --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Ganador.java @@ -0,0 +1,8 @@ +package io.semantic.openscore.core.model; + +public enum Ganador { + + LOCAL, + VISITANTE, + EMPATE +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Grupo.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Grupo.java new file mode 100644 index 0000000..2597545 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Grupo.java @@ -0,0 +1,36 @@ +package io.semantic.openscore.core.model; + +import javax.persistence.Entity; + +@Entity +public class Grupo extends Storable { + + public final static String GRUPO_A = "GRUPO_A"; + public final static String GRUPO_B = "GRUPO_B"; + public final static String GRUPO_C = "GRUPO_C"; + public final static String GRUPO_D = "GRUPO_D"; + public final static String GRUPO_E = "GRUPO_E"; + public final static String GRUPO_F = "GRUPO_F"; + public final static String GRUPO_G = "GRUPO_G"; + public final static String GRUPO_H = "GRUPO_H"; + public final static String NONE = "NONE"; + + private String codigo; + private String nombre; + + public void setCodigo(String codigo) { + this.codigo = codigo; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getCodigo() { + return codigo; + } + + public String getNombre() { + return nombre; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Pais.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Pais.java new file mode 100644 index 0000000..d6b5e62 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Pais.java @@ -0,0 +1,48 @@ +package io.semantic.openscore.core.model; + +import javax.persistence.Entity; +import javax.validation.constraints.NotNull; + +@Entity +public class Pais extends Storable { + + @NotNull + private String nombre; + + @NotNull + private String codigo; + + public Pais() { + } + + public Pais(String codigo, String nombre) { + this.setCodigo(codigo); + this.setNombre(nombre); + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getCodigo() { + return codigo; + } + + public void setCodigo(String codigo) { + this.codigo = codigo; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Pais) { + return this.getCodigo().equals(((Pais) obj).getCodigo()); + } else { + return super.equals(obj); + } + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Partido.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Partido.java new file mode 100644 index 0000000..a41ff1d --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Partido.java @@ -0,0 +1,132 @@ +package io.semantic.openscore.core.model; + +import javax.persistence.Embedded; +import javax.persistence.Entity; +import javax.persistence.ManyToOne; +import java.util.Date; + +@Entity +public class Partido extends Storable { + + @ManyToOne + private Equipo local; + + @ManyToOne + private Equipo visitante; + private Date dia; + private String lugar; + private int fecha; + + @ManyToOne + private Grupo grupo; + + @ManyToOne + private Fase fase; + + @Embedded + private Resultado resultado; + + public Equipo getLocal() { + return local; + } + + public void setLocal(Equipo local) { + this.local = local; + } + + public Equipo getVisitante() { + return visitante; + } + + public void setVisitante(Equipo visitante) { + this.visitante = visitante; + } + + public Date getDia() { + return dia; + } + + public void setDia(Date dia) { + this.dia = dia; + } + + public String getLugar() { + return lugar; + } + + public void setLugar(String lugar) { + this.lugar = lugar; + } + + public Grupo getGrupo() { + return grupo; + } + + public void setGrupo(Grupo grupo) { + this.grupo = grupo; + } + + public Fase getFase() { + return fase; + } + + public void setFase(Fase fase) { + this.fase = fase; + } + + public Resultado getResultado() { + return resultado; + } + + public void setResultado(Resultado resultado) { + this.resultado = resultado; + } + + public int getPuntos(Pronostico pronostico) { + + if (this.getResultado() == null) { + return 0; + } + + int puntosAsignables = calcularPuntos(); + Ganador ganador = this.getResultado().getGanador(); + if (isSumaPuntos(pronostico, ganador)) { + return puntosAsignables; + } else { + return 0; + } + } + + private boolean isSumaPuntos(Pronostico pronostico, Ganador ganador) { + return pronostico.isLocal() && Ganador.LOCAL.equals(ganador) || + pronostico.isVisitante() && Ganador.VISITANTE.equals(ganador) || + pronostico.isEmpate() && Ganador.EMPATE.equals(ganador); + } + + + private int calcularPuntos() { + return this.getFase().getPuntos(); + } + + public boolean isBloqueado() { + return this.getDia().getTime() <= new Date().getTime() + 900000; + } + + public PartidoStatus getStatus() { + if (this.getResultado() != null) { + return PartidoStatus.FINISHED; + } else if (this.isBloqueado()) { + return PartidoStatus.BLOCKED; + } else { + return PartidoStatus.PENDING; + } + } + + public int getFecha() { + return fecha; + } + + public void setFecha(int fecha) { + this.fecha = fecha; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PartidoStatus.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PartidoStatus.java new file mode 100644 index 0000000..6528dec --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PartidoStatus.java @@ -0,0 +1,5 @@ +package io.semantic.openscore.core.model; + +public enum PartidoStatus { + BLOCKED, PENDING, FINISHED +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Post.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Post.java new file mode 100644 index 0000000..f3c8ee1 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Post.java @@ -0,0 +1,51 @@ +package io.semantic.openscore.core.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; + +@Entity +public class Post extends Storable { + + private String titulo; + + @Column(columnDefinition = "TEXT") + private String contenido; + private String autor; + + @Enumerated(EnumType.STRING) + private PostStatus status; + + public String getTitulo() { + return titulo; + } + + public void setTitulo(String titulo) { + this.titulo = titulo; + } + + public String getContenido() { + return contenido; + } + + public void setContenido(String contenido) { + this.contenido = contenido; + } + + public PostStatus getStatus() { + return status; + } + + public void setStatus(PostStatus status) { + this.status = status; + } + + public String getAutor() { + return autor; + } + + public void setAutor(String autor) { + this.autor = autor; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PostStatus.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PostStatus.java new file mode 100644 index 0000000..8b6514d --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PostStatus.java @@ -0,0 +1,5 @@ +package io.semantic.openscore.core.model; + +public enum PostStatus { + PUBLICADO, BORRADOR +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PreguntaSecreta.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PreguntaSecreta.java new file mode 100644 index 0000000..ad0aeaf --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/PreguntaSecreta.java @@ -0,0 +1,28 @@ +package io.semantic.openscore.core.model; + +import javax.persistence.Entity; + +@Entity +public class PreguntaSecreta extends Storable { + + private String codigo; + private String pregunta; + + + public String getPregunta() { + return pregunta; + } + + public void setPregunta(String pregunta) { + this.pregunta = pregunta; + } + + public String getCodigo() { + return codigo; + } + + public void setCodigo(String codigo) { + this.codigo = codigo; + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Pronostico.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Pronostico.java new file mode 100644 index 0000000..5826796 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Pronostico.java @@ -0,0 +1,91 @@ +package io.semantic.openscore.core.model; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import javax.persistence.Entity; +import javax.persistence.ManyToOne; + + +@Entity +public class Pronostico extends Storable { + + private boolean local; + private boolean visitante; + private boolean empate; + + @ManyToOne + private Partido partido; + + @ManyToOne + private Usuario usuario; + + public boolean isLocal() { + return local; + } + + public void setLocal(boolean local) { + this.local = local; + } + + public boolean isVisitante() { + return visitante; + } + + public void setVisitante(boolean visitante) { + this.visitante = visitante; + } + + public boolean isEmpate() { + return empate; + } + + public void setEmpate(boolean empate) { + this.empate = empate; + } + + public Partido getPartido() { + return partido; + } + + public void setPartido(Partido partido) { + this.partido = partido; + } + + public Usuario getUsuario() { + return usuario; + } + + public void setUsuario(Usuario usuario) { + this.usuario = usuario; + } + + public void local() { + this.setLocal(true); + this.setVisitante(false); + this.setEmpate(false); + } + + public void empate() { + this.setLocal(false); + this.setVisitante(false); + this.setEmpate(true); + } + + public void visitante() { + this.setLocal(false); + this.setVisitante(true); + this.setEmpate(false); + } + + public int getPuntos() { + return this.getPartido().getPuntos(this); + } + + @Override + public String toString() { + return new GsonBuilder().setPrettyPrinting().create().toJson(this); + } + + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/RespuestaPreguntaSecreta.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/RespuestaPreguntaSecreta.java new file mode 100644 index 0000000..454b5c2 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/RespuestaPreguntaSecreta.java @@ -0,0 +1,29 @@ +package io.semantic.openscore.core.model; + +import javax.persistence.Entity; +import javax.persistence.ManyToOne; + +@Entity +public class RespuestaPreguntaSecreta extends Storable { + + @ManyToOne + private PreguntaSecreta preguntaSecreta; + + private String respuesta; + + public PreguntaSecreta getPreguntaSecreta() { + return preguntaSecreta; + } + + public void setPreguntaSecreta(PreguntaSecreta preguntaSecreta) { + this.preguntaSecreta = preguntaSecreta; + } + + public String getRespuesta() { + return respuesta; + } + + public void setRespuesta(String respuesta) { + this.respuesta = respuesta; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Resultado.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Resultado.java new file mode 100644 index 0000000..969091c --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Resultado.java @@ -0,0 +1,53 @@ +package io.semantic.openscore.core.model; + +import javax.persistence.Column; +import javax.persistence.Embeddable; +import javax.persistence.Entity; +import javax.persistence.OneToOne; + +@Embeddable +public class Resultado { + + @Column(nullable = true) + private int local; + + @Column(nullable = true) + private int visitante; + + @OneToOne + private Partido partido; + + public int getLocal() { + return local; + } + + public void setLocal(int local) { + this.local = local; + } + + public int getVisitante() { + return visitante; + } + + public void setVisitante(int visitante) { + this.visitante = visitante; + } + + public Ganador getGanador() { + if (local > visitante) { + return Ganador.LOCAL; + } else if (local < visitante) { + return Ganador.VISITANTE; + } else { + return Ganador.EMPATE; + } + } + + public Partido getPartido() { + return partido; + } + + public void setPartido(Partido partido) { + this.partido = partido; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Rol.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Rol.java new file mode 100644 index 0000000..08fe3b1 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Rol.java @@ -0,0 +1,7 @@ +package io.semantic.openscore.core.model; + +public enum Rol { + + ADMIN, USUARIO + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Storable.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Storable.java new file mode 100644 index 0000000..ba1e892 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Storable.java @@ -0,0 +1,67 @@ +package io.semantic.openscore.core.model; + +import javax.persistence.*; +import java.util.Date; + +@MappedSuperclass +public class Storable { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + private boolean deleted; + private Date creationDate; + private Date deletionDate; + private Date modificationDate; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public boolean isDeleted() { + return deleted; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + + public Date getCreationDate() { + return creationDate; + } + + public void setCreationDate(Date creationDate) { + this.creationDate = creationDate; + } + + public Date getDeletionDate() { + return deletionDate; + } + + public void setDeletionDate(Date deletionDate) { + this.deletionDate = deletionDate; + } + + public Date getModificationDate() { + return modificationDate; + } + + public void setModificationDate(Date modificationDate) { + this.modificationDate = modificationDate; + } + + @PrePersist + public void prePersist() { + if (this.id == 0) { + this.creationDate = new Date(); + } + if (this.deleted) { + this.deletionDate = new Date(); + } + this.modificationDate = new Date(); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Usuario.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Usuario.java new file mode 100644 index 0000000..4f970ad --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/model/Usuario.java @@ -0,0 +1,112 @@ +package io.semantic.openscore.core.model; + +import org.hibernate.validator.constraints.Email; +import org.hibernate.validator.constraints.Length; + +import javax.persistence.*; +import javax.validation.constraints.NotNull; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +@Entity +public class Usuario extends Storable { + + + @NotNull + @Length(min = 2) + private String nombre; + + @NotNull + @Length(min = 2) + private String apellido; + + @NotNull + @ManyToOne + private Pais pais; + + @NotNull + @Email + @Column(unique = true) + private String email; + + @NotNull + private String password; + + @OneToMany() + private Set pronosticos; + + public Usuario() { + this.pronosticos = new HashSet<>(); + } + + @ElementCollection + @CollectionTable(name = "roles", joinColumns = @JoinColumn(name = "usuario_id")) + @Enumerated(EnumType.STRING) + private Set roles; + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getApellido() { + return apellido; + } + + public void setApellido(String apellido) { + this.apellido = apellido; + } + + public Pais getPais() { + return pais; + } + + public void setPais(Pais pais) { + this.pais = pais; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Set getRoles() { + return roles; + } + + public void setRoles(Set roles) { + this.roles = roles; + } + + public Set getPronosticos() { + return pronosticos; + } + + public void setPronosticos(Set pronosticos) { + this.pronosticos = pronosticos; + } + + public void addPronostico(Pronostico pronostico) { + this.pronosticos.add(pronostico); + } + + public int getPuntos() { + return this.getPronosticos().stream().mapToInt(Pronostico::getPuntos).sum(); + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/EquiposRepository.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/EquiposRepository.java new file mode 100644 index 0000000..ebdaf90 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/EquiposRepository.java @@ -0,0 +1,41 @@ +package io.semantic.openscore.core.repository; + +import java.util.List; +import java.util.Optional; + +import javax.enterprise.context.ApplicationScoped; +import javax.persistence.TypedQuery; + +import io.semantic.openscore.core.model.Equipo; + +@ApplicationScoped +public class EquiposRepository extends Repository { + + public static final String FIND_BY_CODIGO = "select p from Equipo p where p.codigo = :codigo"; + + public EquiposRepository() { + super(Equipo.class); + } + + public boolean exist(String codigo) { + TypedQuery query = this.createQuery(FIND_BY_CODIGO); + query.setParameter("codigo", codigo); + return this.findByQuery(query).size() > 0; + } + + public Optional findByCodigo(String codigo) { + TypedQuery query = this.createQuery(FIND_BY_CODIGO); + query.setParameter("codigo", codigo); + List found = this.findByQuery(query); + if (found.isEmpty()) { + return Optional.empty(); + } else { + return Optional.of(found.get(0)); + } + } + + @Override + public boolean exist(Equipo entity) { + return false; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/FaseRepository.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/FaseRepository.java new file mode 100644 index 0000000..c7eae71 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/FaseRepository.java @@ -0,0 +1,41 @@ +package io.semantic.openscore.core.repository; + +import java.util.List; +import java.util.Optional; + +import javax.enterprise.context.ApplicationScoped; +import javax.persistence.TypedQuery; + +import io.semantic.openscore.core.model.Fase; + +@ApplicationScoped +public class FaseRepository extends Repository { + + private static final String FIND_ENTITY_BY_CODIGO_QUERY = "select p from Fase p where p.codigo = :codigo"; + + public FaseRepository() { + super(Fase.class); + } + + public boolean exist(String codigo) { + TypedQuery query = this.createQuery(FIND_ENTITY_BY_CODIGO_QUERY); + query.setParameter("codigo", codigo); + return this.findByQuery(query).size() > 0; + } + + public Optional findByCodigo(String codigo) { + TypedQuery query = this.createQuery(FIND_ENTITY_BY_CODIGO_QUERY); + query.setParameter("codigo", codigo); + List results = query.getResultList(); + if (results.isEmpty()) { + return Optional.empty(); + } else { + return Optional.of(results.get(0)); + } + } + + @Override + public boolean exist(Fase entity) { + return false; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/GrupoRepository.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/GrupoRepository.java new file mode 100644 index 0000000..c67bd08 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/GrupoRepository.java @@ -0,0 +1,41 @@ +package io.semantic.openscore.core.repository; + +import java.util.List; +import java.util.Optional; + +import javax.enterprise.context.ApplicationScoped; +import javax.persistence.TypedQuery; + +import io.semantic.openscore.core.model.Grupo; + +@ApplicationScoped +public class GrupoRepository extends Repository { + + private static final String FIND_ENTITY_BY_CODIGO_QUERY = "select p from Grupo p where p.codigo = :codigo"; + + public GrupoRepository() { + super(Grupo.class); + } + + public boolean exist(String codigo) { + TypedQuery query = this.createQuery(FIND_ENTITY_BY_CODIGO_QUERY); + query.setParameter("codigo", codigo); + return this.findByQuery(query).size() > 0; + } + + public Optional findByCodigo(String codigo) { + TypedQuery query = this.createQuery(FIND_ENTITY_BY_CODIGO_QUERY); + query.setParameter("codigo", codigo); + List found = this.findByQuery(query); + if (found.isEmpty()) { + return Optional.empty(); + } else { + return Optional.of(found.get(0)); + } + } + + @Override + public boolean exist(Grupo entity) { + return false; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Page.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Page.java new file mode 100644 index 0000000..1400de4 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Page.java @@ -0,0 +1,22 @@ +package io.semantic.openscore.core.repository; + +public class Page { + + private int page; + private int pageSize; + + public Page(int page, + int pageSize) { + + this.page = page; + this.pageSize = pageSize; + } + + public int getPage() { + return page; + } + + public int getPageSize() { + return pageSize; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PaisRepository.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PaisRepository.java new file mode 100644 index 0000000..6dda37b --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PaisRepository.java @@ -0,0 +1,39 @@ +package io.semantic.openscore.core.repository; + +import javax.enterprise.context.ApplicationScoped; +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; + +import io.semantic.openscore.core.model.Pais; + +@ApplicationScoped +public class PaisRepository extends Repository { + + private static final String FIND_PAIS_BY_CODIGO_QUERY = "select p from Pais p where p.codigo = :codigo"; + + public PaisRepository() { + super(Pais.class); + } + + public PaisRepository(EntityManager entityManager) { + super(Pais.class, entityManager); + } + + public boolean exist(Pais pais) { + TypedQuery query = this.createQuery("select p from Pais p where p.codigo = :codigo"); + query.setParameter("codigo", pais.getCodigo()); + return this.findByQuery(query).size() > 0; + } + + public boolean exist(String codigo) { + TypedQuery query = this.createQuery("select p from Pais p where p.codigo = :codigo"); + query.setParameter("codigo", codigo); + return this.findByQuery(query).size() > 0; + } + + public Pais findByCodigo(String codigo) { + TypedQuery query = this.createQuery(FIND_PAIS_BY_CODIGO_QUERY); + query.setParameter("codigo", codigo); + return query.getSingleResult(); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PartidoRepository.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PartidoRepository.java new file mode 100644 index 0000000..85f796e --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PartidoRepository.java @@ -0,0 +1,107 @@ +package io.semantic.openscore.core.repository; + +import java.util.Calendar; +import java.util.List; +import java.util.TimeZone; + +import javax.enterprise.context.ApplicationScoped; +import javax.persistence.TemporalType; +import javax.persistence.TypedQuery; + +import io.semantic.openscore.core.model.Fase; +import io.semantic.openscore.core.model.Grupo; +import io.semantic.openscore.core.model.Partido; + +@ApplicationScoped +public class PartidoRepository extends Repository { + + private static final String EXIST = "select e from Partido e where " + + "e.local.codigo = :local AND " + + "e.visitante.codigo = :visitante AND " + + "e.fase.id = :fase AND " + + "e.grupo.id = :grupo"; + + private static final String FIND_ALL_BY_GROUP = "from Partido where " + + "grupo.codigo = :grupo " + + "order by dia asc"; + + private static final String FIND_ALL_BY_FASE = "from Partido where " + + "fase.codigo = :fase " + + "order by dia asc"; + + private static final String FIND_ALL_BY_FECHA = "from Partido where " + + "fecha = :fecha " + + "order by dia asc"; + + private static final String FIND_ALL_BY_DIA = "from Partido where " + + "cast(dia as date) BETWEEN :dia1 AND :dia2 " + + "order by dia asc"; + + private static final String FIND_ALL_FECHAS = "select distinct p.fecha from Partido p group by p.fecha order by p.fecha asc"; + + + public PartidoRepository() { + super(Partido.class); + } + + public boolean exist(String codigoLocal, String codigoVisitante, Grupo grupo, Fase fase) { + TypedQuery query = this.createQuery(EXIST) + .setParameter("local", codigoLocal) + .setParameter("visitante", codigoVisitante) + .setParameter("fase", fase.getId()) + .setParameter("grupo", grupo.getId()); + + return this.findByQuery(query).size() > 0; + } + + public List findAllByGrupo(String grupo) { + TypedQuery query = this.createQuery(FIND_ALL_BY_GROUP) + .setParameter("grupo", grupo); + return this.findByQuery(query); + } + + public List findAllByDia(long dia) { + + Calendar dia1 = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + dia1.setTimeInMillis(dia); + dia1.set(Calendar.HOUR, 6); + dia1.set(Calendar.MINUTE, 0); + + Calendar dia2 = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + dia2.setTimeInMillis(dia); + dia2.set(Calendar.HOUR, 6); + dia2.set(Calendar.MINUTE, 0); + dia2.add(Calendar.DATE, 1); + + + + TypedQuery query = this.createQuery(FIND_ALL_BY_DIA) + .setParameter("dia1", dia1, TemporalType.DATE) + .setParameter("dia2", dia2, TemporalType.DATE); + return this.findByQuery(query); + } + + public List findAllByFase(String fase) { + TypedQuery query = this.createQuery(FIND_ALL_BY_FASE) + .setParameter("fase", fase); + return this.findByQuery(query); + } + + public List findAllByFecha(int fecha) { + TypedQuery query = this.createQuery(FIND_ALL_BY_FECHA) + .setParameter("fecha", fecha); + return this.findByQuery(query); + } + + public List findAllFechas() { + return this.entityManager.createQuery(FIND_ALL_FECHAS).getResultList(); + } + + @Override + public boolean exist(Partido entity) { + return this.exist(entity.getLocal().getCodigo(), + entity.getVisitante().getCodigo(), + entity.getGrupo(), + entity.getFase()); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PostRepository.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PostRepository.java new file mode 100644 index 0000000..694cf7f --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PostRepository.java @@ -0,0 +1,30 @@ +package io.semantic.openscore.core.repository; + +import java.util.List; + +import javax.enterprise.context.ApplicationScoped; +import javax.persistence.TypedQuery; + +import io.semantic.openscore.core.model.Post; +import io.semantic.openscore.core.model.PostStatus; + +@ApplicationScoped +public class PostRepository extends Repository { + + private static final String FIND_ALL_BY_STATUS = "from Post where status = :status order by modificationDate"; + + public PostRepository() { + super(Post.class); + } + + public List findAllByStatus(PostStatus postStatus) { + TypedQuery query = this.createQuery(FIND_ALL_BY_STATUS); + query.setParameter("status",postStatus); + return this.findByQuery(query); + } + + @Override + public boolean exist(Post entity) { + return false; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PreguntaSecretaRepository.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PreguntaSecretaRepository.java new file mode 100644 index 0000000..e637dea --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PreguntaSecretaRepository.java @@ -0,0 +1,25 @@ +package io.semantic.openscore.core.repository; + +import javax.enterprise.context.ApplicationScoped; +import javax.persistence.EntityManager; + +import io.semantic.openscore.core.model.PreguntaSecreta; + +@ApplicationScoped +public class PreguntaSecretaRepository extends Repository { + + + public PreguntaSecretaRepository() { + super(PreguntaSecreta.class); + } + + public PreguntaSecretaRepository(EntityManager entityManager) { + super(PreguntaSecreta.class, entityManager); + } + + + @Override + public boolean exist(PreguntaSecreta entity) { + return false; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PronosticoRepository.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PronosticoRepository.java new file mode 100644 index 0000000..db8f219 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/PronosticoRepository.java @@ -0,0 +1,66 @@ +package io.semantic.openscore.core.repository; + +import java.util.List; +import java.util.Optional; + +import javax.enterprise.context.ApplicationScoped; + +import io.semantic.openscore.core.model.Pronostico; + +@ApplicationScoped +public class PronosticoRepository extends Repository { + + private static final String FIND_BY_ID_AND_USER = "select e from Pronostico e where " + + "e.id = :id and " + + "e.usuario.id = :idUsuario and " + + "e.deleted = false"; + + private static final String FIND_BY_PARTIDO_AND_USER = "select e from Pronostico e where " + + "e.partido.id = :idPartido and " + + "e.usuario.id = :idUsuario and " + + "e.deleted = false"; + + private static final String FIND_BY_USER = "select e from Pronostico e where " + + "e.usuario.id = :idUsuario"; + + public PronosticoRepository() { + super(Pronostico.class); + } + + public List findByUsuario(long idUsuario) { + return this.createQuery(FIND_BY_USER) + .setParameter("idUsuario", idUsuario) + .getResultList(); + } + + public Optional findById(long id, long idUsuario) { + List results = this.createQuery(FIND_BY_ID_AND_USER) + .setParameter("id", id) + .setParameter("idUsuario", idUsuario) + .getResultList(); + + if (results.isEmpty()) { + return Optional.empty(); + } else { + return Optional.of(results.get(0)); + } + } + + public Optional findByPartidoAndUsuario(long idPartido, long idUsuario) { + List results = this.createQuery(FIND_BY_PARTIDO_AND_USER) + .setParameter("idPartido", idPartido) + .setParameter("idUsuario", idUsuario) + .getResultList(); + + if (results.isEmpty()) { + return Optional.empty(); + } else { + return Optional.of(results.get(0)); + } + } + + @Override + public boolean exist(Pronostico entity) { + return false; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Repository.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Repository.java new file mode 100644 index 0000000..018cbee --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Repository.java @@ -0,0 +1,178 @@ +package io.semantic.openscore.core.repository; + +import static java.util.stream.Collectors.joining; + +import java.text.MessageFormat; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import javax.inject.Inject; +import javax.persistence.EntityManager; +import javax.persistence.TypedQuery; +import javax.transaction.Transactional; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.semantic.openscore.core.model.Storable; + +public abstract class Repository { + + protected final Class persistentClass; + + private Logger logger = LoggerFactory.getLogger(Repository.class); + + @Inject + protected EntityManager entityManager; + + public Repository(Class clazz) { + this.persistentClass = clazz; + } + + public Repository(Class clazz, + EntityManager entityManager) { + this(clazz); + this.entityManager = entityManager; + } + + @Transactional + public long save(T storable) { + if (storable.getId() != 0) { + this.entityManager.merge(storable); + } else { + this.entityManager.persist(storable); + } + return storable.getId(); + } + + public TypedQuery createQuery(String query) { + return this.entityManager.createQuery(query, + this.persistentClass); + } + + public Optional findById(long id) { + + List found = this.createQuery(MessageFormat.format("from {0} s where s.id=:id and s.deleted=false", + this.persistentClass.getSimpleName())).setParameter("id", + id) + .getResultList(); + + if (!found.isEmpty()) { + return Optional.of(found.get(0)); + } else { + return Optional.empty(); + } + } + + public Optional findByIdWithDeleted(long id) { + + List found = this.createQuery(MessageFormat.format("from {0} s where s.id=:id", + this.persistentClass.getSimpleName())).setParameter("id", + id) + .getResultList(); + + if (!found.isEmpty()) { + return Optional.of(found.get(0)); + } else { + return Optional.empty(); + } + } + + public List findByQuery(TypedQuery query, + Page page) { + + return query.setFirstResult(page.getPage() * page.getPageSize()) + .setMaxResults(page.getPageSize()) + .getResultList(); + } + + public List findByQuery(TypedQuery query) { + + return query.getResultList(); + } + + @Transactional + public void hardDeleteById(long id) { + Optional storable = this.findById(id); + storable.ifPresent(entity -> entityManager.remove(entity)); + } + + @Transactional + public void hardDeleteByQuery(TypedQuery query) { + List found = this.findByQuery(query, + new Page(0, + 0)); + found.forEach(entity -> entityManager.remove(entity)); + } + + public void deleteByQuery(TypedQuery query) { + List found = this.findByQuery(query, + new Page(0, + 0)); + found.forEach(elem -> { + elem.setDeleted(true); + save(elem); + }); + } + + @Transactional + public void deleteById(long id) { + Optional found = this.findById(id); + found.ifPresent(elem -> { + elem.setDeleted(true); + this.save(elem); + }); + } + + public List findAll(Page page) { + TypedQuery query = this.createQuery(MessageFormat.format("from {0}", + this.persistentClass.getSimpleName())); + return this.findByQuery(query, + page); + } + + public List findAll() { + TypedQuery query = this.createQuery(MessageFormat.format("from {0}", + this.persistentClass.getSimpleName())); + return this.findByQuery(query); + } + + public List findAll(Map parameters, Map sort) { + String queryString = this.buildQuery(parameters, sort); + TypedQuery query = this.createQuery(queryString); + + parameters.entrySet().forEach(entry -> { + query.setParameter(entry.getKey().replace(".", "_"), entry.getValue()); + }); + + return this.findByQuery(query); + } + + private String buildQuery(Map parameters, Map sort) { + + String queryString = "from {0} "; + + if (!parameters.isEmpty()) { + queryString += "where "; + queryString += parameters.entrySet() + .stream() + .map(entry -> entry.getKey() + " = :" + entry.getKey().replace(".", "_")) + .collect(joining(" AND ")); + } + + String formatted = MessageFormat.format(queryString, + this.persistentClass.getSimpleName()); + + if (!sort.isEmpty()) { + formatted += " order by " + + sort.entrySet() + .stream() + .map(entry -> entry.getKey() + " " + entry.getValue().toString()) + .collect(joining(" , ")); + } + return formatted; + } + + public abstract boolean exist(T entity); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Sort.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Sort.java new file mode 100644 index 0000000..3fd57ae --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/Sort.java @@ -0,0 +1,10 @@ +package io.semantic.openscore.core.repository; + +public enum Sort { + ASC, DESC; + + @Override + public String toString() { + return super.toString().toLowerCase(); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/UsuarioRepository.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/UsuarioRepository.java new file mode 100644 index 0000000..56ac09e --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/UsuarioRepository.java @@ -0,0 +1,53 @@ +package io.semantic.openscore.core.repository; + +import java.util.List; +import java.util.Optional; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.persistence.EntityManager; + +import io.semantic.openscore.core.model.Usuario; + +@ApplicationScoped +public class UsuarioRepository extends Repository { + + public static final String FIND_BY_EMAIL = "from Usuario s where s.email=:email"; + public static final String FIND_BY_COUNTRY = "from Usuario s where s.pais.codigo=:pais"; + + @Inject + public UsuarioRepository() { + super(Usuario.class); + } + + public UsuarioRepository(EntityManager entityManager) { + super(Usuario.class); + this.entityManager = entityManager; + + } + + public Optional findByEmail(String email) { + List found = this.createQuery(FIND_BY_EMAIL).setParameter("email", email).getResultList(); + + if (!found.isEmpty()) { + return Optional.of(found.get(0)); + } else { + return Optional.empty(); + } + } + + public boolean exist(String email) { + return this.findByEmail(email).isPresent(); + } + + public List findByCountry(String pais) { + List found = this.createQuery(FIND_BY_COUNTRY).setParameter("pais", pais.toUpperCase()) + .getResultList(); + return found; + } + + @Override + public boolean exist(Usuario entity) { + return false; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/PartidoData.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/PartidoData.java new file mode 100644 index 0000000..9e67fca --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/PartidoData.java @@ -0,0 +1,68 @@ +package io.semantic.openscore.core.repository.startup; + +public class PartidoData { + + private String local; + private String visitante; + private String dia; + private String fecha; + private String lugar; + private String grupo; + private String fase; + + public String getLocal() { + return local; + } + + public void setLocal(String local) { + this.local = local; + } + + public String getVisitante() { + return visitante; + } + + public void setVisitante(String visitante) { + this.visitante = visitante; + } + + public String getDia() { + return dia; + } + + public void setDia(String dia) { + this.dia = dia; + } + + public String getLugar() { + return lugar; + } + + public void setLugar(String lugar) { + this.lugar = lugar; + } + + public String getGrupo() { + return grupo; + } + + public void setGrupo(String grupo) { + this.grupo = grupo; + } + + public String getFase() { + return fase; + } + + public void setFase(String fase) { + this.fase = fase; + } + + public String getFecha() { + return fecha; + } + + public void setFecha(String fecha) { + this.fecha = fecha; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/StartupManager.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/StartupManager.java new file mode 100644 index 0000000..0ec620e --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/StartupManager.java @@ -0,0 +1,48 @@ +package io.semantic.openscore.core.repository.startup; + +import java.text.MessageFormat; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.event.Observes; +import javax.enterprise.inject.Instance; +import javax.inject.Inject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.quarkus.runtime.StartupEvent; + +@ApplicationScoped +public class StartupManager { + + private List steps; + private Logger logger = LoggerFactory.getLogger(StartupManager.class); + + public StartupManager() { + + } + + @Inject + public StartupManager(Instance startupSteps) { + steps = StreamSupport.stream(startupSteps.spliterator(), false).collect(Collectors.toList()); + } + + public void initialize(@Observes StartupEvent ev) { + this.logger.info(MessageFormat.format("StartupSteps found: {0}", this.steps.size())); + Collections.sort(this.steps, Comparator.comparingInt(StartupStep::priority)); + this.logger.info(MessageFormat.format("StartupSteps sorted: \n|_ {0}", + this.steps.stream() + .map(startupStep -> startupStep.getClass().getSimpleName() + " -- p: " + startupStep.priority() + + " -- " + startupStep.enabled()) + .collect(Collectors.joining("\n|_ ")))); + this.steps.stream() + .filter(startupStep -> startupStep.enabled()) + .forEach(StartupStep::run); + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/StartupStep.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/StartupStep.java new file mode 100644 index 0000000..ae54ec5 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/StartupStep.java @@ -0,0 +1,12 @@ +package io.semantic.openscore.core.repository.startup; + +public interface StartupStep { + + void run(); + + int priority(); + + default boolean enabled() { + return true; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/DiaBuilder.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/DiaBuilder.java new file mode 100644 index 0000000..fa54471 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/DiaBuilder.java @@ -0,0 +1,10 @@ +package io.semantic.openscore.core.repository.startup.builder; + +import java.util.Date; + +public interface DiaBuilder { + + public static final String DATE_PATTERN = "dd-MM-yyyy'T'HH:mmZ"; + + Date getMatchDate(String fecha); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/DiaBuilderImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/DiaBuilderImpl.java new file mode 100644 index 0000000..4ab89ca --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/DiaBuilderImpl.java @@ -0,0 +1,28 @@ +package io.semantic.openscore.core.repository.startup.builder; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +import javax.enterprise.context.ApplicationScoped; + +@ApplicationScoped +public class DiaBuilderImpl implements DiaBuilder { + + private SimpleDateFormat simpleDateFormat; + + public DiaBuilderImpl() { + simpleDateFormat = new SimpleDateFormat(DATE_PATTERN); + } + + public Date getMatchDate(String fecha) { + + try { + return simpleDateFormat.parse(fecha); + } catch (ParseException e) { + e.printStackTrace(); + return null; + } + + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/TestDiaBuilder.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/TestDiaBuilder.java new file mode 100644 index 0000000..8e982fe --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/builder/TestDiaBuilder.java @@ -0,0 +1,25 @@ +package io.semantic.openscore.core.repository.startup.builder; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.enterprise.inject.Alternative; +import java.util.Calendar; +import java.util.Date; +import java.util.Random; + +@Alternative +public class TestDiaBuilder implements DiaBuilder { + + private Logger logger = LoggerFactory.getLogger(TestDiaBuilder.class); + private static final long ONE_MINUTE_IN_MILLIS = 60000; + private Random random = new Random(); + + public Date getMatchDate(String fecha) { + Calendar date = Calendar.getInstance(); + long t = date.getTimeInMillis(); + Date afterAddingTenMins = new Date(t + (random.nextInt(8 * 60) * ONE_MINUTE_IN_MILLIS)); + logger.info(afterAddingTenMins.toString()); + return afterAddingTenMins; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearEquipos.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearEquipos.java new file mode 100644 index 0000000..2cea881 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearEquipos.java @@ -0,0 +1,67 @@ +package io.semantic.openscore.core.repository.startup.steps; + +import java.text.MessageFormat; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +import io.semantic.openscore.core.model.Equipo; +import io.semantic.openscore.core.repository.EquiposRepository; +import io.semantic.openscore.core.repository.startup.StartupStep; + +@ApplicationScoped +public class CrearEquipos implements StartupStep { + + private EquiposRepository equiposRepository; + + // private String baseUrl = + // "https://fsprdcdnpublic.azureedge.net/global-pictures/flags-fwc2018-3/"; + // private String baseUrl = "https://www.countryflags.io/{0}/flat/64.png"; + private String baseUrl = "https://restcountries.eu/data/{0}.svg"; + + public CrearEquipos() { + } + + @Inject + public CrearEquipos(EquiposRepository equiposRepository) { + this.equiposRepository = equiposRepository; + } + + @Override + public void run() { + + // GRUPO A + this.crearEquipoSiNoExiste("BRA", "Brasil"); + this.crearEquipoSiNoExiste("BOL", "Bolivia"); + this.crearEquipoSiNoExiste("VEN", "Venezuela"); + this.crearEquipoSiNoExiste("PER", "Peru"); + + // GRUPO B + this.crearEquipoSiNoExiste("ARG", "Argentina"); + this.crearEquipoSiNoExiste("COL", "Colombia"); + this.crearEquipoSiNoExiste("PRY", "Paraguay"); + this.crearEquipoSiNoExiste("QAT", "Qatar"); + + // GRUPO C + this.crearEquipoSiNoExiste("URY", "Uruguay"); + this.crearEquipoSiNoExiste("ECU", "Ecuador"); + this.crearEquipoSiNoExiste("JPN", "Japan"); + this.crearEquipoSiNoExiste("CHL", "Chile"); + } + + private String getLogo(String codigo) { + return MessageFormat.format(baseUrl, codigo.toLowerCase()); + } + + private void crearEquipoSiNoExiste(String codigo, String nombre) { + if (!this.equiposRepository.exist(codigo)) { + Equipo equipo = new Equipo(codigo, nombre, this.getLogo(codigo).toLowerCase()); + this.equiposRepository.save(equipo); + } + } + + @Override + public int priority() { + return 1000; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearGruposYFases.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearGruposYFases.java new file mode 100644 index 0000000..782e9b3 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearGruposYFases.java @@ -0,0 +1,77 @@ +package io.semantic.openscore.core.repository.startup.steps; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +import io.semantic.openscore.core.model.Fase; +import io.semantic.openscore.core.model.Grupo; +import io.semantic.openscore.core.repository.FaseRepository; +import io.semantic.openscore.core.repository.GrupoRepository; +import io.semantic.openscore.core.repository.startup.StartupStep; + +@ApplicationScoped +public class CrearGruposYFases implements StartupStep { + + private GrupoRepository grupoRepository; + private FaseRepository faseRepository; + + public CrearGruposYFases() { + + } + + @Inject + public CrearGruposYFases(GrupoRepository grupoRepository, + FaseRepository faseRepository) { + + this.grupoRepository = grupoRepository; + this.faseRepository = faseRepository; + } + + @Override + public void run() { + this.crearEtapaSiNoExiste(Fase.GRUPO, this.crearFase(Fase.GRUPO, "Group", 1)); + // this.crearEtapaSiNoExiste(Fase.OCTAVOS, this.crearFase(Fase.OCTAVOS, "Eighth + // Finals", 2)); + this.crearEtapaSiNoExiste(Fase.CUARTOS, this.crearFase(Fase.CUARTOS, "Quarter Finals", 2)); + this.crearEtapaSiNoExiste(Fase.SEMI, this.crearFase(Fase.SEMI, "Semifinal", 3)); + this.crearEtapaSiNoExiste(Fase.TERCER, this.crearFase(Fase.TERCER, "Third Place", 4)); + this.crearEtapaSiNoExiste(Fase.FINAL, this.crearFase(Fase.FINAL, "Final", 4)); + + this.crearGrupoSiNoExiste(Grupo.GRUPO_A, this.crearGrupo(Grupo.GRUPO_A, "Group A")); + this.crearGrupoSiNoExiste(Grupo.GRUPO_B, this.crearGrupo(Grupo.GRUPO_B, "Group B")); + this.crearGrupoSiNoExiste(Grupo.NONE, this.crearGrupo(Grupo.NONE, "None")); + + } + + @Override + public int priority() { + return 0; + } + + private void crearGrupoSiNoExiste(String codigo, Grupo grupo) { + if (!this.grupoRepository.exist(codigo)) { + this.grupoRepository.save(grupo); + } + } + + private void crearEtapaSiNoExiste(String codigo, Fase estapa) { + if (!this.faseRepository.exist(codigo)) { + this.faseRepository.save(estapa); + } + } + + private Grupo crearGrupo(String codigo, String nombre) { + Grupo grupo = new Grupo(); + grupo.setCodigo(codigo); + grupo.setNombre(nombre); + return grupo; + } + + private Fase crearFase(String codigo, String nombre, int puntos) { + Fase fase = new Fase(); + fase.setCodigo(codigo.toUpperCase()); + fase.setNombre(nombre); + fase.setPuntos(puntos); + return fase; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPaises.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPaises.java new file mode 100644 index 0000000..e511e1f --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPaises.java @@ -0,0 +1,61 @@ +package io.semantic.openscore.core.repository.startup.steps; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.semantic.openscore.core.model.Pais; +import io.semantic.openscore.core.repository.PaisRepository; +import io.semantic.openscore.core.repository.startup.StartupStep; + +@ApplicationScoped +public class CrearPaises implements StartupStep { + + Logger logger = LoggerFactory.getLogger(CrearPaises.class); + private PaisRepository paisRepository; + + public CrearPaises() { + } + + @Inject + public CrearPaises(PaisRepository paisRepository) { + this.paisRepository = paisRepository; + } + + @Override + public void run() { + + logger.info("Inicializando paises"); + + this.guardarSiNoExiste(crearPais("ARG", "Argentina")); + this.guardarSiNoExiste(crearPais("CHI", "Chile")); + this.guardarSiNoExiste(crearPais("PER", "Peru")); + this.guardarSiNoExiste(crearPais("COL", "Colombia")); + this.guardarSiNoExiste(crearPais("MEX", "Mexico")); + this.guardarSiNoExiste(crearPais("BRA", "Brazil")); + + logger.info("Inicial de paises completa"); + } + + @Override + public int priority() { + return 0; + } + + public void guardarSiNoExiste(Pais pais) { + if (!this.paisRepository.exist(pais)) { + logger.info("Se crea pais no existente: " + pais.getCodigo()); + this.paisRepository.save(pais); + } + } + + public Pais crearPais(String codigo, String nombre) { + Pais pais = new Pais(); + pais.setCodigo(codigo); + pais.setNombre(nombre); + return pais; + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPartidos.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPartidos.java new file mode 100644 index 0000000..14f9733 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPartidos.java @@ -0,0 +1,97 @@ +package io.semantic.openscore.core.repository.startup.steps; + +import java.util.List; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.type.TypeReference; + +import io.semantic.openscore.core.model.Equipo; +import io.semantic.openscore.core.model.Fase; +import io.semantic.openscore.core.model.Grupo; +import io.semantic.openscore.core.model.Partido; +import io.semantic.openscore.core.repository.EquiposRepository; +import io.semantic.openscore.core.repository.FaseRepository; +import io.semantic.openscore.core.repository.GrupoRepository; +import io.semantic.openscore.core.repository.PartidoRepository; +import io.semantic.openscore.core.repository.startup.PartidoData; +import io.semantic.openscore.core.repository.startup.builder.DiaBuilder; + +@ApplicationScoped +public class CrearPartidos extends FileBasedStartupStep { + + private Logger logger = LoggerFactory.getLogger(CrearPartidos.class); + + private EquiposRepository equiposRepository; + private GrupoRepository grupoRepository; + private FaseRepository faseRepository; + private DiaBuilder diaBuilder; + + public CrearPartidos() { + super(Partido.class, null, new TypeReference>() { + }); + } + + @Inject + public CrearPartidos(PartidoRepository partidoRepository, + EquiposRepository equiposRepository, + GrupoRepository grupoRepository, + FaseRepository faseRepository, + DiaBuilder diaBuilder) { + + super(Partido.class, partidoRepository, new TypeReference>() { + }); + this.equiposRepository = equiposRepository; + this.grupoRepository = grupoRepository; + this.faseRepository = faseRepository; + this.diaBuilder = diaBuilder; + } + + @Override + public String getFileName() { + return "data/partidos.yml"; + } + + @Override + protected Partido map(PartidoData partidoData) { + + Equipo local = getEquipo(partidoData.getLocal()); + Equipo visitante = getEquipo(partidoData.getVisitante()); + Partido partido = new Partido(); + partido.setLocal(local); + partido.setVisitante(visitante); + partido.setDia(diaBuilder.getMatchDate(partidoData.getDia())); + partido.setLugar(partidoData.getLugar()); + partido.setGrupo(getGrupo(partidoData.getGrupo())); + partido.setFecha(partido.getFecha()); + partido.setFase(getFase(partidoData.getFase())); + return partido; + + } + + private Equipo getEquipo(String codigoLocal) { + return this.equiposRepository.findByCodigo(codigoLocal) + .orElseThrow(() -> new IllegalArgumentException("El equipo " + codigoLocal + "no existe")); + } + + private Grupo getGrupo(String codigo) { + logger.info(codigo); + return this.grupoRepository.findByCodigo(codigo) + .orElseThrow(() -> new IllegalArgumentException("El grupo " + codigo + "no existe")); + } + + private Fase getFase(String codigo) { + return this.faseRepository.findByCodigo(codigo) + .orElseThrow(() -> new IllegalArgumentException("La fase " + codigo + "no existe")); + + } + + @Override + public int priority() { + return 2000; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPreguntaSecreta.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPreguntaSecreta.java new file mode 100644 index 0000000..29ed096 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearPreguntaSecreta.java @@ -0,0 +1,51 @@ +package io.semantic.openscore.core.repository.startup.steps; + +import java.util.List; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +import com.fasterxml.jackson.core.type.TypeReference; + +import io.semantic.openscore.core.model.PreguntaSecreta; +import io.semantic.openscore.core.repository.PreguntaSecretaRepository; + +@ApplicationScoped +public class CrearPreguntaSecreta extends FileBasedStartupStep { + + private static final String FILENAME = "data/preguntas.yml"; + + public CrearPreguntaSecreta() { + super(PreguntaSecreta.class, null, new TypeReference>() { + }); + } + + @Inject + public CrearPreguntaSecreta(PreguntaSecretaRepository preguntaSecretaService) { + super(PreguntaSecreta.class, preguntaSecretaService, new TypeReference>() { + }); + } + + @Override + public int priority() { + return 1000; + } + + @Override + public String getFileName() { + return FILENAME; + } + + @Override + protected PreguntaSecreta map(PreguntaSecretaData dataObject) { + PreguntaSecreta preguntaSecreta = new PreguntaSecreta(); + preguntaSecreta.setCodigo(dataObject.getCodigo()); + preguntaSecreta.setPregunta(dataObject.getPregunta()); + return preguntaSecreta; + } + + @Override + public boolean enabled() { + return false; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearUsuarioAdmin.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearUsuarioAdmin.java new file mode 100644 index 0000000..3c31229 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/CrearUsuarioAdmin.java @@ -0,0 +1,87 @@ +package io.semantic.openscore.core.repository.startup.steps; + +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.model.Usuario; +import io.semantic.openscore.core.repository.PaisRepository; +import io.semantic.openscore.core.repository.UsuarioRepository; +import io.semantic.openscore.core.repository.startup.StartupStep; +import io.semantic.openscore.core.security.TokenGenerator; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import java.util.Arrays; +import java.util.HashSet; + +@ApplicationScoped +public class CrearUsuarioAdmin implements StartupStep { + + private UsuarioRepository usuarioRepository; + private PaisRepository paisRepository; + private TokenGenerator tokenGenerator; + + public CrearUsuarioAdmin() { + + } + + @Inject + public CrearUsuarioAdmin(UsuarioRepository usuarioRepository, + PaisRepository paisRepository, + TokenGenerator tokenGenerator) { + this.usuarioRepository = usuarioRepository; + this.paisRepository = paisRepository; + this.tokenGenerator = tokenGenerator; + } + + @Override + public void run() { + // this.crearUsuarioSiNoExiste("admin@admin.com", this.crearUsuarioAdmin()); + this.crearUsuarioSiNoExiste("aparedes@redhat.com", this.crearUsuarioAparedes()); + this.crearUsuarioSiNoExiste("lberetta@redhat.com", this.crearUsuarioLberetta()); + + } + + @Override + public int priority() { + return 100; + } + + private void crearUsuarioSiNoExiste(String email, Usuario usuario) { + if (!this.usuarioRepository.findByEmail(email).isPresent()) { + this.usuarioRepository.save(usuario); + } + } + + private Usuario crearUsuarioAdmin() { + Usuario usuario = new Usuario(); + usuario.setRoles(new HashSet<>(Arrays.asList(Rol.ADMIN, Rol.USUARIO))); + usuario.setEmail("admin@admin.com"); + usuario.setApellido("Admin"); + usuario.setNombre("Admin"); + usuario.setPassword(tokenGenerator.generarPassword("admin")); + usuario.setPais(this.paisRepository.findByCodigo("ARG")); + return usuario; + } + + private Usuario crearUsuarioAparedes() { + Usuario usuario = new Usuario(); + usuario.setRoles(new HashSet<>(Arrays.asList(Rol.ADMIN, Rol.USUARIO))); + usuario.setEmail("aparedes@redhat.com"); + usuario.setApellido("Paredes"); + usuario.setNombre("Adriel"); + usuario.setPassword(tokenGenerator.generarPassword("admin")); + usuario.setPais(this.paisRepository.findByCodigo("ARG")); + return usuario; + } + + private Usuario crearUsuarioLberetta() { + Usuario usuario = new Usuario(); + usuario.setRoles(new HashSet<>(Arrays.asList(Rol.ADMIN, Rol.USUARIO))); + usuario.setEmail("lberetta@redhat.com"); + usuario.setApellido("Beretta"); + usuario.setNombre("Leandro"); + usuario.setPassword(tokenGenerator.generarPassword("admin")); + usuario.setPais(this.paisRepository.findByCodigo("ARG")); + return usuario; + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/FileBasedStartupStep.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/FileBasedStartupStep.java new file mode 100644 index 0000000..8aec847 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/FileBasedStartupStep.java @@ -0,0 +1,67 @@ +package io.semantic.openscore.core.repository.startup.steps; + +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; + +import io.semantic.openscore.core.model.Storable; +import io.semantic.openscore.core.repository.Repository; +import io.semantic.openscore.core.repository.startup.StartupStep; + +public abstract class FileBasedStartupStep implements StartupStep { + + private final ObjectMapper objectMapper; + private Logger logger = LoggerFactory.getLogger(FileBasedStartupStep.class); + + private Class type; + private TypeReference> typeReference; + private Repository existService; + + public FileBasedStartupStep(Class type, Repository existsService, TypeReference> typeReference) { + this.type = type; + this.typeReference = typeReference; + this.objectMapper = new ObjectMapper(new YAMLFactory()); + this.existService = existsService; + } + + public abstract String getFileName(); + + @Override + public void run() { + List entities = this.loadYaml(this.getFileName()); + + entities.forEach(entity -> { + logger.info("{}", entity.getClass().getSimpleName()); + this.saveIfNotExist(entity); + }); + + } + + private List loadYaml(String fileName) { + try { + InputStream is = CrearPartidos.class.getClassLoader().getResourceAsStream(fileName); + return this.objectMapper.readValue(is, typeReference); + } catch (Exception e) { + logger.error("Error", e); + return new ArrayList<>(); + } + } + + private void saveIfNotExist(D dataObject) { + T entity = map(dataObject); + if (!this.existService.exist(entity)) { + logger.info("Creando {} = {}", this.type.getSimpleName(), entity); + this.existService.save(entity); + } + } + + protected abstract T map(D dataObject); + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/PreguntaSecretaData.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/PreguntaSecretaData.java new file mode 100644 index 0000000..aabac6a --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/repository/startup/steps/PreguntaSecretaData.java @@ -0,0 +1,27 @@ +package io.semantic.openscore.core.repository.startup.steps; + +public class PreguntaSecretaData { + private String codigo; + private String pregunta; + + public String getCodigo() { + return codigo; + } + + public void setCodigo(String codigo) { + this.codigo = codigo; + } + + public String getPregunta() { + return pregunta; + } + + public void setPregunta(String pregunta) { + this.pregunta = pregunta; + } + + @Override + public String toString() { + return getCodigo() + " - " + getPregunta(); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/Secure.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/Secure.java new file mode 100644 index 0000000..0c27c5e --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/Secure.java @@ -0,0 +1,17 @@ +package io.semantic.openscore.core.security; + +import io.semantic.openscore.core.model.Rol; + +import javax.ws.rs.NameBinding; +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target({ElementType.TYPE, ElementType.METHOD}) +@Retention(value = RetentionPolicy.RUNTIME) +@NameBinding +public @interface Secure { + + Rol[] value() default {Rol.USUARIO}; +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/SecureFilter.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/SecureFilter.java new file mode 100644 index 0000000..4f297f6 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/SecureFilter.java @@ -0,0 +1,75 @@ +package io.semantic.openscore.core.security; + +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.model.Usuario; +import io.semantic.openscore.core.repository.UsuarioRepository; +import io.semantic.openscore.core.services.UserInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.inject.Inject; +import javax.ws.rs.NotAuthorizedException; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.ResourceInfo; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.ext.Provider; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; + +@Provider +@Secure +public class SecureFilter implements ContainerRequestFilter { + + @Context + ResourceInfo resourceInfo; + + private Logger logger = LoggerFactory.getLogger(SecureFilter.class); + private UserInfo userInfo; + private UsuarioRepository usuarioRepository; + + public SecureFilter() { + + } + + @Inject + public SecureFilter(UserInfo userInfo, + UsuarioRepository usuarioRepository) { + this.userInfo = userInfo; + this.usuarioRepository = usuarioRepository; + } + + @Override + public void filter(ContainerRequestContext containerRequestContext) { + + Secure secure = resourceInfo.getResourceMethod().getAnnotation(Secure.class); + List roles = Arrays.asList(secure.value()); + + logger.info("Roles autorizados: {}", roles); + + + TokenGenerator tokenGenerator = new TokenGenerator(); + String token = tokenGenerator.getTokenFromAuthHeader(containerRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION)); + boolean isValid = tokenGenerator.verify(token); + + if (isValid) { + logger.info("Token valido"); + Optional usuarioOptional = usuarioRepository.findByEmail(tokenGenerator.getMail(token)); + Usuario usuario = usuarioOptional.orElseThrow(() -> new IllegalArgumentException("usuario inexistente")); + userInfo.setUsuario(usuario); + if (!usuario.getRoles().stream().anyMatch(rol -> roles.contains(rol))) { + logger.info("El usuario no contiene los roles necesarios"); + throw new NotAuthorizedException("El usuario no contiene los roles necesarios"); + } else { + logger.info("El usuario contiene los roles, continua la operacion"); + } + } else { + logger.info("El token es invalido"); + throw new NotAuthorizedException("El token no es valido"); + } + + } +} + diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/TokenGenerator.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/TokenGenerator.java new file mode 100644 index 0000000..18c109b --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/security/TokenGenerator.java @@ -0,0 +1,138 @@ +package io.semantic.openscore.core.security; + +import java.util.Date; +import java.util.Set; + +import javax.enterprise.context.ApplicationScoped; + +import org.apache.commons.lang3.RandomStringUtils; + +import com.google.common.base.Charsets; +import com.google.common.hash.Hashing; +import com.nimbusds.jose.JWSAlgorithm; +import com.nimbusds.jose.JWSHeader; +import com.nimbusds.jose.JWSVerifier; +import com.nimbusds.jose.crypto.MACSigner; +import com.nimbusds.jose.crypto.MACVerifier; +import com.nimbusds.jwt.JWTClaimsSet; +import com.nimbusds.jwt.SignedJWT; + +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.model.Usuario; + +@ApplicationScoped +public class TokenGenerator { + + private static final String OPENSCORE_JWT_SECRET = "OPENSCORE_JWT_SECRET"; + private final String SECRET; + public static final String SUBJECT = "openscore"; + public static final String ISSUER = "openscore"; + public static final String USERNAME = "username"; + public static final String EMAIL = "email"; + public static final String NOMBRE = "nombre"; + public static final String APELLIDO = "apellido"; + public static final String ROLES = "roles"; + public static final JWSAlgorithm ALGORITMO = JWSAlgorithm.HS256; + public static final Date EXPIRACION_TOKEN = new Date(new Date().getTime() + 43800 * 60 * 1000); + + public TokenGenerator() { + String t = System.getenv(OPENSCORE_JWT_SECRET); + if (t != null && !t.isEmpty()) { + this.SECRET = t; + } else { + this.SECRET = "7ZXjPaKE3eJLY6ENu3zcZHIPE3dyOFru"; + } + } + + public String generarToken(Usuario usuario) { + + JWTClaimsSet claimsSet = new JWTClaimsSet.Builder() + .subject(SUBJECT) + .issuer(ISSUER) + .expirationTime(EXPIRACION_TOKEN) + .claim(EMAIL, + usuario.getEmail()) + .claim(NOMBRE, + usuario.getNombre()) + .claim(APELLIDO, + usuario.getApellido()) + .claim(ROLES, + usuario.getRoles()) + .build(); + + SignedJWT signedJWT = new SignedJWT(new JWSHeader(ALGORITMO), + claimsSet); + sign(signedJWT); + return signedJWT.serialize(); + } + + public String generarPassword(String password) { + return Hashing.sha256().hashString(password, + Charsets.UTF_8).toString(); + } + + public String getTokenFromAuthHeader(String authHeader) { + try { + String[] authorizationParts = authHeader.split(" "); + + return authorizationParts[1]; + } catch (Exception e) { + throw new IllegalArgumentException("token vacio o invalido"); + } + } + + public boolean verify(String token) { + try { + SignedJWT signedJWT = SignedJWT.parse(token); + JWSVerifier verifier = new MACVerifier(SECRET); + return signedJWT.verify(verifier) && + signedJWT.getJWTClaimsSet().getExpirationTime().before(new Date()); + } catch (Exception e) { + return false; + } + } + + public String getMail(String token) { + try { + SignedJWT signedJWT = SignedJWT.parse(token); + return (String) signedJWT.getJWTClaimsSet().getClaim(EMAIL); + } catch (Exception e) { + throw new RuntimeException("Error al firmar el token", + e); + } + } + + public Set getRoles(String token) { + try { + SignedJWT signedJWT = SignedJWT.parse(token); + return (Set) signedJWT.getJWTClaimsSet().getClaim(ROLES); + } catch (Exception e) { + throw new RuntimeException("Error al firmar el token", + e); + } + } + + private void sign(SignedJWT signedJWT) { + try { + + MACSigner signer = new MACSigner(SECRET); + signedJWT.sign(signer); + } catch (Exception e) { + throw new RuntimeException("Error al firmar el token", + e); + } + } + + public static String passwordRegex() { + return null; + } + + public String generateRandomToken() { + int length = 10; + boolean useLetters = true; + boolean useNumbers = false; + return RandomStringUtils.random(length, + useLetters, + useNumbers); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/RestUtil.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/RestUtil.java new file mode 100644 index 0000000..6f99780 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/RestUtil.java @@ -0,0 +1,18 @@ +package io.semantic.openscore.core.services; + +import io.semantic.openscore.core.api.ApiResponse; + +public class RestUtil { + + public static ApiResponse ok(T data) { + return new ApiResponse<>(data); + } + + public static ApiResponse error(String error, + String description, + Object data) { + return new ApiResponse<>(error, + description, + data); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/UserInfo.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/UserInfo.java new file mode 100644 index 0000000..b08c65f --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/UserInfo.java @@ -0,0 +1,28 @@ +package io.semantic.openscore.core.services; + +import io.semantic.openscore.core.model.Usuario; + +import javax.enterprise.context.RequestScoped; +import java.util.Optional; + +@RequestScoped +public class UserInfo { + + private Optional usuario; + + public UserInfo() { + usuario = Optional.empty(); + } + + public Optional getUsuario() { + return usuario; + } + + public void setUsuario(Usuario usuario) { + this.usuario = Optional.of(usuario); + } + + public long getUserId() { + return this.usuario.orElseThrow(() -> new IllegalArgumentException("Se necesita un usuario en la sesion para poder obtener el id")).getId(); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/AdminService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/AdminService.java new file mode 100644 index 0000000..493be30 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/AdminService.java @@ -0,0 +1,16 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.admin.UsuarioCompletoDTO; + +import javax.ws.rs.Consumes; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("admin") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface AdminService extends SearchService { + + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/DefinicionCompeticionesService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/DefinicionCompeticionesService.java new file mode 100644 index 0000000..f8b6ed9 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/DefinicionCompeticionesService.java @@ -0,0 +1,45 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.competiciones.CrearDefinicionCompeticionDTO; +import io.semantic.openscore.core.api.competiciones.DefinicionCompeticionDTO; +import io.semantic.openscore.core.api.partidos.CrearOUpdatePartidoDTO; +import io.semantic.openscore.core.api.partidos.PartidoDTO; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.List; + +@Path("competiciones") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface DefinicionCompeticionesService extends StandardService { + + + @GET + @Path("/{id}/partidos") + ApiResponse> getPartidos(@PathParam("id") long id); + + @GET + @Path("/{id}/partidos/{idPartido") + ApiResponse getPartido(@PathParam("id") long id, + @PathParam("idPartido") long idPartido); + + @POST + @Path("/{id}/partidos") + ApiResponse addPartido(@PathParam("id") long id, + CrearOUpdatePartidoDTO crearPartido); + + @POST + @Path("/{id}/partidos/{idPartido}") + ApiResponse updatePartido(@PathParam("id") long id, + @PathParam("idPartido") long idPartido, + CrearOUpdatePartidoDTO crearOUpdatePartidoDTO); + + @DELETE + @Path("/{id}/partidos/{idPartido}") + ApiResponse deletePartido(@PathParam("id") long id, + @PathParam("idPartido") long idPartido); + + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/EquiposService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/EquiposService.java new file mode 100644 index 0000000..0970fb1 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/EquiposService.java @@ -0,0 +1,19 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.equipos.CrearEquipoDTO; +import io.semantic.openscore.core.api.equipos.EquipoDTO; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.List; + +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface EquiposService extends StandardService { + + @Path("/") + @GET + ApiResponse> getAll(@QueryParam("page") int page, + @QueryParam("pageSize") int pageSize); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/FasesService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/FasesService.java new file mode 100644 index 0000000..14cc273 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/FasesService.java @@ -0,0 +1,15 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.model.Fase; + +import javax.ws.rs.Consumes; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("fases") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface FasesService extends GetService { + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/GetService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/GetService.java new file mode 100644 index 0000000..630a5da --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/GetService.java @@ -0,0 +1,16 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.ApiResponse; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; + +public interface GetService extends SearchService { + + + @Path("/{id}") + @GET + ApiResponse get(@PathParam("id") long id); + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/GruposService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/GruposService.java new file mode 100644 index 0000000..8260b24 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/GruposService.java @@ -0,0 +1,14 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.model.Grupo; + +import javax.ws.rs.Consumes; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("grupos") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface GruposService extends GetService { +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/InformationService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/InformationService.java new file mode 100644 index 0000000..aa2d6e7 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/InformationService.java @@ -0,0 +1,27 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.information.Information; +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.security.Secure; + +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("info") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface InformationService { + + @GET + @Path("/") + ApiResponse getInformation(); + + @GET + @Path("/ping/secure") + @Secure({Rol.ADMIN, Rol.USUARIO}) + ApiResponse securePing(); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PaisesService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PaisesService.java new file mode 100644 index 0000000..96a4f4a --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PaisesService.java @@ -0,0 +1,16 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.paises.PaisDTO; + +import javax.ws.rs.Consumes; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +@Path("paises") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface PaisesService extends SearchService { + + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PartidosService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PartidosService.java new file mode 100644 index 0000000..456ef2c --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PartidosService.java @@ -0,0 +1,50 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.partidos.CrearOUpdatePartidoDTO; +import io.semantic.openscore.core.api.partidos.PartidoDTO; +import io.semantic.openscore.core.api.partidos.ResultadoDTO; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.List; + +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +@Path("partidos") +public interface PartidosService { + + @GET + @Path("/") + ApiResponse> getAll(@QueryParam("page") int page, + @QueryParam("pageSize") int pageSize, + @QueryParam("grupo") String grupo, + @QueryParam("fase") String fase, + @QueryParam("fecha") long fecha, + @QueryParam("equipo") String equipo); + + @GET + @Path("/{id}") + ApiResponse get(@PathParam("id") long id); + + @GET + @Path("/fechas") + ApiResponse> getFechas(); + + @DELETE + @Path("/{id}") + ApiResponse delete(@PathParam("id") long id); + + @POST + @Path("/") + ApiResponse add(CrearOUpdatePartidoDTO entity); + + @POST + @Path("/{id}") + ApiResponse update(@PathParam("id") long id, CrearOUpdatePartidoDTO entity); + + @POST + @Path("{id}/resultado") + ApiResponse setResultado(@PathParam("id") long id, ResultadoDTO resultado); +} + diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PostService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PostService.java new file mode 100644 index 0000000..53275d8 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PostService.java @@ -0,0 +1,30 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.post.CrearPost; +import io.semantic.openscore.core.model.Post; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.List; + +@Path("/posts") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface PostService extends StandardService { + + @Path("/") + @GET + ApiResponse> getAll(@QueryParam("page") int page, + @QueryParam("pageSize") int pageSize, + @QueryParam("status") String status); + + @Path("{id}/publicar") + @POST + ApiResponse publicar(@PathParam("id") long id); + + @Path("{id}/retirar") + @POST + ApiResponse retirar(@PathParam("id") long id); + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PronosticosService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PronosticosService.java new file mode 100644 index 0000000..ee07189 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/PronosticosService.java @@ -0,0 +1,66 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.pronosticos.CrearPronosticoDTO; +import io.semantic.openscore.core.api.pronosticos.PartidoPronosticoDTO; +import io.semantic.openscore.core.api.pronosticos.PronosticoDTO; +import io.semantic.openscore.core.security.Secure; + +import javax.enterprise.context.ApplicationScoped; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.List; + + +@Path("pronosticos") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface PronosticosService { + + @Path("/") + @GET + @Secure + ApiResponse> getAll(@QueryParam("page") int page, + @QueryParam("pageSize") int pageSize, + @QueryParam("grupo") String grupo, + @QueryParam("fase") String fase, + @QueryParam("dia") long dia, + @QueryParam("fecha") int fecha); + + @Path("/{id}") + @GET + @Secure + ApiResponse get(@PathParam("id") long id); + + @Path("/{id}") + @DELETE + @Secure + ApiResponse delete(@PathParam("id") long id); + + @Path("/") + @POST + @Secure + ApiResponse add(CrearPronosticoDTO entity); + + @Path("/{id}") + @POST + @Secure + ApiResponse update(@PathParam("id") long id, + CrearPronosticoDTO entity); + + @Path("/{id}/local") + @POST + @Secure + ApiResponse local(@PathParam("id") long idPartido); + + @Path("/{id}/empate") + @POST + @Secure + ApiResponse empate(@PathParam("id") long idPartido); + + @Path("/{id}/visitante") + @POST + @Secure + ApiResponse visitante(@PathParam("id") long idPartido); + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/RankingService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/RankingService.java new file mode 100644 index 0000000..cbc02c2 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/RankingService.java @@ -0,0 +1,24 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.ranking.Ranking; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.List; + +@Path("ranking") +@Produces(MediaType.APPLICATION_JSON) +@Consumes(MediaType.APPLICATION_JSON) +public interface RankingService { + + @GET + @Path("/{id}") + ApiResponse getRanking(@PathParam("id") long id); + + @GET + @Path("/") + ApiResponse> getAllRanking(@QueryParam("pais") String pais, @QueryParam("size") @DefaultValue("0") int size); + + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/SearchService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/SearchService.java new file mode 100644 index 0000000..d4e28c5 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/SearchService.java @@ -0,0 +1,19 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.ApiResponse; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.List; + +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface SearchService { + + @GET + @Path("/") + ApiResponse> getAll(@QueryParam("page") @DefaultValue("0") int page, + @QueryParam("pageSize") @DefaultValue("10") int pageSize, + @QueryParam("q") @DefaultValue("") String filter); + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/StandardService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/StandardService.java new file mode 100644 index 0000000..dbc9dc1 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/StandardService.java @@ -0,0 +1,26 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.ApiResponse; + +import javax.ws.rs.*; + +public interface StandardService { + + + @Path("/{id}") + @GET + ApiResponse get(@PathParam("id") long id); + + @Path("/{id}") + @DELETE + ApiResponse delete(@PathParam("id") long id); + + @Path("/") + @POST + ApiResponse add(Y entity); + + @Path("/{id}") + @POST + ApiResponse update(@PathParam("id") long id, + Z entity); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/UsuariosService.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/UsuariosService.java new file mode 100644 index 0000000..7585a4f --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/api/UsuariosService.java @@ -0,0 +1,62 @@ +package io.semantic.openscore.core.services.api; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.TokenDTO; +import io.semantic.openscore.core.api.usuarios.*; +import io.semantic.openscore.core.security.Secure; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.List; + +@Path("usuarios") +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +public interface UsuariosService extends SearchService { + + @POST + @Path("/registrar") + ApiResponse registrarUsuario(CrearUsuarioDTO crearUsuario); + + @POST + @Path("/update/{id}") + @Secure + ApiResponse updateUsuario(@PathParam("id") long id, UpdateUsuarioDTO crearUsuario); + + + @POST + @Path("/password") + @Secure + ApiResponse updatePassword(UpdatePassword updatePassword); + + @POST + @Path("/recover") + ApiResponse recoverPassword(RecoverPassword updatePassword); + + @GET + @Path("/token/{email}") + ApiResponse sendToken(@PathParam("email") String email); + + + ApiResponse deleteUsuario(long id); + + @GET + @Path("/{id}") + @Secure + ApiResponse getUsuario(@PathParam("id") Long id); + + @GET + @Path("/myself") + @Secure + ApiResponse getMiUsuario(); + + @GET + @Path("/") + @Secure + ApiResponse> getAll(@QueryParam("page") int page, @QueryParam("pageSize") int pageSize, @QueryParam("filter") String filter); + + @POST + @Path("/login") + ApiResponse login(LoginUsuarioDTO loginUsuario); + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/ApplicationExceptionMapper.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/ApplicationExceptionMapper.java new file mode 100644 index 0000000..9bab42e --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/ApplicationExceptionMapper.java @@ -0,0 +1,38 @@ +package io.semantic.openscore.core.services.filters; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +import io.semantic.openscore.core.exceptions.ApplicationException; +import io.semantic.openscore.core.exceptions.ValidationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import static io.semantic.openscore.core.services.RestUtil.error; + +@Provider +public class ApplicationExceptionMapper implements ExceptionMapper { + + private Logger logger = LoggerFactory.getLogger(ApplicationExceptionMapper.class); + + @Override + public Response toResponse(ApplicationException exception) { + logger.error(exception.getMessage(), exception); + + Object data = null; + + if (exception instanceof ValidationException) { + data = ((ValidationException) exception).getData(); + } + + return Response + .status(500) + .type(MediaType.APPLICATION_JSON_TYPE) + .entity(error("ERROR", + exception.getMessage(), + data)) + .build(); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/CorsFilter.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/CorsFilter.java new file mode 100644 index 0000000..708f7c2 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/CorsFilter.java @@ -0,0 +1,35 @@ +package io.semantic.openscore.core.services.filters; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerResponseContext; +import javax.ws.rs.container.ContainerResponseFilter; +import javax.ws.rs.container.PreMatching; +import javax.ws.rs.ext.Provider; +import java.io.IOException; + +@PreMatching +@Provider +public class CorsFilter implements ContainerResponseFilter { + + private Logger logger = LoggerFactory.getLogger(CorsFilter.class); + + private static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; + private static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"; + private static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age"; + private static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"; + private static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"; + + @Override + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { + + responseContext.getHeaders().add(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); + responseContext.getHeaders().add(ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT, DELETE, OPTIONS, HEAD".toUpperCase()); + responseContext.getHeaders().add(ACCESS_CONTROL_MAX_AGE, "-1"); + responseContext.getHeaders().add(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); + responseContext.getHeaders().add(ACCESS_CONTROL_ALLOW_HEADERS, "Authorization, Origin, Content-Type, Accept".toLowerCase()); + } + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/LoggerFilter.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/LoggerFilter.java new file mode 100644 index 0000000..aeed309 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/LoggerFilter.java @@ -0,0 +1,28 @@ +package io.semantic.openscore.core.services.filters; + +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.ContainerRequestFilter; +import javax.ws.rs.container.PreMatching; +import javax.ws.rs.ext.Provider; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; + +@PreMatching +@Provider +public class LoggerFilter implements ContainerRequestFilter { + + private Logger logger = LoggerFactory.getLogger(LoggerFilter.class); + + + @Override + public void filter(ContainerRequestContext requestContext) throws IOException { + byte[] byteArray = IOUtils.toByteArray(requestContext.getEntityStream()); + InputStream entity = new ByteArrayInputStream(byteArray); + requestContext.setEntityStream(new ByteArrayInputStream(byteArray)); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/RuntimeExceptionMapper.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/RuntimeExceptionMapper.java new file mode 100644 index 0000000..2be6234 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/filters/RuntimeExceptionMapper.java @@ -0,0 +1,25 @@ +package io.semantic.openscore.core.services.filters; + +import io.semantic.openscore.core.api.ApiResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.ext.ExceptionMapper; +import javax.ws.rs.ext.Provider; + +@Provider +public class RuntimeExceptionMapper implements ExceptionMapper { + + private Logger logger = LoggerFactory.getLogger(ApplicationExceptionMapper.class); + + @Override + public Response toResponse(IllegalArgumentException e) { + logger.error(e.getLocalizedMessage(), e); + return Response + .serverError() + .type(MediaType.APPLICATION_JSON_TYPE) + .entity(new ApiResponse<>("500", e.getMessage(), null)).build(); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/AdminServiceImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/AdminServiceImpl.java new file mode 100644 index 0000000..f01956e --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/AdminServiceImpl.java @@ -0,0 +1,41 @@ +package io.semantic.openscore.core.services.impl; + +import java.util.List; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.admin.UsuarioCompletoDTO; +import io.semantic.openscore.core.mapping.UsuarioMapper; +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.model.Usuario; +import io.semantic.openscore.core.repository.Page; +import io.semantic.openscore.core.repository.UsuarioRepository; +import io.semantic.openscore.core.security.Secure; +import io.semantic.openscore.core.services.api.AdminService; + +@ApplicationScoped +public class AdminServiceImpl implements AdminService { + + private UsuarioMapper mapper; + private UsuarioRepository usuarioRepository; + + public AdminServiceImpl() { + } + + @Inject + public AdminServiceImpl(UsuarioRepository usuarioRepository, + UsuarioMapper mapper) { + this.usuarioRepository = usuarioRepository; + this.mapper = mapper; + } + + @Override + @Secure(Rol.ADMIN) + public ApiResponse> getAll(int page, int pageSize, String filter) { + List usuarios = this.usuarioRepository.findAll(new Page(page, pageSize)); + List usuariosApi = this.mapper.asCompletoApi(usuarios); + return new ApiResponse<>(usuariosApi); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/EquiposServiceImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/EquiposServiceImpl.java new file mode 100644 index 0000000..8d2bff0 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/EquiposServiceImpl.java @@ -0,0 +1,106 @@ +package io.semantic.openscore.core.services.impl; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.equipos.CrearEquipoDTO; +import io.semantic.openscore.core.api.equipos.EquipoDTO; +import io.semantic.openscore.core.mapping.EquipoMapper; +import io.semantic.openscore.core.model.Equipo; +import io.semantic.openscore.core.model.Pais; +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.repository.EquiposRepository; +import io.semantic.openscore.core.repository.Page; +import io.semantic.openscore.core.repository.PaisRepository; +import io.semantic.openscore.core.security.Secure; +import io.semantic.openscore.core.services.api.EquiposService; +import io.semantic.openscore.core.validation.ApplicationValidator; + +import javax.inject.Inject; +import javax.ws.rs.Path; +import javax.ws.rs.core.UriInfo; +import java.text.MessageFormat; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static io.semantic.openscore.core.services.RestUtil.ok; + +@Path("equipos") +public class EquiposServiceImpl implements EquiposService { + + + private PaisRepository paisRepository; + private EquiposRepository equiposRepository; + private ApplicationValidator validator; + private EquipoMapper mapper; + + public EquiposServiceImpl() { + } + + @Inject + public EquiposServiceImpl(EquiposRepository equiposRepository, + PaisRepository paisRepository, + ApplicationValidator validator, + EquipoMapper mapper) { + this.equiposRepository = equiposRepository; + this.paisRepository = paisRepository; + this.validator = validator; + this.mapper = mapper; + } + + @Override + public ApiResponse> getAll(int page, int pageSize) { + List equipos = this.equiposRepository + .findAll(new Page(page, pageSize)) + .stream() + .map(equipo -> map(equipo)) + .collect(Collectors.toList()); + return ok(equipos); + } + + @Override + public ApiResponse get(long id) { + Equipo equipo = this.equiposRepository + .findById(id).orElseThrow(() -> + new RuntimeException(MessageFormat.format("El equipo con el ID: {0} no fue encontrado", id))); + return ok(map(equipo)); + } + + @Override + @Secure(Rol.ADMIN) + public ApiResponse delete(long id) { + this.equiposRepository.deleteById(id); + return ok(id); + } + + @Override + @Secure(Rol.ADMIN) + public ApiResponse add(CrearEquipoDTO entity) { + validator.validate(entity); + Pais pais = this.paisRepository.findByCodigo(entity.getCodigoPais()); + Equipo equipo = this.mapper.asEquipo(entity); + this.equiposRepository.save(equipo); + return ok(map(equipo)); + } + + @Override + @Secure(Rol.ADMIN) + public ApiResponse update(long id, CrearEquipoDTO entity) { + validator.validate(entity); + Optional equipoOptional = this.equiposRepository.findById(id); + if (equipoOptional.isPresent()) { + Equipo equipo = equipoOptional.get(); + equipo.setCodigo(entity.getCodigo()); + equipo.setLogo(entity.getLogo()); + equipo.setNombre(entity.getNombre()); + this.equiposRepository.save(equipo); + return ok(map(equipo)); + } else { + throw new RuntimeException(MessageFormat.format("No se pudo actualizar el equipo con ID {0}", id)); + } + + } + + private EquipoDTO map(Equipo equipo) { + return this.mapper.asApi(equipo); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/FasesServiceImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/FasesServiceImpl.java new file mode 100644 index 0000000..eebacfe --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/FasesServiceImpl.java @@ -0,0 +1,43 @@ +package io.semantic.openscore.core.services.impl; + +import static io.semantic.openscore.core.services.RestUtil.ok; + +import java.text.MessageFormat; +import java.util.List; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.model.Fase; +import io.semantic.openscore.core.repository.FaseRepository; +import io.semantic.openscore.core.repository.Page; +import io.semantic.openscore.core.services.api.FasesService; + +@ApplicationScoped +public class FasesServiceImpl implements FasesService { + + private FaseRepository faseRepository; + + public FasesServiceImpl() { + } + + @Inject + public FasesServiceImpl(FaseRepository faseRepository) { + this.faseRepository = faseRepository; + } + + @Override + public ApiResponse> getAll(int page, int pageSize, String filter) { + return ok(this.faseRepository.findAll(new Page(page, pageSize))); + } + + @Override + public ApiResponse get(long id) { + return ok(this.faseRepository + .findById(id) + .orElseThrow(() -> new IllegalArgumentException( + MessageFormat + .format("La Fase con el ID {0} no fue encontrada", id)))); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/GruposServiceImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/GruposServiceImpl.java new file mode 100644 index 0000000..69a2e5f --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/GruposServiceImpl.java @@ -0,0 +1,44 @@ +package io.semantic.openscore.core.services.impl; + +import static io.semantic.openscore.core.services.RestUtil.ok; + +import java.text.MessageFormat; +import java.util.List; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.model.Grupo; +import io.semantic.openscore.core.repository.GrupoRepository; +import io.semantic.openscore.core.repository.Page; +import io.semantic.openscore.core.services.api.GruposService; + +@ApplicationScoped +public class GruposServiceImpl implements GruposService { + + + private GrupoRepository grupoRepository; + + public GruposServiceImpl() { + } + + @Inject + public GruposServiceImpl(GrupoRepository grupoRepository) { + this.grupoRepository = grupoRepository; + } + + @Override + public ApiResponse> getAll(int page, int pageSize, String filter) { + return ok(this.grupoRepository.findAll(new Page(page, pageSize))); + } + + @Override + public ApiResponse get(long id) { + return ok(this.grupoRepository + .findById(id) + .orElseThrow(() -> new IllegalArgumentException( + MessageFormat + .format("El Grupo con el ID {0} no fue encontrado", id)))); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/InformationServiceImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/InformationServiceImpl.java new file mode 100644 index 0000000..90720a8 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/InformationServiceImpl.java @@ -0,0 +1,53 @@ +package io.semantic.openscore.core.services.impl; + +import static io.semantic.openscore.core.services.RestUtil.ok; + +import java.io.IOException; +import java.io.InputStream; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.persistence.EntityManager; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.information.Information; +import io.semantic.openscore.core.exceptions.NoSePuedeLeerInformacionException; +import io.semantic.openscore.core.services.api.InformationService; + +@ApplicationScoped +public class InformationServiceImpl implements InformationService { + + @Inject + private EntityManager entityManager; + + @Override + public ApiResponse getInformation() { + try { + Map emfProperties = entityManager.getEntityManagerFactory().getProperties(); + + Map hibernateMap = emfProperties.entrySet().stream() + .filter(x -> x.getKey().startsWith("hibernate")) + .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue())); + + Properties prop = new Properties(); + String filename = "info.properties"; + InputStream input = getClass().getClassLoader().getResourceAsStream(filename); + prop.load(input); + Information information = new Information(); + information.setVersion(prop.getProperty("info.version")); + information.setEnvironment(prop.getProperty("info.environment")); + information.setProperties(hibernateMap); + return ok(information); + } catch (IOException e) { + throw new NoSePuedeLeerInformacionException("No se puede leer info.properties", e); + } + } + + @Override + public ApiResponse securePing() { + return ok("ok"); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PaisesServiceImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PaisesServiceImpl.java new file mode 100644 index 0000000..ad37e26 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PaisesServiceImpl.java @@ -0,0 +1,40 @@ +package io.semantic.openscore.core.services.impl; + +import java.util.List; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.paises.PaisDTO; +import io.semantic.openscore.core.mapping.PaisMapper; +import io.semantic.openscore.core.model.Pais; +import io.semantic.openscore.core.repository.Page; +import io.semantic.openscore.core.repository.PaisRepository; +import io.semantic.openscore.core.services.api.PaisesService; + +@ApplicationScoped +public class PaisesServiceImpl implements PaisesService { + + + private PaisMapper mapper; + private PaisRepository repository; + + public PaisesServiceImpl() { + + } + + @Inject + public PaisesServiceImpl(PaisRepository repository, PaisMapper mapper) { + + this.repository = repository; + this.mapper = mapper; + } + + + @Override + public ApiResponse> getAll(int page, int pageSize, String filter) { + List paises = this.repository.findAll(new Page(page, pageSize)); + return new ApiResponse<>(this.mapper.asApi(paises)); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PartidosServiceImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PartidosServiceImpl.java new file mode 100644 index 0000000..012c673 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PartidosServiceImpl.java @@ -0,0 +1,150 @@ +package io.semantic.openscore.core.services.impl; + +import static io.semantic.openscore.core.services.RestUtil.ok; + +import java.text.MessageFormat; +import java.util.List; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.partidos.CrearOUpdatePartidoDTO; +import io.semantic.openscore.core.api.partidos.PartidoDTO; +import io.semantic.openscore.core.api.partidos.ResultadoDTO; +import io.semantic.openscore.core.mapping.PartidoMapper; +import io.semantic.openscore.core.model.Equipo; +import io.semantic.openscore.core.model.Fase; +import io.semantic.openscore.core.model.Grupo; +import io.semantic.openscore.core.model.Partido; +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.repository.EquiposRepository; +import io.semantic.openscore.core.repository.FaseRepository; +import io.semantic.openscore.core.repository.GrupoRepository; +import io.semantic.openscore.core.repository.PartidoRepository; +import io.semantic.openscore.core.security.Secure; +import io.semantic.openscore.core.services.api.PartidosService; + +@ApplicationScoped +public class PartidosServiceImpl implements PartidosService { + + + private PartidoRepository partidoRepository; + private EquiposRepository equiposRepository; + private GrupoRepository grupoRepository; + private FaseRepository faseRepository; + private PartidoMapper partidoMapper; + + public PartidosServiceImpl() { + } + + @Inject + public PartidosServiceImpl(final PartidoRepository partidoRepository, + final EquiposRepository equiposRepository, + final GrupoRepository grupoRepository, + final FaseRepository faseRepository, + final PartidoMapper partidoMapper) { + this.partidoRepository = partidoRepository; + this.equiposRepository = equiposRepository; + this.grupoRepository = grupoRepository; + this.faseRepository = faseRepository; + this.partidoMapper = partidoMapper; + } + + @Override + public ApiResponse> getAll(int page, + int pageSize, + String grupo, + String fase, + long dia, + String equipo) { + + this.partidoRepository.findAll(); + List partidos = this.partidoRepository.findAll(); + return ok(this.partidoMapper.asApi(partidos)); + } + + + @Override + public ApiResponse get(long id) { + Partido partido = getPartido(id); + return ok(this.partidoMapper.asApi(partido)); + } + + @Override + public ApiResponse> getFechas() { + return ok(this.partidoRepository.findAllFechas()); + } + + @Override + @Secure(Rol.ADMIN) + public ApiResponse delete(long id) { + return null; + } + + @Override + @Secure(Rol.ADMIN) + public ApiResponse add(CrearOUpdatePartidoDTO entity) { + Partido partido = crearPartido(0, entity); + this.partidoRepository.save(partido); + return ok(this.partidoMapper.asApi(partido)); + } + + private Partido crearPartido(long id, CrearOUpdatePartidoDTO entity) { + Partido partido = new Partido(); + if (id > 0) { + partido = this.getPartido(id); + } + Equipo local = this.getEquipo(entity.getLocal()); + Equipo visitante = this.getEquipo(entity.getVisitante()); + partido.setLocal(local); + partido.setVisitante(visitante); + partido.setFecha(entity.getFecha()); + partido.setGrupo(this.getGrupo(entity.getGrupo())); + partido.setFase(this.getFase(entity.getFase())); + partido.setLugar(entity.getLugar()); + partido.setDia(entity.getDia()); + return partido; + } + + private Equipo getEquipo(String codigo) { + return this.equiposRepository.findByCodigo(codigo).orElseThrow(() -> + new IllegalArgumentException(MessageFormat.format("Equipo con codigo [{0}] no encontrado", codigo))); + } + + private Grupo getGrupo(String codigo) { + return this.grupoRepository.findByCodigo(codigo).orElseThrow(() -> + new IllegalArgumentException(MessageFormat.format("Grupo con codigo [{0}] no encontrado", codigo))); + } + + private Fase getFase(String codigo) { + return this.faseRepository.findByCodigo(codigo).orElseThrow(() -> + new IllegalArgumentException(MessageFormat.format("Fase con codigo [{0}] no encontrado", codigo))); + } + + @Override + @Secure(Rol.ADMIN) + public ApiResponse update(long id, CrearOUpdatePartidoDTO entity) { + Partido partido = crearPartido(id, entity); + this.partidoRepository.save(partido); + return ok(this.partidoMapper.asApi(partido)); + } + + @Override + @Secure(Rol.ADMIN) + public ApiResponse setResultado(long partidoId, ResultadoDTO resultado) { + Partido partido = this.getPartido(partidoId); + partido.setResultado(this.partidoMapper.asResultado(resultado)); + this.partidoRepository.save(partido); + return ok(this.partidoMapper.asApi(partido)); + + } + + private Partido getPartido(long partidoId) { + return this.partidoRepository + .findById(partidoId) + .orElseThrow(() -> + new IllegalArgumentException(MessageFormat + .format("El partido <{0}> no fue encontrado", partidoId))); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PostServiceImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PostServiceImpl.java new file mode 100644 index 0000000..3b56be4 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PostServiceImpl.java @@ -0,0 +1,101 @@ +package io.semantic.openscore.core.services.impl; + +import static io.semantic.openscore.core.services.RestUtil.ok; + +import java.text.MessageFormat; +import java.util.List; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.post.CrearPost; +import io.semantic.openscore.core.model.Post; +import io.semantic.openscore.core.model.PostStatus; +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.repository.Page; +import io.semantic.openscore.core.repository.PostRepository; +import io.semantic.openscore.core.security.Secure; +import io.semantic.openscore.core.services.api.PostService; + +@ApplicationScoped +public class PostServiceImpl implements PostService { + + private PostRepository postRepository; + + public PostServiceImpl() { + } + + @Inject + public PostServiceImpl(PostRepository postRepository) { + this.postRepository = postRepository; + } + + public ApiResponse> getAll(int page, int pageSize, String postStatus) { + + if (postStatus != null && !postStatus.isEmpty()) { + PostStatus status = PostStatus.valueOf(postStatus); + return ok(this.postRepository.findAllByStatus(status)); + } else { + return ok(this.postRepository.findAll(new Page(page, pageSize))); + } + } + + @Override + @Secure(Rol.ADMIN) + public ApiResponse publicar(long id) { + return ok(cambiarStatus(id, PostStatus.PUBLICADO)); + } + + @Override + @Secure(Rol.ADMIN) + public ApiResponse retirar(long id) { + return ok(cambiarStatus(id, PostStatus.BORRADOR)); + } + + private Post cambiarStatus(long id, PostStatus status) { + Post post = this.getPost(id); + post.setStatus(status); + this.postRepository.save(post); + return post; + } + + @Override + public ApiResponse get(long id) { + return ok(getPost(id)); + } + + private Post getPost(long id) { + return this.postRepository + .findById(id) + .orElseThrow(() -> new IllegalArgumentException(MessageFormat.format("El post con el ID <{0}> no existe", id))); + } + + @Override + public ApiResponse delete(long id) { + this.postRepository.deleteById(id); + return ok(id); + } + + @Override + public ApiResponse add(CrearPost entity) { + Post post = new Post(); + savePost(entity, post); + return ok(post); + } + + private void savePost(CrearPost entity, Post post) { + post.setTitulo(entity.getTitulo()); + post.setContenido(entity.getContenido()); + post.setAutor(entity.getAutor()); + post.setStatus(PostStatus.BORRADOR); + this.postRepository.save(post); + } + + @Override + public ApiResponse update(long id, CrearPost entity) { + Post post = this.getPost(id); + savePost(entity, post); + return ok(post); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PronosticosServiceImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PronosticosServiceImpl.java new file mode 100644 index 0000000..94ccfb3 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/PronosticosServiceImpl.java @@ -0,0 +1,228 @@ +package io.semantic.openscore.core.services.impl; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.pronosticos.CrearPronosticoDTO; +import io.semantic.openscore.core.api.pronosticos.PartidoPronosticoDTO; +import io.semantic.openscore.core.api.pronosticos.PronosticoDTO; +import io.semantic.openscore.core.exceptions.PartidoBloqueadoException; +import io.semantic.openscore.core.mapping.PartidoMapper; +import io.semantic.openscore.core.mapping.PronosticoMapper; +import io.semantic.openscore.core.model.Partido; +import io.semantic.openscore.core.model.Pronostico; +import io.semantic.openscore.core.model.Usuario; +import io.semantic.openscore.core.repository.PartidoRepository; +import io.semantic.openscore.core.repository.PronosticoRepository; +import io.semantic.openscore.core.repository.UsuarioRepository; +import io.semantic.openscore.core.services.UserInfo; +import io.semantic.openscore.core.services.api.PronosticosService; +import io.semantic.openscore.core.validation.ApplicationValidator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.transaction.Transactional; +import java.text.MessageFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.time.LocalDate; +import java.util.Date; +import java.util.List; + +import static io.semantic.openscore.core.services.RestUtil.ok; + +@ApplicationScoped +public class PronosticosServiceImpl implements PronosticosService { + + private Logger logger = LoggerFactory.getLogger(PronosticosServiceImpl.class); + + private UserInfo userInfo; + private PronosticoRepository pronosticoRepository; + private PartidoRepository partidoRepository; + private UsuarioRepository usuarioRepository; + private ApplicationValidator validator; + private PartidoMapper partidoMapper; + private PronosticoMapper pronosticoMapper; + + public PronosticosServiceImpl() { + } + + @Inject + public PronosticosServiceImpl(UserInfo userInfo, + PronosticoRepository pronosticoRepository, + PartidoRepository partidoRepository, + UsuarioRepository usuarioRepository, + ApplicationValidator validator, + PartidoMapper partidoMapper, + PronosticoMapper pronosticoMapper) { + this.userInfo = userInfo; + this.pronosticoRepository = pronosticoRepository; + this.partidoRepository = partidoRepository; + this.usuarioRepository = usuarioRepository; + this.validator = validator; + this.partidoMapper = partidoMapper; + this.pronosticoMapper = pronosticoMapper; + } + + @Override + public ApiResponse> getAll(int page, + int pageSize, + String grupo, + String fase, + long dia, + int fecha) { + + List partidos = getPartidos(grupo, dia, fase, fecha); + List pronosticos = this.pronosticoRepository.findByUsuario(userInfo.getUserId()); + + logger.info("Pronosticos encontrados para el usuario {}: {}", this.userInfo.getUsuario().get().getEmail(), pronosticos.size()); + + + List partidoDTOs = this.pronosticoMapper.asApiPronostico(partidos); + + partidoDTOs.forEach(partidoPronosticoDTO -> { + pronosticos.forEach(pronostico -> { + if (partidoPronosticoDTO.getId() == pronostico.getPartido().getId()) { + partidoPronosticoDTO.setPronostico(this.pronosticoMapper.asApi(pronostico)); + } + }); + }); + + + return ok(partidoDTOs); + } + + private List getPartidos(String grupo, long dia, String fase, int fecha) { + if (grupo != null && !grupo.isEmpty()) { + return this.partidoRepository.findAllByGrupo(grupo); + } else if (fase != null && !fase.isEmpty()) { + return this.partidoRepository.findAllByFase(fase); + } else if (fecha > 0) { + return this.partidoRepository.findAllByFecha(fecha); + } else if ( dia > 0) { + return this.partidoRepository.findAllByDia(dia); + } else { + return this.partidoRepository.findAll(); + } + } + + @Override + public ApiResponse get(long id) { + long idUsuario = this.userInfo.getUserId(); + Pronostico pronostico = getPronostico(id, + idUsuario); + return ok(this.pronosticoMapper.asApi(pronostico)); + } + + @Override + public ApiResponse delete(long id) { + this.pronosticoRepository.deleteById(id); + return ok(id); + } + + @Override + public ApiResponse add(CrearPronosticoDTO entity) { + throw new UnsupportedOperationException("La operacion ADD para PronosticoService no esta soportada"); + } + + @Override + public ApiResponse update(long id, + CrearPronosticoDTO entity) { + long idUsuario = this.userInfo.getUserId(); + validator.validate(entity); + + Pronostico pronostico = this.getPronostico(id, + idUsuario); + this.pronosticoMapper.updatePronostico(entity, + pronostico); + this.pronosticoRepository.save(pronostico); + return ok(this.pronosticoMapper.asApi(pronostico)); + } + + private Usuario getUsuario(long idUsuario) { + return this.usuarioRepository.findById(idUsuario).orElseThrow(() -> new IllegalArgumentException(MessageFormat + .format("El Usuario con ID {0} no fue encontrado", + idUsuario))); + } + + private Pronostico getPronostico(long id, + long idUsuario) { + return this.pronosticoRepository + .findById(id, + idUsuario) + .orElseThrow(() -> new IllegalArgumentException(MessageFormat + .format("El Pronostico con ID {0} no se encuentra para el usuario {1}", + id, + idUsuario))); + } + + private Partido getPartido(long id) { + return this.partidoRepository.findById(id) + .orElseThrow(() -> new IllegalArgumentException(MessageFormat + .format("El Partido con ID {0} no fue encontrado", + id))); + } + + @Override + @Transactional + public ApiResponse local(long idPartido) { + verificarSiElPartidoEstaBloqueado(idPartido); + long idUsuario = this.userInfo.getUserId(); + Pronostico pronostico = this.getPronosticoOrCreatePronostico(idPartido, + idUsuario); + pronostico.local(); + pronostico.setUsuario(this.userInfo.getUsuario().get()); + this.pronosticoRepository.save(pronostico); + return ok(this.pronosticoMapper.asApi(pronostico)); + + } + + private void verificarSiElPartidoEstaBloqueado(long idPartido) { + Partido partido = this.getPartido(idPartido); + if (partido.isBloqueado()) { + throw new PartidoBloqueadoException(partido.getLocal().getCodigo(), partido.getVisitante().getCodigo()); + } + } + + @Override + @Transactional + public ApiResponse empate(long idPartido) { + verificarSiElPartidoEstaBloqueado(idPartido); + long idUsuario = this.userInfo.getUserId(); + Pronostico pronostico = this.getPronosticoOrCreatePronostico(idPartido, + idUsuario); + pronostico.empate(); + pronostico.setUsuario(this.userInfo.getUsuario().get()); + this.pronosticoRepository.save(pronostico); + return ok(this.pronosticoMapper.asApi(pronostico)); + } + + @Override + @Transactional + public ApiResponse visitante(long idPartido) { + verificarSiElPartidoEstaBloqueado(idPartido); + long idUsuario = this.userInfo.getUserId(); + Pronostico pronostico = this.getPronosticoOrCreatePronostico(idPartido, + idUsuario); + pronostico.visitante(); + pronostico.setUsuario(this.userInfo.getUsuario().get()); + this.pronosticoRepository.save(pronostico); + return ok(this.pronosticoMapper.asApi(pronostico)); + } + + private Pronostico getPronosticoOrCreatePronostico(long idPartido, + long idUsuario) { + return this.pronosticoRepository.findByPartidoAndUsuario(idPartido, + idUsuario).orElseGet(() -> { + Pronostico pronostico = new Pronostico(); + Partido partido = getPartido(idPartido); + pronostico.setPartido(partido); + Usuario usuario = getUsuario(idUsuario); + usuario.addPronostico(pronostico); + + this.pronosticoRepository.save(pronostico); + this.usuarioRepository.save(usuario); + return pronostico; + }); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/RankingServiceImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/RankingServiceImpl.java new file mode 100644 index 0000000..a07c832 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/RankingServiceImpl.java @@ -0,0 +1,97 @@ +package io.semantic.openscore.core.services.impl; + +import static io.semantic.openscore.core.services.RestUtil.ok; +import static java.util.stream.Collectors.toList; + +import java.text.MessageFormat; +import java.util.Comparator; +import java.util.List; +import java.util.stream.IntStream; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.transaction.Transactional; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.ranking.Ranking; +import io.semantic.openscore.core.model.Usuario; +import io.semantic.openscore.core.repository.PaisRepository; +import io.semantic.openscore.core.repository.UsuarioRepository; +import io.semantic.openscore.core.services.api.RankingService; + +@ApplicationScoped +public class RankingServiceImpl implements RankingService { + + private UsuarioRepository usuarioRepository; + private PaisRepository paisRepository; + + public RankingServiceImpl() { + } + + @Inject + public RankingServiceImpl(UsuarioRepository usuarioRepository, + PaisRepository paisRepository) { + this.usuarioRepository = usuarioRepository; + this.paisRepository = paisRepository; + } + + @Override + public ApiResponse getRanking(long id) { + List usuarios = this.usuarioRepository.findAll(); + List rankings = this.calcularRankings(usuarios); + Ranking ranking = rankings + .stream() + .filter(r -> r.getUsuario() == id) + .findAny() + .orElseThrow(() -> new IllegalArgumentException(MessageFormat + .format("El Usuario id {0} no se encuentra en el sistema", id))); + return ok(ranking); + } + + @Override + public ApiResponse> getAllRanking(String pais, int size) { + + + List usuarios; + + if (pais == null || pais.isEmpty()) { + usuarios = this.usuarioRepository.findAll(); + } else { + usuarios = this.usuarioRepository.findByCountry(pais); + } + + List rankings = calcularRankings(usuarios); + if (size > 0) { + int s = rankings.size(); + if (s > size) { + s = size; + } + return ok(rankings.subList(0, s)); + } else { + return ok(rankings); + } + } + + @Transactional + List calcularRankings(List usuarios) { + List rankings = usuarios.stream() + .map(usuario -> { + Ranking ranking = new Ranking(); + ranking.setNombre(usuario.getNombre() + " " + usuario.getApellido()); + ranking.setPais(usuario.getPais().getNombre()); + ranking.setUsuario(usuario.getId()); + ranking.setPuntos(usuario.getPuntos()); + return ranking; + }) + .sorted(Comparator.comparingInt(Ranking::getPuntos).reversed()) + .collect(toList()); + + return IntStream + .range(0, rankings.size()) + .mapToObj(i -> { + Ranking r = rankings.get(i); + r.setRanking(i + 1); + return r; + }).collect(toList()); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/UsuariosServiceImpl.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/UsuariosServiceImpl.java new file mode 100644 index 0000000..5933ff5 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/services/impl/UsuariosServiceImpl.java @@ -0,0 +1,248 @@ +package io.semantic.openscore.core.services.impl; + +import static io.semantic.openscore.core.services.RestUtil.ok; +import static java.util.stream.Collectors.toList; + +import java.text.MessageFormat; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.stream.StreamSupport; + +import javax.enterprise.context.ApplicationScoped; +import javax.enterprise.inject.Instance; +import javax.inject.Inject; +import javax.ws.rs.Path; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.semantic.openscore.core.api.ApiResponse; +import io.semantic.openscore.core.api.TokenDTO; +import io.semantic.openscore.core.api.usuarios.CrearUsuarioDTO; +import io.semantic.openscore.core.api.usuarios.LoginUsuarioDTO; +import io.semantic.openscore.core.api.usuarios.RecoverPassword; +import io.semantic.openscore.core.api.usuarios.UpdatePassword; +import io.semantic.openscore.core.api.usuarios.UpdateUsuarioDTO; +import io.semantic.openscore.core.api.usuarios.UsuarioDTO; +import io.semantic.openscore.core.cache.TokenCache; +import io.semantic.openscore.core.email.MailFactory; +import io.semantic.openscore.core.email.MailServer; +import io.semantic.openscore.core.logging.ServiceLogger; +import io.semantic.openscore.core.mapping.PaisMapper; +import io.semantic.openscore.core.mapping.UsuarioMapper; +import io.semantic.openscore.core.model.Pais; +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.model.Usuario; +import io.semantic.openscore.core.repository.Page; +import io.semantic.openscore.core.repository.PaisRepository; +import io.semantic.openscore.core.repository.UsuarioRepository; +import io.semantic.openscore.core.security.Secure; +import io.semantic.openscore.core.security.TokenGenerator; +import io.semantic.openscore.core.services.UserInfo; +import io.semantic.openscore.core.services.api.UsuariosService; +import io.semantic.openscore.core.validation.ApplicationValidator; +import io.semantic.openscore.core.validation.validators.EmailValidator; + +@Path("/usuarios") +@ApplicationScoped +public class UsuariosServiceImpl implements UsuariosService { + + private UserInfo userInfo; + private TokenCache tokenCache; + private MailServer mailSender; + private MailFactory mailFactory; + private List mailValidators; + private ServiceLogger serviceLogger; + private Logger logger = LoggerFactory.getLogger(UsuariosServiceImpl.class); + + private UsuarioRepository usuarioRepository; + private PaisRepository paisRepository; + private TokenGenerator tokenGenerator; + private ApplicationValidator validator; + private UsuarioMapper mapper; + private PaisMapper paisMapper; + + public UsuariosServiceImpl() { + } + + + @Inject + public UsuariosServiceImpl(UsuarioRepository usuarioRepository, + PaisRepository paisRepository, + TokenGenerator tokenGenerator, + ApplicationValidator appValidator, + UsuarioMapper mapper, + PaisMapper paisMapper, + UserInfo userInfo, + TokenCache tokenCache, + MailServer mailSender, + MailFactory mailFactory, + Instance mailValidators, + ServiceLogger serviceLogger) { + this.usuarioRepository = usuarioRepository; + this.paisRepository = paisRepository; + this.tokenGenerator = tokenGenerator; + this.validator = appValidator; + this.mapper = mapper; + this.paisMapper = paisMapper; + this.userInfo = userInfo; + this.tokenCache = tokenCache; + this.mailSender = mailSender; + this.mailFactory = mailFactory; + this.mailValidators = StreamSupport.stream(mailValidators.spliterator(), false).collect(toList()); + + this.serviceLogger = serviceLogger; + } + + + @Override + public ApiResponse registrarUsuario(CrearUsuarioDTO crearUsuario) { + return new ApiResponse<>(this.saveUser(crearUsuario)); + } + + @Override + public ApiResponse updateUsuario(long id, UpdateUsuarioDTO crearUsuario) { + if (this.userInfo.getUserId() == id) { + return new ApiResponse<>(new TokenDTO(this.tokenGenerator.generarToken(this.updateUser(id, crearUsuario)))); + } else { + throw new IllegalArgumentException("You are trying to modify an user that is not you"); + } + } + + private Usuario updateUser(long id, UpdateUsuarioDTO updateUsuario) { + this.validator.validate(updateUsuario); + Usuario usuario = this.findUsuario(id); + Pais pais = this.paisRepository.findByCodigo(updateUsuario.getPais()); + this.mapper.updateUsuario(updateUsuario, usuario); + usuario.setPais(pais); + this.usuarioRepository.save(usuario); + return usuario; + } + + + @Override + public ApiResponse recoverPassword(RecoverPassword updatePassword) { + this.validator.validate(updatePassword); + + this.tokenCache.getToken(updatePassword.getEmail()) + .map(x -> x.equals(updatePassword.getToken())) + .orElseThrow(() -> new IllegalArgumentException("No token was found to update password. Please try again")); + + Usuario user = this.usuarioRepository.findByEmail(updatePassword.getEmail()) + .orElseThrow(() -> new IllegalArgumentException(MessageFormat.format("User not found with email {0}. Please try again", + updatePassword.getEmail()))); + + user.setPassword(this.tokenGenerator.generarPassword(updatePassword.getPassword())); + this.usuarioRepository.save(user); + this.tokenCache.remove(user.getEmail()); + return ok(this.mapper.asApi(user)); + } + + @Override + public ApiResponse sendToken(String email) { + if (!this.usuarioRepository.exist(email)) { + throw new IllegalArgumentException(MessageFormat.format("User with email {0} does not exist in OpenScore", email)); + } + String token = this.tokenGenerator.generateRandomToken(); + this.tokenCache.add(email, token); + Map params = new HashMap<>(); + params.put("email", email); + params.put("token", token); + this.mailSender.send(this.mailFactory.getRecoverPasswordEmail(email, token)); + return ok(""); + } + + @Override + public ApiResponse updatePassword(UpdatePassword updatePassword) { + this.validator.validate(updatePassword); + long userId = this.userInfo.getUserId(); + + Usuario usuario = this.usuarioRepository.findById(userId).orElseThrow(() -> + new IllegalArgumentException("User is not logged in")); + + if (usuario.getPassword().equals(this.tokenGenerator.generarPassword(updatePassword.getOldPassword()))) { + usuario.setPassword(this.tokenGenerator.generarPassword(updatePassword.getPassword())); + this.usuarioRepository.save(usuario); + } else { + throw new IllegalArgumentException("Old password does not match"); + } + + return ok(this.mapper.asApi(usuario)); + } + + + private UsuarioDTO saveUser(CrearUsuarioDTO crearUsuario) { + this.validator.validate(crearUsuario); + Pais pais = this.paisRepository.findByCodigo(crearUsuario.getPais()); + Usuario usuario = this.mapper.asUsuario(crearUsuario); + usuario.setPassword(this.tokenGenerator.generarPassword(crearUsuario.getPassword())); + usuario.setRoles(new HashSet<>(Arrays.asList(Rol.USUARIO))); + usuario.setPais(pais); + this.usuarioRepository.save(usuario); + + UsuarioDTO usuarioDTO = this.mapper.asApi(usuario); + usuarioDTO.setPais(this.paisMapper.asApi(pais)); + + return usuarioDTO; + } + + @Override + @Secure + public ApiResponse deleteUsuario(long id) { + return null; + } + + @Override + public ApiResponse getUsuario(Long id) { + Usuario usuario = findUsuario(id); + UsuarioDTO usuarioDTO = this.mapper.asApi(usuario); + return new ApiResponse(usuarioDTO); + } + + private Usuario findUsuario(Long id) { + Optional usuarioOptional = this.usuarioRepository.findById(id); + return usuarioOptional.orElseThrow(() -> new IllegalArgumentException("User not found")); + } + + @Override + public ApiResponse getMiUsuario() { + return this.getUsuario(this.userInfo.getUserId()); + } + + public Usuario getUsuario(String email) { + Optional usuarioOptional = this.usuarioRepository.findByEmail(email); + return usuarioOptional.orElseThrow(() -> new IllegalArgumentException("User not found")); + } + + @Override + public ApiResponse login(LoginUsuarioDTO loginUsuario) { + Optional usuarioOptional = this.usuarioRepository.findByEmail(loginUsuario.getEmail().trim()); + Usuario usuario = usuarioOptional.orElseThrow(() -> new IllegalArgumentException("User or password not found")); + + TokenGenerator tokenGenerator = new TokenGenerator(); + + checkPassword(loginUsuario.getPassword(), usuario, tokenGenerator); + + UsuarioDTO usuarioDTO = this.mapper.asApi(usuario); + + TokenDTO tokenDTO = new TokenDTO(tokenGenerator.generarToken(usuario)); + + return new ApiResponse<>(tokenDTO); + } + + private void checkPassword(String password, Usuario usuario, TokenGenerator tokenGenerator) { + if (!usuario.getPassword().equals(tokenGenerator.generarPassword(password))) + throw new IllegalArgumentException("Invalid password"); + } + + @Override + public ApiResponse> getAll(int page, int pageSize, String filter) { + List usuarios = this.usuarioRepository.findAll(new Page(page, pageSize)); + List usuariosApi = this.mapper.asApi(usuarios); + return new ApiResponse<>(usuariosApi); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/template/TemplateEngine.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/template/TemplateEngine.java new file mode 100644 index 0000000..f44bb0b --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/template/TemplateEngine.java @@ -0,0 +1,35 @@ +package io.semantic.openscore.core.template; + +import com.mitchellbosecke.pebble.PebbleEngine; +import com.mitchellbosecke.pebble.template.PebbleTemplate; + +import javax.annotation.PostConstruct; +import javax.enterprise.context.ApplicationScoped; +import java.io.StringWriter; +import java.util.Map; + +@ApplicationScoped +public class TemplateEngine { + + private PebbleEngine engine; + + @PostConstruct + public void initialize() { + engine = new PebbleEngine.Builder().build(); + } + + public String evaluate(String templateName, Map params) { + try { + StringWriter stringWriter = new StringWriter(); + PebbleTemplate compiledTemplate = this.engine.getTemplate(buildTemplateName(templateName)); + compiledTemplate.evaluate(stringWriter, params); + return stringWriter.toString(); + } catch (Exception e) { + throw new TemplateEngineException("Can't process template", e); + } + } + + private String buildTemplateName(String templateName) { + return "templates/" + templateName + ".html"; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/template/TemplateEngineException.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/template/TemplateEngineException.java new file mode 100644 index 0000000..e41b77a --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/template/TemplateEngineException.java @@ -0,0 +1,9 @@ +package io.semantic.openscore.core.template; + +import io.semantic.openscore.core.exceptions.ApplicationException; + +public class TemplateEngineException extends ApplicationException { + public TemplateEngineException(String message, Throwable throwable) { + super(message, throwable); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/util/JsonConverter.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/util/JsonConverter.java new file mode 100644 index 0000000..d845462 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/util/JsonConverter.java @@ -0,0 +1,10 @@ +package io.semantic.openscore.core.util; + +public class JsonConverter { + +// private static final + + public static String toJson() { + return ""; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/ApplicationValidator.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/ApplicationValidator.java new file mode 100644 index 0000000..976df27 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/ApplicationValidator.java @@ -0,0 +1,41 @@ +package io.semantic.openscore.core.validation; + +import io.semantic.openscore.core.exceptions.ValidationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.enterprise.context.ApplicationScoped; +import javax.inject.Inject; +import javax.validation.ConstraintViolation; +import javax.validation.Validator; +import java.util.Set; + +@ApplicationScoped +public class ApplicationValidator { + + private Logger logger = LoggerFactory.getLogger(ApplicationValidator.class); + + private Validator validator; + + public ApplicationValidator() { + } + + @Inject + public ApplicationValidator(Validator validator) { + this.validator = validator; + } + + public void validate(Object object) { + try { + Set> errors = validator.validate(object); + if (!errors.isEmpty()) { + String message = ValidationException.generateMessage(errors); + logger.error(message); + throw new ValidationException(message, ValidationException.generateErrorsList(errors)); + } + } catch (javax.validation.ValidationException e) { + logger.error(e.getLocalizedMessage(), e); + throw new ValidationException(e.getMessage(), e); + } + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/annotations/Matches.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/annotations/Matches.java new file mode 100644 index 0000000..7d2b681 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/annotations/Matches.java @@ -0,0 +1,36 @@ +package io.semantic.openscore.core.validation.annotations; + +import io.semantic.openscore.core.validation.validators.MatchesValidator; + +import javax.validation.Constraint; +import javax.validation.Payload; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Target({TYPE}) +@Retention(RUNTIME) +@Constraint(validatedBy = MatchesValidator.class) +@Documented +public @interface Matches { + + String message() default "{io.semantic.openscore.core.validation.Matches.message}"; + + Class[] groups() default {}; + + Class[] payload() default {}; + + String first(); + + String second(); + + @Target({TYPE}) + @Retention(RUNTIME) + @Documented + @interface List { + Matches[] value(); + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/annotations/Password.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/annotations/Password.java new file mode 100644 index 0000000..3c7010e --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/annotations/Password.java @@ -0,0 +1,26 @@ +package io.semantic.openscore.core.validation.annotations; + +import io.semantic.openscore.core.validation.validators.PasswordValidator; + +import javax.validation.Constraint; +import javax.validation.Payload; +import java.lang.annotation.Documented; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +import static java.lang.annotation.ElementType.FIELD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +@Target({FIELD}) +@Retention(RUNTIME) +@Constraint(validatedBy = PasswordValidator.class) +@Documented +public @interface Password { + + String message() default "{io.semantic.openscore.core.validation.Password.message}"; + + Class[] groups() default {}; + + Class[] payload() default {}; + +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/EmailValidator.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/EmailValidator.java new file mode 100644 index 0000000..1d27d0c --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/EmailValidator.java @@ -0,0 +1,6 @@ +package io.semantic.openscore.core.validation.validators; + +public interface EmailValidator { + + boolean validate(String mail); +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/MatchesValidator.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/MatchesValidator.java new file mode 100644 index 0000000..89f8d9d --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/MatchesValidator.java @@ -0,0 +1,47 @@ +package io.semantic.openscore.core.validation.validators; + +import io.semantic.openscore.core.validation.annotations.Matches; +import org.apache.commons.beanutils.BeanUtils; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import java.util.Objects; + +public class MatchesValidator implements ConstraintValidator { + private String first; + private String second; + + @Override + public void initialize(Matches matches) { + first = matches.first(); + second = matches.second(); + } + + @Override + public boolean isValid(Object object, ConstraintValidatorContext constraintValidatorContext) { + + boolean isValid = false; + + try { + String propert1 = BeanUtils.getProperty(object, first); + String propert2 = BeanUtils.getProperty(object, second); + + isValid = Objects.equals(propert1, propert2); + } catch (Exception e) { + isValid = false; + } finally { + + if (!isValid) { + constraintValidatorContext.disableDefaultConstraintViolation(); + constraintValidatorContext.buildConstraintViolationWithTemplate( + "{io.semantic.openscore.core.validation.Matches.message}" + ).addConstraintViolation(); + } + + + return isValid; + } + + + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/PasswordValidator.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/PasswordValidator.java new file mode 100644 index 0000000..38cb470 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/PasswordValidator.java @@ -0,0 +1,37 @@ +package io.semantic.openscore.core.validation.validators; + +import io.semantic.openscore.core.validation.annotations.Password; + +import javax.validation.ConstraintValidator; +import javax.validation.ConstraintValidatorContext; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class PasswordValidator implements ConstraintValidator { + + + private static final String PASSWORD_PATTERN = "[\\w\\S]{6,30}"; + private Pattern pattern; + + @Override + public void initialize(Password password) { + pattern = Pattern.compile(PASSWORD_PATTERN); + } + + @Override + public boolean isValid(String passw, ConstraintValidatorContext constraintValidatorContext) { + + + Matcher matcher = pattern.matcher(passw); + boolean isValid = matcher.matches(); + + if (!isValid) { + constraintValidatorContext.disableDefaultConstraintViolation(); + constraintValidatorContext.buildConstraintViolationWithTemplate( + "{io.semantic.openscore.core.validation.Password.message}" + ).addConstraintViolation(); + } + + return isValid; + } +} diff --git a/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/RedHatEmailValidator.java b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/RedHatEmailValidator.java new file mode 100644 index 0000000..a797a7d --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/java/io/semantic/openscore/core/validation/validators/RedHatEmailValidator.java @@ -0,0 +1,9 @@ +package io.semantic.openscore.core.validation.validators; + +public class RedHatEmailValidator implements EmailValidator { + + @Override + public boolean validate(String mail) { + return mail.endsWith("@redhat.com"); + } +} diff --git a/packages/openscore-core-quarkus/src/main/resources/ValidationMessages.properties b/packages/openscore-core-quarkus/src/main/resources/ValidationMessages.properties new file mode 100644 index 0000000..2679f5e --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/resources/ValidationMessages.properties @@ -0,0 +1,2 @@ +io.semantic.openscore.core.validation.Matches.message=Field {first} and {second} doesn't match +io.semantic.openscore.core.validation.Password.message=Password is not valid. It should have at least 6 characters and no space. \ No newline at end of file diff --git a/packages/openscore-core-quarkus/src/main/resources/application.properties b/packages/openscore-core-quarkus/src/main/resources/application.properties new file mode 100644 index 0000000..0bf3c62 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/resources/application.properties @@ -0,0 +1,7 @@ +quarkus.datasource.db-kind=postgresql +quarkus.datasource.username=postgres +quarkus.datasource.password=0p3nsc0r3 +quarkus.datasource.jdbc.url=jdbc:postgresql://localhost:5432/postgres +quarkus.datasource.jdbc.max-size=16 +quarkus.hibernate-orm.log.sql=true +quarkus.hibernate-orm.database.generation=drop-and-create diff --git a/packages/openscore-core-quarkus/src/main/resources/data/partidos.yml b/packages/openscore-core-quarkus/src/main/resources/data/partidos.yml new file mode 100644 index 0000000..19ef219 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/resources/data/partidos.yml @@ -0,0 +1,141 @@ +--- +- local: BRA + visitante: VEN + grupo: GRUPO_A + lugar: BRASILIA, ESTADIO NACIONAL DE BRASILIA + dia: 13-06-2021T18:00-0300 + fecha: "1" + fase: GRUPO +- local: COL + visitante: ECU + grupo: GRUPO_A + lugar: CUIABÁ, ARENA PANTANAL + dia: 13-06-2021T21:00-0300 + fecha: "1" + fase: GRUPO +- local: ARG + visitante: CHL + grupo: GRUPO_B + lugar: RIO DE JANEIRO, ESTADIO OLIMPICO + dia: 14-06-2021T18:00-0300 + fecha: "1" + fase: GRUPO +- local: PRY + visitante: BOL + grupo: GRUPO_B + lugar: GOIÂNIA, ESTADIO OLIMPICO PEDRO LUDOVICO + dia: 14-06-2021T21:00-0300 + fecha: "1" + fase: GRUPO +- local: COL + visitante: VEN + grupo: GRUPO_A + lugar: GOIÂNIA, ESTADIO OLIMPICO PEDRO LUDOVICO + dia: 17-06-2021T18:00-0300 + fecha: "2" + fase: GRUPO +- local: BRA + visitante: PER + grupo: GRUPO_A + lugar: RIO DE JANEIRO, ESTADIO OLIMPICO + dia: 17-06-2021T21:00-0300 + fecha: "2" + fase: GRUPO +- local: CHL + visitante: BOL + grupo: GRUPO_B + lugar: CUIABÁ, ARENA PANTANAL + dia: 18-06-2021T18:00-0300 + fecha: "2" + fase: GRUPO +- local: ARG + visitante: URY + grupo: GRUPO_B + lugar: BRASILIA, ESTADIO NACIONAL DE BRASILIA + dia: 18-06-2021T21:00-0300 + fecha: "2" + fase: GRUPO +- local: VEN + visitante: ECU + grupo: GRUPO_A + lugar: RIO DE JANEIRO, ESTADIO OLIMPICO + dia: 20-06-2021T18:00-0300 + fecha: "3" + fase: GRUPO +- local: COL + visitante: PER + grupo: GRUPO_A + lugar: GOIÂNIA, ESTADIO OLIMPICO PEDRO LUDOVICO + dia: 20-06-2021T21:00-0300 + fecha: "3" + fase: GRUPO +- local: URY + visitante: CHL + grupo: GRUPO_B + lugar: CUIABÁ, ARENA PANTANAL + dia: 21-06-2021T18:00-0300 + fecha: "3" + fase: GRUPO +- local: ARG + visitante: PRY + grupo: GRUPO_B + lugar: BRASILIA, ESTADIO NACIONAL DE BRASILIA + dia: 21-06-2021T21:00-0300 + fecha: "3" + fase: GRUPO +- local: ECU + visitante: PER + grupo: GRUPO_A + lugar: GOIÂNIA, ESTADIO OLIMPICO PEDRO LUDOVICO + dia: 23-06-2021T18:00-0300 + fecha: "4" + fase: GRUPO +- local: BRA + visitante: COL + grupo: GRUPO_A + lugar: RIO DE JANEIRO, ESTADIO OLIMPICO + dia: 23-06-2021T21:00-0300 + fecha: "4" + fase: GRUPO +- local: BOL + visitante: URY + grupo: GRUPO_B + lugar: CUIABÁ, ARENA PANTANAL + dia: 24-06-2021T18:00-0300 + fecha: "4" + fase: GRUPO +- local: CHL + visitante: PRY + grupo: GRUPO_B + lugar: BRASILIA, ESTADIO NACIONAL DE BRASILIA + dia: 24-06-2021T21:00-0300 + fecha: "4" + fase: GRUPO +- local: BRA + visitante: ECU + grupo: GRUPO_A + lugar: GOIÂNIA, ESTADIO OLIMPICO PEDRO LUDOVICO + dia: 27-06-2021T18:00-0300 + fecha: "5" + fase: GRUPO +- local: VEN + visitante: PER + grupo: GRUPO_A + lugar: BRASILIA, ESTADIO NACIONAL DE BRASILIA + dia: 27-06-2021T18:00-0300 + fecha: "5" + fase: GRUPO +- local: URY + visitante: PRY + grupo: GRUPO_B + lugar: RIO DE JANEIRO, ESTADIO OLIMPICO + dia: 28-06-2021T21:00-0300 + fecha: "5" + fase: GRUPO +- local: BOL + visitante: ARG + grupo: GRUPO_B + lugar: CUIABÁ, ARENA PANTANAL + dia: 28-06-2021T21:00-0300 + fecha: "5" + fase: GRUPO diff --git a/packages/openscore-core-quarkus/src/main/resources/data/preguntas.yml b/packages/openscore-core-quarkus/src/main/resources/data/preguntas.yml new file mode 100644 index 0000000..639fa5c --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/resources/data/preguntas.yml @@ -0,0 +1,7 @@ +--- +- codigo: PERRO + pregunta: What's the name of your first dog? +- codigo: MADRE + pregunta: What's your mother second name? +- codigo: EQUIPO + pregunta: What's you favorite sport team? diff --git a/packages/openscore-core-quarkus/src/main/resources/info.properties b/packages/openscore-core-quarkus/src/main/resources/info.properties new file mode 100644 index 0000000..111a51c --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/resources/info.properties @@ -0,0 +1,2 @@ +info.version=${project.version} +info.environment=${project.environment} diff --git a/packages/openscore-core-quarkus/src/main/resources/logback.xml b/packages/openscore-core-quarkus/src/main/resources/logback.xml new file mode 100644 index 0000000..9cf17f4 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/resources/logback.xml @@ -0,0 +1,21 @@ + + + + + + + %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + + + + \ No newline at end of file diff --git a/packages/openscore-core-quarkus/src/main/resources/templates/recover.html b/packages/openscore-core-quarkus/src/main/resources/templates/recover.html new file mode 100644 index 0000000..29d8e82 --- /dev/null +++ b/packages/openscore-core-quarkus/src/main/resources/templates/recover.html @@ -0,0 +1,210 @@ + + + + + + + + +
+ + + + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Empezá a palpitar el Mundial Rusia 2018 +
+ + + + + + + +
+ + + + + + + + + + + + + +
Predecí los resultados de los partidos con Red Hat OpenScore, la plataforma diseñada por red hatters para red hatters, que te permitirá vivir el minuto a minuto de la copa del mundo.
Acertá los resultados de los partidos y avanzá hacia la final para coronarte como el ganador del prode.
¡Podés ganar premios!
+
+
+ + + + + + + +
+ + + + + + + + + +
+ + + + + + + + + + https://openscore-ui-openscore.b9ad.pro-us-east-1.openshiftapps.com/#/pages/password?recover={{token}}&email={{email}} + + + + + +
Para participar tenés que ingresar a:
y crear tu usuario y contraseña.
Una vez en la plataforma podrás:
+
+ +
+ + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
01.
02.
03.
04.
05.
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Consultar el fixture
del mundial
Conocer las reglas
Hacer las predicciones
para el próximo partido
Ver el ranking y en qué posición estás.
Leer las noticias
destacadas
+
+
+ +
El juego ya empezó.
Sé parte.
+ + + + + + + + + + + + + +
Red HatFacebook Linkedin Twitter Youtube
+ +
+
+
+
+ + \ No newline at end of file diff --git a/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/model/UsuarioTest.java b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/model/UsuarioTest.java new file mode 100644 index 0000000..1f41bec --- /dev/null +++ b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/model/UsuarioTest.java @@ -0,0 +1,69 @@ +package io.semantic.openscore.core.model; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Spy; +import org.mockito.junit.MockitoJUnitRunner; + +import java.util.Arrays; +import java.util.HashSet; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +@RunWith(MockitoJUnitRunner.class) +public class UsuarioTest { + + @Spy + private Usuario usuarioSinPronosticos; + + + @Spy + private Usuario usuario; + + @Mock + private Fase faseDeGrupos; + + + @Before + public void setUp() { + + when(faseDeGrupos.getPuntos()).thenReturn(1); + + Pronostico p1 = spy(new Pronostico()); + when(p1.isLocal()).thenReturn(true); + + Resultado resultado = new Resultado(); + + Partido partido = new Partido(); + partido.setFase(faseDeGrupos); + + resultado.setPartido(partido); + partido.setResultado(resultado); + + resultado.setLocal(1); + resultado.setVisitante(0); + + when(p1.getPartido()).thenReturn(partido); + + when(usuario.getPronosticos()).thenReturn(new HashSet<>(Arrays.asList(p1))); + + } + + + @Test + public void testCalcularPuntosSinPronostico() { + int puntos = usuarioSinPronosticos.getPuntos(); + assertEquals(0, puntos); + } + + @Test + public void testCalcularPuntosUnPartidoGanado() { + int puntos = usuario.getPuntos(); + assertEquals(1, puntos); + } + +} \ No newline at end of file diff --git a/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/PaisRepositoryTest.java b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/PaisRepositoryTest.java new file mode 100644 index 0000000..156ab83 --- /dev/null +++ b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/PaisRepositoryTest.java @@ -0,0 +1,33 @@ +package io.semantic.openscore.core.repository; + +import io.semantic.openscore.core.model.Pais; +import org.junit.Test; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + + +class PaisRepositoryTest extends RepositoryBaseTest { + + private PaisRepository paisRepository; + + @Override + protected void beforeEach() { + paisRepository = new PaisRepository(entityManager); + } + + @Test + void testExistPais() { + + + assertFalse(this.paisRepository.exist("ARG")); + + Pais pais = new Pais(); + pais.setNombre("Argentina"); + pais.setCodigo("ARG"); + + transaction(() -> this.paisRepository.save(pais)); + assertTrue(this.paisRepository.exist("ARG")); + + } +} \ No newline at end of file diff --git a/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/RepositoryBaseTest.java b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/RepositoryBaseTest.java new file mode 100644 index 0000000..d4cf203 --- /dev/null +++ b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/RepositoryBaseTest.java @@ -0,0 +1,39 @@ +package io.semantic.openscore.core.repository; + + +import org.junit.Before; + +import javax.persistence.EntityManager; +import javax.persistence.EntityTransaction; +import javax.persistence.Persistence; +import java.util.function.Supplier; + +public abstract class RepositoryBaseTest { + + protected EntityManager entityManager; + + @Before + public void setUp() { + entityManager = Persistence + .createEntityManagerFactory("test") + .createEntityManager(); + beforeEach(); + } + + abstract protected void beforeEach(); + + protected void transaction(Runnable runnable) { + EntityTransaction tx = this.entityManager.getTransaction(); + tx.begin(); + runnable.run(); + tx.commit(); + } + + protected T transaction(Supplier runnable) { + EntityTransaction tx = this.entityManager.getTransaction(); + tx.begin(); + T result = runnable.get(); + tx.commit(); + return result; + } +} diff --git a/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/RepositoryTest.java b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/RepositoryTest.java new file mode 100644 index 0000000..c2cb9b5 --- /dev/null +++ b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/RepositoryTest.java @@ -0,0 +1,120 @@ +package io.semantic.openscore.core.repository; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.persistence.TypedQuery; +import java.util.List; +import java.util.Optional; + +import static org.junit.Assert.*; + + +class RepositoryTest extends RepositoryBaseTest { + + private Repository repository; + private Logger logger = LoggerFactory.getLogger(RepositoryTest.class); + + @Override + protected void beforeEach() { + this.repository = new TestRepository(entityManager); + } + + @Test + void testSaveElement() { + TestObject original = new TestObject(); + original.setName("OpenScore"); + + long id = transaction(() -> this.repository.save(original)); + + Optional testObject = this.repository.findById(id); + assertEquals(original.getName(), + testObject.get().getName()); + assertFalse(testObject.get().isDeleted()); + assertNotNull(testObject.get().getCreationDate()); + } + + + @Test + void testFindByQuery() { + TestObject original = new TestObject("OpenScore"); + transaction(() -> this.repository.save(original)); + TypedQuery query = this.repository.createQuery("from TestObject t where t.name = :name").setParameter("name", + "OpenScore"); + List elements = this.repository.findByQuery(query, + new Page(0, + 1)); + assertEquals(original.getName(), + elements.get(0).getName()); + } + + @Test + void testHardDeleteByQuery() { + TestObject original = new TestObject("OpenScore"); + transaction(() -> this.repository.save(original)); + TypedQuery query = this.repository.createQuery("from TestObject where name = :name").setParameter("name", + "OpenScore"); + assertEquals(1, + this.repository.findByQuery(query, + new Page(0, + 1)).size()); + transaction(() -> this.repository.hardDeleteByQuery(query)); + assertEquals(0, + this.repository.findByQuery(query, + new Page(0, + 1)).size()); + } + + @Test + void testHardDeleteById() { + TestObject original = new TestObject("OpenScore"); + long id = transaction(() -> this.repository.save(original)); + TypedQuery query = this.repository.createQuery("from TestObject where name = :name").setParameter("name", + "OpenScore"); + + assertEquals(1, + this.repository.findByQuery(query, + new Page(0, + 1)).size()); + + transaction(() -> this.repository.hardDeleteById(id)); + + assertEquals(0, + this.repository.findByQuery(query, + new Page(0, + 1)).size()); + } + + @Test + void testDeleteByQuery() { + TestObject original = new TestObject("OpenScore"); + long id = transaction(() -> this.repository.save(original)); + TypedQuery query = this.repository.createQuery("from TestObject where name = :name").setParameter("name", + "OpenScore"); + assertEquals(1, + this.repository.findByQuery(query, + new Page(0, + 1)).size()); + this.repository.deleteByQuery(query); + assertEquals(1, + this.repository.findByQuery(query, + new Page(0, + 1)).size()); + assertTrue(query.getSingleResult().isDeleted()); + } + + @Test + void testDeleteById() { + TestObject original = new TestObject("OpenScore"); + long id = transaction(() -> this.repository.save(original)); + TypedQuery query = this.repository.createQuery("from TestObject where name = :name").setParameter("name", + "OpenScore"); + assertEquals(1, + query.getResultList().size()); + this.repository.deleteById(id); + assertEquals(1, + query.getResultList().size()); + assertTrue(query.getSingleResult().isDeleted()); + } +} \ No newline at end of file diff --git a/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/TestObject.java b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/TestObject.java new file mode 100644 index 0000000..2e7a305 --- /dev/null +++ b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/TestObject.java @@ -0,0 +1,26 @@ +package io.semantic.openscore.core.repository; + +import javax.persistence.Entity; + +import io.semantic.openscore.core.model.Storable; + +@Entity +public class TestObject extends Storable { + + private String name; + + public TestObject() { + } + + public TestObject(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } +} diff --git a/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/TestRepository.java b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/TestRepository.java new file mode 100644 index 0000000..8924647 --- /dev/null +++ b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/TestRepository.java @@ -0,0 +1,19 @@ +package io.semantic.openscore.core.repository; + +import javax.enterprise.context.ApplicationScoped; +import javax.persistence.EntityManager; + +@ApplicationScoped +public class TestRepository extends Repository { + + public TestRepository(EntityManager entityManager) { + super(TestObject.class, + entityManager); + } + + @Override + public boolean exist(TestObject entity) { + return false; + } + +} diff --git a/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/UsuarioRepositoryTest.java b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/UsuarioRepositoryTest.java new file mode 100644 index 0000000..fc5389b --- /dev/null +++ b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/repository/UsuarioRepositoryTest.java @@ -0,0 +1,49 @@ +package io.semantic.openscore.core.repository; + +import io.semantic.openscore.core.model.Pais; +import io.semantic.openscore.core.model.Usuario; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Optional; + +import static org.junit.Assert.assertEquals; + +public class UsuarioRepositoryTest extends RepositoryBaseTest { + + private UsuarioRepository repository; + private Logger logger = LoggerFactory.getLogger(RepositoryTest.class); + + @Test + public void testFindByEmail() { + String email = "john.frusciante@gmail.com"; + + Usuario newUser = new Usuario(); + + newUser.setNombre("John"); + newUser.setApellido("Frusciante"); + newUser.setEmail(email); + newUser.setPassword("anthony_kiedis"); + + Pais pais = new Pais(); + pais.setNombre("Argentina"); + pais.setCodigo("ARG"); + + PaisRepository paisRepository = new PaisRepository(this.entityManager); + transaction(() -> paisRepository.save(pais)); + + newUser.setPais(pais); + + transaction(() -> this.repository.save(newUser)); + + Optional user = this.repository.findByEmail(email); + + assertEquals(email, user.get().getEmail()); + } + + @Override + protected void beforeEach() { + this.repository = new UsuarioRepository(this.entityManager); + } +} \ No newline at end of file diff --git a/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/security/GenerateToken.java b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/security/GenerateToken.java new file mode 100644 index 0000000..89f8122 --- /dev/null +++ b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/security/GenerateToken.java @@ -0,0 +1,27 @@ +package io.semantic.openscore.core.security; + +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.model.Usuario; + +import java.util.Arrays; +import java.util.HashSet; + +public class GenerateToken { + + public static void main(String[] args) { + TokenGenerator tokenGenerator = new TokenGenerator(); + Usuario usuario = crearUsuario(tokenGenerator); + String token = tokenGenerator.generarToken(usuario); + System.out.println(token); + } + + public static Usuario crearUsuario(TokenGenerator tokenGenerator) { + Usuario usuario = new Usuario(); + usuario.setRoles(new HashSet<>(Arrays.asList(Rol.ADMIN, Rol.USUARIO))); + usuario.setEmail("admin@admin.com"); + usuario.setApellido("Admin"); + usuario.setNombre("Admin"); + usuario.setPassword(tokenGenerator.generarPassword("admin")); + return usuario; + } +} diff --git a/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/security/TokenGeneratorTest.java b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/security/TokenGeneratorTest.java new file mode 100644 index 0000000..ebf6092 --- /dev/null +++ b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/security/TokenGeneratorTest.java @@ -0,0 +1,57 @@ +package io.semantic.openscore.core.security; + +import java.text.ParseException; + +import com.google.common.collect.Sets; +import com.nimbusds.jwt.SignedJWT; +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.model.Usuario; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class TokenGeneratorTest { + + private TokenGenerator tokenGenerator; + + @Before + public void setUp() { + this.tokenGenerator = new TokenGenerator(); + } + + @Test + public void testCrearToken() throws ParseException { + String nombre = "Lionel"; + String apellido = "Messi"; + String email = "lionel.messi@gmail.com"; + String username = "lmessi"; + + Usuario usuario = new Usuario(); + usuario.setNombre(nombre); + usuario.setApellido(apellido); + usuario.setEmail(email); + usuario.setRoles(Sets.newHashSet(Rol.ADMIN, + Rol.USUARIO)); + String token = this.tokenGenerator.generarToken(usuario); + + SignedJWT signedJWT = SignedJWT.parse(token); + + assertEquals(nombre, + signedJWT.getJWTClaimsSet().getStringClaim(TokenGenerator.NOMBRE)); + assertEquals(apellido, + signedJWT.getJWTClaimsSet().getStringClaim(TokenGenerator.APELLIDO)); + assertEquals(email, + signedJWT.getJWTClaimsSet().getStringClaim(TokenGenerator.EMAIL)); + assertNotNull(signedJWT.getJWTClaimsSet().getExpirationTime().getTime()); + assertTrue(signedJWT.getJWTClaimsSet().getStringListClaim(TokenGenerator.ROLES).contains(Rol.ADMIN.toString())); + } + + @Test + public void testCrearPassword() { + + String password = this.tokenGenerator.generarPassword("123"); + assertEquals(64, + password.length()); + } +} \ No newline at end of file diff --git a/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/services/impl/UsuariosServiceImplTest.java b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/services/impl/UsuariosServiceImplTest.java new file mode 100644 index 0000000..7455547 --- /dev/null +++ b/packages/openscore-core-quarkus/src/test/java/io/semantic/openscore/core/services/impl/UsuariosServiceImplTest.java @@ -0,0 +1,149 @@ +package io.semantic.openscore.core.services.impl; + +import io.semantic.openscore.core.api.usuarios.CrearUsuarioDTO; +import io.semantic.openscore.core.cache.TokenCache; +import io.semantic.openscore.core.email.MailFactory; +import io.semantic.openscore.core.email.MailProvider; +import io.semantic.openscore.core.email.MailServer; +import io.semantic.openscore.core.exceptions.ValidationException; +import io.semantic.openscore.core.logging.ServiceLogger; +import io.semantic.openscore.core.mapping.PaisMapper; +import io.semantic.openscore.core.mapping.UsuarioMapper; +import io.semantic.openscore.core.model.Pais; +import io.semantic.openscore.core.model.Rol; +import io.semantic.openscore.core.model.Usuario; +import io.semantic.openscore.core.repository.PaisRepository; +import io.semantic.openscore.core.repository.UsuarioRepository; +import io.semantic.openscore.core.security.TokenGenerator; +import io.semantic.openscore.core.services.UserInfo; +import io.semantic.openscore.core.services.api.UsuariosService; +import io.semantic.openscore.core.validation.ApplicationValidator; +import io.semantic.openscore.core.validation.validators.EmailValidator; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mapstruct.factory.Mappers; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; + +import javax.enterprise.inject.Instance; +import javax.validation.Validation; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.*; + + +@RunWith(MockitoJUnitRunner.class) +public class UsuariosServiceImplTest { + + + private static final String APELLIDO = "Hendrix"; + private static final String NOMBRE = "Jimi"; + private static final String EMAIL = "jimi@hendrix.com"; + private static final String PAIS = "ARG"; + private static final String PASSWORD = "1234!56"; + + @Mock + private UsuarioRepository usuarioRepository; + + @Mock + private PaisRepository paisRepository; + + private UsuariosService usuariosService; + + @Captor + private ArgumentCaptor usuarioCaptor; + + private Pais pais; + + private TokenGenerator tokenGenerator; + + @Mock + Instance emailValidators; + + @Before + public void setUp() { + + tokenGenerator = new TokenGenerator(); + pais = new Pais("ARG", "Argentina"); + usuariosService = new UsuariosServiceImpl(usuarioRepository, + paisRepository, + tokenGenerator, + new ApplicationValidator(Validation.buildDefaultValidatorFactory().getValidator()), + Mappers.getMapper(UsuarioMapper.class), + Mappers.getMapper(PaisMapper.class), + mock(UserInfo.class), + mock(TokenCache.class), + mock(MailServer.class), + mock(MailFactory.class), + emailValidators, + mock(ServiceLogger.class)); + when(paisRepository.findByCodigo(eq(pais.getCodigo()))).thenReturn(pais); + } + + @Test + public void testSeGuardaUnUsuarioCorrecto() { + CrearUsuarioDTO crearUsuarioDTO = new CrearUsuarioDTO(); + crearUsuarioDTO.setApellido(APELLIDO); + crearUsuarioDTO.setNombre(NOMBRE); + crearUsuarioDTO.setEmail(EMAIL); + crearUsuarioDTO.setConfirmacionEmail(EMAIL); + crearUsuarioDTO.setPassword(PASSWORD); + crearUsuarioDTO.setConfirmacionPassword(PASSWORD); + crearUsuarioDTO.setPais(PAIS); + this.usuariosService.registrarUsuario(crearUsuarioDTO); + verify(usuarioRepository, times(1)).save(usuarioCaptor.capture()); + + assertEquals(NOMBRE, usuarioCaptor.getValue().getNombre()); + assertEquals(APELLIDO, usuarioCaptor.getValue().getApellido()); + assertEquals(EMAIL, usuarioCaptor.getValue().getEmail()); + assertEquals(this.tokenGenerator.generarPassword(PASSWORD), usuarioCaptor.getValue().getPassword()); + assertTrue(usuarioCaptor.getValue().getRoles().contains(Rol.USUARIO)); + assertEquals(new Pais(PAIS, "Argentina"), usuarioCaptor.getValue().getPais()); + + } + + @Test(expected = ValidationException.class) + public void testProblemaAlConfirmarEmail() { + CrearUsuarioDTO crearUsuarioDTO = new CrearUsuarioDTO(); + crearUsuarioDTO.setApellido(APELLIDO); + crearUsuarioDTO.setNombre(NOMBRE); + crearUsuarioDTO.setEmail(EMAIL); + crearUsuarioDTO.setConfirmacionEmail(EMAIL + "IMPOSIBLE_CONFIRMAR"); + crearUsuarioDTO.setPassword(PASSWORD); + crearUsuarioDTO.setConfirmacionPassword(PASSWORD); + crearUsuarioDTO.setPais(PAIS); + this.usuariosService.registrarUsuario(crearUsuarioDTO); + } + + @Test(expected = ValidationException.class) + public void testProblemaAlConfirmarPassword() { + CrearUsuarioDTO crearUsuarioDTO = new CrearUsuarioDTO(); + crearUsuarioDTO.setApellido(APELLIDO); + crearUsuarioDTO.setNombre(NOMBRE); + crearUsuarioDTO.setEmail(EMAIL); + crearUsuarioDTO.setConfirmacionEmail(EMAIL); + crearUsuarioDTO.setPassword(PASSWORD); + crearUsuarioDTO.setConfirmacionPassword(PASSWORD + "IMPOSIBLE_CONFIRMAR"); + crearUsuarioDTO.setPais(PAIS); + this.usuariosService.registrarUsuario(crearUsuarioDTO); + } + + @Test(expected = ValidationException.class) + public void testProblemaAlValidarUsuarioNoNulo() { + CrearUsuarioDTO crearUsuarioDTO = new CrearUsuarioDTO(); + crearUsuarioDTO.setApellido(APELLIDO); + crearUsuarioDTO.setNombre(""); + crearUsuarioDTO.setEmail(EMAIL); + crearUsuarioDTO.setConfirmacionEmail(EMAIL); + crearUsuarioDTO.setPassword(PASSWORD); + crearUsuarioDTO.setConfirmacionPassword(PASSWORD + "IMPOSIBLE_CONFIRMAR"); + crearUsuarioDTO.setPais(PAIS); + this.usuariosService.registrarUsuario(crearUsuarioDTO); + } + +} \ No newline at end of file From db6d370750384859a95e8837b8dec90b2710d4fd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 30 Sep 2022 17:27:38 +0000 Subject: [PATCH 2/2] Bump h2 from 1.4.196 to 2.1.210 in /packages/openscore-core-quarkus Bumps [h2](https://github.com/h2database/h2database) from 1.4.196 to 2.1.210. - [Release notes](https://github.com/h2database/h2database/releases) - [Commits](https://github.com/h2database/h2database/compare/version-1.4.196...version-2.1.210) --- updated-dependencies: - dependency-name: com.h2database:h2 dependency-type: direct:development ... Signed-off-by: dependabot[bot] --- packages/openscore-core-quarkus/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/openscore-core-quarkus/pom.xml b/packages/openscore-core-quarkus/pom.xml index 38232dd..75771fe 100644 --- a/packages/openscore-core-quarkus/pom.xml +++ b/packages/openscore-core-quarkus/pom.xml @@ -99,7 +99,7 @@ com.h2database h2 - 1.4.196 + 2.1.210 test