diff --git a/docker-compose.yml b/docker-compose.yml index 1b221b9fae579a33a6fa896f24216394473b6015..5024b7a7c8fdfd3f9f554a40c1b2426c1e8d87aa 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -14,7 +14,7 @@ services: - POSTGRES_DB - TZ ports: - - "5433:5432" + - "5432:5432" volumes: - './data:/data' healthcheck: @@ -46,8 +46,9 @@ services: command: - "sh" - "-c" - # - "apk add postgresql-client && (psql -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' -c \"SELECT * FROM public.chain2events;\" || pg_restore -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' /data/db/selfuser.sql) && psql -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' -c \"CREATE database ${KEYCLOAK_DB};\" && echo 'Finished creating database...'" - - "apk add postgresql-client && (psql -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' -c \"SELECT * FROM public.chain2events;\" || pg_restore -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' /data/db/selfuser.sql) && psql -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' -c \"SELECT 'CREATE DATABASE ${KEYCLOAK_DB}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '${KEYCLOAK_DB}')\" && echo 'Finished creating database...'" +# - "apk add postgresql-client && (psql -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' -c \"SELECT * FROM public.chain2events;\" || pg_restore -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' /data/db/selfuser.sql) && psql -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' -c \"CREATE database ${KEYCLOAK_DB};\" && echo 'Finished creating database...'" +# - "apk add postgresql-client && (psql -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' -c \"SELECT * FROM public.chain2events;\" || pg_restore -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' /data/db/selfuser.sql) && psql -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' -c \"SELECT 'CREATE DATABASE ${KEYCLOAK_DB}' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '${KEYCLOAK_DB}')\" && echo 'Finished creating database...'" + - "apk add postgresql-client && (psql -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' -c \"SELECT * FROM public.chain2events;\" || pg_restore -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' /data/db/selfuser.sql) && (psql -d 'postgres://postgres:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}' -c \"CREATE DATABASE ${KEYCLOAK_DB};\" && echo 'Finished creating database...') || echo 'Keycloak database exists'" depends_on: db: condition: service_healthy @@ -150,7 +151,7 @@ services: ARG_DB_PORT: ${POSTGRES_PORT} ARG_DB_HOST : ${POSTGRES_HOST} ARG_IDP_AUTH_SERVER : ${IDP_AUTH_SERVER} - ARG_ACTIVE_PROFILE : oid + ARG_ACTIVE_PROFILE : ${ACTIVE_PROFILE} ports: - "8004:8004" volumes: diff --git a/gecoregistration/pom.xml b/gecoregistration/pom.xml index aefd4a4b72c68c9ecf3b6801ee6eaaf70a5d0a78..2b8f7b0869c82e13c3ba6531f116911fda0b988b 100644 --- a/gecoregistration/pom.xml +++ b/gecoregistration/pom.xml @@ -21,6 +21,11 @@ 4.6.2.Final + + org.apache.commons + commons-lang3 + 3.17.0 + org.springframework.boot spring-boot-starter-data-jpa @@ -65,12 +70,12 @@ commons-io commons-io - 2.11.0 + 2.16.1 com.google.guava guava - 18.0 + 30.0-jre @@ -199,6 +204,14 @@ Saxon-HE 10.8 + + + com.h2database + h2 + 2.2.220 + test + + diff --git a/gecoregistration/src/main/java/it/enea/cruise/config/dataDBConfiguration.java b/gecoregistration/src/main/java/it/enea/cruise/config/dataDBConfiguration.java index 91bf8587750a74d36daa5814c8d685850b190dc5..0e6641136ba7168f9e200c04b863932cff45c12d 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/config/dataDBConfiguration.java +++ b/gecoregistration/src/main/java/it/enea/cruise/config/dataDBConfiguration.java @@ -1,7 +1,9 @@ +/* package it.enea.cruise.config; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.core.env.Environment; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -23,17 +25,16 @@ import java.util.HashMap; @SpringBootConfiguration @EnableTransactionManagement + @EnableJpaRepositories( - basePackages = {"it.enea.cruise.model.data", - "it.enea.cruise.service.data", - "it.enea.cruise.service.parametricQuery", - "it.enea.cruise.model.parametricQuery"}, + basePackages = { + "it.enea.cruise.repositories.data", + }, entityManagerFactoryRef = "dataEntityManagerIDP", transactionManagerRef = "dataTransactionManagerIDP") -@ComponentScan(basePackages = {"it.enea.cruise.model.data", - "it.enea.cruise.service.data", - "it.enea.cruise.service.parametricQuery", - "it.enea.cruise.model.parametricQuery"}) + +@EntityScan(basePackages = {"it.enea.cruise.model.data"}) + @RequiredArgsConstructor public class dataDBConfiguration { private final Environment env; @@ -55,10 +56,10 @@ public class dataDBConfiguration { @Bean public LocalContainerEntityManagerFactoryBean dataEntityManagerIDP() { LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); - em.setPackagesToScan("it.enea.cruise.model.data", - "it.enea.cruise.service.data", - "it.enea.cruise.service.parametricQuery", - "it.enea.cruise.model.parametricQuery"); + em.setPackagesToScan( + "it.enea.cruise.model.data", + "it.enea.cruise.model.parametricQuery" + ); em.setJpaVendorAdapter(new HibernateJpaVendorAdapter()); em.setDataSource(dataDataSource()); @@ -80,4 +81,4 @@ public class dataDBConfiguration { return new JdbcTemplate(dataDataSource()); } -} \ No newline at end of file +}*/ diff --git a/gecoregistration/src/main/java/it/enea/cruise/config/userDBConfiguration.java b/gecoregistration/src/main/java/it/enea/cruise/config/userDBConfiguration.java index 643fa589f948a5ede0cc263d1becfeb7ddd07101..33ba385d0a4795313398f642d4e582b9ffe084b8 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/config/userDBConfiguration.java +++ b/gecoregistration/src/main/java/it/enea/cruise/config/userDBConfiguration.java @@ -1,3 +1,4 @@ +/* package it.enea.cruise.config; import java.util.HashMap; @@ -24,10 +25,8 @@ import org.springframework.transaction.PlatformTransactionManager; @SpringBootConfiguration @EnableJpaRepositories( basePackages = { - "it.enea.cruise.model.structure", - "it.enea.cruise.service.structure", - "it.enea.cruise.model.user", - "it.enea.cruise.repositories"}, + "it.enea.cruise.repositories.user" + }, entityManagerFactoryRef = "userEntityManagerIDP", transactionManagerRef = "userTransactionManagerIDP" ) @@ -60,9 +59,7 @@ public class userDBConfiguration { em.setDataSource(userDataSource()); em.setPackagesToScan( "it.enea.cruise.model.structure", - "it.enea.cruise.service.structure", - "it.enea.cruise.model.user", - "it.enea.cruise.repositories"); + "it.enea.cruise.model.user"); HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); @@ -86,4 +83,4 @@ public class userDBConfiguration { userEntityManagerIDP().getObject()); return transactionManager; } -} \ No newline at end of file +}*/ diff --git a/gecoregistration/src/main/java/it/enea/cruise/controller/DataController.java b/gecoregistration/src/main/java/it/enea/cruise/controller/DataController.java index edc3b956a34c199a3478eae039e8c6cb443c95e3..9e5bfef9963364a0c9ff1b0f4978347958101e16 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/controller/DataController.java +++ b/gecoregistration/src/main/java/it/enea/cruise/controller/DataController.java @@ -73,25 +73,25 @@ import it.enea.cruise.data.ElectricMeterReading.UrbanDataset; import it.enea.cruise.data.ElectricMeterReading.Values; import it.enea.cruise.data.InputParameters; import it.enea.cruise.model.data.DataConsumption; -import it.enea.cruise.model.parametricQuery.LocalQueryParameter; -import it.enea.cruise.model.parametricQuery.ParametricQuery; +import it.enea.cruise.model.user.LocalQueryParameter; +import it.enea.cruise.model.user.ParametricQuery; import it.enea.cruise.model.user.User; -import it.enea.cruise.service.data.DataInterface; +import it.enea.cruise.repositories.data.DataConsumptionRepository; import it.enea.cruise.service.data.IDataService; import it.enea.cruise.service.idp.IdpProvider; -import it.enea.cruise.service.parametricQuery.LocalQueryParameterInterface; -import it.enea.cruise.service.parametricQuery.ParametricQueryInterface; +import it.enea.cruise.repositories.user.LocalQueryParameterRepository; +import it.enea.cruise.repositories.user.ParametricQueryRepository; import it.enea.cruise.service.parametricQuery.ParametricQueryManager; import it.enea.cruise.service.parametricQuery.ParametricQueryManager.ResultWithMetadata; -import it.enea.cruise.service.structure.TableMetadataInterface; +import it.enea.cruise.repositories.user.TableMetadataRepository; import it.enea.cruise.repositories.DTOManager; -import it.enea.cruise.repositories.UserRepository; +import it.enea.cruise.repositories.user.UserRepository; import lombok.extern.log4j.Log4j2; @RestController @Api(value = "DataController") @EnableTransactionManagement -@Transactional("dataTransactionManagerIDP") +@Transactional @Log4j2 public class DataController { @@ -99,19 +99,16 @@ public class DataController { UserRepository userInterface; @Autowired - TableMetadataInterface tMetadataInterface; + LocalQueryParameterRepository lqpInterface; @Autowired - LocalQueryParameterInterface lqpInterface; + DataConsumptionRepository dataConsumptionRepository; @Autowired - DataInterface dataInterface; + ParametricQueryRepository pqueryInterface; @Autowired - ParametricQueryInterface pqueryInterface; - - @Autowired - TableMetadataInterface tmInterface; + TableMetadataRepository tmInterface; @Autowired ParametricQueryManager pqm; @@ -253,7 +250,7 @@ public class DataController { inputData.setCommunityid(2); inputData.setFlowid(18); inputData.setUserid(user.getUserid().intValue()); - ParametricQuery pq = pqueryInterface.findByQueryid(new Long(6)); + ParametricQuery pq = pqueryInterface.findById(6L).get(); ResultWithMetadata data = pqm.executeQuery(pq, inputData.getParameters(), "it_IT"); @@ -306,7 +303,7 @@ public class DataController { inputData.setCommunityid(2); inputData.setFlowid(18); inputData.setUserid(user.getUserid().intValue()); - ParametricQuery pq = pqueryInterface.findByQueryid(new Long(9)); + ParametricQuery pq = pqueryInterface.findById(9L).get(); ResultWithMetadata data = pqm.executeQuery(pq, inputData.getParameters(), "it_IT"); emr = new ElectricMeterReading(timeZone); @@ -371,7 +368,7 @@ public class DataController { Date start = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(startDate); Date end = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endDate); - List dataConsumption = dataInterface.findAllByUserIdAndStartDateAndEndDate(userid, start, end, + List dataConsumption = dataConsumptionRepository.findAllByUserIdAndStartDateAndEndDate(userid, start, end, communityid); emr = new ElectricMeterReading(timeZone); diff --git a/gecoregistration/src/main/java/it/enea/cruise/controller/MailController.java b/gecoregistration/src/main/java/it/enea/cruise/controller/MailController.java index ec78d47fdc31dccc7e71dbd2ad2564f24c937a5c..328d4307894477c5e78aef428c79388c59ed842f 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/controller/MailController.java +++ b/gecoregistration/src/main/java/it/enea/cruise/controller/MailController.java @@ -22,7 +22,7 @@ import io.swagger.annotations.Api; import it.enea.cruise.dto.LocalUserDTO; import it.enea.cruise.model.user.User; import it.enea.cruise.service.idp.IdpProvider; -import it.enea.cruise.repositories.UserRepository; +import it.enea.cruise.repositories.user.UserRepository; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; diff --git a/gecoregistration/src/main/java/it/enea/cruise/controller/QueryController.java b/gecoregistration/src/main/java/it/enea/cruise/controller/QueryController.java index 2e58d080f37abb06e329b519424c8ef657ee141e..3fe4511cf57b22ca6ce39d297782b73afa1ad2d2 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/controller/QueryController.java +++ b/gecoregistration/src/main/java/it/enea/cruise/controller/QueryController.java @@ -20,30 +20,30 @@ import org.springframework.web.bind.annotation.RestController; import io.swagger.annotations.Api; import it.enea.cruise.dto.ParametricQueryDTO; import it.enea.cruise.dto.QueryParameterDTO; -import it.enea.cruise.model.parametricQuery.ParametricQuery; +import it.enea.cruise.model.user.ParametricQuery; import it.enea.cruise.model.user.User; -import it.enea.cruise.service.parametricQuery.LocalQueryParameterInterface; -import it.enea.cruise.service.parametricQuery.ParametricQueryInterface; +import it.enea.cruise.repositories.user.LocalQueryParameterRepository; +import it.enea.cruise.repositories.user.ParametricQueryRepository; import it.enea.cruise.service.parametricQuery.ParametricQueryManager; -import it.enea.cruise.repositories.UserRepository; -import it.enea.cruise.model.parametricQuery.LocalQueryParameter; +import it.enea.cruise.repositories.user.UserRepository; +import it.enea.cruise.model.user.LocalQueryParameter; import lombok.extern.log4j.Log4j2; @RestController @Api(value = "QueryController") @EnableTransactionManagement -@Transactional("dataTransactionManagerIDP") +/*@Transactional("dataTransactionManagerIDP")*/ @Log4j2 public class QueryController { @Autowired - LocalQueryParameterInterface lqpInterface; + LocalQueryParameterRepository lqpInterface; @Autowired ParametricQueryManager pqm; @Autowired - ParametricQueryInterface pqueryInterface; + ParametricQueryRepository pqueryInterface; @Autowired IdpProvider idpClientManager; diff --git a/gecoregistration/src/main/java/it/enea/cruise/controller/StructureController.java b/gecoregistration/src/main/java/it/enea/cruise/controller/StructureController.java index ff09dcfc1943bd58a64b0a02dcd29580b864d1fd..85e08e9bda499c6ed8350e8d531f3e51d09439ac 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/controller/StructureController.java +++ b/gecoregistration/src/main/java/it/enea/cruise/controller/StructureController.java @@ -39,13 +39,13 @@ import it.enea.cruise.dto.FieldDTO; import it.enea.cruise.dto.FormDTO; import it.enea.cruise.dto.MetadataDTO; import it.enea.cruise.dto.TableMetadataDTO; -import it.enea.cruise.model.structure.DescriptionDTO; +import it.enea.cruise.dto.DescriptionDTO; import it.enea.cruise.model.structure.ForeignKey; -import it.enea.cruise.model.structure.TableCommentDTO; +import it.enea.cruise.dto.TableCommentDTO; import it.enea.cruise.model.structure.VwTableMetadata; import it.enea.cruise.model.user.User; -import it.enea.cruise.service.structure.ForeignKeyInterface; -import it.enea.cruise.service.structure.TableMetadataInterface; +import it.enea.cruise.repositories.user.ForeignKeyRepository; +import it.enea.cruise.repositories.user.TableMetadataRepository; import it.enea.cruise.repositories.DTOManager; import lombok.extern.log4j.Log4j2; @@ -54,10 +54,10 @@ import lombok.extern.log4j.Log4j2; public class StructureController { @Autowired - TableMetadataInterface tmInterface; + TableMetadataRepository tmInterface; @Autowired - ForeignKeyInterface fkInterface; + ForeignKeyRepository fkInterface; @Autowired DTOManager dtoManager; diff --git a/gecoregistration/src/main/java/it/enea/cruise/controller/UserController.java b/gecoregistration/src/main/java/it/enea/cruise/controller/UserController.java index bb367c8dc06714beb86d6ec2d79f80f82c68a623..eadd1315c4b48f4acc339858478e3b6dd1a49d61 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/controller/UserController.java +++ b/gecoregistration/src/main/java/it/enea/cruise/controller/UserController.java @@ -12,9 +12,11 @@ import java.util.regex.Pattern; import javax.mail.MessagingException; +import ch.qos.logback.core.util.StringCollectionUtil; import it.enea.scp.idp.sdk.model.UserDto; import it.enea.cruise.service.idp.IdpProvider; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; @@ -30,8 +32,6 @@ import org.springframework.web.bind.annotation.RestController; import org.json.JSONObject; -import org.springframework.util.StringUtils; - import freemarker.template.TemplateException; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -46,14 +46,14 @@ import it.enea.cruise.model.user.Role; import it.enea.cruise.model.user.User; import it.enea.cruise.model.user.UserCommunity; import it.enea.cruise.model.user.UserRole; -import it.enea.cruise.model.user.UserToken; -import it.enea.cruise.service.structure.TableMetadataInterface; -import it.enea.cruise.repositories.CommunityRepository; -import it.enea.cruise.repositories.UserRepository; +import it.enea.cruise.dto.UserToken; +import it.enea.cruise.repositories.user.TableMetadataRepository; +import it.enea.cruise.repositories.user.CommunityRepository; +import it.enea.cruise.repositories.user.UserRepository; import it.enea.cruise.repositories.DTOManager; -import it.enea.cruise.repositories.RoleRepository; -import it.enea.cruise.repositories.UserCommunityRepository; -import it.enea.cruise.repositories.UserRoleRepository; +import it.enea.cruise.repositories.user.RoleRepository; +import it.enea.cruise.repositories.user.UserCommunityRepository; +import it.enea.cruise.repositories.user.UserRoleRepository; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; @@ -65,7 +65,7 @@ import lombok.extern.log4j.Log4j2; * User controller for exposing REST API calls This class manages all the * methods for managing both users and communities in the Energy Community * environment. - * + *

* It connects directly to User and Community entities and to the Identiy * Provider tools developed by ENEA. * @@ -76,123 +76,120 @@ import lombok.extern.log4j.Log4j2; @RestController @Api(value = "UserController") -@Transactional("userTransactionManagerIDP") +@Transactional @Log4j2 public class UserController { - @Value("${testingPhase}") - private Boolean testingPhase; - - @Autowired - UserRoleRepository userRoleInterface; - - @Autowired - UserRepository userInterface; - - @Autowired - CommunityRepository communityInterface; - - @Autowired - UserCommunityRepository userCommunityInterface; - - @Autowired - RoleRepository roleInterface; - - @Autowired - TableMetadataInterface tmInterface; - - @Autowired - IdpProvider idpClientManager; - - @Autowired - DTOManager dTOManager; - - @Autowired - MailController jmc; - - @Value("${communityRoleAdmin}") - private String communityRoleAdmin; - - @Value("${oracleRoleAdmin}") - private String oracleRoleAdmin; - - @Value("${platformRoleAdmin}") - private String platformRoleAdmin; - - @Value("${stakeHolderRole}") - private String stakeHolderRole; - - @Value("${communityMemberRole}") - private String communityMemberRole; - - @Value("${idp.clientSecret}") - private String secret; - - List users = new ArrayList(); - - /** - * Returns the list of the users in the DB This method will be removed soon - * because the lackness of secutiry. In fact, it does not evaluate the role of - * the requester and does not select the community the users belong to. - * - * @param: null - * @exception: Return an Internal Server error in case of exception - * - */ - @Deprecated - @GetMapping("/ListAllUsers") - public ResponseEntity> getAllUsers() { - users = new ArrayList(); - try { - userInterface.findAll().forEach(users::add); - } catch (Exception e) { - return new ResponseEntity(e.getLocalizedMessage(), - // headers, - HttpStatus.INTERNAL_SERVER_ERROR); - } - return new ResponseEntity>(users, HttpStatus.OK); - } - - - /** - * Returns the list of the users in the DB This method will be removed soon - * because the lackness of secutiry. In fact, it does not evaluate the role of - * the requester and does not select the community the users belong to. - * - * @param: null - * @exception: Return an Internal Server error in case of exception - * - */ - - @GetMapping("/community/listAllCommunities") - public ResponseEntity> getAllCommunities() { - List communities = new ArrayList(); - try { - List communitiesTemp = communityInterface.findAll(); - for (Community c : communitiesTemp) { - CommunityDTO cDTO = dTOManager.communityDTO(c); - communities.add(cDTO); - } - } catch (Exception e) { - return new ResponseEntity(e.getLocalizedMessage(), - // headers, - HttpStatus.INTERNAL_SERVER_ERROR); - } - return new ResponseEntity>(communities, HttpStatus.OK); - } - - - /** - * Creates or updates a user from a JWT valid token This method will be removed - * because it uses the KeyCloak identity provided. At the moment, it is - * maintained for compatibility purposes. - * - * @params: String token - * @return: The user if the creation or update is successful - * @return: Forbidden if the token is not valid - * @exception: Return an Internal Server error in case of exception - * - */ + @Value("${testingPhase}") + private Boolean testingPhase; + + @Autowired + UserRoleRepository userRoleInterface; + + @Autowired + UserRepository userInterface; + + @Autowired + CommunityRepository communityInterface; + + @Autowired + UserCommunityRepository userCommunityInterface; + + @Autowired + RoleRepository roleInterface; + + @Autowired + TableMetadataRepository tmInterface; + + @Autowired + IdpProvider idpClientManager; + + @Autowired + DTOManager dTOManager; + + @Autowired + MailController jmc; + + @Value("${communityRoleAdmin}") + private String communityRoleAdmin; + + @Value("${oracleRoleAdmin}") + private String oracleRoleAdmin; + + @Value("${platformRoleAdmin}") + private String platformRoleAdmin; + + @Value("${stakeHolderRole}") + private String stakeHolderRole; + + @Value("${communityMemberRole}") + private String communityMemberRole; + + @Value("${idp.clientSecret}") + private String secret; + + List users = new ArrayList(); + + /** + * Returns the list of the users in the DB This method will be removed soon + * because the lackness of secutiry. In fact, it does not evaluate the role of + * the requester and does not select the community the users belong to. + * + * @param: null + * @exception: Return an Internal Server error in case of exception + */ + @Deprecated + @GetMapping("/ListAllUsers") + public ResponseEntity> getAllUsers() { + users = new ArrayList(); + try { + userInterface.findAll().forEach(users::add); + } catch (Exception e) { + return new ResponseEntity(e.getLocalizedMessage(), + // headers, + HttpStatus.INTERNAL_SERVER_ERROR); + } + return new ResponseEntity>(users, HttpStatus.OK); + } + + + /** + * Returns the list of the users in the DB This method will be removed soon + * because the lackness of secutiry. In fact, it does not evaluate the role of + * the requester and does not select the community the users belong to. + * + * @param: null + * @exception: Return an Internal Server error in case of exception + */ + + @GetMapping("/community/listAllCommunities") + public ResponseEntity> getAllCommunities() { + List communities = new ArrayList(); + try { + List communitiesTemp = communityInterface.findAll(); + for (Community c : communitiesTemp) { + CommunityDTO cDTO = dTOManager.communityDTO(c); + communities.add(cDTO); + } + } catch (Exception e) { + return new ResponseEntity(e.getLocalizedMessage(), + // headers, + HttpStatus.INTERNAL_SERVER_ERROR); + } + return new ResponseEntity>(communities, HttpStatus.OK); + } + + + /** + * Creates or updates a user from a JWT valid token This method will be removed + * because it uses the KeyCloak identity provided. At the moment, it is + * maintained for compatibility purposes. + * + * @params: String token + * @return: The user if the creation or update is successful + * @return: Forbidden if the token is not valid + * @exception: Return an Internal Server error in case of exception + */ /*@ApiOperation(value = "Create or update user from KEYCLOAK token", response = User.class, tags = "") @PostMapping("/userFromToken") @@ -207,13 +204,13 @@ public class UserController { try { *//* - * Check if the token is valid connecting to remote keycloak provider. - *//* + * Check if the token is valid connecting to remote keycloak provider. + *//* Boolean isValid = false; *//* - * Remove the usage of the keycloak manager for this application. - * And returns always an error on interrogating this function - *//* + * Remove the usage of the keycloak manager for this application. + * And returns always an error on interrogating this function + *//* //km.isValidToken(token); if (isValid || testingPhase) { @@ -224,9 +221,9 @@ public class UserController { if (userTempFromDB == null) { *//* - * The user does not exist on the DB but the token is valid. => user has to be - * created on the DB - *//* + * The user does not exist on the DB but the token is valid. => user has to be + * created on the DB + *//* for (String localRole : userTemp.getKeycloakRoles()) { Role dbRole = roleInterface.findByRolename(localRole); if (dbRole.getId() > 0) { @@ -284,456 +281,442 @@ public class UserController { } */ - @ApiOperation(value = "Return a list of users from their email", response = User.class, tags = "") - @GetMapping("/userFromEmail") - public ResponseEntity getUserDTOFromEmail( - @ApiParam(name = "email", type = "String", value = "Subject string", example = "", required = true) @RequestParam("email") String email) { - - UserDto user = idpClientManager.getUserByEmail(email); - return new ResponseEntity(user, - // headers, - HttpStatus.CREATED); - } - - - /** - * Returns a user from the Subject code At the moment, it just extact - * information about the user from the subject. It is not connected to the - * Identity Provider, at the moment, so the ressult contains only a userid and a - * subject. - * - * @param: String subject code - * @return: The user if found - * @return: NotFound if the user does not exist on DB - * - */ - @ApiOperation(value = "Return a list of users from their subject code", response = User.class, tags = "") - @GetMapping("/userFromSubject") - public ResponseEntity getUserDTOFromSubject( - @ApiParam(name = "subject", type = "String", value = "Subject string", example = "", required = true) @RequestParam("subject") String subject) { - User user; - LocalUserDTO lUserDTO = new LocalUserDTO(); - try { - user = userInterface.findBySubject(subject); - //String email = encryptionManager.decrypt(user.getSubject()); - UserDto userDto = idpClientManager.getUserByEmail(user.getSubject()); - user.mergeWithDto(userDto); - - lUserDTO = dTOManager.userDTO(user); - - } catch (Exception e) { - log.info(e.getLocalizedMessage()); - return new ResponseEntity("User does not exist in DB", - // headers, - HttpStatus.NOT_FOUND); - - } - return new ResponseEntity(lUserDTO, - // headers, - HttpStatus.FOUND); - } - - /** - * Register a user from the simple Registration form - * - * @params: the User representation coming from the registration form - * @return: The user if created - * @return: Conflict if the user already exists on DB or on KeyCloak - * - */ - // @ApiOperation(value = "Register a user from form data", response = - // User.class, tags = "") - - @PostMapping("/user/remoteLogin") - public ResponseEntity remoteLogin( - @RequestParam String token ){ - - System.out.println(token.toString()); - - return new ResponseEntity(token.toString(), HttpStatus.OK); - } - - @GetMapping("/user/remoteLogin") - public ResponseEntity getRemoteLogin( - @RequestParam String token){ - - System.out.println(token.toString()); - - return new ResponseEntity(token.toString(), HttpStatus.OK); - } - - - @PostMapping("/user/register") - public ResponseEntity registerFromForm( - @ApiParam(name = "user", type = "User", value = "User representation from theinput form", example = "", required = true) - @RequestBody LocalUserDTO user) { - /* - * Controllo che ci sia almeno la mail. - */ - if (user.getEmail().isEmpty()) { - ResultMessage msg = new ResultMessage(false, "The user has not email" ); - return new ResponseEntity(msg, HttpStatus.OK); - } - - /* - * Controllo se l'utente esiste gia' sui due DB o almeno su IDP - */ - - UserDto userIDP = idpClientManager.getUserByEmail(user.getEmail()); - - if (userIDP == null) { - /* - * L'utente non esiste su IDP e quindi posso procedere alla registrazione - * prima su IDP per ottenere il subject - */ - - UserDto uDto = new UserDto(); - uDto.setEmail(user.getEmail()); - uDto.setName(user.getName()); - uDto.setSurname(user.getSurname()); - uDto.setPassword(user.getPassword()); - uDto.setPasswordConfirm(user.getPassword()); - uDto.setEmailConfirmed(true); - uDto.setRole("Citizen"); - uDto.setOrganization("EnergyCommunity"); - - Boolean registerdonIDP = idpClientManager.createUser(uDto); - if (!registerdonIDP) { - log.info("Error on registering on IDP"); - ResultMessage msg = new ResultMessage(false, "Error on registering on IDP" ); - return new ResponseEntity(msg, HttpStatus.OK); - }else { - uDto= idpClientManager.getUserByEmail(uDto.getEmail()); - } - - /* - * Adesso creo l'utente locale con le informazioni e le comunita'. - */ - - User tmpUser = new User(); - tmpUser.setSubject(uDto.getUuid()); - user.setSubject(uDto.getUuid()); - // Inserisco le comunita - for (CommunityDTO cDto : user.getUsercommunities()) { - Community c = communityInterface.findByCommunityid(cDto.getCommunityid()); - UserCommunity uc1 = new UserCommunity(); - uc1.setCommunity(c); - uc1.setUser(tmpUser); - uc1.setWallet(cDto.getWallet()); - uc1.setSubscriptiondate(new Date(System.currentTimeMillis())); - uc1.setActive(true); - tmpUser.setSingleUsercommunity(uc1); - Role tmpRole = roleInterface.getById(new Long(2)); - UserRole ur = new UserRole(); - ur.setCommunity(c); - ur.setUser(tmpUser); - ur.setRole(tmpRole); - tmpUser.setSingleUserRole(ur); - } - - tmpUser = userInterface.save(tmpUser); - log.info("user saved, probably... the number of available users is " + userInterface.count()); - - user.setUserid(tmpUser.getUserid()); - - - - } else { - log.info("User with email " + user.getEmail() + " already exists"); - ResultMessage msg = new ResultMessage(false, "User with email " + user.getEmail() + " already exists" ); - - return new ResponseEntity(msg, HttpStatus.OK); - } - - //OK. Se sono arrivato qui posso mandare la mail di conferma - log.info("Sending activation email to " + user.getEmail()); - - - - try { - jmc.sendMessageUsingFreemarkerTemplate(user); - } catch (IOException | TemplateException | MessagingException e) { - log.info("Mailing failed"); - log.info(e.getLocalizedMessage()); - } - ResultMessage msg = new ResultMessage(true, "User created" ); - return new ResponseEntity(msg, HttpStatus.OK); - } - - /** - * Returns the number of participants in a a community managed by the - * owner of the token - * - * @params: The admin's token - * @return: The number of participants, if the user is and admin - * @return: A forbidden message otherwise - * - */ - @ApiOperation(value = "Get the number of users in a community from the administrator's token", response = User.class, tags = "") - @PostMapping("/getNumberOfParticipants") - ResponseEntity getNumberOfParticipants( - @ApiParam(name = "token", type = "String", value = "The administrator's token", example = "", required = true) @RequestParam String token) { - - - User u = new User(); - Boolean isValid = idpClientManager.isValid(token); - Integer result = 0; - - if (isValid) { - User userdto = idpClientManager.getUserByToken(token); - - u = userInterface.findBySubject(userdto.getUuid()); - if (u.hasRole(communityRoleAdmin) || u.hasRole(oracleRoleAdmin) || u.hasRole(platformRoleAdmin)) { - for (UserCommunity c : u.getUsercommunities()) { - result = userInterface.countBySubjectIsNotNullAndCommunityId(c.getId().getCommunityId()); - } - } - }else { - return new ResponseEntity("User is not an addmin", - HttpStatus.FORBIDDEN); - } - return new ResponseEntity (result, HttpStatus.OK); - } - - - /** - * Returns a user from a wallet if the token owner is an admin for the community - * - * @params: The wallet - * @params: the admin's token - * @return: The user, if the if the token belongs to an admin - * @return: A forbidden message otherwise - * - */ - @ApiOperation(value = "Get a user in a community from the wallet(s)", response = User.class, tags = "") - @PostMapping("/getUserFromWallet") - ResponseEntity getUserFromWallet( - @RequestBody List wallets, - @ApiParam(name = "token", type = "String", value = "The administrator's token", example = "", required = true) @RequestParam String token) - { - LocalUserDTO lUserDTO = new LocalUserDTO(); - - User u = new User(); - Boolean isValid = idpClientManager.isValid(token); - - Map> resultMap = new HashMap>(); - - if (isValid) { - User userdto = idpClientManager.getUserByToken(token); - - u = userInterface.findBySubject(userdto.getUuid()); - if (u.hasRole(communityRoleAdmin) || u.hasRole(oracleRoleAdmin) || u.hasRole(platformRoleAdmin)) { - for (Community c : u.getCommunities()) { - List result = new ArrayList(); - for (String wallet : wallets) { - result.addAll(userInterface.findFromWalletAndCommunityId(wallet, c.getCommunityid())); - } - if (result.size()> 0) { - u = result.get(0); //qualcosa non va se ne trovo piu' di uno - UserDto userdtoNew = idpClientManager.getUserFromUUID( - u.getSubject()); - u.mergeWithDto(userdtoNew); - lUserDTO = dTOManager.userDTO(u); - return new ResponseEntity (lUserDTO, HttpStatus.OK); - } - } - } - if (u.hasRole(stakeHolderRole) || u.hasRole(communityMemberRole)) { - for (Community c : u.getCommunities()) { - List result = new ArrayList(); - for (String wallet : wallets) { - result.addAll(userInterface.findFromWalletAndCommunityId(wallet, c.getCommunityid())); - } - if (result.size()> 0) { - u = result.get(0); - UserDto userdtoNew = idpClientManager.getUserByEmail( - u.getSubject()); - u.mergeWithDto(userdtoNew); - lUserDTO.setEmail(u.getEmail()); - lUserDTO.setPhone(u.getPhone()); - return new ResponseEntity (lUserDTO, HttpStatus.OK); - } - } - } - - - }else { - return new ResponseEntity("User is not an addmin", - HttpStatus.FORBIDDEN); - } - return new ResponseEntity (lUserDTO, HttpStatus.OK); - } - - /** - * Returns the list of communities the user belongs to It uses the Keycloak - * application for controlling the requester's roles. This methd shall be - * duplicated for the Identity Provider tool - * - * @param: the JWT token of the user - * @return: The list of the user communities - * @return: Forbidden if the token is not valid - * @return: Forbidden if the user is not an administrator - * - */ - @ApiOperation(value = "Get all users in a community from the administrator's token", response = User.class, tags = "") - @PostMapping("/getusercommunities") - ResponseEntity> getUserCommunities( - @ApiParam(name = "token", type = "String", value = "The administrator's token", example = "", required = true) @RequestParam String token) { - - - User u = new User(); - List usersInCommunity = new ArrayList(); - List listOfUsers = new ArrayList(); - Boolean isValid = idpClientManager.isValid(token); - - - if (isValid) { - User userdto = idpClientManager.getUserByToken(token); - - u = userInterface.findBySubject(userdto.getUuid()); - if (u.hasRole(communityRoleAdmin) || u.hasRole(oracleRoleAdmin) || u.hasRole(platformRoleAdmin)) { - for (UserCommunity c : u.getUsercommunities()) { - usersInCommunity.addAll(userInterface.findBySubjectIsNotNullAndActiveIsTrueAndCommunityId(c.getId().getCommunityId())); - } - - for (User uTmp : usersInCommunity) { - - String subejct = uTmp.getSubject(); - log.info("email: " + subejct); - if(subejct != null && !subejct.isEmpty()) { - UserDto tmpUserDto = idpClientManager.getUserByEmail(subejct); - if (tmpUserDto != null ) { - uTmp.mergeWithDto(tmpUserDto); - LocalUserDTO lUserDTO = dTOManager.userDTO(uTmp); - lUserDTO.setEmail(tmpUserDto.getEmail()); - listOfUsers.add(lUserDTO); - } - } - } - - - - - - } else { - return new ResponseEntity("User is not an addmin", - HttpStatus.FORBIDDEN); - } - } else { - return new ResponseEntity("Provided token is not valid ", // headers, - HttpStatus.FORBIDDEN); - } - return new ResponseEntity>(listOfUsers, // headers, - HttpStatus.OK); - } - - - @ApiOperation(value = "Generate subject", response = String.class, tags = "") - @PostMapping("/generateSubject") - @Deprecated - ResponseEntity generateSubject( - @ApiParam(name = "mail", type = "String", value = "The user's email", example = "", required = false) - @RequestBody String email){ - //String subject = encryptionManager.encrypt(email); - - return new ResponseEntity ("", HttpStatus.OK); - } - - - @ApiOperation(value = "Generate email", response = String.class, tags = "") - @PostMapping("/returnEmail") - @Deprecated - ResponseEntity generateEmail( - @ApiParam(name = "Subject", type = "String", value = "The user's subject", example = "", required = false) - @RequestBody String subject){ - //String email = encryptionManager.decrypt(subject); - - return new ResponseEntity ("", HttpStatus.OK); - } - - - /** - * Returns the list of users if the requester is a platform admin This method - * shall be moved for using the Identity Provider tool - * - * @param: the JWT token of the user - * @return: The list of the users - * @return: Forbidden if the token is not valid - * @return: Forbidden if the user is not an administrator - * - */ - - @ApiOperation(value = "Get all users if the requester is a platform admin", response = User.class, tags = "") - @PostMapping("/getusers") - ResponseEntity> getUsers( - @ApiParam(name = "token", type = "String", value = "The administrator's token", example = "", required = false) @RequestParam(required = false) String token, - @ApiParam(name = "Authorization", type = "String", value = "The administrator's token", example = "", required = false) @RequestHeader(name = "Authorization", required = false) String tokenAuth) { - List users = new ArrayList(); - List resultList = new ArrayList(); - Boolean isValid = false; - User u = new User(); - User userdto; - String subject = ""; - if ((token == null || token.length() == 0) && (tokenAuth == null || tokenAuth.length() == 0)) { - return new ResponseEntity("Token has not been provided", // headers, - HttpStatus.FORBIDDEN); - } - if (token != null) { - //isValid = km.isValidToken(token); - - //if (isValid) { - /* Ok, I'm using the keycloak manager */ - //subject = JWTManager.getSubject(token); - //} - } else { - isValid = idpClientManager.isValid(tokenAuth); - if (isValid) { - userdto = idpClientManager.getUserByToken(tokenAuth); - subject = userdto.getUuid(); - } else { - return new ResponseEntity("Provided token is not valid ", // headers, - HttpStatus.FORBIDDEN); - } - - u = userInterface.findBySubject(userdto.getUuid()); - if (u.hasRole(platformRoleAdmin)) { - users = userInterface.findBySubjectIsNotNull(); - - for (User uTmp : users) { - - String subjectLocal = uTmp.getSubject(); - if(subjectLocal != null && !subjectLocal.isEmpty()) { - UserDto tmpUserDto = idpClientManager.getUserByEmail(subjectLocal); - if (tmpUserDto != null ) { - uTmp.mergeWithDto(tmpUserDto); - LocalUserDTO lUserDTO = dTOManager.userDTO(uTmp); - lUserDTO.setEmail(tmpUserDto.getEmail()); - resultList.add(lUserDTO); - } - } - } - - - - } else { - return new ResponseEntity("User is not a " + platformRoleAdmin, // headers, - HttpStatus.FORBIDDEN); - } - - } - return new ResponseEntity>(resultList, // headers, - HttpStatus.OK); - } - - // @ApiOperation(value = "Get all users as the requester is a platform admin", - // response = User.class, tags = "") - // @GetMapping("/getusers") - // ResponseEntity> getgetUsers( - // @ApiParam(name = "token", type = "String", value = "The administrator's - // token", example = "", required = true) - // @RequestParam String token) { - // return getUsers(token, ""); - // } + @ApiOperation(value = "Return a list of users from their email", response = User.class, tags = "") + @GetMapping("/userFromEmail") + public ResponseEntity getUserDTOFromEmail( + @ApiParam(name = "email", type = "String", value = "Subject string", example = "", required = true) @RequestParam("email") String email) { + + UserDto user = idpClientManager.getUserByEmail(email); + return new ResponseEntity(user, + // headers, + HttpStatus.CREATED); + } + + + /** + * Returns a user from the Subject code At the moment, it just extact + * information about the user from the subject. It is not connected to the + * Identity Provider, at the moment, so the ressult contains only a userid and a + * subject. + * + * @param: String subject code + * @return: The user if found + * @return: NotFound if the user does not exist on DB + */ + @ApiOperation(value = "Return a list of users from their subject code", response = User.class, tags = "") + @GetMapping("/userFromSubject") + public ResponseEntity getUserDTOFromSubject( + @ApiParam(name = "subject", type = "String", value = "Subject string", example = "", required = true) @RequestParam("subject") String subject) { + User user; + LocalUserDTO lUserDTO = new LocalUserDTO(); + try { + user = userInterface.findBySubject(subject); + //String email = encryptionManager.decrypt(user.getSubject()); + UserDto userDto = idpClientManager.getUserByEmail(user.getSubject()); + user.mergeWithDto(userDto); + + lUserDTO = dTOManager.userDTO(user); + + } catch (Exception e) { + log.info(e.getLocalizedMessage()); + return new ResponseEntity("User does not exist in DB", + // headers, + HttpStatus.NOT_FOUND); + + } + return new ResponseEntity(lUserDTO, + // headers, + HttpStatus.FOUND); + } + + /** + * Register a user from the simple Registration form + * + * @params: the User representation coming from the registration form + * @return: The user if created + * @return: Conflict if the user already exists on DB or on KeyCloak + */ + // @ApiOperation(value = "Register a user from form data", response = + // User.class, tags = "") + @PostMapping("/user/remoteLogin") + public ResponseEntity remoteLogin( + @RequestParam String token) { + + System.out.println(token.toString()); + + return new ResponseEntity(token.toString(), HttpStatus.OK); + } + + @GetMapping("/user/remoteLogin") + public ResponseEntity getRemoteLogin( + @RequestParam String token) { + + System.out.println(token.toString()); + + return new ResponseEntity(token.toString(), HttpStatus.OK); + } + + + @PostMapping("/user/register") + public ResponseEntity registerFromForm( + @ApiParam(name = "user", type = "User", value = "User representation from theinput form", example = "", required = true) + @RequestBody LocalUserDTO user) { + /* + * Controllo che ci sia almeno la mail. + */ + if (user.getEmail().isEmpty()) { + ResultMessage msg = new ResultMessage(false, "The user has not email"); + return new ResponseEntity(msg, HttpStatus.OK); + } + + /* + * Controllo se l'utente esiste gia' sui due DB o almeno su IDP + */ + + UserDto userIDP = idpClientManager.getUserByEmail(user.getEmail()); + + if (userIDP == null) { + /* + * L'utente non esiste su IDP e quindi posso procedere alla registrazione + * prima su IDP per ottenere il subject + */ + + UserDto uDto = new UserDto(); + uDto.setEmail(user.getEmail()); + uDto.setName(user.getName()); + uDto.setSurname(user.getSurname()); + uDto.setPassword(user.getPassword()); + uDto.setPasswordConfirm(user.getPassword()); + uDto.setEmailConfirmed(true); + uDto.setRole("Citizen"); + uDto.setOrganization("EnergyCommunity"); + + Boolean registerdonIDP = idpClientManager.createUser(uDto); + if (!registerdonIDP) { + log.info("Error on registering on IDP"); + ResultMessage msg = new ResultMessage(false, "Error on registering on IDP"); + return new ResponseEntity(msg, HttpStatus.OK); + } else { + uDto = idpClientManager.getUserByEmail(uDto.getEmail()); + } + + /* + * Adesso creo l'utente locale con le informazioni e le comunita'. + */ + + User tmpUser = new User(); + tmpUser.setSubject(uDto.getUuid()); + user.setSubject(uDto.getUuid()); + // Inserisco le comunita + for (CommunityDTO cDto : user.getUsercommunities()) { + Community c = communityInterface.findById(cDto.getCommunityid()).get(); + UserCommunity uc1 = new UserCommunity(); + uc1.setCommunity(c); + uc1.setUser(tmpUser); + uc1.setWallet(cDto.getWallet()); + uc1.setSubscriptiondate(new Date(System.currentTimeMillis())); + uc1.setActive(true); + tmpUser.setSingleUsercommunity(uc1); + Role tmpRole = roleInterface.getById(new Long(2)); + UserRole ur = new UserRole(); + ur.setCommunity(c); + ur.setUser(tmpUser); + ur.setRole(tmpRole); + tmpUser.setSingleUserRole(ur); + } + + tmpUser = userInterface.save(tmpUser); + log.info("user saved, probably... the number of available users is " + userInterface.count()); + + user.setUserid(tmpUser.getUserid()); + + + } else { + log.info("User with email " + user.getEmail() + " already exists"); + ResultMessage msg = new ResultMessage(false, "User with email " + user.getEmail() + " already exists"); + + return new ResponseEntity(msg, HttpStatus.OK); + } + + //OK. Se sono arrivato qui posso mandare la mail di conferma + log.info("Sending activation email to " + user.getEmail()); + + + try { + jmc.sendMessageUsingFreemarkerTemplate(user); + } catch (IOException | TemplateException | MessagingException e) { + log.info("Mailing failed"); + log.info(e.getLocalizedMessage()); + } + ResultMessage msg = new ResultMessage(true, "User created"); + return new ResponseEntity(msg, HttpStatus.OK); + } + + /** + * Returns the number of participants in a a community managed by the + * owner of the token + * + * @params: The admin's token + * @return: The number of participants, if the user is and admin + * @return: A forbidden message otherwise + */ + @ApiOperation(value = "Get the number of users in a community from the administrator's token", response = User.class, tags = "") + @PostMapping("/getNumberOfParticipants") + ResponseEntity getNumberOfParticipants( + @ApiParam(name = "token", type = "String", value = "The administrator's token", example = "", required = true) @RequestParam String token) { + + + User u = new User(); + Boolean isValid = idpClientManager.isValid(token); + Integer result = 0; + + if (isValid) { + User userdto = idpClientManager.getUserByToken(token); + + u = userInterface.findBySubject(userdto.getUuid()); + if (u.hasRole(communityRoleAdmin) || u.hasRole(oracleRoleAdmin) || u.hasRole(platformRoleAdmin)) { + for (UserCommunity c : u.getUsercommunities()) { + result = userInterface.countBySubjectIsNotNullAndCommunityId(c.getId().getCommunityId()); + } + } + } else { + return new ResponseEntity("User is not an addmin", + HttpStatus.FORBIDDEN); + } + return new ResponseEntity(result, HttpStatus.OK); + } + + + /** + * Returns a user from a wallet if the token owner is an admin for the community + * + * @params: The wallet + * @params: the admin's token + * @return: The user, if the if the token belongs to an admin + * @return: A forbidden message otherwise + */ + @ApiOperation(value = "Get a user in a community from the wallet(s)", response = User.class, tags = "") + @PostMapping("/getUserFromWallet") + ResponseEntity getUserFromWallet( + @RequestBody List wallets, + @ApiParam(name = "token", type = "String", value = "The administrator's token", example = "", required = true) @RequestParam String token) { + LocalUserDTO lUserDTO = new LocalUserDTO(); + + User u = new User(); + Boolean isValid = idpClientManager.isValid(token); + + Map> resultMap = new HashMap>(); + + if (isValid) { + User userdto = idpClientManager.getUserByToken(token); + + u = userInterface.findBySubject(userdto.getUuid()); + if (u.hasRole(communityRoleAdmin) || u.hasRole(oracleRoleAdmin) || u.hasRole(platformRoleAdmin)) { + for (Community c : u.getCommunities()) { + List result = new ArrayList(); + for (String wallet : wallets) { + result.addAll(userInterface.findFromWalletAndCommunityId(wallet, c.getId())); + } + if (result.size() > 0) { + u = result.get(0); //qualcosa non va se ne trovo piu' di uno + UserDto userdtoNew = idpClientManager.getUserFromUUID( + u.getSubject()); + u.mergeWithDto(userdtoNew); + lUserDTO = dTOManager.userDTO(u); + return new ResponseEntity(lUserDTO, HttpStatus.OK); + } + } + } + if (u.hasRole(stakeHolderRole) || u.hasRole(communityMemberRole)) { + for (Community c : u.getCommunities()) { + List result = new ArrayList(); + for (String wallet : wallets) { + result.addAll(userInterface.findFromWalletAndCommunityId(wallet, c.getId())); + } + if (result.size() > 0) { + u = result.get(0); + UserDto userdtoNew = idpClientManager.getUserByEmail( + u.getSubject()); + u.mergeWithDto(userdtoNew); + lUserDTO.setEmail(u.getEmail()); + lUserDTO.setPhone(u.getPhone()); + return new ResponseEntity(lUserDTO, HttpStatus.OK); + } + } + } + + + } else { + return new ResponseEntity("User is not an addmin", + HttpStatus.FORBIDDEN); + } + return new ResponseEntity(lUserDTO, HttpStatus.OK); + } + + /** + * Returns the list of communities the user belongs to It uses the Keycloak + * application for controlling the requester's roles. This methd shall be + * duplicated for the Identity Provider tool + * + * @param: the JWT token of the user + * @return: The list of the user communities + * @return: Forbidden if the token is not valid + * @return: Forbidden if the user is not an administrator + */ + @ApiOperation(value = "Get all users in a community from the administrator's token", response = User.class, tags = "") + @PostMapping("/getusercommunities") + ResponseEntity> getUserCommunities( + @ApiParam(name = "token", type = "String", value = "The administrator's token", example = "", required = true) @RequestParam String token) { + + + User u = new User(); + List usersInCommunity = new ArrayList(); + List listOfUsers = new ArrayList(); + Boolean isValid = idpClientManager.isValid(token); + + + if (isValid) { + User userdto = idpClientManager.getUserByToken(token); + + u = userInterface.findBySubject(userdto.getUuid()); + if (u.hasRole(communityRoleAdmin) || u.hasRole(oracleRoleAdmin) || u.hasRole(platformRoleAdmin)) { + for (UserCommunity c : u.getUsercommunities()) { + usersInCommunity.addAll(userInterface.findBySubjectIsNotNullAndActiveIsTrueAndCommunityId(c.getId().getCommunityId())); + } + + for (User uTmp : usersInCommunity) { + + String subejct = uTmp.getSubject(); + log.info("email: " + subejct); + if (subejct != null && !subejct.isEmpty()) { + UserDto tmpUserDto = idpClientManager.getUserByEmail(subejct); + if (tmpUserDto != null) { + uTmp.mergeWithDto(tmpUserDto); + LocalUserDTO lUserDTO = dTOManager.userDTO(uTmp); + lUserDTO.setEmail(tmpUserDto.getEmail()); + listOfUsers.add(lUserDTO); + } + } + } + + + } else { + return new ResponseEntity("User is not an addmin", + HttpStatus.FORBIDDEN); + } + } else { + return new ResponseEntity("Provided token is not valid ", // headers, + HttpStatus.FORBIDDEN); + } + return new ResponseEntity>(listOfUsers, // headers, + HttpStatus.OK); + } + + + @ApiOperation(value = "Generate subject", response = String.class, tags = "") + @PostMapping("/generateSubject") + @Deprecated + ResponseEntity generateSubject( + @ApiParam(name = "mail", type = "String", value = "The user's email", example = "", required = false) + @RequestBody String email) { + //String subject = encryptionManager.encrypt(email); + + return new ResponseEntity("", HttpStatus.OK); + } + + + @ApiOperation(value = "Generate email", response = String.class, tags = "") + @PostMapping("/returnEmail") + @Deprecated + ResponseEntity generateEmail( + @ApiParam(name = "Subject", type = "String", value = "The user's subject", example = "", required = false) + @RequestBody String subject) { + //String email = encryptionManager.decrypt(subject); + + return new ResponseEntity("", HttpStatus.OK); + } + + + /** + * Returns the list of users if the requester is a platform admin This method + * shall be moved for using the Identity Provider tool + * + * @param: the JWT token of the user + * @return: The list of the users + * @return: Forbidden if the token is not valid + * @return: Forbidden if the user is not an administrator + */ + + @ApiOperation(value = "Get all users if the requester is a platform admin", response = User.class, tags = "") + @PostMapping("/getusers") + ResponseEntity> getUsers( + @ApiParam(name = "token", type = "String", value = "The administrator's token", example = "", required = false) @RequestParam(required = false) String token, + @ApiParam(name = "Authorization", type = "String", value = "The administrator's token", example = "", required = false) @RequestHeader(name = "Authorization", required = false) String tokenAuth) { + List users = new ArrayList(); + List resultList = new ArrayList(); + Boolean isValid = false; + User u = new User(); + User userdto; + String subject = ""; + if ((token == null || token.length() == 0) && (tokenAuth == null || tokenAuth.length() == 0)) { + return new ResponseEntity("Token has not been provided", // headers, + HttpStatus.FORBIDDEN); + } + if (token != null) { + //isValid = km.isValidToken(token); + + //if (isValid) { + /* Ok, I'm using the keycloak manager */ + //subject = JWTManager.getSubject(token); + //} + } else { + isValid = idpClientManager.isValid(tokenAuth); + if (isValid) { + userdto = idpClientManager.getUserByToken(tokenAuth); + subject = userdto.getUuid(); + } else { + return new ResponseEntity("Provided token is not valid ", // headers, + HttpStatus.FORBIDDEN); + } + + u = userInterface.findBySubject(userdto.getUuid()); + if (u.hasRole(platformRoleAdmin)) { + users = userInterface.findBySubjectIsNotNull(); + + for (User uTmp : users) { + + String subjectLocal = uTmp.getSubject(); + if (subjectLocal != null && !subjectLocal.isEmpty()) { + UserDto tmpUserDto = idpClientManager.getUserByEmail(subjectLocal); + if (tmpUserDto != null) { + uTmp.mergeWithDto(tmpUserDto); + LocalUserDTO lUserDTO = dTOManager.userDTO(uTmp); + lUserDTO.setEmail(tmpUserDto.getEmail()); + resultList.add(lUserDTO); + } + } + } + + + } else { + return new ResponseEntity("User is not a " + platformRoleAdmin, // headers, + HttpStatus.FORBIDDEN); + } + + } + return new ResponseEntity>(resultList, // headers, + HttpStatus.OK); + } + + // @ApiOperation(value = "Get all users as the requester is a platform admin", + // response = User.class, tags = "") + // @GetMapping("/getusers") + // ResponseEntity> getgetUsers( + // @ApiParam(name = "token", type = "String", value = "The administrator's + // token", example = "", required = true) + // @RequestParam String token) { + // return getUsers(token, ""); + // } // /** // * Returns the list of users belonging to a community @@ -750,489 +733,488 @@ public class UserController { // return new ResponseEntity>(usersInCommunity, HttpStatus.OK); // } - /** - * Delete the user from DB and ID-Provider - * - * @param: User: the user to be deleted - * @return: True if cancellation is complete - */ - @ApiOperation(value = "Delete the user.", response = Boolean.class, tags = "") - @DeleteMapping("/user/delete") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), - @ApiResponse(code = 403, message = "Token is null or not valid"), - @ApiResponse(code = 500, message = "User cannot delete from DBs"), }) - public ResponseEntity deleteUser( - @ApiParam(name = "userToken", type = "String", value = "The user's IDP token or email", example = "", required = true) @RequestBody String userToken) { - - // log.info("Deleting user with token = {} ", userToken); - if (userToken == null || userToken == "") { - log.info("Input is null "); - return new ResponseEntity(false, HttpStatus.FORBIDDEN); - } - Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", - Pattern.CASE_INSENSITIVE); - Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(userToken); - UserDto userdto = new UserDto(); - Boolean isEmail = false; - User userDel = new User(); - if (matcher.find()) { - log.info("Deleting user with email = {} ", userToken); - userdto = idpClientManager.getUserByEmail(userToken); - isEmail = true; + /** + * Delete the user from DB and ID-Provider + * + * @param: User: the user to be deleted + * @return: True if cancellation is complete + */ + @ApiOperation(value = "Delete the user.", response = Boolean.class, tags = "") + @DeleteMapping("/user/delete") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), + @ApiResponse(code = 403, message = "Token is null or not valid"), + @ApiResponse(code = 500, message = "User cannot delete from DBs"),}) + public ResponseEntity deleteUser( + @ApiParam(name = "userToken", type = "String", value = "The user's IDP token or email", example = "", required = true) @RequestBody String userToken) { + + // log.info("Deleting user with token = {} ", userToken); + if (userToken == null || userToken == "") { + log.info("Input is null "); + return new ResponseEntity(false, HttpStatus.FORBIDDEN); + } + Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$", + Pattern.CASE_INSENSITIVE); + Matcher matcher = VALID_EMAIL_ADDRESS_REGEX.matcher(userToken); + UserDto userdto = new UserDto(); + Boolean isEmail = false; + User userDel = new User(); + if (matcher.find()) { + log.info("Deleting user with email = {} ", userToken); + userdto = idpClientManager.getUserByEmail(userToken); + isEmail = true; + + } + if (idpClientManager.isValid(userToken)) { + log.info("Deleting user with token = {} ", userToken); + userDel = idpClientManager.getUserByToken(userToken); + } + if (userDel != null) { + Boolean resultIDPRemove = idpClientManager.deleteUser(userDel.getEmail()); + + if (!resultIDPRemove) { + log.info("Failed to delete user from ID-Provider"); + return new ResponseEntity(false, HttpStatus.INTERNAL_SERVER_ERROR); + } + + User user = userInterface.findBySubject(userdto.getUuid()); + + if (user == null) { + log.info("Failed to delete user from DB because the user does not exist"); + return new ResponseEntity(false, HttpStatus.INTERNAL_SERVER_ERROR); + } + userInterface.delete(user); + + } else if (isEmail) { + User user = userInterface.findBySubject(userdto.getUuid()); + if (user == null) { + log.info("Failed to delete user from DB because the user does not exist"); + return new ResponseEntity(false, HttpStatus.INTERNAL_SERVER_ERROR); + } + userInterface.delete(user); + } else { + log.info("Provided input is not valid or user not present in IDP", userToken); + return new ResponseEntity(false, HttpStatus.FORBIDDEN); + } + return new ResponseEntity(true, HttpStatus.OK); + } + + /** + * Login the user by providing user's details if username and password are + * correct. + * + * @param: Username: the user's username + * @param: Password: the user's password + * @return: a full user if both username and password are correct, an empty user + * if not. + */ + + @ApiOperation(value = "Login the user. Returns Http.OK and User object if username and password are valid, Http.Forbidden otherwise", response = User.class, tags = "") + @PostMapping("/user/login") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), + @ApiResponse(code = 403, message = "Username or password are invalid")}) + ResponseEntity login( + @ApiParam(name = "username", type = "String", value = "The username", example = "", required = true) @RequestParam String username, + @ApiParam(name = "password", type = "String", value = "The password", example = "", required = true) @RequestParam String password) { + if (StringUtils.isBlank(username) || StringUtils.isBlank(username)) { + log.info("Username or password are empty"); + return new ResponseEntity<>(new LocalUserDTO(), HttpStatus.FORBIDDEN); + } + + User userdto = idpClientManager.login(username, password); + if (userdto == null) { + log.info("Wrong username or password"); + return new ResponseEntity<>(new LocalUserDTO(), HttpStatus.FORBIDDEN); + } + + log.info("UUID: " + userdto.getSubject()); + + User user = userInterface.findBySubject(userdto.getSubject()); + if (user == null) { + log.info("Adding into local DB"); + User tempUser = new User(); + tempUser.setSubject(userdto.getSubject()); + tempUser.merge(userdto); + + tempUser = userInterface.save(tempUser); + LocalUserDTO lUserDTO = dTOManager.userDTO(tempUser); + + return new ResponseEntity(lUserDTO, HttpStatus.OK); + } + for (Device d : user.getDevices()) { + log.info(d.getDevicename()); + } + + user.merge(userdto); + + LocalUserDTO lUserDTO = dTOManager.userDTO(user); + log.info(lUserDTO.toString()); + + return new ResponseEntity<>(lUserDTO, HttpStatus.OK); + } + + /** + * Logout the user using the token + * + * @param: User Token + * @return: True if the user is correctly logged out, false otherwise + */ + @ApiOperation(value = "Logout the user. Returns Http.OK and User object if username and password are valid, Http.Forbidden otherwise", response = Boolean.class, tags = "") + @PostMapping("/user/logout") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), + @ApiResponse(code = 500, message = "Logout has failed for unknown causes")}) + ResponseEntity logout( + @ApiParam(name = "token", type = "String", value = "The user's token", example = "", required = true) @RequestParam String token, + @RequestHeader(name = "Authorization", required = false) String tokenAuth) { + if (StringUtils.isBlank(token)) { + if (StringUtils.isBlank(tokenAuth)) { + log.info("Token is empty"); + return new ResponseEntity<>(false, HttpStatus.INTERNAL_SERVER_ERROR); + } else + token = tokenAuth; + } + Boolean result = idpClientManager.logout(token); + + if (result) { + return new ResponseEntity<>(result, HttpStatus.OK); + } else { + log.info("Failed to logout"); + return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR); + } + + } + + /** + * Check if the token is valid and alive + * + * @param: User Token + * @return: True if the user is the token is valid, false otherwise + */ + @ApiOperation(value = "Check if the token is valid and return a boolean", response = Boolean.class, tags = "") + @PostMapping("/user/isTokenValid") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), + @ApiResponse(code = 403, message = "Token not valid"), + @ApiResponse(code = 500, message = "Token is null")}) + ResponseEntity checkToken( + @RequestHeader(name = "Authorization", required = false) String token, + @ApiParam(name = "token", type = "String", value = "The user's token", example = "", required = false) + @RequestParam(name = "token", required = false) String token2) { + token = StringUtils.isNotBlank(token) ? token : token2; + if (!StringUtils.isNotBlank(token)) { + log.info("Token is empty"); + return new ResponseEntity(false, HttpStatus.INTERNAL_SERVER_ERROR); + } + Boolean result = idpClientManager.isValid(token); + + if (result) { + return new ResponseEntity<>(result, HttpStatus.OK); + } else { + return new ResponseEntity<>(result, HttpStatus.FORBIDDEN); + } + + } + + /** + * Returns the list of available roles on the platform + * + * @return: A list of Roles + */ + + @ApiOperation(value = "Return the list of the roles active on the platform", response = Role.class, tags = "") + @GetMapping("/role/listRoles") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), + @ApiResponse(code = 500, message = "Internal error")}) + ResponseEntity> getRoles() { + List result = roleInterface.findAll(); + if (result != null) { + return new ResponseEntity>(result, HttpStatus.OK); + } else { + return new ResponseEntity>(result, HttpStatus.INTERNAL_SERVER_ERROR); + } + + } + + User getUserFromJWTToken(String token) { + User user = new User(); + + String[] chunks = token.split("\\."); + Base64.Decoder decoder = Base64.getUrlDecoder(); + String header = new String(decoder.decode(chunks[0])); + + JSONObject payloadObj = new JSONObject(new String(decoder.decode(chunks[1]))); + + UserToken userToken = new UserToken(); + userToken.setValue(token); + + user.setUsername(payloadObj.getString("username")); + user.setName(payloadObj.getString("name")); + user.setEmail(payloadObj.getString("email")); + user.setSurname(payloadObj.getString("family_name")); + user.setSubject(payloadObj.getString("sub")); + + return user; + + } + + + /** + * Check if the token is valid and returns the user's details + * + * @param: User Token + * @return: the user's details if the token is valid, an error otherwise + */ + @ApiOperation(value = "Check if the token is valid and return the user", response = Boolean.class, tags = "") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), + @ApiResponse(code = 403, message = "Token not valid or access forbidden"), + @ApiResponse(code = 500, message = "Token is null")}) + @PostMapping("/user/getUserFromToken") + ResponseEntity getUserFromToken( + @ApiParam(name = "token", type = "String", value = "The user's ID-Provider token", example = "", required = true) + @RequestParam String token + ) { + + if (token == null || token == "") { + log.info("GetUserFromToken: Token is empty"); + return new ResponseEntity<>(new LocalUserDTO(), HttpStatus.BAD_REQUEST); + } + + Boolean isJWT = checkIsJWTToken(token); + User userdto = new User(); + if (isJWT == false) { + userdto = idpClientManager.getUserByToken(token); + } else { + //è un token JWT + userdto = getUserFromJWTToken(token); + } + + if (userdto == null) { + log.info("User not found on ID-Provider - Token is not valid"); + + return new ResponseEntity(new LocalUserDTO(), HttpStatus.FORBIDDEN); + } + User user = getUserFromSubject(userdto.getUuid()); + if (user == null) { + + log.info("User not found on local DB"); + /*@TO-DO + * L'utente e' registrato nell'identity provider e quindi dovrei abilitarlo anche localmente, mandandolo pero' nella pagina per + * completare la registrazione. + */ + + LocalUserDTO lUDto = dTOManager.userDTO(userdto); + lUDto.setNewUser(true); + + return new ResponseEntity(lUDto, HttpStatus.OK); + } + user.merge(userdto); + + LocalUserDTO lUserDTO = dTOManager.userDTO(user); + + log.info(lUserDTO); + + return new ResponseEntity(lUserDTO, HttpStatus.OK); + + } + + /** + * Check if the token is valid and returns the user's id code + * + * @param: User Token + * @return: the user's details if the token is valid, an error otherwise + */ + @ApiOperation(value = "Check if the token is valid and return the user's id", response = Boolean.class, tags = "") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), + @ApiResponse(code = 403, message = "Token not valid or access forbidden"), + @ApiResponse(code = 500, message = "Token is null")}) + @PostMapping("/user/getUserIdFromToken") + ResponseEntity getUserFromIdToken( + @ApiParam(name = "Authorization", type = "String", value = "The user's ID-Provider token", example = "", required = true) @RequestHeader(name = "Authorization", required = true) String token) { + User result = new User(); + + if (token == null || token == "") { + log.info("Token is empty"); + return new ResponseEntity(0, HttpStatus.INTERNAL_SERVER_ERROR); + } + User userdto = idpClientManager.getUserByToken(token); + + if (userdto == null) { + log.info("User not found on ID-Provider - Token is not valid"); + + return new ResponseEntity(0, HttpStatus.FORBIDDEN); + } + //String subject = encryptionManager.encrypt(userdto.getEmail()); + User user = getUserFromSubject(userdto.getUuid()); + if (user == null) { + log.info("User not found on local DB"); + + return new ResponseEntity(0, HttpStatus.FORBIDDEN); + } + user.merge(userdto); + + return new ResponseEntity(user.getUserid().intValue(), HttpStatus.OK); + + } + + /** + * Update the user's password if the tkoen is valid + */ + @PostMapping("/user/updatepassword") + public ResponseEntity updatePassword( + @ApiParam(name = "Password", type = "Password", value = "User's new pasword", example = "", required = true) + @RequestBody LocalUserDTO userDTO, + @RequestHeader(name = "Authorization", required = false) String token) { + + User userdto = idpClientManager.getUserByToken(token); + + if (userdto == null) { + log.info("User not found on ID-Provider - Token is not valid"); + return new ResponseEntity(false, HttpStatus.FORBIDDEN); + } + + Boolean result = idpClientManager.updatePassword(token, userDTO.getPassword()); + + return new ResponseEntity(result, HttpStatus.OK); + + } + + /** + * Update the user's password if the tkoen is valid + */ + @PostMapping("/user/update") + public ResponseEntity updateUserInfo( + @RequestBody LocalUserDTO userDTO, + @RequestHeader(name = "Authorization", required = false) String token) { + + User userdto = idpClientManager.getUserByToken(token); + + + if (userdto == null) { + log.info("User not found on ID-Provider - Token is not valid"); + return new ResponseEntity(false, HttpStatus.FORBIDDEN); + } + + User tmpUser = userInterface.findBySubject(userdto.getUuid()); + + if (tmpUser == null) { + tmpUser = new User(); + tmpUser.setSubject(userdto.getUuid()); + } + + for (CommunityDTO cDto : userDTO.getUsercommunities()) { + Community c = communityInterface.findById(cDto.getCommunityid()).get(); + if (tmpUser.getCommunities() == null || !tmpUser.getCommunities().contains(c)) { + UserCommunity uc1 = new UserCommunity(); + uc1.setCommunity(c); + uc1.setUser(tmpUser); + uc1.setWallet(cDto.getWallet()); + uc1.setSubscriptiondate(new Date(System.currentTimeMillis())); + uc1.setActive(true); + tmpUser.setSingleUsercommunity(uc1); + Role tmpRole = roleInterface.getById(new Long(2)); + UserRole ur = new UserRole(); + ur.setCommunity(c); + ur.setUser(tmpUser); + ur.setRole(tmpRole); + tmpUser.setSingleUserRole(ur); + } + } + try { + tmpUser = userInterface.save(tmpUser); + } catch (Exception e) { + log.info("Eccezione " + e.getLocalizedMessage()); + } + log.info("user saved, probably... the number of available users is " + userInterface.count()); - } - if (idpClientManager.isValid(userToken)) { - log.info("Deleting user with token = {} ", userToken); - userDel = idpClientManager.getUserByToken(userToken); - } - if (userDel != null) { - Boolean resultIDPRemove = idpClientManager.deleteUser(userDel.getEmail()); + Boolean result = true; - if (!resultIDPRemove) { - log.info("Failed to delete user from ID-Provider"); - return new ResponseEntity(false, HttpStatus.INTERNAL_SERVER_ERROR); - } + return new ResponseEntity(result, HttpStatus.OK); - User user = userInterface.findBySubject(userdto.getUuid()); + } - if (user == null) { - log.info("Failed to delete user from DB because the user does not exist"); - return new ResponseEntity(false, HttpStatus.INTERNAL_SERVER_ERROR); - } - userInterface.delete(user); - } else if (isEmail) { - User user = userInterface.findBySubject(userdto.getUuid()); - if (user == null) { - log.info("Failed to delete user from DB because the user does not exist"); - return new ResponseEntity(false, HttpStatus.INTERNAL_SERVER_ERROR); - } - userInterface.delete(user); - } else { - log.info("Provided input is not valid or user not present in IDP", userToken); - return new ResponseEntity(false, HttpStatus.FORBIDDEN); - } - return new ResponseEntity(true, HttpStatus.OK); - } + /** + * List the devices associated to a user + * + * @param: User Token + * @return: the user's details if the token is valid, an error otherwise + */ + @ApiOperation(value = "List the devices associated to a user", response = Boolean.class, tags = "") + @ApiResponses(value = {@ApiResponse(code = 200, message = "Success"), + @ApiResponse(code = 403, message = "Token not valid or access forbidden"), + @ApiResponse(code = 500, message = "Token is null")}) + @PostMapping("/user/getDevices") + ResponseEntity getDevices( + @ApiParam(name = "token", type = "String", value = "The user's ID-Provider token", example = "", required = true) @RequestParam String token) { - /** - * Login the user by providing user's details if username and password are - * correct. - * - * @param: Username: the user's username - * @param: Password: the user's password - * @return: a full user if both username and password are correct, an empty user - * if not. - */ - - @ApiOperation(value = "Login the user. Returns Http.OK and User object if username and password are valid, Http.Forbidden otherwise", response = User.class, tags = "") - @PostMapping("/user/login") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), - @ApiResponse(code = 403, message = "Username or password are invalid") }) - ResponseEntity login( - @ApiParam(name = "username", type = "String", value = "The username", example = "", required = true) @RequestParam String username, - @ApiParam(name = "password", type = "String", value = "The password", example = "", required = true) @RequestParam String password) { - if (username == null || username == "" || password == null || password == "") { - log.info("Username or password are empty"); - return new ResponseEntity(new LocalUserDTO(), HttpStatus.FORBIDDEN); - } + List result = new ArrayList(); - User userdto = idpClientManager.login(username, password); - if (userdto == null) { - log.info("Wrong username or password"); - return new ResponseEntity(new LocalUserDTO(), HttpStatus.FORBIDDEN); - } - - log.info("UUID: " + userdto.getSubject()); - - User user = userInterface.findBySubject(userdto.getSubject()); - if (user == null) { - log.info("Adding into local DB"); - User tempUser = new User(); - tempUser.setSubject(userdto.getSubject()); - tempUser.merge(userdto); - - tempUser = userInterface.save(tempUser); - LocalUserDTO lUserDTO = dTOManager.userDTO(tempUser); - - return new ResponseEntity(lUserDTO, HttpStatus.OK); - } - for (Device d : user.getDevices()) { - log.info(d.getDevicename()); - } + if (token == null || token == "") { + log.info("Token is empty"); + return new ResponseEntity>(result, HttpStatus.INTERNAL_SERVER_ERROR); + } + User userdto = idpClientManager.getUserByToken(token); - user.merge(userdto); - - LocalUserDTO lUserDTO = dTOManager.userDTO(user); - log.info(lUserDTO.toString()); - - return new ResponseEntity<>(lUserDTO, HttpStatus.OK); - } + if (userdto == null) { + log.info("User not found on ID-Provider - Token is not valid"); - /** - * Logout the user using the token - * - * @param: User Token - * @return: True if the user is correctly logged out, false otherwise - */ - @ApiOperation(value = "Logout the user. Returns Http.OK and User object if username and password are valid, Http.Forbidden otherwise", response = Boolean.class, tags = "") - @PostMapping("/user/logout") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), - @ApiResponse(code = 500, message = "Logout has failed for unknown causes") }) - ResponseEntity logout( - @ApiParam(name = "token", type = "String", value = "The user's token", example = "", required = true) @RequestParam String token, - @RequestHeader(name = "Authorization", required = false) String tokenAuth) { - if (token == null || token == "") { - if (tokenAuth == null || tokenAuth == "") { - log.info("Token is empty"); - return new ResponseEntity(false, HttpStatus.INTERNAL_SERVER_ERROR); - } else - token = tokenAuth; - } - Boolean result = idpClientManager.logout(token); + return new ResponseEntity>(result, HttpStatus.FORBIDDEN); + } + //String subject = encryptionManager.encrypt(userdto.getEmail()); + User user = getUserFromSubject(userdto.getUuid()); + if (user == null) { + log.info("User not found on local DB"); - if (result) { - return new ResponseEntity(result, HttpStatus.OK); - } else { - log.info("Failed to logout"); - return new ResponseEntity(result, HttpStatus.INTERNAL_SERVER_ERROR); - } + return new ResponseEntity>(result, HttpStatus.FORBIDDEN); + } - } + try { + result = userInterface.findAllDevicesByUserid(user.getUserid()); - /** - * Check if the token is valid and alive - * - * @param: User Token - * @return: True if the user is the token is valid, false otherwise - */ - @ApiOperation(value = "Check if the token is valid and return a boolean", response = Boolean.class, tags = "") - @PostMapping("/user/isTokenValid") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), - @ApiResponse(code = 403, message = "Token not valid"), - @ApiResponse(code = 500, message = "Token is null") }) - ResponseEntity checkToken( - @RequestHeader(name = "Authorization", required = false) String token, - @ApiParam(name = "token", type = "String", value = "The user's token", example = "", required = false) - @RequestParam (name = "token", required = false) String token2 ) { - token = StringUtils.hasText(token) ? token : token2; - if (!StringUtils.hasText(token)) { - log.info("Token is empty"); - return new ResponseEntity(false, HttpStatus.INTERNAL_SERVER_ERROR); - } - Boolean result = idpClientManager.isValid(token); + } catch (Exception e) { + System.out.println(e.getLocalizedMessage()); + } + return new ResponseEntity>(result, HttpStatus.OK); - if (result) { - return new ResponseEntity(result, HttpStatus.OK); - } else { - return new ResponseEntity(result, HttpStatus.FORBIDDEN); - } + } - } + public User persistNewUser(User u, Community c, Role r) { - /** - * Returns the list of available roles on the platform - * - * @return: A list of Roles - */ - - @ApiOperation(value = "Return the list of the roles active on the platform", response = Role.class, tags = "") - @GetMapping("/role/listRoles") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), - @ApiResponse(code = 500, message = "Internal error") }) - ResponseEntity> getRoles() { - List result = roleInterface.findAll(); - if (result != null) { - return new ResponseEntity>(result, HttpStatus.OK); - } else { - return new ResponseEntity>(result, HttpStatus.INTERNAL_SERVER_ERROR); - } + UserCommunity uc = new UserCommunity(); + uc.setCommunity(c); + uc.setUser(u); - } - - User getUserFromJWTToken(String token) { - User user = new User(); - - String[] chunks = token.split("\\."); - Base64.Decoder decoder = Base64.getUrlDecoder(); - String header = new String(decoder.decode(chunks[0])); - - JSONObject payloadObj = new JSONObject(new String(decoder.decode(chunks[1]))); - - UserToken userToken = new UserToken(); - userToken.setValue(token); - - user.setUsername(payloadObj.getString("username")); - user.setName(payloadObj.getString("name")); - user.setEmail(payloadObj.getString("email")); - user.setSurname(payloadObj.getString("family_name")); - user.setSubject(payloadObj.getString("sub")); - - return user; - - } + u.setSingleUsercommunity(uc); + UserRole ur = new UserRole(); - /** - * Check if the token is valid and returns the user's details - * - * @param: User Token - * @return: the user's details if the token is valid, an error otherwise - */ - @ApiOperation(value = "Check if the token is valid and return the user", response = Boolean.class, tags = "") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), - @ApiResponse(code = 403, message = "Token not valid or access forbidden"), - @ApiResponse(code = 500, message = "Token is null") }) - @PostMapping("/user/getUserFromToken") - ResponseEntity getUserFromToken( - @ApiParam(name = "token", type = "String", value = "The user's ID-Provider token", example = "", required = true) - @RequestParam String token - ) { - - if (token == null || token == "") { - log.info("GetUserFromToken: Token is empty"); - return new ResponseEntity<>(new LocalUserDTO(), HttpStatus.BAD_REQUEST); - } - - Boolean isJWT = checkIsJWTToken(token); - User userdto = new User(); - if (isJWT == false) { - userdto = idpClientManager.getUserByToken(token);} - else { - //è un token JWT - userdto = getUserFromJWTToken(token); - } + ur.setRole(r); + ur.setCommunity(c); + ur.setUser(u); + u.addUserRole(ur); - if (userdto == null) { - log.info("User not found on ID-Provider - Token is not valid"); + userInterface.save(u); - return new ResponseEntity(new LocalUserDTO(), HttpStatus.FORBIDDEN); - } - User user = getUserFromSubject(userdto.getUuid()); - if (user == null) { - - log.info("User not found on local DB"); - /*@TO-DO - * L'utente e' registrato nell'identity provider e quindi dovrei abilitarlo anche localmente, mandandolo pero' nella pagina per - * completare la registrazione. - */ - - LocalUserDTO lUDto = dTOManager.userDTO(userdto); - lUDto.setNewUser(true); - - return new ResponseEntity(lUDto, HttpStatus.OK); - } - user.merge(userdto); + return u; - LocalUserDTO lUserDTO = dTOManager.userDTO(user); + } - log.info(lUserDTO); + private User persistNewUserWithCommunityIdAndRoleId(User u, Long cId, Long rId) { - return new ResponseEntity(lUserDTO, HttpStatus.OK); + Community c = communityInterface.findById(cId).get(); - } + Role r = roleInterface.findById(rId).get(); - /** - * Check if the token is valid and returns the user's id code - * - * @param: User Token - * @return: the user's details if the token is valid, an error otherwise - */ - @ApiOperation(value = "Check if the token is valid and return the user's id", response = Boolean.class, tags = "") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), - @ApiResponse(code = 403, message = "Token not valid or access forbidden"), - @ApiResponse(code = 500, message = "Token is null") }) - @PostMapping("/user/getUserIdFromToken") - ResponseEntity getUserFromIdToken( - @ApiParam(name = "Authorization", type = "String", value = "The user's ID-Provider token", example = "", required = true) @RequestHeader(name = "Authorization", required = true) String token) { - User result = new User(); - - if (token == null || token == "") { - log.info("Token is empty"); - return new ResponseEntity(0, HttpStatus.INTERNAL_SERVER_ERROR); - } - User userdto = idpClientManager.getUserByToken(token); + return persistNewUser(u, c, r); - if (userdto == null) { - log.info("User not found on ID-Provider - Token is not valid"); + } - return new ResponseEntity(0, HttpStatus.FORBIDDEN); - } - //String subject = encryptionManager.encrypt(userdto.getEmail()); - User user = getUserFromSubject(userdto.getUuid()); - if (user == null) { - log.info("User not found on local DB"); + private User persistNewUserWithCommunityNameAndRoleName(User u, String cName, String rName) { + Community c = communityInterface.findByCommunityName(cName); - return new ResponseEntity(0, HttpStatus.FORBIDDEN); - } - user.merge (userdto); - - return new ResponseEntity(user.getUserid().intValue(), HttpStatus.OK); - - } - /** - * Update the user's password if the tkoen is valid - * - */ - @PostMapping("/user/updatepassword") - public ResponseEntity updatePassword( - @ApiParam(name = "Password", type = "Password", value = "User's new pasword", example = "", required = true) - @RequestBody LocalUserDTO userDTO, - @RequestHeader(name = "Authorization", required = false) String token) { - - User userdto = idpClientManager.getUserByToken(token); - - if (userdto == null) { - log.info("User not found on ID-Provider - Token is not valid"); - return new ResponseEntity(false, HttpStatus.FORBIDDEN); - } - - Boolean result = idpClientManager.updatePassword(token, userDTO.getPassword()); - - return new ResponseEntity(result, HttpStatus.OK); - - } - - /** - * Update the user's password if the tkoen is valid - * - */ - @PostMapping("/user/update") - public ResponseEntity updateUserInfo( - @RequestBody LocalUserDTO userDTO, - @RequestHeader(name = "Authorization", required = false) String token) { - - User userdto = idpClientManager.getUserByToken(token); - - - if (userdto == null) { - log.info("User not found on ID-Provider - Token is not valid"); - return new ResponseEntity(false, HttpStatus.FORBIDDEN); - } - - User tmpUser = userInterface.findBySubject(userdto.getUuid()); - - if (tmpUser == null) { - tmpUser = new User(); - tmpUser.setSubject(userdto.getUuid()); - } - - for (CommunityDTO cDto : userDTO.getUsercommunities()) { - Community c = communityInterface.findByCommunityid(cDto.getCommunityid()); - if (tmpUser.getCommunities() == null || !tmpUser.getCommunities().contains(c)) { - UserCommunity uc1 = new UserCommunity(); - uc1.setCommunity(c); - uc1.setUser(tmpUser); - uc1.setWallet(cDto.getWallet()); - uc1.setSubscriptiondate(new Date(System.currentTimeMillis())); - uc1.setActive(true); - tmpUser.setSingleUsercommunity(uc1); - Role tmpRole = roleInterface.getById(new Long(2)); - UserRole ur = new UserRole(); - ur.setCommunity(c); - ur.setUser(tmpUser); - ur.setRole(tmpRole); - tmpUser.setSingleUserRole(ur); - } - } - try { - tmpUser = userInterface.save(tmpUser); - }catch (Exception e) { - log.info("Eccezione " + e.getLocalizedMessage()); - } - log.info("user saved, probably... the number of available users is " + userInterface.count()); - - Boolean result = true; - - return new ResponseEntity(result, HttpStatus.OK); - - } - - - /** - * List the devices associated to a user - * - * @param: User Token - * @return: the user's details if the token is valid, an error otherwise - */ - @ApiOperation(value = "List the devices associated to a user", response = Boolean.class, tags = "") - @ApiResponses(value = { @ApiResponse(code = 200, message = "Success"), - @ApiResponse(code = 403, message = "Token not valid or access forbidden"), - @ApiResponse(code = 500, message = "Token is null") }) - @PostMapping("/user/getDevices") - ResponseEntity getDevices( - @ApiParam(name = "token", type = "String", value = "The user's ID-Provider token", example = "", required = true) @RequestParam String token) { - - List result = new ArrayList(); - - if (token == null || token == "") { - log.info("Token is empty"); - return new ResponseEntity>(result, HttpStatus.INTERNAL_SERVER_ERROR); - } - User userdto = idpClientManager.getUserByToken(token); - - if (userdto == null) { - log.info("User not found on ID-Provider - Token is not valid"); + Role r = roleInterface.findByRolename(rName); - return new ResponseEntity>(result, HttpStatus.FORBIDDEN); - } - //String subject = encryptionManager.encrypt(userdto.getEmail()); - User user = getUserFromSubject(userdto.getUuid()); - if (user == null) { - log.info("User not found on local DB"); - - return new ResponseEntity>(result, HttpStatus.FORBIDDEN); - } - - try { - result = userInterface.findAllDevicesByUserid(user.getUserid()); + return persistNewUser(u, c, r); - } catch (Exception e) { - System.out.println(e.getLocalizedMessage()); - } - return new ResponseEntity>(result, HttpStatus.OK); - - } - - public User persistNewUser(User u, Community c, Role r) { - - UserCommunity uc = new UserCommunity(); - uc.setCommunity(c); - uc.setUser(u); - - u.setSingleUsercommunity(uc); - - UserRole ur = new UserRole(); - - ur.setRole(r); - ur.setCommunity(c); - ur.setUser(u); - u.addUserRole(ur); - - userInterface.save(u); - - return u; - - } - - private User persistNewUserWithCommunityIdAndRoleId(User u, Long cId, Long rId) { - - Community c = communityInterface.findByCommunityid(cId); - - Role r = roleInterface.findById(rId).get(); - - return persistNewUser(u, c, r); - - } - - private User persistNewUserWithCommunityNameAndRoleName(User u, String cName, String rName) { - Community c = communityInterface.findByCommunityName(cName); - - Role r = roleInterface.findByRolename(rName); - - return persistNewUser(u, c, r); - - } + } // // private void deleteUserBySubject(String subject) { // User newUser; @@ -1278,52 +1260,51 @@ public class UserController { // // } - public User getUserFromSubject(String subject) { - User user = new User(); - try { - user = userInterface.findBySubject(subject); + public User getUserFromSubject(String subject) { + User user = new User(); + try { + user = userInterface.findBySubject(subject); + + } catch (Exception e) { + log.info(e.getLocalizedMessage()); + return user; + + } + return user; + } + + @Getter + @Setter + @AllArgsConstructor + @NoArgsConstructor + private class ResultMessage { + private Boolean success; + private String message; + + } + + public User getLocalUserFromToken(String token) { + User user = new User(); + Boolean isValid = idpClientManager.isValid(token); + + if (isValid) { + User userdto = idpClientManager.getUserByToken(token); + + user = userInterface.findBySubject(userdto.getUuid()); + } + return user; + } + + private Boolean checkIsJWTToken(String token) { + + String[] chunks = token.split("\\."); + Base64.Decoder decoder = Base64.getUrlDecoder(); + + String header = new String(decoder.decode(chunks[0])); + if (header.contains("JWT")) return true; + + return false; + } - } catch (Exception e) { - log.info(e.getLocalizedMessage()); - return user; - } - return user; - } - - @Getter - @Setter - @AllArgsConstructor - @NoArgsConstructor - private class ResultMessage{ - private Boolean success; - private String message; - - } - - public User getLocalUserFromToken(String token) { - User user = new User(); - Boolean isValid = idpClientManager.isValid(token); - - if (isValid) { - User userdto = idpClientManager.getUserByToken(token); - - user = userInterface.findBySubject(userdto.getUuid()); - } - return user; - } - - private Boolean checkIsJWTToken(String token) { - - String[] chunks = token.split("\\."); - Base64.Decoder decoder = Base64.getUrlDecoder(); - - String header = new String(decoder.decode(chunks[0])); - if (header.contains("JWT")) return true; - - return false; - } - - - } diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/structure/ColumnCommentDTO.java b/gecoregistration/src/main/java/it/enea/cruise/dto/ColumnCommentDTO.java similarity index 95% rename from gecoregistration/src/main/java/it/enea/cruise/model/structure/ColumnCommentDTO.java rename to gecoregistration/src/main/java/it/enea/cruise/dto/ColumnCommentDTO.java index 0a4ce5e5daa50907aff4a63f43822eeb1cf5d981..9c584fdd660052ad39da06d9dd949cb2049206fe 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/structure/ColumnCommentDTO.java +++ b/gecoregistration/src/main/java/it/enea/cruise/dto/ColumnCommentDTO.java @@ -1,4 +1,4 @@ -package it.enea.cruise.model.structure; +package it.enea.cruise.dto; import java.util.HashMap; import java.util.List; diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/structure/DescriptionDTO.java b/gecoregistration/src/main/java/it/enea/cruise/dto/DescriptionDTO.java similarity index 84% rename from gecoregistration/src/main/java/it/enea/cruise/model/structure/DescriptionDTO.java rename to gecoregistration/src/main/java/it/enea/cruise/dto/DescriptionDTO.java index def57f49629dbb2d0760503614f8d45ed00933c9..27d9d46e250919dcabbd75082a8b404ea3791708 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/structure/DescriptionDTO.java +++ b/gecoregistration/src/main/java/it/enea/cruise/dto/DescriptionDTO.java @@ -1,4 +1,4 @@ -package it.enea.cruise.model.structure; +package it.enea.cruise.dto; import lombok.Getter; import lombok.Setter; diff --git a/gecoregistration/src/main/java/it/enea/cruise/dto/LocalUserDTO.java b/gecoregistration/src/main/java/it/enea/cruise/dto/LocalUserDTO.java index e27a748d9bd9881cac2175a1fbbce1649e7954e3..b8f307e13e0d212f51fda8983f66014d0c858496 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/dto/LocalUserDTO.java +++ b/gecoregistration/src/main/java/it/enea/cruise/dto/LocalUserDTO.java @@ -4,7 +4,6 @@ import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; -import it.enea.cruise.model.user.UserToken; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/structure/TableCommentDTO.java b/gecoregistration/src/main/java/it/enea/cruise/dto/TableCommentDTO.java similarity index 94% rename from gecoregistration/src/main/java/it/enea/cruise/model/structure/TableCommentDTO.java rename to gecoregistration/src/main/java/it/enea/cruise/dto/TableCommentDTO.java index ff3fedbf2637de7c88df67c42b2bb70e098ddf07..62b4e34c6a1c4c201bc3dfdf3f36ef47d9f93742 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/structure/TableCommentDTO.java +++ b/gecoregistration/src/main/java/it/enea/cruise/dto/TableCommentDTO.java @@ -1,4 +1,4 @@ -package it.enea.cruise.model.structure; +package it.enea.cruise.dto; import java.util.HashMap; import java.util.List; diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/UserToken.java b/gecoregistration/src/main/java/it/enea/cruise/dto/UserToken.java similarity index 81% rename from gecoregistration/src/main/java/it/enea/cruise/model/user/UserToken.java rename to gecoregistration/src/main/java/it/enea/cruise/dto/UserToken.java index 18a29be906c3e9b02d25f8f20e196e273b32a90d..9502bc2e256bb26c17354103559d72fd10bafc34 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/UserToken.java +++ b/gecoregistration/src/main/java/it/enea/cruise/dto/UserToken.java @@ -1,14 +1,15 @@ -package it.enea.cruise.model.user; +package it.enea.cruise.dto; import java.util.Date; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; +import lombok.*; @Getter @Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor @ToString() public class UserToken { @@ -16,8 +17,6 @@ public class UserToken { private Date expiration; private String value; - public UserToken() {} - // public Date getCreation() { // return creation; // } diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/Cluster.java b/gecoregistration/src/main/java/it/enea/cruise/model/Cluster.java index 71b53b977474f7b825cd70d97853dff89c9eff66..15fb3f11e084e54d93b3fbb75e53d70f92a3f84e 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/Cluster.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/Cluster.java @@ -10,10 +10,10 @@ import lombok.Getter; import lombok.Setter; @Entity -@Table (name = "Cluster") +@Table (name = "clusters") @Getter @Setter -public class Cluster implements Serializable{ +public class Cluster implements Serializable { @Id private Integer clusterid; diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/ClusterGroup.java b/gecoregistration/src/main/java/it/enea/cruise/model/ClusterGroup.java index c32d7a4cbcb81a4eb0d4e92532a65ff367fa7992..c0918ab56c18ec37c26b6bfd0b00d171238b014f 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/ClusterGroup.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/ClusterGroup.java @@ -9,9 +9,9 @@ import lombok.Getter; import lombok.Setter; @Entity -@Table (name = "clustergroups") @Getter @Setter +@Table (name = "clustergroups") public class ClusterGroup { @Id diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/Flow.java b/gecoregistration/src/main/java/it/enea/cruise/model/Flow.java deleted file mode 100644 index 2f93b68ce4349534b029911a76b216793cbe7cfb..0000000000000000000000000000000000000000 --- a/gecoregistration/src/main/java/it/enea/cruise/model/Flow.java +++ /dev/null @@ -1,231 +0,0 @@ -package it.enea.cruise.model; - -import java.io.Serializable; -import javax.persistence.*; - - -/** - * The persistent class for the flows database table. - * - */ -@Entity -@Table(name="flows") -@NamedQuery(name="Flow.findAll", query="SELECT f FROM Flow f") -public class Flow implements Serializable { - private static final long serialVersionUID = 1L; - - @Id - private Integer flowid; - - private String channeldescription; - - private String cronfrequence; - - private String dataformatreference; - - private Integer datasyntax; - - private String description; - - private String endtime; - - private String flowname; - - private Integer frequence; - - private Integer frequencederogation; - - private Integer gdprclassification; - - private String measurecronfrequence; - - private Integer measurefrequence; - - private Integer measurefrequencederogation; - - private Integer measurementtable; - - private Integer measurementtype; - - private String note; - - private String onerrordo; - - private String starttime; - - private Integer supplierid; - - private String userightsstatement; - - public Flow() { - } - - public Integer getFlowid() { - return this.flowid; - } - - public void setFlowid(Integer flowid) { - this.flowid = flowid; - } - - public String getChanneldescription() { - return this.channeldescription; - } - - public void setChanneldescription(String channeldescription) { - this.channeldescription = channeldescription; - } - - public String getCronfrequence() { - return this.cronfrequence; - } - - public void setCronfrequence(String cronfrequence) { - this.cronfrequence = cronfrequence; - } - - public String getDataformatreference() { - return this.dataformatreference; - } - - public void setDataformatreference(String dataformatreference) { - this.dataformatreference = dataformatreference; - } - - public Integer getDatasyntax() { - return this.datasyntax; - } - - public void setDatasyntax(Integer datasyntax) { - this.datasyntax = datasyntax; - } - - public String getDescription() { - return this.description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getEndtime() { - return this.endtime; - } - - public void setEndtime(String endtime) { - this.endtime = endtime; - } - - public String getFlowname() { - return this.flowname; - } - - public void setFlowname(String flowname) { - this.flowname = flowname; - } - - public Integer getFrequence() { - return this.frequence; - } - - public void setFrequence(Integer frequence) { - this.frequence = frequence; - } - - public Integer getFrequencederogation() { - return this.frequencederogation; - } - - public void setFrequencederogation(Integer frequencederogation) { - this.frequencederogation = frequencederogation; - } - - public Integer getGdprclassification() { - return this.gdprclassification; - } - - public void setGdprclassification(Integer gdprclassification) { - this.gdprclassification = gdprclassification; - } - - public String getMeasurecronfrequence() { - return this.measurecronfrequence; - } - - public void setMeasurecronfrequence(String measurecronfrequence) { - this.measurecronfrequence = measurecronfrequence; - } - - public Integer getMeasurefrequence() { - return this.measurefrequence; - } - - public void setMeasurefrequence(Integer measurefrequence) { - this.measurefrequence = measurefrequence; - } - - public Integer getMeasurefrequencederogation() { - return this.measurefrequencederogation; - } - - public void setMeasurefrequencederogation(Integer measurefrequencederogation) { - this.measurefrequencederogation = measurefrequencederogation; - } - - public Integer getMeasurementtable() { - return this.measurementtable; - } - - public void setMeasurementtable(Integer measurementtable) { - this.measurementtable = measurementtable; - } - - public Integer getMeasurementtype() { - return this.measurementtype; - } - - public void setMeasurementtype(Integer measurementtype) { - this.measurementtype = measurementtype; - } - - public String getNote() { - return this.note; - } - - public void setNote(String note) { - this.note = note; - } - - public String getOnerrordo() { - return this.onerrordo; - } - - public void setOnerrordo(String onerrordo) { - this.onerrordo = onerrordo; - } - - public String getStarttime() { - return this.starttime; - } - - public void setStarttime(String starttime) { - this.starttime = starttime; - } - - public Integer getSupplierid() { - return this.supplierid; - } - - public void setSupplierid(Integer supplierid) { - this.supplierid = supplierid; - } - - public String getUserightsstatement() { - return this.userightsstatement; - } - - public void setUserightsstatement(String userightsstatement) { - this.userightsstatement = userightsstatement; - } - -} \ No newline at end of file diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/data/DataConsumption.java b/gecoregistration/src/main/java/it/enea/cruise/model/data/DataConsumption.java index de0541aaa354a3b44663f02a28a772afcba5c699..bfa130eabd53ecc58b2d09545b1fcbcb9cb87454 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/data/DataConsumption.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/data/DataConsumption.java @@ -12,11 +12,11 @@ import lombok.Getter; import lombok.Setter; -@Entity(name = "dataConsumption") -@Table(name = "vw_counterreadingusers") -@JsonInclude(JsonInclude.Include.NON_NULL) @Getter @Setter +@Entity +@Table(name = "vw_counterreadingusers") +@JsonInclude(JsonInclude.Include.NON_NULL) public class DataConsumption { @Id diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/parametricQuery/AdmittedQueryValues.java b/gecoregistration/src/main/java/it/enea/cruise/model/parametricQuery/AdmittedQueryValues.java deleted file mode 100644 index 42826fb51c8c0ea05d8eb5750a1634961fcdb0a0..0000000000000000000000000000000000000000 --- a/gecoregistration/src/main/java/it/enea/cruise/model/parametricQuery/AdmittedQueryValues.java +++ /dev/null @@ -1,44 +0,0 @@ -package it.enea.cruise.model.parametricQuery; - -import java.util.List; -import java.util.Map; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; -import javax.persistence.Transient; - -import lombok.Getter; -import lombok.Setter; - -@Entity (name = "admittedqueryvalues") -@Table(name = "cruise.t_admittedqueryvalues") -@Getter -@Setter -public class AdmittedQueryValues { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private int admittedqueryvalueid; - - private String type; - - private String value; - - @Transient - private List queries; - - @Transient - private Map> listOfValue; - - public int getId() { - return admittedqueryvalueid; - } - - public void setId(int admittedqueryvalueid) { - this.admittedqueryvalueid = admittedqueryvalueid; - } - -} diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/parametricQuery/ParametricQuery.java b/gecoregistration/src/main/java/it/enea/cruise/model/parametricQuery/ParametricQuery.java deleted file mode 100644 index 22f480ad59928a609294929c12655ea6af226115..0000000000000000000000000000000000000000 --- a/gecoregistration/src/main/java/it/enea/cruise/model/parametricQuery/ParametricQuery.java +++ /dev/null @@ -1,150 +0,0 @@ -package it.enea.cruise.model.parametricQuery; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.JoinTable; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToMany; -import javax.persistence.PostLoad; -import javax.persistence.Table; -import javax.persistence.Transient; - -import org.hibernate.annotations.FetchMode; -import org.hibernate.annotations.Fetch; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - -import lombok.Getter; -import lombok.Setter; - - -@Entity (name = "parametricquery") -@Table (name = "cruise.parametricquery") -@Getter -@Setter -@JsonInclude(JsonInclude.Include.NON_NULL) -public class ParametricQuery { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private Long queryid; - private String name; - //@JsonIgnore - private String sql; - private String description; - private String queryType; // {SQL, API}; - - @Transient - @JsonProperty("metadata") - @JsonInclude(JsonInclude.Include.NON_NULL) - List> parameterMetadata; - - @ManyToMany - @JoinTable( - name = "cruise.queries_parameters", - joinColumns = @JoinColumn - (name = "queryid"), - inverseJoinColumns = @JoinColumn(name = "paramid")) - @Fetch(FetchMode.JOIN) - //@JsonManagedReference(value = "parametricquery-parameter") - @JsonProperty("parameters") - @JsonIgnoreProperties("parametricquery") - private List parameters; - - @ManyToMany - @JoinTable( - name = "cruise.queries_admittedqueryvalues", - joinColumns = @JoinColumn (name = "queryid"), - inverseJoinColumns = @JoinColumn(name = "admittedqueryvalueid")) - private List admittedqueryvalues; - - @Transient - Map> values = new HashMap>(); - - @PostLoad - public void postLoad(){ - - - for(AdmittedQueryValues aqv : admittedqueryvalues) { - List tempList; - if (values.containsKey(aqv.getType())) { - tempList = values.get(aqv.getType()); - tempList.add(aqv.getValue()); - - }else { - tempList = new ArrayList(); - tempList.add(aqv.getValue()); - } - values.put(aqv.getType(), tempList); - } - } - -// public String getName() { -// return name; -// } -// public void setName(String name) { -// this.name = name; -// } -// public String getSql() { -// return sql; -// } -// public void setSql(String sQL) { -// sql = sQL; -// } -// public List getParameters() { -// return parameters; -// } -// public void setParameters(List parameters) { -// this.parameters = parameters; -// } -// public Long getQueryid() { -// return queryid; -// } -// public void setQueryid(Long queryid) { -// this.queryid = queryid; -// } -// public String getDescription() { -// return description; -// } -// public void setDescription(String description) { -// this.description = description; -// } -// public String getQueryType() { -// return queryType; -// } -// public void setQueryType(String queryType) { -// this.queryType = queryType; -// } -// -// public void setAdmittedqueryvalues(List admittedqueryvalues) { -// this.admittedqueryvalues = admittedqueryvalues; -// } -// -// public void setValues(Map> values) { -// this.values = values; -// } -// -// public Map> getValues() { -// return values; -// } -// -// public List> getParameterMetadata() { -// return parameterMetadata; -// } -// -// public void setParameterMetadata(List> parameterMetadata) { -// this.parameterMetadata = parameterMetadata; -// } - - - -} diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/structure/ForeignKey.java b/gecoregistration/src/main/java/it/enea/cruise/model/structure/ForeignKey.java index 7d721b005b37c626038c6a7ea9e32ca7b6353c92..f55be36734a6ab305a11215a8b5b658b6cd50e31 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/structure/ForeignKey.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/structure/ForeignKey.java @@ -13,12 +13,12 @@ import lombok.Setter; import lombok.ToString; @Entity -@Table(name="vw_foreignkey", schema="cruise") @Immutable @Getter @Setter -@NoArgsConstructor @ToString +@NoArgsConstructor +@Table(name="vw_foreignkey", schema="cruise") public class ForeignKey { @Id diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/structure/VwTableMetadata.java b/gecoregistration/src/main/java/it/enea/cruise/model/structure/VwTableMetadata.java index ba35487010d24d7dd693dcec535d3f103e700ca3..6973983a5a57cae49b7421b99ddca72209fed749 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/structure/VwTableMetadata.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/structure/VwTableMetadata.java @@ -16,12 +16,12 @@ import lombok.ToString; * */ @Entity -@Table(name="vw_table_metadata", schema="cruise") -@Immutable @Getter @Setter -@NoArgsConstructor @ToString +@Immutable +@NoArgsConstructor +@Table(name="vw_table_metadata", schema="cruise") public class VwTableMetadata implements Serializable { private static final long serialVersionUID = 1L; diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/AdmittedQueryValues.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/AdmittedQueryValues.java new file mode 100644 index 0000000000000000000000000000000000000000..184396956322882f72df3cb3a284ed9e4910e681 --- /dev/null +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/AdmittedQueryValues.java @@ -0,0 +1,31 @@ +package it.enea.cruise.model.user; + +import java.util.List; +import java.util.Map; + +import javax.persistence.*; + +import lombok.Getter; +import lombok.Setter; + +@Entity +@Getter +@Setter +@Table(name = "t_admittedqueryvalues", schema = "cruise") +public class AdmittedQueryValues { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @Column(name = "admittedqueryvalueid") + private Long id; + + private String type; + + private String value; + + @Transient + private List queries; + + @Transient + private Map> listOfValue; +} diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/Community.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/Community.java index f3923e1c518e4d82b4f80e93a80ebe2dd7c32b9e..1842fda8dcd43f65d7da4654bb07bd9f05537116 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/Community.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/Community.java @@ -1,29 +1,18 @@ package it.enea.cruise.model.user; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.FetchType; -import javax.persistence.GeneratedValue; -import javax.persistence.Id; -import javax.persistence.NamedQuery; -import javax.persistence.OneToMany; -import javax.persistence.Table; - -import org.hibernate.annotations.Fetch; -import org.hibernate.annotations.FetchMode; - import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.ObjectIdGenerators; - import lombok.Getter; import lombok.Setter; +import org.hibernate.annotations.Fetch; +import org.hibernate.annotations.FetchMode; + +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; /** * @@ -34,15 +23,14 @@ import lombok.Setter; * */ -@Entity(name = "community") -@Table(name = "communities") +@Entity @Getter @Setter +@Table(name = "communities") @JsonIdentityInfo( generator = ObjectIdGenerators.PropertyGenerator.class, property = "communityid", scope = User.class) -@NamedQuery(name = "Community.findAllOnlyNameandid", query = "select c.communityid as id, c.communityName as name, c.description as desc from community c") public class Community { /* * Properties of the Community @@ -51,7 +39,7 @@ public class Community { @Id @GeneratedValue @Column(name = "communityid") - private Long communityid; + private Long id; @JsonInclude(JsonInclude.Include.NON_NULL) @Column(name = "communityname") @@ -84,7 +72,7 @@ public class Community { } public Community(Long id, String name, String description) { - this.communityid = id; + this.id = id; this.communityName = name; this.description = description; } @@ -103,41 +91,4 @@ public class Community { public int hashCode() { return Objects.hash(communityName); } - - /* - * Getters and Setters - */ - -// public Long getCommunityid() { -// return communityid; -// } -// -// public void setCommunityid(Long communityid) { -// this.communityid = communityid; -// } -// -// public String getCommunityName() { -// return communityName; -// } -// -// public void setCommunityName(String communityName) { -// this.communityName = communityName; -// } -// -// public List getUserCommunities() { -// return userCommunities; -// } -// -// public void setUserCommunities(List userCommunities) { -// this.userCommunities = userCommunities; -// } -// -// public String getDescription() { -// return description; -// } -// -// public void setDescription(String description) { -// this.description = description; -// } - } diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/Device.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/Device.java index 8e29a764cc4a34c7ce59bda7e4c273637d9e62b9..0470e771accb2251c7b11f817561f9e3cac9f4db 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/Device.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/Device.java @@ -1,36 +1,29 @@ package it.enea.cruise.model.user; -import java.io.Serializable; -import java.util.Date; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.MapsId; -import javax.persistence.Table; - -import org.springframework.stereotype.Component; - import com.fasterxml.jackson.annotation.JsonInclude; - import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; +import org.springframework.stereotype.Component; -@Entity (name="device") -@Table (name= "devices") -@JsonInclude(JsonInclude.Include.NON_NULL) +import javax.persistence.*; +import java.io.Serializable; +import java.util.Date; + +@Entity @Getter @Setter -@NoArgsConstructor @ToString @Component +@NoArgsConstructor +@Table(name= "devices") +@JsonInclude(JsonInclude.Include.NON_NULL) public class Device implements Serializable { @Id - private String deviceid; + @Column(name = "deviceid") + private String id; private int supplierid; @@ -68,5 +61,4 @@ public class Device implements Serializable { private String activationdate; private Date deactivationdate; - } diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/Flow.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/Flow.java index 21f15a34b6cd05e55b57c12b30e215ab5fd76f61..850dfbe53e92cdfdd5da55c181f9b97897c146d5 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/Flow.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/Flow.java @@ -15,17 +15,18 @@ import lombok.ToString; * The persistent class for the flows database table. * */ -@Entity (name="flow") -@Table(name="flows") +@Entity @Getter @Setter -@NoArgsConstructor @ToString +@NoArgsConstructor +@Table(name="flows") public class Flow implements Serializable { private static final long serialVersionUID = 1L; @Id - private Integer flowid; + @Column(name = "flowid") + private Integer id; private String channeldescription; diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/FlowCommunity.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/FlowCommunity.java index 42cf1fbce612da702a3aac86e8c1606aa1e19e50..92e6440b49b7c075a05f169e8cb3d7b0b2194465 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/FlowCommunity.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/FlowCommunity.java @@ -1,21 +1,13 @@ package it.enea.cruise.model.user; -import javax.persistence.Column; -import javax.persistence.EmbeddedId; -import javax.persistence.Entity; -import javax.persistence.JoinColumn; -import javax.persistence.ManyToOne; -import javax.persistence.MapsId; -import javax.persistence.Table; - import com.fasterxml.jackson.annotation.JsonIgnore; +import javax.persistence.*; + -@Entity(name = "flowCommunity") +@Entity @Table(name = "flows_communities") public class FlowCommunity { - - @EmbeddedId @JsonIgnore private FlowCommunityId id = new FlowCommunityId(); diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/FlowCommunityId.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/FlowCommunityId.java index 14a835f306e4a05186fb2d16ed162cf1bbe8694e..1229cbdc3d9da3be6ce74b714a43a063d030669a 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/FlowCommunityId.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/FlowCommunityId.java @@ -1,22 +1,19 @@ package it.enea.cruise.model.user; -import java.io.Serializable; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; import javax.persistence.Column; import javax.persistence.Embeddable; import javax.persistence.Transient; - -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; +import java.io.Serializable; @Getter @Setter -@NoArgsConstructor @Embeddable -public class FlowCommunityId implements Serializable{ - - +@NoArgsConstructor +public class FlowCommunityId implements Serializable { @Transient private static final long serialVersionUID = 1L; diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/parametricQuery/LocalQueryParameter.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/LocalQueryParameter.java similarity index 74% rename from gecoregistration/src/main/java/it/enea/cruise/model/parametricQuery/LocalQueryParameter.java rename to gecoregistration/src/main/java/it/enea/cruise/model/user/LocalQueryParameter.java index b3c63fc57f84f3fc118a7181bf83973185833c9b..408dea0889b9de3296da88514f5ff987f104e549 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/parametricQuery/LocalQueryParameter.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/LocalQueryParameter.java @@ -1,33 +1,21 @@ -package it.enea.cruise.model.parametricQuery; +package it.enea.cruise.model.user; -import java.util.List; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.ManyToMany; -import javax.persistence.Table; - -//import org.codehaus.jackson.annotate.JsonBackReference; - import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import javax.persistence.*; +import java.util.List; + -@Entity (name = "localqueryparameter") -@Table (name= "cruise.localqueryparameters") +@Entity +@Table (name= "localqueryparameters", schema = "cruise") public class LocalQueryParameter { @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) + @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="localqueryparameterid") private Long paramId; - - //@JsonIgnore - //private Long queryid; - + private String description; private String name; @@ -55,14 +43,6 @@ public class LocalQueryParameter { this.paramId = paramId; } -// public Long getQueryid() { -// return queryid; -// } -// -// public void setQueryid(Long queryid) { -// this.queryid = queryid; -// } - public String getDescription() { return description; } diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/OldUser.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/OldUser.java index e458064b2fe1292fabbabef60a5a9449cab299cb..3a7da924978db41e788d8c5c2fdf20440087a1d9 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/OldUser.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/OldUser.java @@ -29,7 +29,7 @@ import com.fasterxml.jackson.annotation.JsonManagedReference; public class OldUser { @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) + @GeneratedValue(strategy = GenerationType.AUTO) private Long userid; @JsonAlias({ "preferred_username", "username" }) diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/ParametricQuery.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/ParametricQuery.java new file mode 100644 index 0000000000000000000000000000000000000000..094f39e04466518e2482566529ac9dd4c1a4f2b1 --- /dev/null +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/ParametricQuery.java @@ -0,0 +1,79 @@ +package it.enea.cruise.model.user; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import lombok.Getter; +import lombok.Setter; +import org.hibernate.annotations.Fetch; +import org.hibernate.annotations.FetchMode; + +import javax.persistence.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +@Getter +@Setter +@Entity +@Table(name = "parametricquery", schema = "cruise") +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ParametricQuery { + + @Id + @Column(name = "queryid") + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String name; + private String sql; + private String description; + @Column(name = "querytype") + private String queryType; // {SQL, API}; + + @Transient + @JsonProperty("metadata") + @JsonInclude(JsonInclude.Include.NON_NULL) + List> parameterMetadata; + + @ManyToMany + @JoinTable( + schema = "cruise", + name = "queries_parameters", + joinColumns = @JoinColumn + (name = "queryid"), + inverseJoinColumns = @JoinColumn(name = "paramid")) + @Fetch(FetchMode.SUBSELECT) + @JsonProperty("parameters") + @JsonIgnoreProperties("parametricquery") + private List parameters; + + @ManyToMany + @JoinTable( + schema = "cruise", + name = "queries_admittedqueryvalues", + joinColumns = @JoinColumn(name = "queryid"), + inverseJoinColumns = @JoinColumn(name = "admittedqueryvalueid")) + private List admittedqueryvalues; + + @Transient + Map> values = new HashMap<>(); + + @PostLoad + public void postLoad() { + for (AdmittedQueryValues aqv : admittedqueryvalues) { + List tempList; + if (values.containsKey(aqv.getType())) { + tempList = values.get(aqv.getType()); + tempList.add(aqv.getValue()); + + } else { + tempList = new ArrayList(); + tempList.add(aqv.getValue()); + } + values.put(aqv.getType(), tempList); + } + } +} diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/Role.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/Role.java index 919f79447dc805d4a345ade008f798e7dc8a3755..17698fc82e75ef18420fd2a2e9d84f57c95d16f9 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/Role.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/Role.java @@ -1,24 +1,17 @@ package it.enea.cruise.model.user; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.CascadeType; -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.OneToMany; -import javax.persistence.Table; - import com.fasterxml.jackson.annotation.JsonIgnore; - import lombok.Getter; import lombok.Setter; -@Entity(name = "role") -@Table(name = "t_roles") +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; + +@Entity @Getter @Setter +@Table(name = "t_roles") public class Role { @Id @@ -33,39 +26,6 @@ public class Role { @JsonIgnore private List userRoles = new ArrayList<>(); - -// public Long getId() { -// return id; -// } -// -// public void setId(Long id) { -// this.id = id; -// } -// -// public String getDescription() { -// return description; -// } -// -// public void setDescription(String description) { -// this.description = description; -// } -// -// public String getRolename() { -// return rolename; -// } -// -// public void setRolename(String roleName) { -// this.rolename = roleName; -// } -// -// public List getUserRoles() { -// return userRoles; -// } -// -// public void setUserRoles(List userRoles) { -// this.userRoles = userRoles; -// } - @Override public String toString() { String result = "{\"id\":" + this.id + "," diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/User.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/User.java index 627f400327acb5d40c29808be0348494ef775011..dd055f7ec8ebde125260cc266449bf5ee488a7e3 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/User.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/User.java @@ -1,34 +1,28 @@ package it.enea.cruise.model.user; -import java.util.ArrayList; -import java.util.List; - -import javax.persistence.*; - +import com.fasterxml.jackson.annotation.*; +import it.enea.cruise.dto.UserToken; import it.enea.scp.idp.sdk.model.UserDto; +import lombok.Getter; +import lombok.Setter; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; -import com.fasterxml.jackson.annotation.JsonIdentityInfo; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.ObjectIdGenerators; - -import lombok.Getter; -import lombok.Setter; +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; @Getter @Setter -@Entity(name = "user") -@Table(name = "Users") +@Entity +@Table(name = "users") @Access(AccessType.FIELD) @JsonInclude(JsonInclude.Include.NON_NULL) @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "userid") public class User { @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) + @GeneratedValue(strategy = GenerationType.AUTO) private Long userid; private String subject; diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/UserCommunity.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/UserCommunity.java index 4fe5e2f0524d4e64c43952bb598bc790516d98ac..71e7979a6b5ba1582347277ccc2e37eeeedf3547 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/UserCommunity.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/UserCommunity.java @@ -24,7 +24,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; * */ -@Entity(name = "userCommunity") +@Entity @Table(name = "users_communities") public class UserCommunity { @@ -71,7 +71,7 @@ public class UserCommunity { public UserCommunity(User user, Community community) { this.user = user; this.community = community; - this.id = new UserCommunityId(user.getUserid(), community.getCommunityid()); + this.id = new UserCommunityId(user.getUserid(), community.getId()); } /* @@ -108,21 +108,10 @@ public class UserCommunity { } public void setCommunity(Community community) { - id.setCommunityId(community.getCommunityid()); + id.setCommunityId(community.getId()); this.community = community; } -// @Override -// public String toString() { -// String result = ""; -// result = "{\"user\" : " + this.user.getUserid() + "," -// + "\"community\" : " + this.community.getCommunityid() + "," -// + "\"wallet\" : \"" + this.wallet +"\"" -// + "}"; -// -// return result; -// } - public void clear() { this.user = null; this.community = null; diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/UserCommunityId.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/UserCommunityId.java index 2a023e98153b5e8dee930cea98b2fb6a4e1ced4a..a1e6be7d44364d9812f0da5b2ee5f4779c4403a9 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/UserCommunityId.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/UserCommunityId.java @@ -7,81 +7,69 @@ import javax.persistence.Embeddable; import javax.persistence.Transient; /** - * * @author gianluca - * Questa classe rappresenta l'ID della tabella users_communities che - * non esiste all'interno del DB. - * Attraverso questa classe e' possibile creare una relazione tra Users e + * Questa classe rappresenta l'ID della tabella users_communities che + * non esiste all'interno del DB. + * Attraverso questa classe e' possibile creare una relazione tra Users e * Communities che contenga anche altre informazioni. * I dati di questa classe vengono registrati all'interno dell'oggetto * UserCommunity in cui questa classe e' inserita. */ @Embeddable public class UserCommunityId implements Serializable { - + /* - * Properties - */ - @Transient - private static final long serialVersionUID = 1L; - - @Column ( name = "userid") - private Long userid; - @Column ( name = "communityid") - private Long communityid; - - /* - * Generic Methods - */ - - public UserCommunityId() {} - + * Properties + */ + @Transient + private static final long serialVersionUID = 1L; + + @Column(name = "userid") + private Long userid; + @Column(name = "communityid") + private Long communityid; + + /* + * Generic Methods + */ + + public UserCommunityId() { + } + public UserCommunityId( - Long userId, - Long communityid) { + Long userId, + Long communityid) { this.setUserId(userId); this.setCommunityId(communityid); } - - public boolean equals(UserCommunityId o) { - Boolean result = false; - - if (o == null) - result = false; - - if (this.communityid.equals(o.communityid) && - this.userid.equals(o.userid)) { - result = true; + + public boolean equals(UserCommunityId o) { + Boolean result = false; + + if (o == null) + result = false; + + if (this.communityid.equals(o.communityid) && + this.userid.equals(o.userid)) { + result = true; } - - - + return result; - } - - //@Override - // public int hashCode() { - // return Objects.hash(this); - // } - /* - * Getters and setters - */ - - public Long getUserId() { - return userid; - } - - public void setUserId(Long userId) { - this.userid = userId; - } - - public Long getCommunityId() { - return communityid; - } - - public void setCommunityId(Long communityId) { - this.communityid = communityId; - } + public Long getUserId() { + return userid; + } + + public void setUserId(Long userId) { + this.userid = userId; + } + + public Long getCommunityId() { + return communityid; + } + + public void setCommunityId(Long communityId) { + this.communityid = communityId; + } } \ No newline at end of file diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/UserRole.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/UserRole.java index 1857caade4cd001c0a146df3c4fcfea693928f10..96779cf05355ca47e69d27c2a02ff3ea264bd519 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/UserRole.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/UserRole.java @@ -23,7 +23,7 @@ import com.fasterxml.jackson.annotation.JsonIgnore; * */ -@Entity(name = "userRole") +@Entity @Table(name = "users_roles") public class UserRole { @@ -65,7 +65,7 @@ public class UserRole { this.user = user; this.role = role; this.community = community; - this.id = new UserRoleId(user.getUserid(), role.getId(), community.getCommunityid()); + this.id = new UserRoleId(user.getUserid(), role.getId(), community.getId()); } // public UserRole(User user, Role role, Long communityid) { @@ -81,7 +81,7 @@ public class UserRole { */ public Long getCommunityid() { - return community.getCommunityid(); + return community.getId(); } public UserRoleId getId() { @@ -115,7 +115,7 @@ public class UserRole { } public void setCommunity(Community community) { - id.setCommunityId(community.getCommunityid()); + id.setCommunityId(community.getId()); this.community = community; } diff --git a/gecoregistration/src/main/java/it/enea/cruise/model/user/UserRoleId.java b/gecoregistration/src/main/java/it/enea/cruise/model/user/UserRoleId.java index 8b73f03f4d83f488f94e6db05fa714b47b5c86e4..f8d0868ee982b7ac892fea187630ed29ed093fab 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/model/user/UserRoleId.java +++ b/gecoregistration/src/main/java/it/enea/cruise/model/user/UserRoleId.java @@ -8,87 +8,83 @@ import javax.persistence.Embeddable; import javax.persistence.Transient; /** - * * @author gianluca - * Questa classe rappresenta l'ID della tabella users_communities che - * non esiste all'interno del DB. - * Attraverso questa classe e' possibile creare una relazione tra Users e + * Questa classe rappresenta l'ID della tabella users_communities che + * non esiste all'interno del DB. + * Attraverso questa classe e' possibile creare una relazione tra Users e * Communities che contenga anche altre informazioni. * I dati di questa classe vengono registrati all'interno dell'oggetto * UserCommunity in cui questa classe e' inserita. */ @Embeddable public class UserRoleId implements Serializable { - + /* - * Properties - */ - @Transient - private static final long serialVersionUID = 1L; + * Properties + */ + @Transient + private static final long serialVersionUID = 1L; - @Column ( name = "userid") + @Column(name = "userid") private Long userid; - @Column ( name = "roleid") + @Column(name = "roleid") private Long roleid; - @Column ( name = "communityid") + @Column(name = "communityid") private Long communityid; - /* - * Generic Methods - */ - - public UserRoleId() {} - + public UserRoleId() { + } + public UserRoleId( - Long userId, - Long roleid, - Long communityid) { + Long userId, + Long roleid, + Long communityid) { this.setUserId(userId); this.setRoleId(roleid); this.setCommunityId(communityid); } - + @Override public boolean equals(Object o) { if (this == o) return true; - + if (o == null || getClass() != o.getClass()) return false; - + UserRoleId that = (UserRoleId) o; return Objects.equals(this, that); } - + @Override public int hashCode() { return Objects.hash(this); } /* - * Getters and setters - */ - - public Long getUserId() { - return userid; - } - - public void setUserId(Long userId) { - this.userid = userId; - } - - public Long getRoleId() { - return roleid; - } - - public void setRoleId(Long roleid) { - this.roleid = roleid; - } - - public Long getCommunityId() { - return communityid; - } - - public void setCommunityId(Long communityid) { - this.communityid = communityid; - } + * Getters and setters + */ + + public Long getUserId() { + return userid; + } + + public void setUserId(Long userId) { + this.userid = userId; + } + + public Long getRoleId() { + return roleid; + } + + public void setRoleId(Long roleid) { + this.roleid = roleid; + } + + public Long getCommunityId() { + return communityid; + } + + public void setCommunityId(Long communityid) { + this.communityid = communityid; + } } \ No newline at end of file diff --git a/gecoregistration/src/main/java/it/enea/cruise/repositories/DTOManager.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/DTOManager.java index c5066546177ec1e91e69f644dcd8e8582c2ac78b..74fe390a2af2c9a0489d2f78249fe51e3da00dc3 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/repositories/DTOManager.java +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/DTOManager.java @@ -16,7 +16,7 @@ import it.enea.cruise.dto.CommunityDTO; import it.enea.cruise.dto.DeviceDTO; import it.enea.cruise.dto.LocalUserDTO; import it.enea.cruise.dto.MetadataDTO; -import it.enea.cruise.model.structure.ColumnCommentDTO; +import it.enea.cruise.dto.ColumnCommentDTO; import it.enea.cruise.model.structure.VwTableMetadata; import it.enea.cruise.model.user.Community; import it.enea.cruise.model.user.Device; @@ -53,7 +53,7 @@ public class DTOManager { public CommunityDTO communityDTO(UserCommunity c) { CommunityDTO communityDTO = new CommunityDTO(); log.info("preparing CommunityTO for export"); - communityDTO.setCommunityid(c.getCommunity().getCommunityid()); + communityDTO.setCommunityid(c.getCommunity().getId()); communityDTO.setDescription(c.getCommunity().getDescription()); communityDTO.setWallet(c.getWallet() != null ? c.getWallet().toString() : "noWallet"); communityDTO.setCommunityName(c.getCommunity().getCommunityName()); @@ -64,7 +64,7 @@ public class DTOManager { public CommunityDTO communityDTO(Community c) { CommunityDTO communityDTO = new CommunityDTO(); log.info("preparing CommunityTO for export"); - communityDTO.setCommunityid(c.getCommunityid()); + communityDTO.setCommunityid(c.getId()); communityDTO.setDescription(c.getDescription()); communityDTO.setWallet("noWallet"); communityDTO.setCommunityName(c.getCommunityName()); @@ -79,7 +79,7 @@ public class DTOManager { deviceDTO.setActivationdate(d.getActivationdate()); deviceDTO.setAltdeviceid(d.getAltdeviceid()); deviceDTO.setDescription(d.getDescription()); - deviceDTO.setDeviceid(d.getDeviceid()); + deviceDTO.setDeviceid(d.getId()); deviceDTO.setDevicename(d.getDevicename()); deviceDTO.setDevicestatus(d.getDevicestatus()); deviceDTO.setDevicetype(d.getDevicetype()); diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/data/DataInterface.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/data/DataConsumptionRepository.java similarity index 87% rename from gecoregistration/src/main/java/it/enea/cruise/service/data/DataInterface.java rename to gecoregistration/src/main/java/it/enea/cruise/repositories/data/DataConsumptionRepository.java index 890fa6953d71901fb288828e21133346b6f63920..3546281248afabe5d5d269d63ef3461a7a2e8218 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/service/data/DataInterface.java +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/data/DataConsumptionRepository.java @@ -1,4 +1,4 @@ -package it.enea.cruise.service.data; +package it.enea.cruise.repositories.data; import java.util.Date; import java.util.List; @@ -9,9 +9,9 @@ import org.springframework.data.repository.query.Param; import it.enea.cruise.model.data.DataConsumption; -public interface DataInterface extends JpaRepository { +public interface DataConsumptionRepository extends JpaRepository { - @Query("SELECT dc FROM dataConsumption dc " + @Query("SELECT dc FROM DataConsumption dc " + "WHERE dc.userid = :userid " + "AND dc.timestamp >= :startDate " + "AND dc.timestamp < :endDate " diff --git a/gecoregistration/src/main/java/it/enea/cruise/repositories/CommunityRepository.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/CommunityRepository.java similarity index 73% rename from gecoregistration/src/main/java/it/enea/cruise/repositories/CommunityRepository.java rename to gecoregistration/src/main/java/it/enea/cruise/repositories/user/CommunityRepository.java index 587f6fc08d237ed8a09fd60614c0662f1af9cd18..26a6c89be838560e88e9e16577462693cb423499 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/repositories/CommunityRepository.java +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/CommunityRepository.java @@ -1,4 +1,4 @@ -package it.enea.cruise.repositories; +package it.enea.cruise.repositories.user; import org.springframework.data.jpa.repository.JpaRepository; @@ -6,6 +6,5 @@ import it.enea.cruise.model.user.Community; public interface CommunityRepository extends JpaRepository { Community findByCommunityName(String communityName); - Community findByCommunityid(Long communityId); } \ No newline at end of file diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/structure/ForeignKeyInterface.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/ForeignKeyRepository.java similarity index 84% rename from gecoregistration/src/main/java/it/enea/cruise/service/structure/ForeignKeyInterface.java rename to gecoregistration/src/main/java/it/enea/cruise/repositories/user/ForeignKeyRepository.java index 34920149bcd53c3511277405656450e263898158..1989a18401878ace8a9119e5fb1d3ac6610afa95 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/service/structure/ForeignKeyInterface.java +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/ForeignKeyRepository.java @@ -1,4 +1,4 @@ -package it.enea.cruise.service.structure; +package it.enea.cruise.repositories.user; import java.util.List; @@ -8,7 +8,7 @@ import org.springframework.data.repository.query.Param; import it.enea.cruise.model.structure.ForeignKey; -public interface ForeignKeyInterface extends JpaRepository { +public interface ForeignKeyRepository extends JpaRepository { List findByTableName (String tableName); diff --git a/gecoregistration/src/main/java/it/enea/cruise/repositories/user/LocalQueryParameterRepository.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/LocalQueryParameterRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..bbe354685b010f2cfa68a9ae91b0007093a70489 --- /dev/null +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/LocalQueryParameterRepository.java @@ -0,0 +1,13 @@ +package it.enea.cruise.repositories.user; + +import java.util.List; + +import org.springframework.data.jpa.repository.JpaRepository; + +import it.enea.cruise.model.user.LocalQueryParameter; + +public interface LocalQueryParameterRepository extends JpaRepository{ + + List findAllByName(String paramName); + +} diff --git a/gecoregistration/src/main/java/it/enea/cruise/repositories/OldUserRepository.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/OldUserRepository.java similarity index 93% rename from gecoregistration/src/main/java/it/enea/cruise/repositories/OldUserRepository.java rename to gecoregistration/src/main/java/it/enea/cruise/repositories/user/OldUserRepository.java index a139a1c7a88097427411831c36ca1bae96e9c1c9..f25af02b1b296e0d8cdb15250eae9205b5724b12 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/repositories/OldUserRepository.java +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/OldUserRepository.java @@ -1,4 +1,5 @@ -package it.enea.cruise.repositories; +/* +package it.enea.cruise.repositories.user; import java.util.List; @@ -24,3 +25,4 @@ public interface OldUserRepository extends CrudRepository{ User findBySubject(String subject); } +*/ diff --git a/gecoregistration/src/main/java/it/enea/cruise/repositories/user/ParametricQueryRepository.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/ParametricQueryRepository.java new file mode 100644 index 0000000000000000000000000000000000000000..d3f1105004fa11b8126174decb7399f3fc2d24d3 --- /dev/null +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/ParametricQueryRepository.java @@ -0,0 +1,12 @@ +package it.enea.cruise.repositories.user; + +import java.util.List; +import java.util.Optional; + +import org.springframework.data.jpa.repository.JpaRepository; + +import it.enea.cruise.model.user.ParametricQuery; + +public interface ParametricQueryRepository extends JpaRepository { + List findAll(); +} diff --git a/gecoregistration/src/main/java/it/enea/cruise/repositories/RoleRepository.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/RoleRepository.java similarity index 90% rename from gecoregistration/src/main/java/it/enea/cruise/repositories/RoleRepository.java rename to gecoregistration/src/main/java/it/enea/cruise/repositories/user/RoleRepository.java index 5f88736ac50b451230f2a51415a58a1009948080..3aa4b3a5ff9b3858bb9941d44d41c41239d86f5d 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/repositories/RoleRepository.java +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/RoleRepository.java @@ -1,4 +1,4 @@ -package it.enea.cruise.repositories; +package it.enea.cruise.repositories.user; import java.util.List; import java.util.Optional; @@ -7,7 +7,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import it.enea.cruise.model.user.Role; -public interface RoleRepository extends JpaRepository{ +public interface RoleRepository extends JpaRepository { List findAllByDescription(String description); diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/structure/TableMetadataInterface.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/TableMetadataRepository.java similarity index 67% rename from gecoregistration/src/main/java/it/enea/cruise/service/structure/TableMetadataInterface.java rename to gecoregistration/src/main/java/it/enea/cruise/repositories/user/TableMetadataRepository.java index 1129c13f1f30af814558f3c304ec1c64ca254b26..f4f696e349a51e2b7008ca475f8749fefc766f71 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/service/structure/TableMetadataInterface.java +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/TableMetadataRepository.java @@ -1,4 +1,4 @@ -package it.enea.cruise.service.structure; +package it.enea.cruise.repositories.user; import java.util.List; @@ -7,7 +7,7 @@ import org.springframework.data.jpa.repository.JpaRepository; import it.enea.cruise.model.structure.VwTableMetadata; -public interface TableMetadataInterface extends JpaRepository +public interface TableMetadataRepository extends JpaRepository { List findByTableName(String tableName); List findByColumnName(String columnName); diff --git a/gecoregistration/src/main/java/it/enea/cruise/repositories/UserCommunityRepository.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/UserCommunityRepository.java similarity index 82% rename from gecoregistration/src/main/java/it/enea/cruise/repositories/UserCommunityRepository.java rename to gecoregistration/src/main/java/it/enea/cruise/repositories/user/UserCommunityRepository.java index 6f74025636c537a5b573c93bf2a6574d49d80b4d..09b771d848a31bdf2c677e4d090a8105a8c9deb9 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/repositories/UserCommunityRepository.java +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/UserCommunityRepository.java @@ -1,4 +1,4 @@ -package it.enea.cruise.repositories; +package it.enea.cruise.repositories.user; import org.springframework.data.jpa.repository.JpaRepository; diff --git a/gecoregistration/src/main/java/it/enea/cruise/repositories/UserRepository.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/UserRepository.java similarity index 74% rename from gecoregistration/src/main/java/it/enea/cruise/repositories/UserRepository.java rename to gecoregistration/src/main/java/it/enea/cruise/repositories/user/UserRepository.java index 99a5b498a55deec575ad8ef1b61117a47d834866..593ec8cd4085aeddcf95b184d74a9156da8d1bb6 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/repositories/UserRepository.java +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/UserRepository.java @@ -1,4 +1,4 @@ -package it.enea.cruise.repositories; +package it.enea.cruise.repositories.user; import java.util.List; import java.util.Optional; @@ -19,31 +19,31 @@ public interface UserRepository extends JpaRepository{ @Transactional(noRollbackFor=Exception.class) User findBySubject(String subject); - @Query ("SELECT u FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE uc.id.communityid = ?1") + @Query ("SELECT u FROM User as u JOIN UserCommunity as uc ON u.userid = uc.id.userid WHERE uc.id.communityid = ?1") List findAllByCommunityId(Long communityid); - @Query("Select d from device d WHERE d.user.userid = :userid") + @Query("Select d from Device d WHERE d.user.userid = :userid") List findAllDevicesByUserid(@Param("userid") Long userid); - @Query("Select u from user as u WHERE u.subject LIKE :subject") + @Query("Select u from User as u WHERE u.subject LIKE :subject") User findUserBySubject(@Param("subject") String subject); List findBySubjectIsNotNull(); - @Query ("SELECT u FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE u.subject IS NOT NULL AND uc.id.communityid = ?1") + @Query ("SELECT u FROM User as u JOIN UserCommunity as uc ON u.userid = uc.id.userid WHERE u.subject IS NOT NULL AND uc.id.communityid = ?1") List findBySubjectIsNotNullAndCommunityId(Long communityid); - @Query ("SELECT u FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE u.subject IS NOT NULL AND uc.active = TRUE AND uc.id.communityid = ?1") + @Query ("SELECT u FROM User as u JOIN UserCommunity as uc ON u.userid = uc.id.userid WHERE u.subject IS NOT NULL AND uc.active = TRUE AND uc.id.communityid = ?1") List findBySubjectIsNotNullAndActiveIsTrueAndCommunityId(Long communityid); - @Query ("SELECT count(*) FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE u.subject IS NOT NULL AND uc.id.communityid = ?1") + @Query ("SELECT count(*) FROM User as u JOIN UserCommunity as uc ON u.userid = uc.id.userid WHERE u.subject IS NOT NULL AND uc.id.communityid = ?1") Integer countBySubjectIsNotNullAndCommunityId(Long communityid); - @Query ("SELECT u FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE uc.wallet = ?1") + @Query ("SELECT u FROM User as u JOIN UserCommunity as uc ON u.userid = uc.id.userid WHERE uc.wallet = ?1") List findFromWallet(String wallet); - @Query ("SELECT u FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE uc.wallet = ?1 AND uc.id.communityid = ?2") + @Query ("SELECT u FROM User as u JOIN UserCommunity as uc ON u.userid = uc.id.userid WHERE uc.wallet = ?1 AND uc.id.communityid = ?2") List findFromWalletAndCommunityId(String wallet, Long communityid); } diff --git a/gecoregistration/src/main/java/it/enea/cruise/repositories/UserRoleRepository.java b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/UserRoleRepository.java similarity index 81% rename from gecoregistration/src/main/java/it/enea/cruise/repositories/UserRoleRepository.java rename to gecoregistration/src/main/java/it/enea/cruise/repositories/user/UserRoleRepository.java index 587f7d060e7742d777576b249a7cb6eb2c7950e7..ea2169808c0971faaf3956d0f738e7815fd82405 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/repositories/UserRoleRepository.java +++ b/gecoregistration/src/main/java/it/enea/cruise/repositories/user/UserRoleRepository.java @@ -1,4 +1,4 @@ -package it.enea.cruise.repositories; +package it.enea.cruise.repositories.user; import org.springframework.data.jpa.repository.JpaRepository; diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/data/DataCacher.java b/gecoregistration/src/main/java/it/enea/cruise/service/data/DataCacher.java index e4e8a7fe11429b197b1bd49e0a3d02d68065c876..78cfdcc7d4bedfc89dc01be63bd608e1142bf848 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/service/data/DataCacher.java +++ b/gecoregistration/src/main/java/it/enea/cruise/service/data/DataCacher.java @@ -7,8 +7,7 @@ import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.stereotype.Component; @Component -public class DataCacher - implements CacheManagerCustomizer { +public class DataCacher implements CacheManagerCustomizer { @Override public void customize(ConcurrentMapCacheManager cacheManager) { diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/data/DataService.java b/gecoregistration/src/main/java/it/enea/cruise/service/data/DataService.java index a0e44cff2105dd479fd270fed3b3666bb75e3d9c..636a9ae60940371a4c0be4c765b04eebfaf8608b 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/service/data/DataService.java +++ b/gecoregistration/src/main/java/it/enea/cruise/service/data/DataService.java @@ -1,19 +1,21 @@ package it.enea.cruise.service.data; import java.util.Map; +import java.util.Optional; import it.enea.cruise.exceptions.TokenNotValidException; +import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import it.enea.cruise.model.parametricQuery.ParametricQuery; +import it.enea.cruise.model.user.ParametricQuery; import it.enea.cruise.model.user.User; import it.enea.cruise.service.idp.IdpProvider; -import it.enea.cruise.service.parametricQuery.LocalQueryParameterInterface; -import it.enea.cruise.service.parametricQuery.ParametricQueryInterface; +import it.enea.cruise.repositories.user.LocalQueryParameterRepository; +import it.enea.cruise.repositories.user.ParametricQueryRepository; import it.enea.cruise.service.parametricQuery.ParametricQueryManager; import it.enea.cruise.service.parametricQuery.ParametricQueryManager.ResultWithMetadata; -import it.enea.cruise.repositories.UserRepository; +import it.enea.cruise.repositories.user.UserRepository; import lombok.extern.log4j.Log4j2; import javax.transaction.Transactional; @@ -21,23 +23,12 @@ import javax.transaction.Transactional; @Service @Log4j2 +@RequiredArgsConstructor public class DataService implements IDataService { - @Autowired - LocalQueryParameterInterface lqpInterface; - - @Autowired - UserRepository userInterface; - - - @Autowired - ParametricQueryInterface pqueryInterface; - - - @Autowired - ParametricQueryManager pqm; - - @Autowired - IdpProvider idpClientManager; + private final UserRepository userInterface; + private final ParametricQueryRepository pqueryInterface; + private final ParametricQueryManager pqm; + private final IdpProvider idpClientManager; @Override @Transactional @@ -47,16 +38,13 @@ public class DataService implements IDataService { String language) { log.info("Input data:" + inputData.toString()); + log.info("Token to check:" + token); if (idpClientManager.isValid(token)) { - User userdto = idpClientManager.getUserByToken(token); - User user = userInterface.findBySubject(userdto.getUuid()); - inputData.put("userid", user.getUserid().toString()); - - ParametricQuery pq = pqueryInterface.findByQueryid(new Long(inputData.get("queryid"))); - return pqm.executeQuery(pq, inputData, language); + Optional pq = pqueryInterface.findById(Long.valueOf(inputData.get("queryid"))); + return pq.isPresent() ? pqm.executeQuery(pq.get(), inputData, language) : new ResultWithMetadata(); } log.info("Warning: token is not valid"); diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/idp/EneaProvider.java b/gecoregistration/src/main/java/it/enea/cruise/service/idp/EneaProvider.java index 46596a7142a5a014ee5936c843384adb491fb952..d71789c66b016523991af31deb5b0e09187445f3 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/service/idp/EneaProvider.java +++ b/gecoregistration/src/main/java/it/enea/cruise/service/idp/EneaProvider.java @@ -21,7 +21,7 @@ import it.enea.scp.idp.sdk.model.TokenValidityResponse; import it.enea.scp.idp.sdk.model.UpdateUserRequest; import it.enea.scp.idp.sdk.model.UserDto; import it.enea.cruise.model.user.User; -import it.enea.cruise.model.user.UserToken; +import it.enea.cruise.dto.UserToken; import lombok.extern.log4j.Log4j2; @Log4j2 diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/idp/IEncryptionManager.java b/gecoregistration/src/main/java/it/enea/cruise/service/idp/IEncryptionManager.java index da425e6d7eb0eb4e95efc8af6d124cd96581869c..c2289e4cf347beba7807e59d24f254ce5eaf8bbb 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/service/idp/IEncryptionManager.java +++ b/gecoregistration/src/main/java/it/enea/cruise/service/idp/IEncryptionManager.java @@ -1,14 +1,8 @@ package it.enea.cruise.service.idp; public interface IEncryptionManager { - - - public void init(String password); - - public void init(); - - public String encrypt(String s); - - public String decrypt(String s); - + void init(String password); + void init(); + String encrypt(String s); + String decrypt(String s); } diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/idp/IdpCachedProvider.java b/gecoregistration/src/main/java/it/enea/cruise/service/idp/IdpCachedProvider.java index 32bee23c5a51c1837a49284dbafe7b0f6bb7f9f3..40fcd4f332c1826bab92484d1b7f37ef6d04d776 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/service/idp/IdpCachedProvider.java +++ b/gecoregistration/src/main/java/it/enea/cruise/service/idp/IdpCachedProvider.java @@ -13,75 +13,75 @@ import org.springframework.stereotype.Service; @Service @Log4j2 -@Profile("test") +@Profile("none") public class IdpCachedProvider extends EneaProvider implements IdpProvider { - - /*@Autowired*/ - EneaProvider idpClientManager; - - @Override - public String getTokenFromUsernameAndPassword(String username, String password) { - // TODO Auto-generated method stub - return null; - } - - @Override - //@Cacheable(value="users", key="#username") - public User login(String username, String password) { - log.info("logging"); - return super.login(username, password); - // TODO Auto-generated method stub - } - - @Override - public boolean logout(String token) { - // TODO Auto-generated method stub - return false; - } - - @Override - public boolean isValid(String token) { - // TODO Auto-generated method stub - return false; - } - - @Override - public List userList() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Boolean deleteUser(String email) { - // TODO Auto-generated method stub - return null; - } - - @Override - public Boolean createUser(UserDto newUser) { - // TODO Auto-generated method stub - return null; - } - - @Override - public UserDto getUserByEmail(String email) { - // TODO Auto-generated method stub - return null; - } - - @Override - @Cacheable(value="users",key="#token") - public User getUserByToken(String token) { - log.info("getting user with token: " + token); - return super.getUserByToken(token); - - } - - @Override - public Boolean updateUser(UserDto user) { - // TODO Auto-generated method stub - return null; - } + + /*@Autowired*/ + EneaProvider idpClientManager; + + @Override + public String getTokenFromUsernameAndPassword(String username, String password) { + // TODO Auto-generated method stub + return null; + } + + @Override + //@Cacheable(value="users", key="#username") + public User login(String username, String password) { + log.info("logging"); + return super.login(username, password); + // TODO Auto-generated method stub + } + + @Override + public boolean logout(String token) { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isValid(String token) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List userList() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Boolean deleteUser(String email) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Boolean createUser(UserDto newUser) { + // TODO Auto-generated method stub + return null; + } + + @Override + public UserDto getUserByEmail(String email) { + // TODO Auto-generated method stub + return null; + } + + @Override + @Cacheable(value = "users", key = "#token") + public User getUserByToken(String token) { + log.info("getting user with token: " + token); + return super.getUserByToken(token); + + } + + @Override + public Boolean updateUser(UserDto user) { + // TODO Auto-generated method stub + return null; + } } diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/idp/KeycloakProvider.java b/gecoregistration/src/main/java/it/enea/cruise/service/idp/KeycloakProvider.java index 98ce9b58b05cd14416e188e38f89d908591976ec..26314654fe8740be087bb368b225b07602ab5e20 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/service/idp/KeycloakProvider.java +++ b/gecoregistration/src/main/java/it/enea/cruise/service/idp/KeycloakProvider.java @@ -1,7 +1,7 @@ package it.enea.cruise.service.idp; import it.enea.cruise.exceptions.TokenNotValidException; -import it.enea.cruise.repositories.UserRepository; +import it.enea.cruise.repositories.user.UserRepository; import it.enea.scp.idp.sdk.model.UserDto; import it.enea.cruise.model.user.User; import lombok.RequiredArgsConstructor; diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/idp/TestIdpClient.java b/gecoregistration/src/main/java/it/enea/cruise/service/idp/TestIdpClient.java new file mode 100644 index 0000000000000000000000000000000000000000..97b784e0d5935004eb8b20342801a3d1c8087e6a --- /dev/null +++ b/gecoregistration/src/main/java/it/enea/cruise/service/idp/TestIdpClient.java @@ -0,0 +1,105 @@ +package it.enea.cruise.service.idp; + +import it.enea.cruise.dto.UserToken; +import it.enea.cruise.model.user.User; +import it.enea.scp.idp.sdk.model.UserDto; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +@Slf4j +@Service +@RequiredArgsConstructor +@Profile("test") +@Transactional +public class TestIdpClient implements IdpProvider { + @Value("${idp.testAdminEmail}") + String userAdminEmail; + + @Value("${idp.testAdminPwd}") + String userAdminPwd; + + @Value("${idp.testUserEmail}") + String testUserEmail; + + @Value("${idp.testUserPwd}") + String testUserPwd; + + private User user = new User(); + + @Override + public String getTokenFromUsernameAndPassword(String username, String password) { + return "the_token"; + } + + @Override + public User login(String username, String password) { + if (!userAdminEmail.equalsIgnoreCase(username) && !testUserEmail.equalsIgnoreCase(username)) return null; + + Calendar cal = Calendar.getInstance(); + cal.setTime(new Date()); + cal.add(Calendar.MINUTE, 10); + user.setToken(UserToken.builder().creation(new Date()).value("the_token").expiration(cal.getTime()).build()); + user.setUsername(username); + return user; + } + + @Override + public User getUserByToken(String token) { + return user; + } + + @Override + public UserDto getUserByEmail(String email) { + UserDto user = new UserDto(); + user.setEmail(email); + return user; + } + + @Override + public boolean logout(String token) { + return true; + } + + @Override + public boolean isValid(String token) { + return true; + } + + @Override + public List userList() { + return List.of(); + } + + @Override + public Boolean deleteUser(String email) { + return null; + } + + @Override + public Boolean createUser(UserDto newUser) { + return null; + } + + @Override + public Boolean updateUser(UserDto user) { + return null; + } + + @Override + public UserDto getUserFromUUID(String uuid) { + return null; + } + + @Override + public Boolean updatePassword(String token, String password) { + return null; + } +} diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/parametricQuery/LocalQueryParameterInterface.java b/gecoregistration/src/main/java/it/enea/cruise/service/parametricQuery/LocalQueryParameterInterface.java deleted file mode 100644 index c8a632d69a5ce8faebe5cea2da5044b4419b676a..0000000000000000000000000000000000000000 --- a/gecoregistration/src/main/java/it/enea/cruise/service/parametricQuery/LocalQueryParameterInterface.java +++ /dev/null @@ -1,13 +0,0 @@ -package it.enea.cruise.service.parametricQuery; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; - -import it.enea.cruise.model.parametricQuery.LocalQueryParameter; - -public interface LocalQueryParameterInterface extends JpaRepository{ - - List findAllByName(String paramName); - -} diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/parametricQuery/ParametricQueryInterface.java b/gecoregistration/src/main/java/it/enea/cruise/service/parametricQuery/ParametricQueryInterface.java deleted file mode 100644 index 1828f92bf79f7e83592a96a0e3963759b302a00f..0000000000000000000000000000000000000000 --- a/gecoregistration/src/main/java/it/enea/cruise/service/parametricQuery/ParametricQueryInterface.java +++ /dev/null @@ -1,14 +0,0 @@ -package it.enea.cruise.service.parametricQuery; - -import java.util.List; - -import org.springframework.data.jpa.repository.JpaRepository; - -import it.enea.cruise.model.parametricQuery.ParametricQuery; - -public interface ParametricQueryInterface extends JpaRepository { - - - ParametricQuery findByQueryid(Long queryid); - List findAll(); -} diff --git a/gecoregistration/src/main/java/it/enea/cruise/service/parametricQuery/ParametricQueryManager.java b/gecoregistration/src/main/java/it/enea/cruise/service/parametricQuery/ParametricQueryManager.java index 6f3e5edc5597761fe5608bab7c9e264c9bcc2ba4..4944a8400522745492fe649bb39efa754b83ded8 100644 --- a/gecoregistration/src/main/java/it/enea/cruise/service/parametricQuery/ParametricQueryManager.java +++ b/gecoregistration/src/main/java/it/enea/cruise/service/parametricQuery/ParametricQueryManager.java @@ -12,6 +12,7 @@ import java.util.List; import java.util.Map; +import it.enea.cruise.repositories.user.LocalQueryParameterRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; @@ -20,8 +21,8 @@ import org.springframework.jdbc.support.rowset.SqlRowSet; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; -import it.enea.cruise.model.parametricQuery.LocalQueryParameter; -import it.enea.cruise.model.parametricQuery.ParametricQuery; +import it.enea.cruise.model.user.LocalQueryParameter; +import it.enea.cruise.model.user.ParametricQuery; import lombok.ToString; import lombok.extern.log4j.Log4j2; @@ -33,7 +34,7 @@ public class ParametricQueryManager { private NamedParameterJdbcTemplate namedParameterJdbcTemplate; @Autowired - LocalQueryParameterInterface lqpInterface; + LocalQueryParameterRepository lqpInterface; private ParametricQuery pQuery = new ParametricQuery(); @@ -231,7 +232,7 @@ public class ParametricQueryManager { } @ToString - public class ResultWithMetadata { + public static class ResultWithMetadata { List> metadata; List> result; diff --git a/gecoregistration/src/main/resources/application.properties b/gecoregistration/src/main/resources/application.properties index f6541cfa08711d21c3da670ed780b00c3344617c..b02f031e81f4c319152d29d1c106f79783c7861a 100644 --- a/gecoregistration/src/main/resources/application.properties +++ b/gecoregistration/src/main/resources/application.properties @@ -9,42 +9,48 @@ testingPhase = false # Log logging.level.root=INFO - - activationLink=https://winter.bologna.enea.it/cruise/account/activate/ #Community admin oracleRoleAdmin=oracle-admin platformRoleAdmin=platform-admin communityRoleAdmin=community-admin -communityMemberRole = community-member +communityMemberRole = community-member stakeHolderRole = stakeholder # JPA -spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect -spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy +#spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +#spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy -# IDP DB -spring.data-datasource-idp.hikari.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:selfuser}?currentSchema=public -spring.data-datasource-idp.hikari.maximumPoolSize=5 +spring.datasource.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:selfuser}?currentSchema=public +spring.datasource.username=${DB_USER} +spring.datasource.password=${DB_PASSWORD} +spring.datasource.driver-class-name=org.postgresql.Driver +spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect +spring.jpa.hibernate.ddl-auto=none +spring.jpa.show-sql=true -spring.data-datasource-idp.jdbcUrl=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:selfuser}?currentSchema=public -spring.data-datasource-idp.username=${DB_USER} -spring.data-datasource-idp.password=${DB_PASSWORD} -spring.data-datasource-idp.driver-class-name=org.postgresql.Driver -spring.data-datasource-idp.maximumPoolSize=2 -spring.data-datasource-idp.minimumIdle=1 -spring.data-datasource-idp.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect -spring.data-datasource-idp.hibernate.hbm2ddl=none - -# User DB -spring.user-datasource-idp.jdbcUrl=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:selfuser}?currentSchema=public -spring.user-datasource-idp.hikari.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:selfuser}?currentSchema=public -spring.user-datasource-idp.username=${DB_USER} -spring.user-datasource-idp.password=${DB_PASSWORD} -spring.user-datasource-idp.driver-class-name=org.postgresql.Driver -spring.user-datasource-idp.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect -spring.user-datasource-idp.hibernate.hbm2ddl=none +# IDP DB +#spring.data-datasource-idp.hikari.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:selfuser}?currentSchema=public +#spring.data-datasource-idp.hikari.maximumPoolSize=5 +# +#spring.data-datasource-idp.jdbcUrl=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:selfuser}?currentSchema=public +#spring.data-datasource-idp.username=${DB_USER} +#spring.data-datasource-idp.password=${DB_PASSWORD} +#spring.data-datasource-idp.driver-class-name=org.postgresql.Driver +#spring.data-datasource-idp.maximumPoolSize=2 +#spring.data-datasource-idp.minimumIdle=1 +#spring.data-datasource-idp.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +#spring.data-datasource-idp.hibernate.hbm2ddl=none +# +## User DB +#spring.user-datasource-idp.jdbcUrl=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:selfuser}?currentSchema=public +##spring.user-datasource-idp.hikari.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:selfuser}?currentSchema=public +#spring.user-datasource-idp.username=${DB_USER} +#spring.user-datasource-idp.password=${DB_PASSWORD} +#spring.user-datasource-idp.driver-class-name=org.postgresql.Driver +#spring.user-datasource-idp.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +#spring.user-datasource-idp.hibernate.hbm2ddl=none # Mail spring.mail.host= diff --git a/gecoregistration/src/test/java/it/enea/cruise/DataRepositoryTest.java b/gecoregistration/src/test/java/it/enea/cruise/DataRepositoryTest.java new file mode 100644 index 0000000000000000000000000000000000000000..8202a193759db31387b231afeeda9fd770ff680f --- /dev/null +++ b/gecoregistration/src/test/java/it/enea/cruise/DataRepositoryTest.java @@ -0,0 +1,32 @@ +package it.enea.cruise; + +import it.enea.cruise.model.user.ParametricQuery; +import it.enea.cruise.repositories.user.ParametricQueryRepository; +import org.junit.Test; +import org.junit.jupiter.api.Assertions; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import javax.transaction.Transactional; +import java.util.Optional; + +@RunWith(SpringRunner.class) +/*@ContextConfiguration(classes = {dataDBConfiguration.class})*/ +@SpringBootTest +public class DataRepositoryTest { + @Autowired + private ParametricQueryRepository parametricQueryRepository; + + @Test + @Transactional + public void testIfParametricQueryCanBeQueried() { + ParametricQuery parametricQuery = new ParametricQuery(); + parametricQuery.setName("test"); + //parametricQuery.setId(1L); + parametricQueryRepository.save(parametricQuery); + Optional result = parametricQueryRepository.findById(1L); + Assertions.assertTrue(result.isPresent()); + } +} diff --git a/gecoregistration/src/test/java/it/enea/cruise/GecoRegistrationSpringApplicationTests.java b/gecoregistration/src/test/java/it/enea/cruise/GecoRegistrationSpringApplicationTests.java index aeecdda057fc5daf1bea44cbb48a8393bcfe2661..cf640d74590c8688cca79c885c0c9a4710f211d6 100644 --- a/gecoregistration/src/test/java/it/enea/cruise/GecoRegistrationSpringApplicationTests.java +++ b/gecoregistration/src/test/java/it/enea/cruise/GecoRegistrationSpringApplicationTests.java @@ -1,108 +1,99 @@ package it.enea.cruise; -import org.junit.jupiter.api.MethodOrderer; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestMethodOrder; +import com.fasterxml.jackson.databind.ObjectMapper; +import it.enea.cruise.dto.LocalUserDTO; +import it.enea.cruise.service.idp.IdpProvider; +import it.enea.scp.idp.sdk.model.UserDto; import org.junit.jupiter.api.Order; -import org.junit.runner.RunWith; - +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.AutoConfigurationPackage; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.ComponentScan; import org.springframework.http.MediaType; import org.springframework.test.context.TestPropertySource; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultHandler; -import com.fasterxml.jackson.databind.ObjectMapper; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; -import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; -import it.enea.cruise.config.SpringFoxConfig; -import it.enea.cruise.config.dataDBConfiguration; -import it.enea.cruise.config.userDBConfiguration; -import it.enea.cruise.controller.UserController; -import it.enea.cruise.dto.LocalUserDTO; -import it.enea.cruise.service.idp.IEncryptionManager; -import it.enea.cruise.service.idp.IdpProvider; -import it.enea.scp.idp.sdk.model.UserDto; - - -@RunWith(SpringRunner.class) -@SpringBootTest(classes= {userDBConfiguration.class, SpringFoxConfig.class, dataDBConfiguration.class}) +@SpringBootTest +@ExtendWith(MockitoExtension.class) +/*@SpringBootTest(classes= {userDBConfiguration.class, SpringFoxConfig.class, dataDBConfiguration.class})*/ @TestPropertySource( - locations = "classpath:application.properties") + locations = "classpath:application.properties") @AutoConfigureMockMvc @ComponentScan(basePackages = "it.enea.cruise") -@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +@AutoConfigurationPackage(basePackages = "it.enea.cruise") class GecoRegistrationSpringApplicationTests { - //@Value("${t.userToken}") - //private String userToken; - - //@Value("${t.adminToken}") - //private String adminToken; - - @Value("${idp.testAdminEmail}") - String userAdminEmail; - - @Value("${idp.testAdminPwd}") - String userAdminPwd; - - @Value("${idp.testUserEmail}") - String testUserEmail; - - @Value("${idp.testUserPwd}") - String testUserPwd; - - @Autowired - private MockMvc mvc; - - @Autowired - IdpProvider idpClientManager; - - @Autowired - IEncryptionManager encryptionManager; - - @Autowired - UserController userController; - - private String token; - - - @Test - @Order(5) - void getUserFromEmailAndPassword() throws Exception { - - mvc.perform( - post("/user/login") - .contentType(MediaType.APPLICATION_JSON) - .param("username", userAdminEmail) - .param("password", userAdminPwd)) - .andExpect(status().isOk()) - .andDo(print()); - - mvc.perform( - post("/user/login") - .contentType(MediaType.APPLICATION_JSON) - .param("username", testUserEmail) - .param("password", testUserPwd)) - .andExpect(status().isOk()) - .andDo(print()); - - mvc.perform( - post("/user/login") - .contentType(MediaType.APPLICATION_JSON) - .param("username", testUserEmail + "w") - .param("password", testUserPwd)) - .andExpect(status().isForbidden()) - .andDo(print()); - + //@Value("${t.userToken}") + //private String userToken; + + //@Value("${t.adminToken}") + //private String adminToken; + + @Value("${idp.testAdminEmail}") + String userAdminEmail; + + @Value("${idp.testAdminPwd}") + String userAdminPwd; + + @Value("${idp.testUserEmail}") + String testUserEmail; + + @Value("${idp.testUserPwd}") + String testUserPwd; + + @Autowired + private MockMvc mvc; + + @Mock + private IdpProvider idpProvider; + + private String token; + + + @Test + @Order(5) + void getUserFromEmailAndPassword() throws Exception { + /*User user = new User(); + user.setEmail(userAdminEmail);*/ + /*when(idpProvider.login(userAdminEmail, userAdminPwd)).thenReturn(user); + when(idpProvider.login(testUserEmail, testUserPwd)).thenReturn(user);*/ + + mvc.perform( + post("/user/login") + .contentType(MediaType.APPLICATION_JSON) + .param("username", userAdminEmail) + .param("password", userAdminPwd)) + .andExpect(status().isOk()) + .andDo(print()); + + mvc.perform( + post("/user/login") + .contentType(MediaType.APPLICATION_JSON) + .param("username", testUserEmail) + .param("password", testUserPwd)) + .andExpect(status().isOk()) + .andDo(print()); + + mvc.perform( + post("/user/login") + .contentType(MediaType.APPLICATION_JSON) + .param("username", testUserEmail + "w") + .param("password", testUserPwd)) + .andExpect(status().isForbidden()) + .andDo(print()); + // String userContent ="{\n" // + " \"name\": \"Gianluca\",\n" // + " \"surname\": \"D'Agosta\",\n" @@ -146,226 +137,225 @@ class GecoRegistrationSpringApplicationTests { // .content(deleteContent)) // .andExpect(status().isOk()) // .andDo(print()); - - } - - @Test - @Order(6) - void getData() throws Exception { - - Handler handler = new Handler(); - - mvc.perform( - post("/user/login") - .contentType(MediaType.APPLICATION_JSON) - .param("username", testUserEmail) - .param("password", testUserPwd)) - .andExpect(status().isOk()) - .andDo(handler) - .andDo(print()); - - - mvc.perform( - post("/user/getUserIdFromToken") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", token)) - .andExpect(status().isOk()) - .andDo(print()); - - mvc.perform( - post("/user/isTokenValid") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", token)) - .andExpect(status().isOk()) - .andDo(print()); - - mvc.perform( - post("/data/getListOfFunctions") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", token)) - .andExpect(status().isOk()) - .andDo(print()); - - String content ="{" - + "\"communityid\": 2,\n" - + " \"queryid\":2,\n" - + "\" endDate\": \"2021-09-22 23:59:59\",\n" - + "\" startDate\":\"2021-09-22 00:00:00\"\n" - + "}"; - - - - mvc.perform( - post("/data/getData") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", token) - .header("Content-Language", "it_IT") - .content (content)) - .andExpect(status().isOk()) - //.andExpect(jsonPath("$.result", greaterThan(2))) - .andDo(print()); - - content ="{\"communityid\": 2,\n" - + " \"queryid\":1,\n" - + "\" maxValue\": \"3000\",\n" - + "\" minValue\":\"0\"\n" - + "}"; - - - mvc.perform( - post("/data/getData") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", token) - .header("Content-Language", "it_IT") - .content(content)) - .andExpect(status().isOk()) - .andDo(print()); - - content ="{\"communityid\": 2,\n" - + " \"queryid\":5,\n" - + "\" endDate\": \"2021-09-22 23:59:59\",\n" - + "\" startDate\":\"2021-09-21 00:00:00\"\n" - + "}"; - - mvc.perform( - post("/data/getData") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", token) - .header("Content-Language", "it_IT") - .content(content)) - .andExpect(status().isOk()) - .andDo(print()); - - content ="{\"communityid\": 2,\n" - + " \"queryid\":2,\n" - + "\" endDate\": \"2021-09-22 23:59:59\",\n" - + "\" startDate\":\"2021-09-21 00:00:00\"\n" - + "}"; - - - mvc.perform( - post("/data/getData") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", token) - .header("Content-Language", "it_IT") - .content(content)) - .andExpect(status().isOk()) - .andDo(print()); - - content ="{\"communityid\": 2,\n" - + " \"queryid\":6\n" - + "}"; - - mvc.perform( - post("/data/getData") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", token) - .header("Content-Language", "it_IT") - .content(content)) - .andExpect(status().isOk()) - .andDo(print()); - - content ="{\"queryid\":4\n" - + "}"; - - mvc.perform( - post("/data/getData") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", token) - .content(content)) - .andExpect(status().isOk()) - .andDo(print()); - - mvc.perform( - post("/user/logout") - .contentType(MediaType.APPLICATION_JSON) - .header("Authorization", token) - .param("token", token)) - .andExpect(status().isOk()) - .andDo(print()); - - } - - /* - * Questo test verifica le funzioni di estrazione dei dati dal DB. - * Devono ancora implementare la gestione degli utenti. - * - */ - // @Test - // @Order(12) - // void getConsumptionData() throws Exception { - // mvc.perform( - // post("/data/getInstantConsumption")) - // .andExpect(status().isOk()) - // .andDo(print()) - // .andExpect(jsonPath("$..property").exists()) - // .andExpect(jsonPath("$..val").isNotEmpty()); - // - // mvc.perform( - // post("/data/todayConsumption")) - // .andExpect(status().isOk()) - // .andDo(print()) - // .andExpect(jsonPath("$..property").exists()) - // .andExpect(jsonPath("$..val").isNotEmpty()); - // - // mvc.perform( - // post("/data/getConsumptionInAPeriod") - // .queryParam("startDate", "2021-06-01 00:00:00") - // .queryParam("endDate", "2021-06-07 00:00:00") - // ) - // .andExpect(status().isOk()) - // .andDo(print()) - // .andExpect(jsonPath("$..property").exists()) - // .andExpect(jsonPath("$..val").isNotEmpty()); - // - // - // } - - - private class Token { - String token; - - public Token(String token) { - this.token = token; - } - - public String getToken() { - return this.token; - } - - public void setToken (String token) { - this.token = token; - } - } - - private UserDto createFakeUserDto(){ - - UserDto user = new UserDto(); - - user.setAddress("Via qualsiasi, un po' piu' in la' 32, 00100 Ovunque"); - user.setName("cancellami"); - user.setSurname("D'Agosta"); - user.setPhone("0516098466"); - user.setEmail("utente.ec@test.it"); - user.setEmailConfirmed(true); - user.setPassword("gianluca.dagosta"); - user.setOrganization("Comunita' GECO"); - user.setPasswordConfirm("gianluca.dagosta"); - user.setRole("Citizen"); - - return user; - - } - - private class Handler implements ResultHandler{ - - @Override - public void handle(MvcResult result) throws Exception { - String pippo = result.getResponse().getContentAsString(); - LocalUserDTO user = new ObjectMapper().readValue(pippo, LocalUserDTO.class); - token = user.getToken().getValue(); - //System.out.println(result); - - } - } + + } + + @Test + @Order(6) + void getData() throws Exception { + + Handler handler = new Handler(); + + mvc.perform( + post("/user/login") + .contentType(MediaType.APPLICATION_JSON) + .param("username", testUserEmail) + .param("password", testUserPwd)) + .andExpect(status().isOk()) + .andDo(handler) + .andDo(print()); + + + mvc.perform( + post("/user/getUserIdFromToken") + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", token)) + .andExpect(status().isOk()) + .andDo(print()); + + mvc.perform( + post("/user/isTokenValid") + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", token)) + .andExpect(status().isOk()) + .andDo(print()); + + mvc.perform( + post("/data/getListOfFunctions") + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", token)) + .andExpect(status().isOk()) + .andDo(print()); + + String content = "{" + + "\"communityid\": 2,\n" + + " \"queryid\":2,\n" + + "\" endDate\": \"2021-09-22 23:59:59\",\n" + + "\" startDate\":\"2021-09-22 00:00:00\"\n" + + "}"; + + + mvc.perform( + post("/data/getData") + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", token) + .header("Content-Language", "it_IT") + .content(content)) + .andExpect(status().isOk()) + //.andExpect(jsonPath("$.result", greaterThan(2))) + .andDo(print()); + + content = "{\"communityid\": 2,\n" + + " \"queryid\":1,\n" + + "\" maxValue\": \"3000\",\n" + + "\" minValue\":\"0\"\n" + + "}"; + + + mvc.perform( + post("/data/getData") + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", token) + .header("Content-Language", "it_IT") + .content(content)) + .andExpect(status().isOk()) + .andDo(print()); + + content = "{\"communityid\": 2,\n" + + " \"queryid\":5,\n" + + "\" endDate\": \"2021-09-22 23:59:59\",\n" + + "\" startDate\":\"2021-09-21 00:00:00\"\n" + + "}"; + + mvc.perform( + post("/data/getData") + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", token) + .header("Content-Language", "it_IT") + .content(content)) + .andExpect(status().isOk()) + .andDo(print()); + + content = "{\"communityid\": 2,\n" + + " \"queryid\":2,\n" + + "\" endDate\": \"2021-09-22 23:59:59\",\n" + + "\" startDate\":\"2021-09-21 00:00:00\"\n" + + "}"; + + + mvc.perform( + post("/data/getData") + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", token) + .header("Content-Language", "it_IT") + .content(content)) + .andExpect(status().isOk()) + .andDo(print()); + + content = "{\"communityid\": 2,\n" + + " \"queryid\":6\n" + + "}"; + + mvc.perform( + post("/data/getData") + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", token) + .header("Content-Language", "it_IT") + .content(content)) + .andExpect(status().isOk()) + .andDo(print()); + + content = "{\"queryid\":4\n" + + "}"; + + mvc.perform( + post("/data/getData") + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", token) + .content(content)) + .andExpect(status().isOk()) + .andDo(print()); + + mvc.perform( + post("/user/logout") + .contentType(MediaType.APPLICATION_JSON) + .header("Authorization", token) + .param("token", token)) + .andExpect(status().isOk()) + .andDo(print()); + + } + + /* + * Questo test verifica le funzioni di estrazione dei dati dal DB. + * Devono ancora implementare la gestione degli utenti. + * + */ + // @Test + // @Order(12) + // void getConsumptionData() throws Exception { + // mvc.perform( + // post("/data/getInstantConsumption")) + // .andExpect(status().isOk()) + // .andDo(print()) + // .andExpect(jsonPath("$..property").exists()) + // .andExpect(jsonPath("$..val").isNotEmpty()); + // + // mvc.perform( + // post("/data/todayConsumption")) + // .andExpect(status().isOk()) + // .andDo(print()) + // .andExpect(jsonPath("$..property").exists()) + // .andExpect(jsonPath("$..val").isNotEmpty()); + // + // mvc.perform( + // post("/data/getConsumptionInAPeriod") + // .queryParam("startDate", "2021-06-01 00:00:00") + // .queryParam("endDate", "2021-06-07 00:00:00") + // ) + // .andExpect(status().isOk()) + // .andDo(print()) + // .andExpect(jsonPath("$..property").exists()) + // .andExpect(jsonPath("$..val").isNotEmpty()); + // + // + // } + + + private class Token { + String token; + + public Token(String token) { + this.token = token; + } + + public String getToken() { + return this.token; + } + + public void setToken(String token) { + this.token = token; + } + } + + private UserDto createFakeUserDto() { + + UserDto user = new UserDto(); + + user.setAddress("Via qualsiasi, un po' piu' in la' 32, 00100 Ovunque"); + user.setName("cancellami"); + user.setSurname("D'Agosta"); + user.setPhone("0516098466"); + user.setEmail("utente.ec@test.it"); + user.setEmailConfirmed(true); + user.setPassword("gianluca.dagosta"); + user.setOrganization("Comunita' GECO"); + user.setPasswordConfirm("gianluca.dagosta"); + user.setRole("Citizen"); + + return user; + + } + + private class Handler implements ResultHandler { + + @Override + public void handle(MvcResult result) throws Exception { + String pippo = result.getResponse().getContentAsString(); + LocalUserDTO user = new ObjectMapper().readValue(pippo, LocalUserDTO.class); + token = user.getToken().getValue(); + //System.out.println(result); + + } + } } diff --git a/gecoregistration/src/test/resources/application.properties b/gecoregistration/src/test/resources/application.properties index 4a069c63f87ca1a0ac09720c16f81de4b2996d96..20a3af45f8d6da5d00684d27cca617c0c90a9e08 100644 --- a/gecoregistration/src/test/resources/application.properties +++ b/gecoregistration/src/test/resources/application.properties @@ -4,6 +4,7 @@ spring.jackson.time-zone=Europe/Rome #Testing testingPhase = true +spring.profiles.active=test #ActivationLink activationLink= @@ -12,23 +13,55 @@ activationLink= oracleRoleAdmin=oracle-admin platformRoleAdmin=platform-admin communityRoleAdmin=community-admin +communityMemberRole = community-member +stakeHolderRole = stakeholder + +# Database +spring.datasource.url=jdbc:h2:mem:user_db;INIT=CREATE SCHEMA IF NOT EXISTS CRUISE; +spring.datasource.username=sa +spring.datasource.password=password +spring.datasource.driver-class-name=org.h2.Driver +spring.jpa.database-platform=org.hibernate.dialect.H2Dialect +spring.jpa.hibernate.ddl-auto=update ## correct column naming -spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy -spring.data-datasource-idp.jdbcUrl= -spring.data-datasource-idp.hikari.url= -spring.data-datasource-idp.username= -spring.data-datasource-idp.password= -spring.data-datasource-idp.driver-class-name=org.postgresql.Driver -spring.data-datasource-idp.maximumPoolSize=2 -spring.data-datasource-idp.minimumIdle=1 -spring.data-datasource-idp.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect -spring.data-datasource-idp.hibernate.hbm2ddl=none +# spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.EJB3NamingStrategy +# spring.data-datasource-idp.jdbcUrl= +# spring.data-datasource-idp.hikari.url= +# spring.data-datasource-idp.username= +# spring.data-datasource-idp.password= +# spring.data-datasource-idp.driver-class-name=org.postgresql.Driver +# spring.data-datasource-idp.maximumPoolSize=2 +# spring.data-datasource-idp.minimumIdle=1 +# spring.data-datasource-idp.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect +# spring.data-datasource-idp.hibernate.hbm2ddl=none +# IDP DB +#spring.data-datasource-idp.jdbcUrl=jdbc:h2:mem:data_db;INIT=CREATE SCHEMA IF NOT EXISTS CRUISE +#spring.data-datasource-idp.username=sa +#spring.data-datasource-idp.password=password +#spring.data-datasource-idp.driver-class-name=org.h2.Driver +#spring.data-datasource-idp.maximumPoolSize=2 +#spring.data-datasource-idp.minimumIdle=1 +#spring.data-datasource-idp.hibernate.dialect=org.hibernate.dialect.H2Dialect +#spring.data-datasource-idp.hibernate.hbm2ddl=update +#spring.data-datasource-idp.hikari.maximumPoolSize=5 +#spring.data-datasource-idp.hikari.pool-name=HikariDataPool +# +## User DB +#spring.user-datasource-idp.jdbcUrl=jdbc:h2:mem:user_db;INIT=CREATE SCHEMA IF NOT EXISTS POSTGRES +##spring.user-datasource-idp.hikari.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:selfuser}?currentSchema=public +#spring.user-datasource-idp.username=sa +#spring.user-datasource-idp.password=password +#spring.user-datasource-idp.driver-class-name=org.h2.Driver +#spring.user-datasource-idp.hibernate.dialect=org.hibernate.dialect.H2Dialect +#spring.user-datasource-idp.hibernate.hbm2ddl=update +#spring.user-datasource-idp.hikari.pool-name=HikariUserPool spring.jpa.show-sql=true -logging.level.org.hibernate.SQL=TRACE -logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE + +logging.level.org.hibernate.SQL=info +logging.level.org.hibernate.type.descriptor.sql.BasicBinder=info @@ -40,33 +73,35 @@ keycloak.credentials.secret = k.adminusername = k.adminpassword = -# Email +# Mail spring.mail.host= spring.mail.port= spring.mail.username= spring.mail.password= spring.mail.properties.mail.smtp.auth= spring.mail.properties.mail.smtp.starttls.enable= -spring.mail.templates.path= +spring.mail.templates.path=classpath:templates -idp.auth-server-url = idp.id = 4 idp.clientName = -idp.clientId = -idp.clientSecret = +idp.testAdminEmail = admin@mail.com +idp.testAdminPwd = pass123 +idp.testUserEmail = user@mail.com +idp.testUserPwd = pass123 + +t.userToken = +t.adminToken = + +# IDP +idp.auth-server-url = http://${IDP_AUTH_SERVER:localhost}:8005 +idp.realm = cruise +idp.clientId = enea +idp.clientSecret = password idp.m2mUserEmail = idp.m2mUserPwd = -idp.testAdminEmail = -idp.testAdminPwd = -idp.testUserEmail = -idp.testUserPwd = idp.login-callback.url = idp.logout-callback.url = idp.profile-callback.url = - idp.keyManager.privateKeyContent = idp.keyManager.publicKeyContent = - -t.userToken = -t.adminToken = idp.keyManager.AESKey = \ No newline at end of file diff --git a/gecoregistration/src/test/resources/templates/mailMassage_it_IT.ftl b/gecoregistration/src/test/resources/templates/mailMassage_it_IT.ftl new file mode 100644 index 0000000000000000000000000000000000000000..fcb2cb37718082efa252d719dd40141e5a98b3bf --- /dev/null +++ b/gecoregistration/src/test/resources/templates/mailMassage_it_IT.ftl @@ -0,0 +1,15 @@ + + + + + + +

Hi ${recipientName},

+

please activate your registration using the link

+

${link}

+

Regards,

+

+ Administrator at SmartEnergyCommunity
+

+ + \ No newline at end of file diff --git a/lec/Dockerfile b/lec/Dockerfile index 147c26f9ddbc796834cd9e1dfb1821b3e1b194ba..2fe2f388ec7441e4b6a83f4e03bb50a55af344f8 100644 --- a/lec/Dockerfile +++ b/lec/Dockerfile @@ -1,13 +1,4 @@ -#FROM node:12.22.12-alpine -#WORKDIR /lec -#RUN npm install -g @angular/cli@12.1.1 -#RUN npm set strict-ssl false -#EXPOSE 4200:4200 -#ENTRYPOINT ["/bin/sh", "-c" , "(test -d node_modules || npm install) && ng serve --host 0.0.0.0 --proxy-config proxy.conf.json --poll"] - - - -FROM node:14 +FROM node:20-alpine #ENV NODE_OPTIONS=--openssl-legacy-provider #RUN mkdir /lec WORKDIR /lec @@ -15,10 +6,8 @@ WORKDIR /lec COPY . /lec RUN npm set strict-ssl false -RUN npm install -g @angular/cli@13 +RUN npm install -g @angular/cli@18.2.6 RUN npm install - - RUN npm ci EXPOSE 4200:4200 diff --git a/lec/src/app/app-routing.module.ts b/lec/src/app/app-routing.module.ts index 6486edbc074c33c3f7ced0f1235ce2e4e191bcf8..39a72d272befaf91bdcaff569b993d8df5882e4a 100644 --- a/lec/src/app/app-routing.module.ts +++ b/lec/src/app/app-routing.module.ts @@ -11,12 +11,14 @@ import {UpdateComponent} from "./components/update/update.component"; import {ChangepasswordComponent} from "./components/changepassword/changepassword.component"; import {LoginOidComponent} from "./components/login-oid/login-oid.component"; import {AuthGuard} from "./guards/auth.guard"; +import {LogoutOidComponent} from "./components/logout-oid/logout-oid.component"; const routes: Routes = [ { path: '', component: HomeComponent }, { path: 'login', component: LoginComponent }, { path: 'login-oid', component: LoginOidComponent }, + { path: 'logout-oid', component: LogoutOidComponent }, { path: 'account/activate/:code', component: AccountActivateComponent }, { path: 'register', component: RegisterComponent }, { path: 'update', component: UpdateComponent }, diff --git a/lec/src/app/app.module.ts b/lec/src/app/app.module.ts index 7bc497384b2722840ea41c9e2f44d0e6482ecc62..9cc4c45311b4f29499a4958f9a8544ea1811cdbf 100644 --- a/lec/src/app/app.module.ts +++ b/lec/src/app/app.module.ts @@ -88,6 +88,7 @@ import {BaseChartDirective, provideCharts, withDefaultRegisterables} from 'ng2-c import {MatButtonModule} from "@angular/material/button"; import {OAuthModule, OAuthStorage} from "angular-oauth2-oidc"; import { LoginOidComponent } from './components/login-oid/login-oid.component'; +import { LogoutOidComponent } from './components/logout-oid/logout-oid.component'; @@ -137,7 +138,8 @@ export function storageFactory() : OAuthStorage { ChangepasswordComponent, AccountActivateComponent, MenuComponent, - LoginOidComponent + LoginOidComponent, + LogoutOidComponent ], exports: [ RawHtmlPipe, diff --git a/lec/src/app/components/header/header.component.ts b/lec/src/app/components/header/header.component.ts index ea5477a5a2cac1bab37c12a525d3ed2b944b6661..42bdc7c5803ae2824bccf94d032e7dc4f8d132ac 100644 --- a/lec/src/app/components/header/header.component.ts +++ b/lec/src/app/components/header/header.component.ts @@ -160,14 +160,16 @@ export class HeaderComponent implements OnInit, OnDestroy { this.router.resetConfig(this.router.config.filter(o => !o.data || !o.data.dynamic)); this.authService.removeAuthorization(); - this.userService.logout().subscribe( { + /*this.disposeOnDestroySubscriptions.push(this.userService.logout().subscribe( { next: _ => { + console.info("Logging out...") this.router.navigateByUrl("/"); }, error: err => { + console.error("Error logging out: ", err); this.router.navigateByUrl("/"); } - }); + }));*/ } diff --git a/lec/src/app/components/login-oid/login-oid.component.ts b/lec/src/app/components/login-oid/login-oid.component.ts index 0eb31f1ee5dea9384675ce5c3d1f8a5664707bd6..d1e0b49030015aa9a9e5cb08960908545dd5fb47 100644 --- a/lec/src/app/components/login-oid/login-oid.component.ts +++ b/lec/src/app/components/login-oid/login-oid.component.ts @@ -1,23 +1,26 @@ -import {Component, OnInit} from '@angular/core'; +import {Component, OnDestroy, OnInit} from '@angular/core'; import {UserService} from "../../services/user.service"; import {OAuthEvent, OAuthService} from "angular-oauth2-oidc"; import {environment} from "../../../environments/environment"; import {AuthService} from "../../services/auth.service"; +import {Subscription} from "rxjs"; @Component({ selector: 'app-login-oid', templateUrl: './login-oid.component.html', styleUrls: ['./login-oid.component.css'] }) -export class LoginOidComponent implements OnInit { +export class LoginOidComponent implements OnInit, OnDestroy { provider: string = environment.oidProvider; + oauthHandler?: Subscription; constructor(private userService: UserService, private authService: OAuthService, private appAuth: AuthService) {} ngOnInit(): void { // IMPORTANT: Entry point from OID provider. Token will not be present immediately. Must start the open id flow - this.authService.events + this.oauthHandler = this.authService.events .subscribe((e: OAuthEvent) => { + console.info("OAuth subscribe") // TODO: Manage here other events if needed. Refer to angular-oauth2-oidc library if (e.type === 'token_received') { this.userService.login(); @@ -31,4 +34,10 @@ export class LoginOidComponent implements OnInit { // IMPORTANT: this reloads the open id flow and tries login, which fires the token_received handled in constructor this.userService.initOpenId(); } + + ngOnDestroy(): void { + if (this.oauthHandler) + this.oauthHandler.unsubscribe(); + this.oauthHandler = undefined; + } } diff --git a/lec/src/app/components/logout-oid/logout-oid.component.css b/lec/src/app/components/logout-oid/logout-oid.component.css new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/lec/src/app/components/logout-oid/logout-oid.component.html b/lec/src/app/components/logout-oid/logout-oid.component.html new file mode 100644 index 0000000000000000000000000000000000000000..9f9c7e8f60b389ae03aff3171213140f1c706b58 --- /dev/null +++ b/lec/src/app/components/logout-oid/logout-oid.component.html @@ -0,0 +1,4 @@ +
+ +
{{ 'LOGOUT.LOADING' | translate }} {{ 'LABEL.WITH' | translate }} {{provider}}
+
\ No newline at end of file diff --git a/lec/src/app/components/logout-oid/logout-oid.component.spec.ts b/lec/src/app/components/logout-oid/logout-oid.component.spec.ts new file mode 100644 index 0000000000000000000000000000000000000000..839aef366341eb18bcf1d0726bd706787ca597d2 --- /dev/null +++ b/lec/src/app/components/logout-oid/logout-oid.component.spec.ts @@ -0,0 +1,25 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { LogoutOidComponent } from './logout-oid.component'; + +describe('LogoutOidComponent', () => { + let component: LogoutOidComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + declarations: [ LogoutOidComponent ] + }) + .compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(LogoutOidComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/lec/src/app/components/logout-oid/logout-oid.component.ts b/lec/src/app/components/logout-oid/logout-oid.component.ts new file mode 100644 index 0000000000000000000000000000000000000000..34cb9419520bf3f5fd244f3a0b83bf9c2ef3e593 --- /dev/null +++ b/lec/src/app/components/logout-oid/logout-oid.component.ts @@ -0,0 +1,39 @@ +import {Component, OnDestroy, OnInit} from '@angular/core'; +import {environment} from "../../../environments/environment"; +import {Subscription} from "rxjs"; +import {UserService} from "../../services/user.service"; +import {OAuthEvent, OAuthService} from "angular-oauth2-oidc"; +import {AuthService} from "../../services/auth.service"; + +@Component({ + selector: 'app-logout-oid', + templateUrl: './logout-oid.component.html', + styleUrls: ['./logout-oid.component.css'] +}) +export class LogoutOidComponent implements OnInit, OnDestroy { + provider: string = environment.oidProvider; + oauthHandler?: Subscription; + + constructor(private userService: UserService, private authService: OAuthService, private appAuth: AuthService) {} + + ngOnInit(): void { + // IMPORTANT: Entry point from OID provider. Token will not be present immediately. Must start the open id flow + this.oauthHandler = this.authService.events + .subscribe((e: OAuthEvent) => { + console.info("OAuth logout") + + if (e.type === 'logout') { + this.appAuth.removeAuthorization(); + } + }); + + // IMPORTANT: this reloads the open id flow and tries login, which fires the token_received handled in constructor + this.userService.initOpenId(); + } + + ngOnDestroy(): void { + if (this.oauthHandler) + this.oauthHandler.unsubscribe(); + this.oauthHandler = undefined; + } +} diff --git a/lec/src/app/interceptors/http-request.interceptor.ts b/lec/src/app/interceptors/http-request.interceptor.ts index fda39fa6075e56edd5ef0195dcf454c9228d35fe..dcc9681a269f5c22d75f05cd736d36054c4ea05a 100644 --- a/lec/src/app/interceptors/http-request.interceptor.ts +++ b/lec/src/app/interceptors/http-request.interceptor.ts @@ -3,10 +3,7 @@ import {HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest} from import {Observable, Subscription, throwError} from 'rxjs'; import {Authorization} from '../models/Authorization'; import {catchError} from "rxjs/operators"; -import {MessageService} from "primeng/api"; import {AuthService} from "../services/auth.service"; -import {environment} from "../../environments/environment"; -import {OAuthService} from "angular-oauth2-oidc"; @Injectable() export class HttpRequestInterceptor implements HttpInterceptor, OnDestroy { @@ -15,9 +12,7 @@ export class HttpRequestInterceptor implements HttpInterceptor, OnDestroy { private readonly authObserver?: Subscription ; constructor( - private authService: AuthService, - private oauthService: OAuthService, - private messageService: MessageService) { + private authService: AuthService) { this.authObserver = this.authService.onAuthChange().subscribe((authorization: Authorization) => { this.token = authorization?.authenticated ? "Auth-Token " + authorization?.token : ""; }); @@ -50,6 +45,7 @@ export class HttpRequestInterceptor implements HttpInterceptor, OnDestroy { private handleAuthError(err: any): Observable { if (err.status === 401 || err.status === 403) { + this.token = ""; this.authService.removeAuthorization(); } diff --git a/lec/src/app/services/auth.service.ts b/lec/src/app/services/auth.service.ts index 8bbe7656652b91885423d5d5d262fbc0e947ff1d..c04de11c44c677d022c137f26a1e5df3f0768f30 100644 --- a/lec/src/app/services/auth.service.ts +++ b/lec/src/app/services/auth.service.ts @@ -1,6 +1,8 @@ import {Injectable} from '@angular/core'; import {Authorization} from "../models/Authorization"; import {BehaviorSubject} from "rxjs"; +import {Router} from "@angular/router"; +import {environment} from "../../environments/environment"; @Injectable({ providedIn: 'root' @@ -32,7 +34,19 @@ export class AuthService { removeAuthorization() { this.authorization = undefined; - sessionStorage.removeItem("authorization"); + sessionStorage.removeItem("authorization") + /*localStorage.clear(); + sessionStorage.clear();*/ + + /*// Clear caches to remove oid data + if ('caches' in window) { + caches.keys().then(function(cacheNames) { + cacheNames.forEach(function(cacheName) { + caches.delete(cacheName); + }); + }); + }*/ + this.authorizationSubject.next(this.authorization); } diff --git a/lec/src/app/services/user.service.ts b/lec/src/app/services/user.service.ts index 1b3b8c18c99fe1ee9f7d1ec4e5c87723971a4ad0..86a638864b40c33b0e9404f9b3a303c9752d18e6 100644 --- a/lec/src/app/services/user.service.ts +++ b/lec/src/app/services/user.service.ts @@ -26,13 +26,10 @@ export class UserService implements OnDestroy { constructor(private http: HttpClient, private router: Router, private auth: AuthService, private utils: UtilsService, private oauthService: OAuthService) { this.authSubscription = this.auth.onAuthChange().subscribe((authorization) => { - this.user = authorization?.user; - - this.selectedCommunity = this.user?.usercommunities[0].communityid! ? +this.user?.usercommunities[0].communityid! : 0; - this.community = this.user?.usercommunities[0] ? this.user?.usercommunities[0] : new Community(); + this.updateUserInfo(authorization); + this.checkIfShouldLogout(authorization); }) auth.initAuthorization(); - } ngOnDestroy(): void { @@ -40,11 +37,23 @@ export class UserService implements OnDestroy { this.authSubscription.unsubscribe(); } + private updateUserInfo(authorization: any) { + this.user = authorization?.user; + this.selectedCommunity = this.user?.usercommunities[0].communityid! ? +this.user?.usercommunities[0].communityid! : 0; + this.community = this.user?.usercommunities[0] ? this.user?.usercommunities[0] : new Community(); + } + + private checkIfShouldLogout(authorization: any) { + /*if (!authorization) { + this.router.navigateByUrl("/"); + }*/ + } + public initOpenId() { const authConfig: AuthConfig = { issuer: environment.oidIssuer, redirectUri: window.location.origin + "/login-oid", - logoutUrl: window.location.origin, + logoutUrl: window.location.origin + "/logout-oid", clientId: environment.oidClient, dummyClientSecret: environment.oidSecret, responseType: environment.oidResponseType, @@ -162,19 +171,6 @@ export class UserService implements OnDestroy { } } - getUserFullName() { - this.http.get(environment.baseUrl + "/lecservice/admin") - .subscribe( - data => { - console.log("getUserFullName: ", data); - alert(data); - }, - (err: HttpErrorResponse) => { - console.error('An error occurred:', err.error); - } - ); - } - getCommunities(): Observable { return this.http.get(environment.baseUrl + "/lecservice/listCommunities"); } diff --git a/lec/src/assets/i18n/it.json b/lec/src/assets/i18n/it.json index c2e4e2a8d673d0afefdf01ef8b724a2b4e729ddb..cba44f6d7e8c5c1ac01114ac8176c64ac5deed44 100644 --- a/lec/src/assets/i18n/it.json +++ b/lec/src/assets/i18n/it.json @@ -43,6 +43,9 @@ "LOADING": "Effettuando l'accesso", "NO_PAGES_ASSIGNED": "Accesso effettuato ma al tuo account non è stato associato nessun servizio" }, + "LOGOUT": { + "LOADING": "Uscendo dal sistema" + }, "HEADER": { "TITLE": "Comunità energetiche locali", "SIGN_IN": "Entra", diff --git a/lecservice/Dockerfile b/lecservice/Dockerfile index 5c62c297fe5b3130e2d62b7a1b76a50143da835a..076a478cff37002ddee0b41b24f7946335fccbac 100644 --- a/lecservice/Dockerfile +++ b/lecservice/Dockerfile @@ -1,4 +1,3 @@ - FROM maven:3.8-amazoncorretto-11 as build WORKDIR /lecservice @@ -31,6 +30,7 @@ RUN echo ## DB_PORT = ${DB_PORT} ## RUN echo ## DB_PASSWORD = ${DB_PASSWORD} ## RUN echo ## DB_HOST = ${DB_HOST} ## RUN echo ## BACKOFFICE_API = ${ARG_BACKOFFICE_API} ## +RUN echo ## BACKOFFICE_API = ${ARG_BACKOFFICE_API} ## RUN echo ################################## ENV JAVA_OPTS="-Xmx1512m -Dfile.encoding=UTF-8" diff --git a/lecservice/src/main/java/enea/lecservice/configuration/StartUpRunner.java b/lecservice/src/main/java/enea/lecservice/configuration/StartUpRunner.java index 1f800a2a570a97aec920ae7d342eca94132a8151..745fb37a74db663d7a157d59d2f9d6a8cbdd6633 100644 --- a/lecservice/src/main/java/enea/lecservice/configuration/StartUpRunner.java +++ b/lecservice/src/main/java/enea/lecservice/configuration/StartUpRunner.java @@ -9,8 +9,9 @@ import org.springframework.context.annotation.Configuration; @Configuration public class StartUpRunner implements CommandLineRunner { - @Value("${DB_USER}") + @Value("${DB_HOST}") protected String dbHost; + @Override public void run(String... args) throws Exception { log.error("Host is: {}", dbHost); diff --git a/lecservice/src/main/java/enea/lecservice/controllers/advice/ENEAAdvice.java b/lecservice/src/main/java/enea/lecservice/controllers/advice/ENEAAdvice.java index 105d8a106da628b285cfc90c1449f8c3fe7a41d3..dde93f5d104a373a7244da9bb95b9c19916ce51b 100644 --- a/lecservice/src/main/java/enea/lecservice/controllers/advice/ENEAAdvice.java +++ b/lecservice/src/main/java/enea/lecservice/controllers/advice/ENEAAdvice.java @@ -2,6 +2,7 @@ package enea.lecservice.controllers.advice; import enea.lecservice.models.dto.ServiceResponse; import org.springframework.http.HttpStatus; +import org.springframework.security.access.AccessDeniedException; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.web.bind.annotation.ExceptionHandler; @@ -10,12 +11,15 @@ import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; +import javax.servlet.http.HttpServletResponse; + @RestControllerAdvice public class ENEAAdvice extends ResponseEntityExceptionHandler { @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ExceptionHandler(value = { Exception.class, RuntimeException.class }) - public ServiceResponse unknownException(Exception ex, WebRequest req) { + public ServiceResponse unknownException(Exception ex, WebRequest req, HttpServletResponse res) { + res.setStatus(HttpStatus.OK.value()); return ServiceResponse.Error(ex); } @@ -26,7 +30,7 @@ public class ENEAAdvice extends ResponseEntityExceptionHandler { } @ResponseStatus(HttpStatus.UNAUTHORIZED) - @ExceptionHandler(value = { UsernameNotFoundException.class }) + @ExceptionHandler(value = { UsernameNotFoundException.class, AccessDeniedException.class }) public ServiceResponse notAuthorizedException(Exception ex, WebRequest req) { return ServiceResponse.Error(ex); } diff --git a/lecservice/src/main/java/enea/lecservice/security/jwt/JWTRequestFilter.java b/lecservice/src/main/java/enea/lecservice/security/jwt/JWTRequestFilter.java index 17a9f391b10b1297373bb460d163ec8d4b410afc..b2ccce6e8c63f16d15bcaf66fc11fd98abb5101b 100644 --- a/lecservice/src/main/java/enea/lecservice/security/jwt/JWTRequestFilter.java +++ b/lecservice/src/main/java/enea/lecservice/security/jwt/JWTRequestFilter.java @@ -14,6 +14,7 @@ import org.springframework.context.annotation.Profile; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; @@ -56,6 +57,11 @@ public class JWTRequestFilter extends OncePerRequestFilter { httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } + catch (UsernameNotFoundException ex) { + log.error("Username not found: {}", ExceptionUtils.getStackTrace(ex)); + httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + return; + } } filterChain.doFilter(httpServletRequest, httpServletResponse); diff --git a/lecservice/src/main/java/enea/lecservice/services/DataService.java b/lecservice/src/main/java/enea/lecservice/services/DataService.java index 7d4dc2db2ed5a3bd4f5a616a013fa38914e40644..a6b8861a459167cfa3284be4ba40461f7e419a7d 100644 --- a/lecservice/src/main/java/enea/lecservice/services/DataService.java +++ b/lecservice/src/main/java/enea/lecservice/services/DataService.java @@ -11,6 +11,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.ResponseEntity; import org.springframework.security.access.AccessDeniedException; import org.springframework.stereotype.Service; +import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import javax.security.sasl.AuthenticationException; @@ -72,11 +73,22 @@ public class DataService implements IDataService { var entity = new HttpEntity<>(map, headers); - ResponseEntity response = new RestTemplate().postForEntity(url, entity, String.class); - if (response.getStatusCode().is4xxClientError()) { + ResponseEntity response = null; + + try { + response = new RestTemplate().postForEntity(url, entity, String.class); + } + catch (HttpClientErrorException.Unauthorized e) { throw new AccessDeniedException("Serve data refused with 4xx error!"); } + catch (Exception e) { + log.error("Error reading data: ", e); + } + + if (response != null && response.getStatusCode().is4xxClientError()) { + throw new AccessDeniedException("Data server refused with 4xx error!"); + } - return response.getBody(); + return response != null ? response.getBody() : "[]"; } } diff --git a/lecservice/src/main/resources/application-oid.properties b/lecservice/src/main/resources/application-oid.properties index 27128fc7c3521a8774b0e3b727babd14e71df56f..f4165c979899e9630d173a7fa27658a9f4ad6445 100644 --- a/lecservice/src/main/resources/application-oid.properties +++ b/lecservice/src/main/resources/application-oid.properties @@ -3,9 +3,4 @@ authentication.endpoint=http://${BACKOFFICE_API:localhost}:8004/geco authentication.secret= authentication.login=/user/getUserFromToken authentication.logout=/user/logout -authentication.userFromToken= - -spring.datasource.url=jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5433}/${DB_NAME:selfuser}?currentSchema=cruise -spring.datasource.username=postgres -spring.datasource.password=secret -spring.datasource.driver-class-name=org.postgresql.Driver \ No newline at end of file +authentication.userFromToken= \ No newline at end of file