Initial commit

This commit is contained in:
2020-09-02 19:17:11 +02:00
commit aedadea912
363 changed files with 55473 additions and 0 deletions

16
src/main/docker/app.yml Normal file
View File

@@ -0,0 +1,16 @@
version: '2'
services:
evental-app:
image: evental
environment:
- _JAVA_OPTIONS=-Xmx512m -Xms256m
- SPRING_PROFILES_ACTIVE=prod,swagger
- MANAGEMENT_METRICS_EXPORT_PROMETHEUS_ENABLED=true
- SPRING_DATASOURCE_URL=jdbc:mysql://evental-mysql:3306/evental?useUnicode=true&characterEncoding=utf8&useSSL=false&createDatabaseIfNotExist=true
- JHIPSTER_SLEEP=30 # gives time for other services to boot before the application
ports:
- 8080:8080
evental-mysql:
extends:
file: mysql.yml
service: evental-mysql

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: 'Prometheus'
orgId: 1
folder: ''
type: file
disableDeletion: false
editable: true
options:
path: /etc/grafana/provisioning/dashboards

View File

@@ -0,0 +1,50 @@
apiVersion: 1
# list of datasources that should be deleted from the database
deleteDatasources:
- name: Prometheus
orgId: 1
# list of datasources to insert/update depending
# whats available in the database
datasources:
# <string, required> name of the datasource. Required
- name: Prometheus
# <string, required> datasource type. Required
type: prometheus
# <string, required> access mode. direct or proxy. Required
access: proxy
# <int> org id. will default to orgId 1 if not specified
orgId: 1
# <string> url
# On MacOS, replace localhost by host.docker.internal
url: http://localhost:9090
# <string> database password, if used
password:
# <string> database user, if used
user:
# <string> database name, if used
database:
# <bool> enable/disable basic auth
basicAuth: false
# <string> basic auth username
basicAuthUser: admin
# <string> basic auth password
basicAuthPassword: admin
# <bool> enable/disable with credentials headers
withCredentials:
# <bool> mark as default datasource. Max one per org
isDefault: true
# <map> fields that will be converted to json and stored in json_data
jsonData:
graphiteVersion: '1.1'
tlsAuth: false
tlsAuthWithCACert: false
# <string> json object of data that will be encrypted.
secureJsonData:
tlsCACert: '...'
tlsClientCert: '...'
tlsClientKey: '...'
version: 1
# <bool> allow users to edit datasources from the UI.
editable: true

View File

@@ -0,0 +1,26 @@
version: '2'
services:
evental-prometheus:
image: prom/prometheus:v2.16.0
volumes:
- ./prometheus/:/etc/prometheus/
command:
- '--config.file=/etc/prometheus/prometheus.yml'
ports:
- 9090:9090
# On MacOS, remove next line and replace localhost by host.docker.internal in prometheus/prometheus.yml and
# grafana/provisioning/datasources/datasource.yml
network_mode: 'host' # to test locally running service
evental-grafana:
image: grafana/grafana:6.6.2
volumes:
- ./grafana/provisioning/:/etc/grafana/provisioning/
environment:
- GF_SECURITY_ADMIN_PASSWORD=admin
- GF_USERS_ALLOW_SIGN_UP=false
- GF_INSTALL_PLUGINS=grafana-piechart-panel
ports:
- 3000:3000
# On MacOS, remove next line and replace localhost by host.docker.internal in prometheus/prometheus.yml and
# grafana/provisioning/datasources/datasource.yml
network_mode: 'host' # to test locally running service

13
src/main/docker/mysql.yml Normal file
View File

@@ -0,0 +1,13 @@
version: '2'
services:
evental-mysql:
image: mysql:8.0.19
# volumes:
# - ~/volumes/jhipster/evental/mysql/:/var/lib/mysql/
environment:
- MYSQL_USER=root
- MYSQL_ALLOW_EMPTY_PASSWORD=yes
- MYSQL_DATABASE=evental
ports:
- 3306:3306
command: mysqld --lower_case_table_names=1 --skip-ssl --character_set_server=utf8mb4 --explicit_defaults_for_timestamp

View File

@@ -0,0 +1,31 @@
# Sample global config for monitoring JHipster applications
global:
scrape_interval: 15s # By default, scrape targets every 15 seconds.
evaluation_interval: 15s # By default, scrape targets every 15 seconds.
# scrape_timeout is set to the global default (10s).
# Attach these labels to any time series or alerts when communicating with
# external systems (federation, remote storage, Alertmanager).
external_labels:
monitor: 'jhipster'
# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'prometheus'
# Override the global default and scrape targets from this job every 5 seconds.
scrape_interval: 5s
# scheme defaults to 'http' enable https in case your application is server via https
#scheme: https
# basic auth is not needed by default. See https://www.jhipster.tech/monitoring/#configuring-metrics-forwarding for details
#basic_auth:
# username: admin
# password: admin
metrics_path: /management/prometheus
static_configs:
- targets:
# On MacOS, replace localhost by host.docker.internal
- localhost:8080

View File

@@ -0,0 +1,7 @@
version: '2'
services:
evental-sonar:
image: sonarqube:8.2-community
ports:
- 9002:9000
- 9092:9092

View File

@@ -0,0 +1,20 @@
package edu.uoc.evental;
import io.github.jhipster.config.DefaultProfileUtil;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
/**
* This is a helper Java class that provides an alternative to creating a {@code web.xml}.
* This will be invoked only when the application is deployed to a Servlet container like Tomcat, JBoss etc.
*/
public class ApplicationWebXml extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
// set a default to use when no profile is configured.
DefaultProfileUtil.addDefaultProfile(application.application());
return application.sources(EventalApp.class);
}
}

View File

@@ -0,0 +1,98 @@
package edu.uoc.evental;
import edu.uoc.evental.config.ApplicationProperties;
import io.github.jhipster.config.DefaultProfileUtil;
import io.github.jhipster.config.JHipsterConstants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.core.env.Environment;
import javax.annotation.PostConstruct;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collection;
@SpringBootApplication
@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class})
public class EventalApp {
private static final Logger log = LoggerFactory.getLogger(EventalApp.class);
private final Environment env;
public EventalApp(Environment env) {
this.env = env;
}
/**
* Initializes evental.
* <p>
* Spring profiles can be configured with a program argument --spring.profiles.active=your-active-profile
* <p>
* You can find more information on how profiles work with JHipster on <a href="https://www.jhipster.tech/profiles/">https://www.jhipster.tech/profiles/</a>.
*/
@PostConstruct
public void initApplication() {
Collection<String> activeProfiles = Arrays.asList(env.getActiveProfiles());
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_PRODUCTION)) {
log.error("You have misconfigured your application! It should not run " +
"with both the 'dev' and 'prod' profiles at the same time.");
}
if (activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT) && activeProfiles.contains(JHipsterConstants.SPRING_PROFILE_CLOUD)) {
log.error("You have misconfigured your application! It should not " +
"run with both the 'dev' and 'cloud' profiles at the same time.");
}
}
/**
* Main method, used to run the application.
*
* @param args the command line arguments.
*/
public static void main(String[] args) {
SpringApplication app = new SpringApplication(EventalApp.class);
DefaultProfileUtil.addDefaultProfile(app);
Environment env = app.run(args).getEnvironment();
logApplicationStartup(env);
}
private static void logApplicationStartup(Environment env) {
String protocol = "http";
if (env.getProperty("server.ssl.key-store") != null) {
protocol = "https";
}
String serverPort = env.getProperty("server.port");
String contextPath = env.getProperty("server.servlet.context-path");
if (StringUtils.isBlank(contextPath)) {
contextPath = "/";
}
String hostAddress = "localhost";
try {
hostAddress = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.warn("The host name could not be determined, using `localhost` as fallback");
}
log.info("\n----------------------------------------------------------\n\t" +
"Application '{}' is running! Access URLs:\n\t" +
"Local: \t\t{}://localhost:{}{}\n\t" +
"External: \t{}://{}:{}{}\n\t" +
"Profile(s): \t{}\n----------------------------------------------------------",
env.getProperty("spring.application.name"),
protocol,
serverPort,
contextPath,
protocol,
hostAddress,
serverPort,
contextPath,
env.getActiveProfiles());
}
}

View File

@@ -0,0 +1,113 @@
package edu.uoc.evental.aop.logging;
import io.github.jhipster.config.JHipsterConstants;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import java.util.Arrays;
/**
* Aspect for logging execution of service and repository Spring components.
*
* By default, it only runs with the "dev" profile.
*/
@Aspect
public class LoggingAspect {
private final Environment env;
public LoggingAspect(Environment env) {
this.env = env;
}
/**
* Pointcut that matches all repositories, services and Web REST endpoints.
*/
@Pointcut("within(@org.springframework.stereotype.Repository *)" +
" || within(@org.springframework.stereotype.Service *)" +
" || within(@org.springframework.web.bind.annotation.RestController *)")
public void springBeanPointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Pointcut that matches all Spring beans in the application's main packages.
*/
@Pointcut("within(edu.uoc.evental.repository..*)"+
" || within(edu.uoc.evental.service..*)"+
" || within(edu.uoc.evental.web.rest..*)")
public void applicationPackagePointcut() {
// Method is empty as this is just a Pointcut, the implementations are in the advices.
}
/**
* Retrieves the {@link Logger} associated to the given {@link JoinPoint}.
*
* @param joinPoint join point we want the logger for.
* @return {@link Logger} associated to the given {@link JoinPoint}.
*/
private Logger logger(JoinPoint joinPoint) {
return LoggerFactory.getLogger(joinPoint.getSignature().getDeclaringTypeName());
}
/**
* Advice that logs methods throwing exceptions.
*
* @param joinPoint join point for advice.
* @param e exception.
*/
@AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
logger(joinPoint)
.error(
"Exception in {}() with cause = \'{}\' and exception = \'{}\'",
joinPoint.getSignature().getName(),
e.getCause() != null ? e.getCause() : "NULL",
e.getMessage(),
e
);
} else {
logger(joinPoint)
.error(
"Exception in {}() with cause = {}",
joinPoint.getSignature().getName(),
e.getCause() != null ? e.getCause() : "NULL"
);
}
}
/**
* Advice that logs when a method is entered and exited.
*
* @param joinPoint join point for advice.
* @return result.
* @throws Throwable throws {@link IllegalArgumentException}.
*/
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
Logger log = logger(joinPoint);
if (log.isDebugEnabled()) {
log.debug("Enter: {}() with argument[s] = {}", joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
try {
Object result = joinPoint.proceed();
if (log.isDebugEnabled()) {
log.debug("Exit: {}() with result = {}", joinPoint.getSignature().getName(), result);
}
return result;
} catch (IllegalArgumentException e) {
log.error("Illegal argument: {} in {}()", Arrays.toString(joinPoint.getArgs()), joinPoint.getSignature().getName());
throw e;
}
}
}

View File

@@ -0,0 +1,13 @@
package edu.uoc.evental.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Properties specific to Evental.
* <p>
* Properties are configured in the {@code application.yml} file.
* See {@link io.github.jhipster.config.JHipsterProperties} for a good example.
*/
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false)
public class ApplicationProperties {
}

View File

@@ -0,0 +1,47 @@
package edu.uoc.evental.config;
import io.github.jhipster.async.ExceptionHandlingAsyncTaskExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer {
private final Logger log = LoggerFactory.getLogger(AsyncConfiguration.class);
private final TaskExecutionProperties taskExecutionProperties;
public AsyncConfiguration(TaskExecutionProperties taskExecutionProperties) {
this.taskExecutionProperties = taskExecutionProperties;
}
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
log.debug("Creating Async Task Executor");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(taskExecutionProperties.getPool().getCoreSize());
executor.setMaxPoolSize(taskExecutionProperties.getPool().getMaxSize());
executor.setQueueCapacity(taskExecutionProperties.getPool().getQueueCapacity());
executor.setThreadNamePrefix(taskExecutionProperties.getThreadNamePrefix());
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new SimpleAsyncUncaughtExceptionHandler();
}
}

View File

@@ -0,0 +1,72 @@
package edu.uoc.evental.config;
import java.time.Duration;
import org.ehcache.config.builders.*;
import org.ehcache.jsr107.Eh107Configuration;
import org.hibernate.cache.jcache.ConfigSettings;
import io.github.jhipster.config.JHipsterProperties;
import org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer;
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.*;
@Configuration
@EnableCaching
public class CacheConfiguration {
private final javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration;
public CacheConfiguration(JHipsterProperties jHipsterProperties) {
JHipsterProperties.Cache.Ehcache ehcache = jHipsterProperties.getCache().getEhcache();
jcacheConfiguration = Eh107Configuration.fromEhcacheCacheConfiguration(
CacheConfigurationBuilder.newCacheConfigurationBuilder(Object.class, Object.class,
ResourcePoolsBuilder.heap(ehcache.getMaxEntries()))
.withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(ehcache.getTimeToLiveSeconds())))
.build());
}
@Bean
public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(javax.cache.CacheManager cacheManager) {
return hibernateProperties -> hibernateProperties.put(ConfigSettings.CACHE_MANAGER, cacheManager);
}
@Bean
public JCacheManagerCustomizer cacheManagerCustomizer() {
return cm -> {
createCache(cm, edu.uoc.evental.repository.UserRepository.USERS_BY_LOGIN_CACHE);
createCache(cm, edu.uoc.evental.repository.UserRepository.USERS_BY_EMAIL_CACHE);
createCache(cm, edu.uoc.evental.domain.User.class.getName());
createCache(cm, edu.uoc.evental.domain.Authority.class.getName());
createCache(cm, edu.uoc.evental.domain.User.class.getName() + ".authorities");
createCache(cm, edu.uoc.evental.domain.FiscalData.class.getName());
createCache(cm, edu.uoc.evental.domain.Artist.class.getName());
createCache(cm, edu.uoc.evental.domain.Artist.class.getName() + ".artists");
createCache(cm, edu.uoc.evental.domain.Venue.class.getName());
createCache(cm, edu.uoc.evental.domain.Venue.class.getName() + ".venues");
createCache(cm, edu.uoc.evental.domain.Event.class.getName());
createCache(cm, edu.uoc.evental.domain.Event.class.getName() + ".artists");
createCache(cm, edu.uoc.evental.domain.Event.class.getName() + ".venues");
createCache(cm, edu.uoc.evental.domain.Event.class.getName() + ".fees");
createCache(cm, edu.uoc.evental.domain.Fee.class.getName());
createCache(cm, edu.uoc.evental.domain.Fee.class.getName() + ".fees");
createCache(cm, edu.uoc.evental.domain.Ticket.class.getName());
createCache(cm, edu.uoc.evental.domain.Artist.class.getName() + ".events");
createCache(cm, edu.uoc.evental.domain.Venue.class.getName() + ".events");
createCache(cm, edu.uoc.evental.domain.Fee.class.getName() + ".events");
createCache(cm, edu.uoc.evental.domain.Event.class.getName() + ".tickets");
// jhipster-needle-ehcache-add-entry
};
}
private void createCache(javax.cache.CacheManager cm, String cacheName) {
javax.cache.Cache<Object, Object> cache = cm.getCache(cacheName);
if (cache == null) {
cm.createCache(cacheName, jcacheConfiguration);
}
}
}

View File

@@ -0,0 +1,28 @@
package edu.uoc.evental.config;
import io.github.jhipster.config.JHipsterConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.config.java.AbstractCloudConfig;
import org.springframework.context.annotation.*;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
@Configuration
@Profile(JHipsterConstants.SPRING_PROFILE_CLOUD)
public class CloudDatabaseConfiguration extends AbstractCloudConfig {
private final Logger log = LoggerFactory.getLogger(CloudDatabaseConfiguration.class);
private static final String CLOUD_CONFIGURATION_HIKARI_PREFIX = "spring.datasource.hikari";
@Bean
@ConfigurationProperties(CLOUD_CONFIGURATION_HIKARI_PREFIX)
public DataSource dataSource() {
log.info("Configuring JDBC datasource from a cloud provider");
return connectionFactory().dataSource();
}
}

View File

@@ -0,0 +1,17 @@
package edu.uoc.evental.config;
/**
* Application constants.
*/
public final class Constants {
// Regex for acceptable logins
public static final String LOGIN_REGEX = "^[_.@A-Za-z0-9-]*$";
public static final String SYSTEM_ACCOUNT = "system";
public static final String DEFAULT_LANGUAGE = "en";
public static final String ANONYMOUS_USER = "anonymoususer";
private Constants() {
}
}

View File

@@ -0,0 +1,59 @@
package edu.uoc.evental.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.h2.H2ConfigurationHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.sql.SQLException;
@Configuration
@EnableJpaRepositories("edu.uoc.evental.repository")
@EnableJpaAuditing(auditorAwareRef = "springSecurityAuditorAware")
@EnableTransactionManagement
public class DatabaseConfiguration {
private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class);
private final Environment env;
public DatabaseConfiguration(Environment env) {
this.env = env;
}
/**
* Open the TCP port for the H2 database, so it is available remotely.
*
* @return the H2 database TCP server.
* @throws SQLException if the server failed to start.
*/
@Bean(initMethod = "start", destroyMethod = "stop")
@Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
public Object h2TCPServer() throws SQLException {
String port = getValidPortForH2();
log.debug("H2 database is available on port {}", port);
return H2ConfigurationHelper.createServer(port);
}
private String getValidPortForH2() {
int port = Integer.parseInt(env.getProperty("server.port"));
if (port < 10000) {
port = 10000 + port;
} else {
if (port < 63536) {
port = port + 2000;
} else {
port = port - 2000;
}
}
return String.valueOf(port);
}
}

View File

@@ -0,0 +1,20 @@
package edu.uoc.evental.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Configure the converters to use the ISO format for dates by default.
*/
@Configuration
public class DateTimeFormatConfiguration implements WebMvcConfigurer {
@Override
public void addFormatters(FormatterRegistry registry) {
DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar();
registrar.setUseIsoFormat(true);
registrar.registerFormatters(registry);
}
}

View File

@@ -0,0 +1,61 @@
package edu.uoc.evental.config;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.afterburner.AfterburnerModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.problem.ProblemModule;
import org.zalando.problem.violations.ConstraintViolationProblemModule;
@Configuration
public class JacksonConfiguration {
/**
* Support for Java date and time API.
* @return the corresponding Jackson module.
*/
@Bean
public JavaTimeModule javaTimeModule() {
return new JavaTimeModule();
}
@Bean
public Jdk8Module jdk8TimeModule() {
return new Jdk8Module();
}
/*
* Support for Hibernate types in Jackson.
*/
@Bean
public Hibernate5Module hibernate5Module() {
return new Hibernate5Module();
}
/*
* Jackson Afterburner module to speed up serialization/deserialization.
*/
@Bean
public AfterburnerModule afterburnerModule() {
return new AfterburnerModule();
}
/*
* Module for serialization/deserialization of RFC7807 Problem.
*/
@Bean
ProblemModule problemModule() {
return new ProblemModule();
}
/*
* Module for serialization/deserialization of ConstraintViolationProblem.
*/
@Bean
ConstraintViolationProblemModule constraintViolationProblemModule() {
return new ConstraintViolationProblemModule();
}
}

View File

@@ -0,0 +1,60 @@
package edu.uoc.evental.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.liquibase.SpringLiquibaseUtil;
import liquibase.integration.spring.SpringLiquibase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseDataSource;
import org.springframework.boot.autoconfigure.liquibase.LiquibaseProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import javax.sql.DataSource;
import java.util.concurrent.Executor;
@Configuration
public class LiquibaseConfiguration {
private final Logger log = LoggerFactory.getLogger(LiquibaseConfiguration.class);
private final Environment env;
public LiquibaseConfiguration(Environment env) {
this.env = env;
}
@Bean
public SpringLiquibase liquibase(@Qualifier("taskExecutor") Executor executor,
@LiquibaseDataSource ObjectProvider<DataSource> liquibaseDataSource, LiquibaseProperties liquibaseProperties,
ObjectProvider<DataSource> dataSource, DataSourceProperties dataSourceProperties) {
// If you don't want Liquibase to start asynchronously, substitute by this:
// SpringLiquibase liquibase = SpringLiquibaseUtil.createSpringLiquibase(liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties);
SpringLiquibase liquibase = SpringLiquibaseUtil.createAsyncSpringLiquibase(this.env, executor, liquibaseDataSource.getIfAvailable(), liquibaseProperties, dataSource.getIfUnique(), dataSourceProperties);
liquibase.setChangeLog("classpath:config/liquibase/master.xml");
liquibase.setContexts(liquibaseProperties.getContexts());
liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema());
liquibase.setLiquibaseSchema(liquibaseProperties.getLiquibaseSchema());
liquibase.setLiquibaseTablespace(liquibaseProperties.getLiquibaseTablespace());
liquibase.setDatabaseChangeLogLockTable(liquibaseProperties.getDatabaseChangeLogLockTable());
liquibase.setDatabaseChangeLogTable(liquibaseProperties.getDatabaseChangeLogTable());
liquibase.setDropFirst(liquibaseProperties.isDropFirst());
liquibase.setLabels(liquibaseProperties.getLabels());
liquibase.setChangeLogParameters(liquibaseProperties.getParameters());
liquibase.setRollbackFile(liquibaseProperties.getRollbackFile());
liquibase.setTestRollbackOnUpdate(liquibaseProperties.isTestRollbackOnUpdate());
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_NO_LIQUIBASE))) {
liquibase.setShouldRun(false);
} else {
liquibase.setShouldRun(liquibaseProperties.isEnabled());
log.debug("Configuring Liquibase");
}
return liquibase;
}
}

View File

@@ -0,0 +1,27 @@
package edu.uoc.evental.config;
import io.github.jhipster.config.locale.AngularCookieLocaleResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
@Configuration
public class LocaleConfiguration implements WebMvcConfigurer {
@Bean(name = "localeResolver")
public LocaleResolver localeResolver() {
AngularCookieLocaleResolver cookieLocaleResolver = new AngularCookieLocaleResolver();
cookieLocaleResolver.setCookieName("NG_TRANSLATE_LANG_KEY");
return cookieLocaleResolver;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
localeChangeInterceptor.setParamName("language");
registry.addInterceptor(localeChangeInterceptor);
}
}

View File

@@ -0,0 +1,19 @@
package edu.uoc.evental.config;
import edu.uoc.evental.aop.logging.LoggingAspect;
import io.github.jhipster.config.JHipsterConstants;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
@Configuration
@EnableAspectJAutoProxy
public class LoggingAspectConfiguration {
@Bean
@Profile(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)
public LoggingAspect loggingAspect(Environment env) {
return new LoggingAspect(env);
}
}

View File

@@ -0,0 +1,50 @@
package edu.uoc.evental.config;
import ch.qos.logback.classic.LoggerContext;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.jhipster.config.JHipsterProperties;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
import static io.github.jhipster.config.logging.LoggingUtils.*;
/*
* Configures the console and Logstash log appenders from the app properties
*/
@Configuration
public class LoggingConfiguration {
public LoggingConfiguration(@Value("${spring.application.name}") String appName,
@Value("${server.port}") String serverPort,
JHipsterProperties jHipsterProperties,
ObjectMapper mapper) throws JsonProcessingException {
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
Map<String, String> map = new HashMap<>();
map.put("app_name", appName);
map.put("app_port", serverPort);
String customFields = mapper.writeValueAsString(map);
JHipsterProperties.Logging loggingProperties = jHipsterProperties.getLogging();
JHipsterProperties.Logging.Logstash logstashProperties = loggingProperties.getLogstash();
if (loggingProperties.isUseJsonFormat()) {
addJsonConsoleAppender(context, customFields);
}
if (logstashProperties.isEnabled()) {
addLogstashTcpSocketAppender(context, customFields, logstashProperties);
}
if (loggingProperties.isUseJsonFormat() || logstashProperties.isEnabled()) {
addContextListener(context, customFields, loggingProperties);
}
if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
setMetricsMarkerLogbackFilter(context, loggingProperties.isUseJsonFormat());
}
}
}

View File

@@ -0,0 +1,101 @@
package edu.uoc.evental.config;
import edu.uoc.evental.security.*;
import edu.uoc.evental.security.jwt.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.writers.ReferrerPolicyHeaderWriter;
import org.springframework.web.filter.CorsFilter;
import org.zalando.problem.spring.web.advice.security.SecurityProblemSupport;
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private final TokenProvider tokenProvider;
private final CorsFilter corsFilter;
private final SecurityProblemSupport problemSupport;
public SecurityConfiguration(TokenProvider tokenProvider, CorsFilter corsFilter, SecurityProblemSupport problemSupport) {
this.tokenProvider = tokenProvider;
this.corsFilter = corsFilter;
this.problemSupport = problemSupport;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/h2-console/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**");
}
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.csrf()
.disable()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.headers()
.contentSecurityPolicy("default-src 'self'; frame-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://storage.googleapis.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:")
.and()
.referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
.and()
.featurePolicy("geolocation 'none'; midi 'none'; sync-xhr 'none'; microphone 'none'; camera 'none'; magnetometer 'none'; gyroscope 'none'; speaker 'none'; fullscreen 'self'; payment 'none'")
.and()
.frameOptions()
.deny()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/activate").permitAll()
.antMatchers("/api/account/reset-password/init").permitAll()
.antMatchers("/api/account/reset-password/finish").permitAll()
.antMatchers(HttpMethod.GET, "/api/events").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/prometheus").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.and()
.httpBasic()
.and()
.apply(securityConfigurerAdapter());
// @formatter:on
}
private JWTConfigurer securityConfigurerAdapter() {
return new JWTConfigurer(tokenProvider);
}
}

View File

@@ -0,0 +1,153 @@
package edu.uoc.evental.config;
import io.github.jhipster.config.JHipsterConstants;
import io.github.jhipster.config.JHipsterProperties;
import io.github.jhipster.config.h2.H2ConfigurationHelper;
import io.github.jhipster.web.filter.CachingHttpHeadersFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.server.*;
import org.springframework.boot.web.servlet.ServletContextInitializer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import org.springframework.http.MediaType;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import javax.servlet.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.*;
import static java.net.URLDecoder.decode;
/**
* Configuration of web application with Servlet 3.0 APIs.
*/
@Configuration
public class WebConfigurer implements ServletContextInitializer, WebServerFactoryCustomizer<WebServerFactory> {
private final Logger log = LoggerFactory.getLogger(WebConfigurer.class);
private final Environment env;
private final JHipsterProperties jHipsterProperties;
public WebConfigurer(Environment env, JHipsterProperties jHipsterProperties) {
this.env = env;
this.jHipsterProperties = jHipsterProperties;
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
if (env.getActiveProfiles().length != 0) {
log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles());
}
EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC);
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_PRODUCTION))) {
initCachingHttpHeadersFilter(servletContext, disps);
}
if (env.acceptsProfiles(Profiles.of(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT))) {
initH2Console(servletContext);
}
log.info("Web application fully configured");
}
/**
* Customize the Servlet engine: Mime types, the document root, the cache.
*/
@Override
public void customize(WebServerFactory server) {
setMimeMappings(server);
// When running in an IDE or with ./mvnw spring-boot:run, set location of the static web assets.
setLocationForStaticAssets(server);
}
private void setMimeMappings(WebServerFactory server) {
if (server instanceof ConfigurableServletWebServerFactory) {
MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
// IE issue, see https://github.com/jhipster/generator-jhipster/pull/711
mappings.add("html", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase());
// CloudFoundry issue, see https://github.com/cloudfoundry/gorouter/issues/64
mappings.add("json", MediaType.TEXT_HTML_VALUE + ";charset=" + StandardCharsets.UTF_8.name().toLowerCase());
ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server;
servletWebServer.setMimeMappings(mappings);
}
}
private void setLocationForStaticAssets(WebServerFactory server) {
if (server instanceof ConfigurableServletWebServerFactory) {
ConfigurableServletWebServerFactory servletWebServer = (ConfigurableServletWebServerFactory) server;
File root;
String prefixPath = resolvePathPrefix();
root = new File(prefixPath + "target/classes/static/");
if (root.exists() && root.isDirectory()) {
servletWebServer.setDocumentRoot(root);
}
}
}
/**
* Resolve path prefix to static resources.
*/
private String resolvePathPrefix() {
String fullExecutablePath;
try {
fullExecutablePath = decode(this.getClass().getResource("").getPath(), StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
/* try without decoding if this ever happens */
fullExecutablePath = this.getClass().getResource("").getPath();
}
String rootPath = Paths.get(".").toUri().normalize().getPath();
String extractedPath = fullExecutablePath.replace(rootPath, "");
int extractionEndIndex = extractedPath.indexOf("target/");
if (extractionEndIndex <= 0) {
return "";
}
return extractedPath.substring(0, extractionEndIndex);
}
/**
* Initializes the caching HTTP Headers Filter.
*/
private void initCachingHttpHeadersFilter(ServletContext servletContext,
EnumSet<DispatcherType> disps) {
log.debug("Registering Caching HTTP Headers Filter");
FilterRegistration.Dynamic cachingHttpHeadersFilter =
servletContext.addFilter("cachingHttpHeadersFilter",
new CachingHttpHeadersFilter(jHipsterProperties));
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/i18n/*");
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/content/*");
cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/app/*");
cachingHttpHeadersFilter.setAsyncSupported(true);
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = jHipsterProperties.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v2/api-docs", config);
}
return new CorsFilter(source);
}
/**
* Initializes H2 console.
*/
private void initH2Console(ServletContext servletContext) {
log.debug("Initialize H2 console");
H2ConfigurationHelper.initH2Console(servletContext);
}
}

View File

@@ -0,0 +1,86 @@
package edu.uoc.evental.config.audit;
import edu.uoc.evental.domain.PersistentAuditEvent;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import java.util.*;
@Component
public class AuditEventConverter {
/**
* Convert a list of {@link PersistentAuditEvent}s to a list of {@link AuditEvent}s.
*
* @param persistentAuditEvents the list to convert.
* @return the converted list.
*/
public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) {
if (persistentAuditEvents == null) {
return Collections.emptyList();
}
List<AuditEvent> auditEvents = new ArrayList<>();
for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) {
auditEvents.add(convertToAuditEvent(persistentAuditEvent));
}
return auditEvents;
}
/**
* Convert a {@link PersistentAuditEvent} to an {@link AuditEvent}.
*
* @param persistentAuditEvent the event to convert.
* @return the converted list.
*/
public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) {
if (persistentAuditEvent == null) {
return null;
}
return new AuditEvent(persistentAuditEvent.getAuditEventDate(), persistentAuditEvent.getPrincipal(),
persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData()));
}
/**
* Internal conversion. This is needed to support the current SpringBoot actuator {@code AuditEventRepository} interface.
*
* @param data the data to convert.
* @return a map of {@link String}, {@link Object}.
*/
public Map<String, Object> convertDataToObjects(Map<String, String> data) {
Map<String, Object> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
results.put(entry.getKey(), entry.getValue());
}
}
return results;
}
/**
* Internal conversion. This method will allow to save additional data.
* By default, it will save the object as string.
*
* @param data the data to convert.
* @return a map of {@link String}, {@link String}.
*/
public Map<String, String> convertDataToStrings(Map<String, Object> data) {
Map<String, String> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, Object> entry : data.entrySet()) {
// Extract the data that will be saved.
if (entry.getValue() instanceof WebAuthenticationDetails) {
WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue();
results.put("remoteAddress", authenticationDetails.getRemoteAddress());
results.put("sessionId", authenticationDetails.getSessionId());
} else {
results.put(entry.getKey(), Objects.toString(entry.getValue()));
}
}
}
return results;
}
}

View File

@@ -0,0 +1,4 @@
/**
* Audit specific code.
*/
package edu.uoc.evental.config.audit;

View File

@@ -0,0 +1,4 @@
/**
* Spring Framework configuration files.
*/
package edu.uoc.evental.config;

View File

@@ -0,0 +1,77 @@
package edu.uoc.evental.domain;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import java.io.Serializable;
import java.time.Instant;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.MappedSuperclass;
/**
* Base abstract class for entities which will hold definitions for created, last modified, created by,
* last modified by attributes.
*/
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@CreatedBy
@Column(name = "created_by", nullable = false, length = 50, updatable = false)
@JsonIgnore
private String createdBy;
@CreatedDate
@Column(name = "created_date", updatable = false)
@JsonIgnore
private Instant createdDate = Instant.now();
@LastModifiedBy
@Column(name = "last_modified_by", length = 50)
@JsonIgnore
private String lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
@JsonIgnore
private Instant lastModifiedDate = Instant.now();
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
}

View File

@@ -0,0 +1,112 @@
package edu.uoc.evental.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
/**
* A Artist.
*/
@Entity
@Table(name = "artist")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Artist implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "artist_name", nullable = false)
private String artistName;
@Lob
@Column(name = "info_url")
private String infoUrl;
@ManyToOne
@JsonIgnoreProperties("artists")
private User user;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getArtistName() {
return artistName;
}
public Artist artistName(String artistName) {
this.artistName = artistName;
return this;
}
public void setArtistName(String artistName) {
this.artistName = artistName;
}
public String getInfoUrl() {
return infoUrl;
}
public Artist infoUrl(String infoUrl) {
this.infoUrl = infoUrl;
return this;
}
public void setInfoUrl(String infoUrl) {
this.infoUrl = infoUrl;
}
public User getUser() {
return user;
}
public Artist user(User user) {
this.user = user;
return this;
}
public void setUser(User user) {
this.user = user;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Artist)) {
return false;
}
return id != null && id.equals(((Artist) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "Artist{" +
"id=" + getId() +
", artistName='" + getArtistName() + "'" +
", infoUrl='" + getInfoUrl() + "'" +
"}";
}
}

View File

@@ -0,0 +1,60 @@
package edu.uoc.evental.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.Objects;
/**
* An authority (a security role) used by Spring Security.
*/
@Entity
@Table(name = "jhi_authority")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Authority implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull
@Size(max = 50)
@Id
@Column(length = 50)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Authority)) {
return false;
}
return Objects.equals(name, ((Authority) o).name);
}
@Override
public int hashCode() {
return Objects.hashCode(name);
}
@Override
public String toString() {
return "Authority{" +
"name='" + name + '\'' +
"}";
}
}

View File

@@ -0,0 +1,303 @@
package edu.uoc.evental.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
import edu.uoc.evental.domain.enumeration.FeeModel;
/**
* A Event.
*/
@Entity
@Table(name = "event")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Event implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "event_date_time", nullable = false)
private Instant eventDateTime;
@NotNull
@Column(name = "ticket_price", precision = 21, scale = 2, nullable = false)
private BigDecimal ticketPrice;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "fee_model", nullable = false)
private FeeModel feeModel;
@NotNull
@Column(name = "fee_amount", nullable = false)
private Integer feeAmount;
@Column(name = "artist_user_id")
private Long artistUserId;
@Column(name = "venue_user_id")
private Long venueUserId;
@Column(name = "is_confirmed_by_artist")
private Boolean isConfirmedByArtist;
@Column(name = "is_confirmed_by_venue")
private Boolean isConfirmedByVenue;
@Column(name = "is_rejected")
private Boolean isRejected;
@Column(name = "tickets_sold")
private Integer ticketsSold;
@OneToMany(mappedBy = "event")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Ticket> tickets = new HashSet<>();
@ManyToOne
@JsonIgnoreProperties("events")
private Artist artist;
@ManyToOne
@JsonIgnoreProperties("events")
private Venue venue;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Instant getEventDateTime() {
return eventDateTime;
}
public Event eventDateTime(Instant eventDateTime) {
this.eventDateTime = eventDateTime;
return this;
}
public void setEventDateTime(Instant eventDateTime) {
this.eventDateTime = eventDateTime;
}
public BigDecimal getTicketPrice() {
return ticketPrice;
}
public Event ticketPrice(BigDecimal ticketPrice) {
this.ticketPrice = ticketPrice;
return this;
}
public void setTicketPrice(BigDecimal ticketPrice) {
this.ticketPrice = ticketPrice;
}
public FeeModel getFeeModel() {
return feeModel;
}
public Event feeModel(FeeModel feeModel) {
this.feeModel = feeModel;
return this;
}
public void setFeeModel(FeeModel feeModel) {
this.feeModel = feeModel;
}
public Integer getFeeAmount() {
return feeAmount;
}
public Event feeAmount(Integer feeAmount) {
this.feeAmount = feeAmount;
return this;
}
public void setFeeAmount(Integer feeAmount) {
this.feeAmount = feeAmount;
}
public Long getArtistUserId() {
return artistUserId;
}
public Event artistUserId(Long artistUserId) {
this.artistUserId = artistUserId;
return this;
}
public void setArtistUserId(Long artistUserId) {
this.artistUserId = artistUserId;
}
public Long getVenueUserId() {
return venueUserId;
}
public Event venueUserId(Long venueUserId) {
this.venueUserId = venueUserId;
return this;
}
public void setVenueUserId(Long venueUserId) {
this.venueUserId = venueUserId;
}
public Boolean isIsConfirmedByArtist() {
return isConfirmedByArtist;
}
public Event isConfirmedByArtist(Boolean isConfirmedByArtist) {
this.isConfirmedByArtist = isConfirmedByArtist;
return this;
}
public void setIsConfirmedByArtist(Boolean isConfirmedByArtist) {
this.isConfirmedByArtist = isConfirmedByArtist;
}
public Boolean isIsConfirmedByVenue() {
return isConfirmedByVenue;
}
public Event isConfirmedByVenue(Boolean isConfirmedByVenue) {
this.isConfirmedByVenue = isConfirmedByVenue;
return this;
}
public void setIsConfirmedByVenue(Boolean isConfirmedByVenue) {
this.isConfirmedByVenue = isConfirmedByVenue;
}
public Boolean isIsRejected() {
return isRejected;
}
public Event isRejected(Boolean isRejected) {
this.isRejected = isRejected;
return this;
}
public void setIsRejected(Boolean isRejected) {
this.isRejected = isRejected;
}
public Integer getTicketsSold() {
return ticketsSold;
}
public Event ticketsSold(Integer ticketsSold) {
this.ticketsSold = ticketsSold;
return this;
}
public void setTicketsSold(Integer ticketsSold) {
this.ticketsSold = ticketsSold;
}
public Set<Ticket> getTickets() {
return tickets;
}
public Event tickets(Set<Ticket> tickets) {
this.tickets = tickets;
return this;
}
public Event addTicket(Ticket ticket) {
this.tickets.add(ticket);
ticket.setEvent(this);
return this;
}
public Event removeTicket(Ticket ticket) {
this.tickets.remove(ticket);
ticket.setEvent(null);
return this;
}
public void setTickets(Set<Ticket> tickets) {
this.tickets = tickets;
}
public Artist getArtist() {
return artist;
}
public Event artist(Artist artist) {
this.artist = artist;
return this;
}
public void setArtist(Artist artist) {
this.artist = artist;
}
public Venue getVenue() {
return venue;
}
public Event venue(Venue venue) {
this.venue = venue;
return this;
}
public void setVenue(Venue venue) {
this.venue = venue;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Event)) {
return false;
}
return id != null && id.equals(((Event) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "Event{" +
"id=" + getId() +
", eventDateTime='" + getEventDateTime() + "'" +
", ticketPrice=" + getTicketPrice() +
", feeModel='" + getFeeModel() + "'" +
", feeAmount=" + getFeeAmount() +
", artistUserId=" + getArtistUserId() +
", venueUserId=" + getVenueUserId() +
", isConfirmedByArtist='" + isIsConfirmedByArtist() + "'" +
", isConfirmedByVenue='" + isIsConfirmedByVenue() + "'" +
", isRejected='" + isIsRejected() + "'" +
", ticketsSold=" + getTicketsSold() +
"}";
}
}

View File

@@ -0,0 +1,116 @@
package edu.uoc.evental.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import java.math.BigDecimal;
import edu.uoc.evental.domain.enumeration.FeeModel;
/**
* A Fee.
*/
@Entity
@Table(name = "fee")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Fee implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Enumerated(EnumType.STRING)
@Column(name = "fee_model", nullable = false)
private FeeModel feeModel;
@Column(name = "fixed_rate", precision = 21, scale = 2)
private BigDecimal fixedRate;
@Min(value = 0)
@Max(value = 100)
@Column(name = "percentage")
private Integer percentage;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public FeeModel getFeeModel() {
return feeModel;
}
public Fee feeModel(FeeModel feeModel) {
this.feeModel = feeModel;
return this;
}
public void setFeeModel(FeeModel feeModel) {
this.feeModel = feeModel;
}
public BigDecimal getFixedRate() {
return fixedRate;
}
public Fee fixedRate(BigDecimal fixedRate) {
this.fixedRate = fixedRate;
return this;
}
public void setFixedRate(BigDecimal fixedRate) {
this.fixedRate = fixedRate;
}
public Integer getPercentage() {
return percentage;
}
public Fee percentage(Integer percentage) {
this.percentage = percentage;
return this;
}
public void setPercentage(Integer percentage) {
this.percentage = percentage;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Fee)) {
return false;
}
return id != null && id.equals(((Fee) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "Fee{" +
"id=" + getId() +
", feeModel='" + getFeeModel() + "'" +
", fixedRate=" + getFixedRate() +
", percentage=" + getPercentage() +
"}";
}
}

View File

@@ -0,0 +1,112 @@
package edu.uoc.evental.domain;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import java.time.LocalDate;
/**
* A FiscalData.
*/
@Entity
@Table(name = "fiscal_data")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class FiscalData implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Size(max = 9)
@Column(name = "nif", length = 9, nullable = false)
private String nif;
@Column(name = "birth_date")
private LocalDate birthDate;
@OneToOne
@JoinColumn(unique = true)
private User user;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNif() {
return nif;
}
public FiscalData nif(String nif) {
this.nif = nif;
return this;
}
public void setNif(String nif) {
this.nif = nif;
}
public LocalDate getBirthDate() {
return birthDate;
}
public FiscalData birthDate(LocalDate birthDate) {
this.birthDate = birthDate;
return this;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public User getUser() {
return user;
}
public FiscalData user(User user) {
this.user = user;
return this;
}
public void setUser(User user) {
this.user = user;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof FiscalData)) {
return false;
}
return id != null && id.equals(((FiscalData) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "FiscalData{" +
"id=" + getId() +
", nif='" + getNif() + "'" +
", birthDate='" + getBirthDate() + "'" +
"}";
}
}

View File

@@ -0,0 +1,106 @@
package edu.uoc.evental.domain;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
/**
* Persist AuditEvent managed by the Spring Boot actuator.
*
* @see org.springframework.boot.actuate.audit.AuditEvent
*/
@Entity
@Table(name = "jhi_persistent_audit_event")
public class PersistentAuditEvent implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "event_id")
private Long id;
@NotNull
@Column(nullable = false)
private String principal;
@Column(name = "event_date")
private Instant auditEventDate;
@Column(name = "event_type")
private String auditEventType;
@ElementCollection
@MapKeyColumn(name = "name")
@Column(name = "value")
@CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id"))
private Map<String, String> data = new HashMap<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public Instant getAuditEventDate() {
return auditEventDate;
}
public void setAuditEventDate(Instant auditEventDate) {
this.auditEventDate = auditEventDate;
}
public String getAuditEventType() {
return auditEventType;
}
public void setAuditEventType(String auditEventType) {
this.auditEventType = auditEventType;
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof PersistentAuditEvent)) {
return false;
}
return id != null && id.equals(((PersistentAuditEvent) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "PersistentAuditEvent{" +
"principal='" + principal + '\'' +
", auditEventDate=" + auditEventDate +
", auditEventType='" + auditEventType + '\'' +
'}';
}
}

View File

@@ -0,0 +1,92 @@
package edu.uoc.evental.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;
/**
* A Ticket.
*/
@Entity
@Table(name = "ticket")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Ticket implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne
@JsonIgnoreProperties("tickets")
private FiscalData fiscalData;
@ManyToOne
@JsonIgnoreProperties("tickets")
private Event event;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public FiscalData getFiscalData() {
return fiscalData;
}
public Ticket fiscalData(FiscalData fiscalData) {
this.fiscalData = fiscalData;
return this;
}
public void setFiscalData(FiscalData fiscalData) {
this.fiscalData = fiscalData;
}
public Event getEvent() {
return event;
}
public Ticket event(Event event) {
this.event = event;
return this;
}
public void setEvent(Event event) {
this.event = event;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Ticket)) {
return false;
}
return id != null && id.equals(((Ticket) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "Ticket{" +
"id=" + getId() +
"}";
}
}

View File

@@ -0,0 +1,231 @@
package edu.uoc.evental.domain;
import edu.uoc.evental.config.Constants;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.BatchSize;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.time.Instant;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;
/**
* A user.
*/
@Entity
@Table(name = "jhi_user")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class User extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
@Column(length = 50, unique = true, nullable = false)
private String login;
@JsonIgnore
@NotNull
@Size(min = 60, max = 60)
@Column(name = "password_hash", length = 60, nullable = false)
private String password;
@Size(max = 50)
@Column(name = "first_name", length = 50)
private String firstName;
@Size(max = 50)
@Column(name = "last_name", length = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
@Column(length = 254, unique = true)
private String email;
@NotNull
@Column(nullable = false)
private boolean activated = false;
@Size(min = 2, max = 10)
@Column(name = "lang_key", length = 10)
private String langKey;
@Size(max = 256)
@Column(name = "image_url", length = 256)
private String imageUrl;
@Size(max = 20)
@Column(name = "activation_key", length = 20)
@JsonIgnore
private String activationKey;
@Size(max = 20)
@Column(name = "reset_key", length = 20)
@JsonIgnore
private String resetKey;
@Column(name = "reset_date")
private Instant resetDate = null;
@JsonIgnore
@ManyToMany
@JoinTable(
name = "jhi_user_authority",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@BatchSize(size = 20)
private Set<Authority> authorities = new HashSet<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
// Lowercase the login before saving it in database
public void setLogin(String login) {
this.login = StringUtils.lowerCase(login, Locale.ENGLISH);
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean getActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getActivationKey() {
return activationKey;
}
public void setActivationKey(String activationKey) {
this.activationKey = activationKey;
}
public String getResetKey() {
return resetKey;
}
public void setResetKey(String resetKey) {
this.resetKey = resetKey;
}
public Instant getResetDate() {
return resetDate;
}
public void setResetDate(Instant resetDate) {
this.resetDate = resetDate;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public Set<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<Authority> authorities) {
this.authorities = authorities;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof User)) {
return false;
}
return id != null && id.equals(((User) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated='" + activated + '\'' +
", langKey='" + langKey + '\'' +
", activationKey='" + activationKey + '\'' +
"}";
}
}

View File

@@ -0,0 +1,152 @@
package edu.uoc.evental.domain;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import javax.persistence.*;
import javax.validation.constraints.*;
import java.io.Serializable;
import java.util.Objects;
import edu.uoc.evental.domain.enumeration.Location;
/**
* A Venue.
*/
@Entity
@Table(name = "venue")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Venue implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
@Column(name = "venue_name", nullable = false)
private String venueName;
@Lob
@Column(name = "info_url")
private String infoUrl;
@Enumerated(EnumType.STRING)
@Column(name = "location")
private Location location;
@NotNull
@Min(value = 50)
@Max(value = 100000)
@Column(name = "capacity", nullable = false)
private Integer capacity;
@ManyToOne
@JsonIgnoreProperties("venues")
private User user;
// jhipster-needle-entity-add-field - JHipster will add fields here, do not remove
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getVenueName() {
return venueName;
}
public Venue venueName(String venueName) {
this.venueName = venueName;
return this;
}
public void setVenueName(String venueName) {
this.venueName = venueName;
}
public String getInfoUrl() {
return infoUrl;
}
public Venue infoUrl(String infoUrl) {
this.infoUrl = infoUrl;
return this;
}
public void setInfoUrl(String infoUrl) {
this.infoUrl = infoUrl;
}
public Location getLocation() {
return location;
}
public Venue location(Location location) {
this.location = location;
return this;
}
public void setLocation(Location location) {
this.location = location;
}
public Integer getCapacity() {
return capacity;
}
public Venue capacity(Integer capacity) {
this.capacity = capacity;
return this;
}
public void setCapacity(Integer capacity) {
this.capacity = capacity;
}
public User getUser() {
return user;
}
public Venue user(User user) {
this.user = user;
return this;
}
public void setUser(User user) {
this.user = user;
}
// jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Venue)) {
return false;
}
return id != null && id.equals(((Venue) o).id);
}
@Override
public int hashCode() {
return 31;
}
@Override
public String toString() {
return "Venue{" +
"id=" + getId() +
", venueName='" + getVenueName() + "'" +
", infoUrl='" + getInfoUrl() + "'" +
", location='" + getLocation() + "'" +
", capacity=" + getCapacity() +
"}";
}
}

View File

@@ -0,0 +1,8 @@
package edu.uoc.evental.domain.enumeration;
/**
* The FeeModel enumeration.
*/
public enum FeeModel {
Fijo, Porcentaje
}

View File

@@ -0,0 +1,8 @@
package edu.uoc.evental.domain.enumeration;
/**
* The Location enumeration.
*/
public enum Location {
Madrid, Barcelona, Valencia, Sevilla, Zaragoza
}

View File

@@ -0,0 +1,4 @@
/**
* JPA domain objects.
*/
package edu.uoc.evental.domain;

View File

@@ -0,0 +1,19 @@
package edu.uoc.evental.repository;
import edu.uoc.evental.domain.Artist;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Spring Data repository for the Artist entity.
*/
@SuppressWarnings("unused")
@Repository
public interface ArtistRepository extends JpaRepository<Artist, Long>, JpaSpecificationExecutor<Artist> {
@Query("select artist from Artist artist where artist.user.login = ?#{principal.username}")
List<Artist> findByUserIsCurrentUser();
}

View File

@@ -0,0 +1,11 @@
package edu.uoc.evental.repository;
import edu.uoc.evental.domain.Authority;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Spring Data JPA repository for the {@link Authority} entity.
*/
public interface AuthorityRepository extends JpaRepository<Authority, String> {
}

View File

@@ -0,0 +1,89 @@
package edu.uoc.evental.repository;
import edu.uoc.evental.config.Constants;
import edu.uoc.evental.config.audit.AuditEventConverter;
import edu.uoc.evental.domain.PersistentAuditEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.boot.actuate.audit.AuditEventRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.*;
/**
* An implementation of Spring Boot's {@link AuditEventRepository}.
*/
@Repository
public class CustomAuditEventRepository implements AuditEventRepository {
private static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE";
/**
* Should be the same as in Liquibase migration.
*/
protected static final int EVENT_DATA_COLUMN_MAX_LENGTH = 255;
private final PersistenceAuditEventRepository persistenceAuditEventRepository;
private final AuditEventConverter auditEventConverter;
private final Logger log = LoggerFactory.getLogger(getClass());
public CustomAuditEventRepository(PersistenceAuditEventRepository persistenceAuditEventRepository,
AuditEventConverter auditEventConverter) {
this.persistenceAuditEventRepository = persistenceAuditEventRepository;
this.auditEventConverter = auditEventConverter;
}
@Override
public List<AuditEvent> find(String principal, Instant after, String type) {
Iterable<PersistentAuditEvent> persistentAuditEvents =
persistenceAuditEventRepository.findByPrincipalAndAuditEventDateAfterAndAuditEventType(principal, after, type);
return auditEventConverter.convertToAuditEvent(persistentAuditEvents);
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void add(AuditEvent event) {
if (!AUTHORIZATION_FAILURE.equals(event.getType()) &&
!Constants.ANONYMOUS_USER.equals(event.getPrincipal())) {
PersistentAuditEvent persistentAuditEvent = new PersistentAuditEvent();
persistentAuditEvent.setPrincipal(event.getPrincipal());
persistentAuditEvent.setAuditEventType(event.getType());
persistentAuditEvent.setAuditEventDate(event.getTimestamp());
Map<String, String> eventData = auditEventConverter.convertDataToStrings(event.getData());
persistentAuditEvent.setData(truncate(eventData));
persistenceAuditEventRepository.save(persistentAuditEvent);
}
}
/**
* Truncate event data that might exceed column length.
*/
private Map<String, String> truncate(Map<String, String> data) {
Map<String, String> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
String value = entry.getValue();
if (value != null) {
int length = value.length();
if (length > EVENT_DATA_COLUMN_MAX_LENGTH) {
value = value.substring(0, EVENT_DATA_COLUMN_MAX_LENGTH);
log.warn("Event data for {} too long ({}) has been truncated to {}. Consider increasing column width.",
entry.getKey(), length, EVENT_DATA_COLUMN_MAX_LENGTH);
}
}
results.put(entry.getKey(), value);
}
}
return results;
}
}

View File

@@ -0,0 +1,14 @@
package edu.uoc.evental.repository;
import edu.uoc.evental.domain.Event;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the Event entity.
*/
@SuppressWarnings("unused")
@Repository
public interface EventRepository extends JpaRepository<Event, Long>, JpaSpecificationExecutor<Event> {
}

View File

@@ -0,0 +1,14 @@
package edu.uoc.evental.repository;
import edu.uoc.evental.domain.Fee;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the Fee entity.
*/
@SuppressWarnings("unused")
@Repository
public interface FeeRepository extends JpaRepository<Fee, Long> {
}

View File

@@ -0,0 +1,14 @@
package edu.uoc.evental.repository;
import edu.uoc.evental.domain.FiscalData;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the FiscalData entity.
*/
@SuppressWarnings("unused")
@Repository
public interface FiscalDataRepository extends JpaRepository<FiscalData, Long>, JpaSpecificationExecutor<FiscalData> {
}

View File

@@ -0,0 +1,23 @@
package edu.uoc.evental.repository;
import edu.uoc.evental.domain.PersistentAuditEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.Instant;
import java.util.List;
/**
* Spring Data JPA repository for the {@link PersistentAuditEvent} entity.
*/
public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, Long> {
List<PersistentAuditEvent> findByPrincipal(String principal);
List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfterAndAuditEventType(String principal, Instant after, String type);
Page<PersistentAuditEvent> findAllByAuditEventDateBetween(Instant fromDate, Instant toDate, Pageable pageable);
List<PersistentAuditEvent> findByAuditEventDateBefore(Instant before);
}

View File

@@ -0,0 +1,14 @@
package edu.uoc.evental.repository;
import edu.uoc.evental.domain.Ticket;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
/**
* Spring Data repository for the Ticket entity.
*/
@SuppressWarnings("unused")
@Repository
public interface TicketRepository extends JpaRepository<Ticket, Long>, JpaSpecificationExecutor<Ticket> {
}

View File

@@ -0,0 +1,51 @@
package edu.uoc.evental.repository;
import edu.uoc.evental.domain.User;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
import java.time.Instant;
/**
* Spring Data JPA repository for the {@link User} entity.
*/
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
String USERS_BY_LOGIN_CACHE = "usersByLogin";
String USERS_BY_EMAIL_CACHE = "usersByEmail";
Optional<User> findOneByActivationKey(String activationKey);
List<User> findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant dateTime);
Optional<User> findOneByResetKey(String resetKey);
Optional<User> findOneByEmailIgnoreCase(String email);
Optional<User> findOneByLogin(String login);
@EntityGraph(attributePaths = "authorities")
Optional<User> findOneWithAuthoritiesById(Long id);
@EntityGraph(attributePaths = "authorities")
@Cacheable(cacheNames = USERS_BY_LOGIN_CACHE)
Optional<User> findOneWithAuthoritiesByLogin(String login);
@EntityGraph(attributePaths = "authorities")
@Cacheable(cacheNames = USERS_BY_EMAIL_CACHE)
Optional<User> findOneWithAuthoritiesByEmailIgnoreCase(String email);
Page<User> findAllByLoginNot(Pageable pageable, String login);
}

View File

@@ -0,0 +1,19 @@
package edu.uoc.evental.repository;
import edu.uoc.evental.domain.Venue;
import org.springframework.data.jpa.repository.*;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Spring Data repository for the Venue entity.
*/
@SuppressWarnings("unused")
@Repository
public interface VenueRepository extends JpaRepository<Venue, Long>, JpaSpecificationExecutor<Venue> {
@Query("select venue from Venue venue where venue.user.login = ?#{principal.username}")
List<Venue> findByUserIsCurrentUser();
}

View File

@@ -0,0 +1,4 @@
/**
* Spring Data JPA repositories.
*/
package edu.uoc.evental.repository;

View File

@@ -0,0 +1,16 @@
package edu.uoc.evental.security;
/**
* Constants for Spring Security authorities.
*/
public final class AuthoritiesConstants {
public static final String ADMIN = "ROLE_ADMIN";
public static final String USER = "ROLE_USER";
public static final String ANONYMOUS = "ROLE_ANONYMOUS";
private AuthoritiesConstants() {
}
}

View File

@@ -0,0 +1,62 @@
package edu.uoc.evental.security;
import edu.uoc.evental.domain.User;
import edu.uoc.evental.repository.UserRepository;
import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
/**
* Authenticate a user from the database.
*/
@Component("userDetailsService")
public class DomainUserDetailsService implements UserDetailsService {
private final Logger log = LoggerFactory.getLogger(DomainUserDetailsService.class);
private final UserRepository userRepository;
public DomainUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional
public UserDetails loadUserByUsername(final String login) {
log.debug("Authenticating {}", login);
if (new EmailValidator().isValid(login, null)) {
return userRepository.findOneWithAuthoritiesByEmailIgnoreCase(login)
.map(user -> createSpringSecurityUser(login, user))
.orElseThrow(() -> new UsernameNotFoundException("User with email " + login + " was not found in the database"));
}
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
return userRepository.findOneWithAuthoritiesByLogin(lowercaseLogin)
.map(user -> createSpringSecurityUser(lowercaseLogin, user))
.orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database"));
}
private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
if (!user.getActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<GrantedAuthority> grantedAuthorities = user.getAuthorities().stream()
.map(authority -> new SimpleGrantedAuthority(authority.getName()))
.collect(Collectors.toList());
return new org.springframework.security.core.userdetails.User(user.getLogin(),
user.getPassword(),
grantedAuthorities);
}
}

View File

@@ -0,0 +1,85 @@
package edu.uoc.evental.security;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Optional;
import java.util.stream.Stream;
/**
* Utility class for Spring Security.
*/
public final class SecurityUtils {
private SecurityUtils() {
}
/**
* Get the login of the current user.
*
* @return the login of the current user.
*/
public static Optional<String> getCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(extractPrincipal(securityContext.getAuthentication()));
}
private static String extractPrincipal(Authentication authentication) {
if (authentication == null) {
return null;
} else if (authentication.getPrincipal() instanceof UserDetails) {
UserDetails springSecurityUser = (UserDetails) authentication.getPrincipal();
return springSecurityUser.getUsername();
} else if (authentication.getPrincipal() instanceof String) {
return (String) authentication.getPrincipal();
}
return null;
}
/**
* Get the JWT of the current user.
*
* @return the JWT of the current user.
*/
public static Optional<String> getCurrentUserJWT() {
SecurityContext securityContext = SecurityContextHolder.getContext();
return Optional.ofNullable(securityContext.getAuthentication())
.filter(authentication -> authentication.getCredentials() instanceof String)
.map(authentication -> (String) authentication.getCredentials());
}
/**
* Check if a user is authenticated.
*
* @return true if the user is authenticated, false otherwise.
*/
public static boolean isAuthenticated() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null &&
getAuthorities(authentication).noneMatch(AuthoritiesConstants.ANONYMOUS::equals);
}
/**
* If the current user has a specific authority (security role).
* <p>
* The name of this method comes from the {@code isUserInRole()} method in the Servlet API.
*
* @param authority the authority to check.
* @return true if the current user has the authority, false otherwise.
*/
public static boolean isCurrentUserInRole(String authority) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication != null &&
getAuthorities(authentication).anyMatch(authority::equals);
}
private static Stream<String> getAuthorities(Authentication authentication) {
return authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority);
}
}

View File

@@ -0,0 +1,20 @@
package edu.uoc.evental.security;
import edu.uoc.evental.config.Constants;
import java.util.Optional;
import org.springframework.data.domain.AuditorAware;
import org.springframework.stereotype.Component;
/**
* Implementation of {@link AuditorAware} based on Spring Security.
*/
@Component
public class SpringSecurityAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.of(SecurityUtils.getCurrentUserLogin().orElse(Constants.SYSTEM_ACCOUNT));
}
}

View File

@@ -0,0 +1,19 @@
package edu.uoc.evental.security;
import org.springframework.security.core.AuthenticationException;
/**
* This exception is thrown in case of a not activated user trying to authenticate.
*/
public class UserNotActivatedException extends AuthenticationException {
private static final long serialVersionUID = 1L;
public UserNotActivatedException(String message) {
super(message);
}
public UserNotActivatedException(String message, Throwable t) {
super(message, t);
}
}

View File

@@ -0,0 +1,21 @@
package edu.uoc.evental.security.jwt;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
public class JWTConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
private final TokenProvider tokenProvider;
public JWTConfigurer(TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
@Override
public void configure(HttpSecurity http) {
JWTFilter customFilter = new JWTFilter(tokenProvider);
http.addFilterBefore(customFilter, UsernamePasswordAuthenticationFilter.class);
}
}

View File

@@ -0,0 +1,48 @@
package edu.uoc.evental.security.jwt;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* Filters incoming requests and installs a Spring Security principal if a header corresponding to a valid user is
* found.
*/
public class JWTFilter extends GenericFilterBean {
public static final String AUTHORIZATION_HEADER = "Authorization";
private final TokenProvider tokenProvider;
public JWTFilter(TokenProvider tokenProvider) {
this.tokenProvider = tokenProvider;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
String jwt = resolveToken(httpServletRequest);
if (StringUtils.hasText(jwt) && this.tokenProvider.validateToken(jwt)) {
Authentication authentication = this.tokenProvider.getAuthentication(jwt);
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(servletRequest, servletResponse);
}
private String resolveToken(HttpServletRequest request) {
String bearerToken = request.getHeader(AUTHORIZATION_HEADER);
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7);
}
return null;
}
}

View File

@@ -0,0 +1,110 @@
package edu.uoc.evental.security.jwt;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import io.github.jhipster.config.JHipsterProperties;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
@Component
public class TokenProvider {
private final Logger log = LoggerFactory.getLogger(TokenProvider.class);
private static final String AUTHORITIES_KEY = "auth";
private Key key;
private long tokenValidityInMilliseconds;
private long tokenValidityInMillisecondsForRememberMe;
private final JHipsterProperties jHipsterProperties;
public TokenProvider(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@PostConstruct
public void init() {
byte[] keyBytes;
String secret = jHipsterProperties.getSecurity().getAuthentication().getJwt().getSecret();
if (!StringUtils.isEmpty(secret)) {
log.warn("Warning: the JWT key used is not Base64-encoded. " +
"We recommend using the `jhipster.security.authentication.jwt.base64-secret` key for optimum security.");
keyBytes = secret.getBytes(StandardCharsets.UTF_8);
} else {
log.debug("Using a Base64-encoded JWT secret key");
keyBytes = Decoders.BASE64.decode(jHipsterProperties.getSecurity().getAuthentication().getJwt().getBase64Secret());
}
this.key = Keys.hmacShaKeyFor(keyBytes);
this.tokenValidityInMilliseconds =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt().getTokenValidityInSeconds();
this.tokenValidityInMillisecondsForRememberMe =
1000 * jHipsterProperties.getSecurity().getAuthentication().getJwt()
.getTokenValidityInSecondsForRememberMe();
}
public String createToken(Authentication authentication, boolean rememberMe) {
String authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));
long now = (new Date()).getTime();
Date validity;
if (rememberMe) {
validity = new Date(now + this.tokenValidityInMillisecondsForRememberMe);
} else {
validity = new Date(now + this.tokenValidityInMilliseconds);
}
return Jwts.builder()
.setSubject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.signWith(key, SignatureAlgorithm.HS512)
.setExpiration(validity)
.compact();
}
public Authentication getAuthentication(String token) {
Claims claims = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(token)
.getBody();
Collection<? extends GrantedAuthority> authorities =
Arrays.stream(claims.get(AUTHORITIES_KEY).toString().split(","))
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
User principal = new User(claims.getSubject(), "", authorities);
return new UsernamePasswordAuthenticationToken(principal, token, authorities);
}
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(key).parseClaimsJws(authToken);
return true;
} catch (JwtException | IllegalArgumentException e) {
log.info("Invalid JWT token.");
log.trace("Invalid JWT token trace.", e);
}
return false;
}
}

View File

@@ -0,0 +1,4 @@
/**
* Spring Security configuration.
*/
package edu.uoc.evental.security;

View File

@@ -0,0 +1,98 @@
package edu.uoc.evental.service;
import java.util.List;
import javax.persistence.criteria.JoinType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.github.jhipster.service.QueryService;
import edu.uoc.evental.domain.Artist;
import edu.uoc.evental.domain.*; // for static metamodels
import edu.uoc.evental.repository.ArtistRepository;
import edu.uoc.evental.service.dto.ArtistCriteria;
/**
* Service for executing complex queries for {@link Artist} entities in the database.
* The main input is a {@link ArtistCriteria} which gets converted to {@link Specification},
* in a way that all the filters must apply.
* It returns a {@link List} of {@link Artist} or a {@link Page} of {@link Artist} which fulfills the criteria.
*/
@Service
@Transactional(readOnly = true)
public class ArtistQueryService extends QueryService<Artist> {
private final Logger log = LoggerFactory.getLogger(ArtistQueryService.class);
private final ArtistRepository artistRepository;
public ArtistQueryService(ArtistRepository artistRepository) {
this.artistRepository = artistRepository;
}
/**
* Return a {@link List} of {@link Artist} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public List<Artist> findByCriteria(ArtistCriteria criteria) {
log.debug("find by criteria : {}", criteria);
final Specification<Artist> specification = createSpecification(criteria);
return artistRepository.findAll(specification);
}
/**
* Return a {@link Page} of {@link Artist} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @param page The page, which should be returned.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public Page<Artist> findByCriteria(ArtistCriteria criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<Artist> specification = createSpecification(criteria);
return artistRepository.findAll(specification, page);
}
/**
* Return the number of matching entities in the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the number of matching entities.
*/
@Transactional(readOnly = true)
public long countByCriteria(ArtistCriteria criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<Artist> specification = createSpecification(criteria);
return artistRepository.count(specification);
}
/**
* Function to convert {@link ArtistCriteria} to a {@link Specification}
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching {@link Specification} of the entity.
*/
protected Specification<Artist> createSpecification(ArtistCriteria criteria) {
Specification<Artist> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildRangeSpecification(criteria.getId(), Artist_.id));
}
if (criteria.getArtistName() != null) {
specification = specification.and(buildStringSpecification(criteria.getArtistName(), Artist_.artistName));
}
if (criteria.getUserId() != null) {
specification = specification.and(buildSpecification(criteria.getUserId(),
root -> root.join(Artist_.user, JoinType.LEFT).get(User_.id)));
}
}
return specification;
}
}

View File

@@ -0,0 +1,45 @@
package edu.uoc.evental.service;
import edu.uoc.evental.domain.Artist;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Optional;
/**
* Service Interface for managing {@link Artist}.
*/
public interface ArtistService {
/**
* Save a artist.
*
* @param artist the entity to save.
* @return the persisted entity.
*/
Artist save(Artist artist);
/**
* Get all the artists.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
Page<Artist> findAll(Pageable pageable);
/**
* Get the "id" artist.
*
* @param id the id of the entity.
* @return the entity.
*/
Optional<Artist> findOne(Long id);
/**
* Delete the "id" artist.
*
* @param id the id of the entity.
*/
void delete(Long id);
}

View File

@@ -0,0 +1,74 @@
package edu.uoc.evental.service;
import io.github.jhipster.config.JHipsterProperties;
import edu.uoc.evental.config.audit.AuditEventConverter;
import edu.uoc.evental.repository.PersistenceAuditEventRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
/**
* Service for managing audit events.
* <p>
* This is the default implementation to support SpringBoot Actuator {@code AuditEventRepository}.
*/
@Service
@Transactional
public class AuditEventService {
private final Logger log = LoggerFactory.getLogger(AuditEventService.class);
private final JHipsterProperties jHipsterProperties;
private final PersistenceAuditEventRepository persistenceAuditEventRepository;
private final AuditEventConverter auditEventConverter;
public AuditEventService(
PersistenceAuditEventRepository persistenceAuditEventRepository,
AuditEventConverter auditEventConverter, JHipsterProperties jhipsterProperties) {
this.persistenceAuditEventRepository = persistenceAuditEventRepository;
this.auditEventConverter = auditEventConverter;
this.jHipsterProperties = jhipsterProperties;
}
/**
* Old audit events should be automatically deleted after 30 days.
*
* This is scheduled to get fired at 12:00 (am).
*/
@Scheduled(cron = "0 0 12 * * ?")
public void removeOldAuditEvents() {
persistenceAuditEventRepository
.findByAuditEventDateBefore(Instant.now().minus(jHipsterProperties.getAuditEvents().getRetentionPeriod(), ChronoUnit.DAYS))
.forEach(auditEvent -> {
log.debug("Deleting audit data {}", auditEvent);
persistenceAuditEventRepository.delete(auditEvent);
});
}
public Page<AuditEvent> findAll(Pageable pageable) {
return persistenceAuditEventRepository.findAll(pageable)
.map(auditEventConverter::convertToAuditEvent);
}
public Page<AuditEvent> findByDates(Instant fromDate, Instant toDate, Pageable pageable) {
return persistenceAuditEventRepository.findAllByAuditEventDateBetween(fromDate, toDate, pageable)
.map(auditEventConverter::convertToAuditEvent);
}
public Optional<AuditEvent> find(Long id) {
return persistenceAuditEventRepository.findById(id)
.map(auditEventConverter::convertToAuditEvent);
}
}

View File

@@ -0,0 +1,11 @@
package edu.uoc.evental.service;
public class EmailAlreadyUsedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public EmailAlreadyUsedException() {
super("Email is already in use!");
}
}

View File

@@ -0,0 +1,133 @@
package edu.uoc.evental.service;
import java.util.List;
import javax.persistence.criteria.JoinType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.github.jhipster.service.QueryService;
import edu.uoc.evental.domain.Event;
import edu.uoc.evental.domain.*; // for static metamodels
import edu.uoc.evental.repository.EventRepository;
import edu.uoc.evental.service.dto.EventCriteria;
/**
* Service for executing complex queries for {@link Event} entities in the database.
* The main input is a {@link EventCriteria} which gets converted to {@link Specification},
* in a way that all the filters must apply.
* It returns a {@link List} of {@link Event} or a {@link Page} of {@link Event} which fulfills the criteria.
*/
@Service
@Transactional(readOnly = true)
public class EventQueryService extends QueryService<Event> {
private final Logger log = LoggerFactory.getLogger(EventQueryService.class);
private final EventRepository eventRepository;
public EventQueryService(EventRepository eventRepository) {
this.eventRepository = eventRepository;
}
/**
* Return a {@link List} of {@link Event} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public List<Event> findByCriteria(EventCriteria criteria) {
log.debug("find by criteria : {}", criteria);
final Specification<Event> specification = createSpecification(criteria);
return eventRepository.findAll(specification);
}
/**
* Return a {@link Page} of {@link Event} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @param page The page, which should be returned.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public Page<Event> findByCriteria(EventCriteria criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<Event> specification = createSpecification(criteria);
return eventRepository.findAll(specification, page);
}
/**
* Return the number of matching entities in the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the number of matching entities.
*/
@Transactional(readOnly = true)
public long countByCriteria(EventCriteria criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<Event> specification = createSpecification(criteria);
return eventRepository.count(specification);
}
/**
* Function to convert {@link EventCriteria} to a {@link Specification}
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching {@link Specification} of the entity.
*/
protected Specification<Event> createSpecification(EventCriteria criteria) {
Specification<Event> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildRangeSpecification(criteria.getId(), Event_.id));
}
if (criteria.getEventDateTime() != null) {
specification = specification.and(buildRangeSpecification(criteria.getEventDateTime(), Event_.eventDateTime));
}
if (criteria.getTicketPrice() != null) {
specification = specification.and(buildRangeSpecification(criteria.getTicketPrice(), Event_.ticketPrice));
}
if (criteria.getFeeModel() != null) {
specification = specification.and(buildSpecification(criteria.getFeeModel(), Event_.feeModel));
}
if (criteria.getFeeAmount() != null) {
specification = specification.and(buildRangeSpecification(criteria.getFeeAmount(), Event_.feeAmount));
}
if (criteria.getArtistUserId() != null) {
specification = specification.and(buildRangeSpecification(criteria.getArtistUserId(), Event_.artistUserId));
}
if (criteria.getVenueUserId() != null) {
specification = specification.and(buildRangeSpecification(criteria.getVenueUserId(), Event_.venueUserId));
}
if (criteria.getIsConfirmedByArtist() != null) {
specification = specification.and(buildSpecification(criteria.getIsConfirmedByArtist(), Event_.isConfirmedByArtist));
}
if (criteria.getIsConfirmedByVenue() != null) {
specification = specification.and(buildSpecification(criteria.getIsConfirmedByVenue(), Event_.isConfirmedByVenue));
}
if (criteria.getIsRejected() != null) {
specification = specification.and(buildSpecification(criteria.getIsRejected(), Event_.isRejected));
}
if (criteria.getTicketsSold() != null) {
specification = specification.and(buildRangeSpecification(criteria.getTicketsSold(), Event_.ticketsSold));
}
if (criteria.getTicketId() != null) {
specification = specification.and(buildSpecification(criteria.getTicketId(),
root -> root.join(Event_.tickets, JoinType.LEFT).get(Ticket_.id)));
}
if (criteria.getArtistId() != null) {
specification = specification.and(buildSpecification(criteria.getArtistId(),
root -> root.join(Event_.artist, JoinType.LEFT).get(Artist_.id)));
}
if (criteria.getVenueId() != null) {
specification = specification.and(buildSpecification(criteria.getVenueId(),
root -> root.join(Event_.venue, JoinType.LEFT).get(Venue_.id)));
}
}
return specification;
}
}

View File

@@ -0,0 +1,45 @@
package edu.uoc.evental.service;
import edu.uoc.evental.domain.Event;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Optional;
/**
* Service Interface for managing {@link Event}.
*/
public interface EventService {
/**
* Save a event.
*
* @param event the entity to save.
* @return the persisted entity.
*/
Event save(Event event);
/**
* Get all the events.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
Page<Event> findAll(Pageable pageable);
/**
* Get the "id" event.
*
* @param id the id of the entity.
* @return the entity.
*/
Optional<Event> findOne(Long id);
/**
* Delete the "id" event.
*
* @param id the id of the entity.
*/
void delete(Long id);
}

View File

@@ -0,0 +1,101 @@
package edu.uoc.evental.service;
import java.util.List;
import javax.persistence.criteria.JoinType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.github.jhipster.service.QueryService;
import edu.uoc.evental.domain.FiscalData;
import edu.uoc.evental.domain.*; // for static metamodels
import edu.uoc.evental.repository.FiscalDataRepository;
import edu.uoc.evental.service.dto.FiscalDataCriteria;
/**
* Service for executing complex queries for {@link FiscalData} entities in the database.
* The main input is a {@link FiscalDataCriteria} which gets converted to {@link Specification},
* in a way that all the filters must apply.
* It returns a {@link List} of {@link FiscalData} or a {@link Page} of {@link FiscalData} which fulfills the criteria.
*/
@Service
@Transactional(readOnly = true)
public class FiscalDataQueryService extends QueryService<FiscalData> {
private final Logger log = LoggerFactory.getLogger(FiscalDataQueryService.class);
private final FiscalDataRepository fiscalDataRepository;
public FiscalDataQueryService(FiscalDataRepository fiscalDataRepository) {
this.fiscalDataRepository = fiscalDataRepository;
}
/**
* Return a {@link List} of {@link FiscalData} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public List<FiscalData> findByCriteria(FiscalDataCriteria criteria) {
log.debug("find by criteria : {}", criteria);
final Specification<FiscalData> specification = createSpecification(criteria);
return fiscalDataRepository.findAll(specification);
}
/**
* Return a {@link Page} of {@link FiscalData} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @param page The page, which should be returned.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public Page<FiscalData> findByCriteria(FiscalDataCriteria criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<FiscalData> specification = createSpecification(criteria);
return fiscalDataRepository.findAll(specification, page);
}
/**
* Return the number of matching entities in the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the number of matching entities.
*/
@Transactional(readOnly = true)
public long countByCriteria(FiscalDataCriteria criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<FiscalData> specification = createSpecification(criteria);
return fiscalDataRepository.count(specification);
}
/**
* Function to convert {@link FiscalDataCriteria} to a {@link Specification}
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching {@link Specification} of the entity.
*/
protected Specification<FiscalData> createSpecification(FiscalDataCriteria criteria) {
Specification<FiscalData> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildRangeSpecification(criteria.getId(), FiscalData_.id));
}
if (criteria.getNif() != null) {
specification = specification.and(buildStringSpecification(criteria.getNif(), FiscalData_.nif));
}
if (criteria.getBirthDate() != null) {
specification = specification.and(buildRangeSpecification(criteria.getBirthDate(), FiscalData_.birthDate));
}
if (criteria.getUserId() != null) {
specification = specification.and(buildSpecification(criteria.getUserId(),
root -> root.join(FiscalData_.user, JoinType.LEFT).get(User_.id)));
}
}
return specification;
}
}

View File

@@ -0,0 +1,42 @@
package edu.uoc.evental.service;
import edu.uoc.evental.domain.FiscalData;
import java.util.List;
import java.util.Optional;
/**
* Service Interface for managing {@link FiscalData}.
*/
public interface FiscalDataService {
/**
* Save a fiscalData.
*
* @param fiscalData the entity to save.
* @return the persisted entity.
*/
FiscalData save(FiscalData fiscalData);
/**
* Get all the fiscalData.
*
* @return the list of entities.
*/
List<FiscalData> findAll();
/**
* Get the "id" fiscalData.
*
* @param id the id of the entity.
* @return the entity.
*/
Optional<FiscalData> findOne(Long id);
/**
* Delete the "id" fiscalData.
*
* @param id the id of the entity.
*/
void delete(Long id);
}

View File

@@ -0,0 +1,11 @@
package edu.uoc.evental.service;
public class InvalidPasswordException extends RuntimeException {
private static final long serialVersionUID = 1L;
public InvalidPasswordException() {
super("Incorrect password");
}
}

View File

@@ -0,0 +1,106 @@
package edu.uoc.evental.service;
import edu.uoc.evental.domain.User;
import io.github.jhipster.config.JHipsterProperties;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;
/**
* Service for sending emails.
* <p>
* We use the {@link Async} annotation to send emails asynchronously.
*/
@Service
public class MailService {
private final Logger log = LoggerFactory.getLogger(MailService.class);
private static final String USER = "user";
private static final String BASE_URL = "baseUrl";
private final JHipsterProperties jHipsterProperties;
private final JavaMailSender javaMailSender;
private final MessageSource messageSource;
private final SpringTemplateEngine templateEngine;
public MailService(JHipsterProperties jHipsterProperties, JavaMailSender javaMailSender,
MessageSource messageSource, SpringTemplateEngine templateEngine) {
this.jHipsterProperties = jHipsterProperties;
this.javaMailSender = javaMailSender;
this.messageSource = messageSource;
this.templateEngine = templateEngine;
}
@Async
public void sendEmail(String to, String subject, String content, boolean isMultipart, boolean isHtml) {
log.debug("Send email[multipart '{}' and html '{}'] to '{}' with subject '{}' and content={}",
isMultipart, isHtml, to, subject, content);
// Prepare message using a Spring helper
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
try {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, StandardCharsets.UTF_8.name());
message.setTo(to);
message.setFrom(jHipsterProperties.getMail().getFrom());
message.setSubject(subject);
message.setText(content, isHtml);
javaMailSender.send(mimeMessage);
log.debug("Sent email to User '{}'", to);
} catch (MailException | MessagingException e) {
log.warn("Email could not be sent to user '{}'", to, e);
}
}
@Async
public void sendEmailFromTemplate(User user, String templateName, String titleKey) {
if (user.getEmail() == null) {
log.debug("Email doesn't exist for user '{}'", user.getLogin());
return;
}
Locale locale = Locale.forLanguageTag(user.getLangKey());
Context context = new Context(locale);
context.setVariable(USER, user);
context.setVariable(BASE_URL, jHipsterProperties.getMail().getBaseUrl());
String content = templateEngine.process(templateName, context);
String subject = messageSource.getMessage(titleKey, null, locale);
sendEmail(user.getEmail(), subject, content, false, true);
}
@Async
public void sendActivationEmail(User user) {
log.debug("Sending activation email to '{}'", user.getEmail());
sendEmailFromTemplate(user, "mail/activationEmail", "email.activation.title");
}
@Async
public void sendCreationEmail(User user) {
log.debug("Sending creation email to '{}'", user.getEmail());
sendEmailFromTemplate(user, "mail/creationEmail", "email.activation.title");
}
@Async
public void sendPasswordResetMail(User user) {
log.debug("Sending password reset email to '{}'", user.getEmail());
sendEmailFromTemplate(user, "mail/passwordResetEmail", "email.reset.title");
}
}

View File

@@ -0,0 +1,99 @@
package edu.uoc.evental.service;
import java.util.List;
import javax.persistence.criteria.JoinType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.github.jhipster.service.QueryService;
import edu.uoc.evental.domain.Ticket;
import edu.uoc.evental.domain.*; // for static metamodels
import edu.uoc.evental.repository.TicketRepository;
import edu.uoc.evental.service.dto.TicketCriteria;
/**
* Service for executing complex queries for {@link Ticket} entities in the database.
* The main input is a {@link TicketCriteria} which gets converted to {@link Specification},
* in a way that all the filters must apply.
* It returns a {@link List} of {@link Ticket} or a {@link Page} of {@link Ticket} which fulfills the criteria.
*/
@Service
@Transactional(readOnly = true)
public class TicketQueryService extends QueryService<Ticket> {
private final Logger log = LoggerFactory.getLogger(TicketQueryService.class);
private final TicketRepository ticketRepository;
public TicketQueryService(TicketRepository ticketRepository) {
this.ticketRepository = ticketRepository;
}
/**
* Return a {@link List} of {@link Ticket} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public List<Ticket> findByCriteria(TicketCriteria criteria) {
log.debug("find by criteria : {}", criteria);
final Specification<Ticket> specification = createSpecification(criteria);
return ticketRepository.findAll(specification);
}
/**
* Return a {@link Page} of {@link Ticket} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @param page The page, which should be returned.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public Page<Ticket> findByCriteria(TicketCriteria criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<Ticket> specification = createSpecification(criteria);
return ticketRepository.findAll(specification, page);
}
/**
* Return the number of matching entities in the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the number of matching entities.
*/
@Transactional(readOnly = true)
public long countByCriteria(TicketCriteria criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<Ticket> specification = createSpecification(criteria);
return ticketRepository.count(specification);
}
/**
* Function to convert {@link TicketCriteria} to a {@link Specification}
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching {@link Specification} of the entity.
*/
protected Specification<Ticket> createSpecification(TicketCriteria criteria) {
Specification<Ticket> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildRangeSpecification(criteria.getId(), Ticket_.id));
}
if (criteria.getFiscalDataId() != null) {
specification = specification.and(buildSpecification(criteria.getFiscalDataId(),
root -> root.join(Ticket_.fiscalData, JoinType.LEFT).get(FiscalData_.id)));
}
if (criteria.getEventId() != null) {
specification = specification.and(buildSpecification(criteria.getEventId(),
root -> root.join(Ticket_.event, JoinType.LEFT).get(Event_.id)));
}
}
return specification;
}
}

View File

@@ -0,0 +1,45 @@
package edu.uoc.evental.service;
import edu.uoc.evental.domain.Ticket;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Optional;
/**
* Service Interface for managing {@link Ticket}.
*/
public interface TicketService {
/**
* Save a ticket.
*
* @param ticket the entity to save.
* @return the persisted entity.
*/
Ticket save(Ticket ticket);
/**
* Get all the tickets.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
Page<Ticket> findAll(Pageable pageable);
/**
* Get the "id" ticket.
*
* @param id the id of the entity.
* @return the entity.
*/
Optional<Ticket> findOne(Long id);
/**
* Delete the "id" ticket.
*
* @param id the id of the entity.
*/
void delete(Long id);
}

View File

@@ -0,0 +1,306 @@
package edu.uoc.evental.service;
import edu.uoc.evental.config.Constants;
import edu.uoc.evental.domain.Authority;
import edu.uoc.evental.domain.User;
import edu.uoc.evental.repository.AuthorityRepository;
import edu.uoc.evental.repository.UserRepository;
import edu.uoc.evental.security.AuthoritiesConstants;
import edu.uoc.evental.security.SecurityUtils;
import edu.uoc.evental.service.dto.UserDTO;
import io.github.jhipster.security.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
/**
* Service class for managing users.
*/
@Service
@Transactional
public class UserService {
private final Logger log = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final AuthorityRepository authorityRepository;
private final CacheManager cacheManager;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository, CacheManager cacheManager) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.authorityRepository = authorityRepository;
this.cacheManager = cacheManager;
}
public Optional<User> activateRegistration(String key) {
log.debug("Activating user for activation key {}", key);
return userRepository.findOneByActivationKey(key)
.map(user -> {
// activate given user for the registration key.
user.setActivated(true);
user.setActivationKey(null);
this.clearUserCaches(user);
log.debug("Activated user: {}", user);
return user;
});
}
public Optional<User> completePasswordReset(String newPassword, String key) {
log.debug("Reset user password for reset key {}", key);
return userRepository.findOneByResetKey(key)
.filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400)))
.map(user -> {
user.setPassword(passwordEncoder.encode(newPassword));
user.setResetKey(null);
user.setResetDate(null);
this.clearUserCaches(user);
return user;
});
}
public Optional<User> requestPasswordReset(String mail) {
return userRepository.findOneByEmailIgnoreCase(mail)
.filter(User::getActivated)
.map(user -> {
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
this.clearUserCaches(user);
return user;
});
}
public User registerUser(UserDTO userDTO, String password) {
userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).ifPresent(existingUser -> {
boolean removed = removeNonActivatedUser(existingUser);
if (!removed) {
throw new UsernameAlreadyUsedException();
}
});
userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).ifPresent(existingUser -> {
boolean removed = removeNonActivatedUser(existingUser);
if (!removed) {
throw new EmailAlreadyUsedException();
}
});
User newUser = new User();
String encryptedPassword = passwordEncoder.encode(password);
newUser.setLogin(userDTO.getLogin().toLowerCase());
// new user gets initially a generated password
newUser.setPassword(encryptedPassword);
newUser.setFirstName(userDTO.getFirstName());
newUser.setLastName(userDTO.getLastName());
if (userDTO.getEmail() != null) {
newUser.setEmail(userDTO.getEmail().toLowerCase());
}
newUser.setImageUrl(userDTO.getImageUrl());
newUser.setLangKey(userDTO.getLangKey());
// new user is not active
newUser.setActivated(false);
// new user gets registration key
newUser.setActivationKey(RandomUtil.generateActivationKey());
Set<Authority> authorities = new HashSet<>();
authorityRepository.findById(AuthoritiesConstants.USER).ifPresent(authorities::add);
newUser.setAuthorities(authorities);
userRepository.save(newUser);
this.clearUserCaches(newUser);
log.debug("Created Information for User: {}", newUser);
return newUser;
}
private boolean removeNonActivatedUser(User existingUser) {
if (existingUser.getActivated()) {
return false;
}
userRepository.delete(existingUser);
userRepository.flush();
this.clearUserCaches(existingUser);
return true;
}
public User createUser(UserDTO userDTO) {
User user = new User();
user.setLogin(userDTO.getLogin().toLowerCase());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
if (userDTO.getEmail() != null) {
user.setEmail(userDTO.getEmail().toLowerCase());
}
user.setImageUrl(userDTO.getImageUrl());
if (userDTO.getLangKey() == null) {
user.setLangKey(Constants.DEFAULT_LANGUAGE); // default language
} else {
user.setLangKey(userDTO.getLangKey());
}
String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword());
user.setPassword(encryptedPassword);
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
user.setActivated(true);
if (userDTO.getAuthorities() != null) {
Set<Authority> authorities = userDTO.getAuthorities().stream()
.map(authorityRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
user.setAuthorities(authorities);
}
userRepository.save(user);
this.clearUserCaches(user);
log.debug("Created Information for User: {}", user);
return user;
}
/**
* Update basic information (first name, last name, email, language) for the current user.
*
* @param firstName first name of user.
* @param lastName last name of user.
* @param email email id of user.
* @param langKey language key.
* @param imageUrl image URL of user.
*/
public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
user.setFirstName(firstName);
user.setLastName(lastName);
if (email != null) {
user.setEmail(email.toLowerCase());
}
user.setLangKey(langKey);
user.setImageUrl(imageUrl);
this.clearUserCaches(user);
log.debug("Changed Information for User: {}", user);
});
}
/**
* Update all information for a specific user, and return the modified user.
*
* @param userDTO user to update.
* @return updated user.
*/
public Optional<UserDTO> updateUser(UserDTO userDTO) {
return Optional.of(userRepository
.findById(userDTO.getId()))
.filter(Optional::isPresent)
.map(Optional::get)
.map(user -> {
this.clearUserCaches(user);
user.setLogin(userDTO.getLogin().toLowerCase());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
if (userDTO.getEmail() != null) {
user.setEmail(userDTO.getEmail().toLowerCase());
}
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> managedAuthorities = user.getAuthorities();
managedAuthorities.clear();
userDTO.getAuthorities().stream()
.map(authorityRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(managedAuthorities::add);
this.clearUserCaches(user);
log.debug("Changed Information for User: {}", user);
return user;
})
.map(UserDTO::new);
}
public void deleteUser(String login) {
userRepository.findOneByLogin(login).ifPresent(user -> {
userRepository.delete(user);
this.clearUserCaches(user);
log.debug("Deleted User: {}", user);
});
}
public void changePassword(String currentClearTextPassword, String newPassword) {
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
String currentEncryptedPassword = user.getPassword();
if (!passwordEncoder.matches(currentClearTextPassword, currentEncryptedPassword)) {
throw new InvalidPasswordException();
}
String encryptedPassword = passwordEncoder.encode(newPassword);
user.setPassword(encryptedPassword);
this.clearUserCaches(user);
log.debug("Changed password for User: {}", user);
});
}
@Transactional(readOnly = true)
public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneWithAuthoritiesByLogin(login);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthorities(Long id) {
return userRepository.findOneWithAuthoritiesById(id);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthorities() {
return SecurityUtils.getCurrentUserLogin().flatMap(userRepository::findOneWithAuthoritiesByLogin);
}
/**
* Not activated users should be automatically deleted after 3 days.
* <p>
* This is scheduled to get fired everyday, at 01:00 (am).
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
userRepository
.findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS))
.forEach(user -> {
log.debug("Deleting not activated user {}", user.getLogin());
userRepository.delete(user);
this.clearUserCaches(user);
});
}
/**
* Gets a list of all the authorities.
* @return a list of all the authorities.
*/
public List<String> getAuthorities() {
return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList());
}
private void clearUserCaches(User user) {
Objects.requireNonNull(cacheManager.getCache(UserRepository.USERS_BY_LOGIN_CACHE)).evict(user.getLogin());
if (user.getEmail() != null) {
Objects.requireNonNull(cacheManager.getCache(UserRepository.USERS_BY_EMAIL_CACHE)).evict(user.getEmail());
}
}
}

View File

@@ -0,0 +1,11 @@
package edu.uoc.evental.service;
public class UsernameAlreadyUsedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public UsernameAlreadyUsedException() {
super("Login name already used!");
}
}

View File

@@ -0,0 +1,104 @@
package edu.uoc.evental.service;
import java.util.List;
import javax.persistence.criteria.JoinType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import io.github.jhipster.service.QueryService;
import edu.uoc.evental.domain.Venue;
import edu.uoc.evental.domain.*; // for static metamodels
import edu.uoc.evental.repository.VenueRepository;
import edu.uoc.evental.service.dto.VenueCriteria;
/**
* Service for executing complex queries for {@link Venue} entities in the database.
* The main input is a {@link VenueCriteria} which gets converted to {@link Specification},
* in a way that all the filters must apply.
* It returns a {@link List} of {@link Venue} or a {@link Page} of {@link Venue} which fulfills the criteria.
*/
@Service
@Transactional(readOnly = true)
public class VenueQueryService extends QueryService<Venue> {
private final Logger log = LoggerFactory.getLogger(VenueQueryService.class);
private final VenueRepository venueRepository;
public VenueQueryService(VenueRepository venueRepository) {
this.venueRepository = venueRepository;
}
/**
* Return a {@link List} of {@link Venue} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public List<Venue> findByCriteria(VenueCriteria criteria) {
log.debug("find by criteria : {}", criteria);
final Specification<Venue> specification = createSpecification(criteria);
return venueRepository.findAll(specification);
}
/**
* Return a {@link Page} of {@link Venue} which matches the criteria from the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @param page The page, which should be returned.
* @return the matching entities.
*/
@Transactional(readOnly = true)
public Page<Venue> findByCriteria(VenueCriteria criteria, Pageable page) {
log.debug("find by criteria : {}, page: {}", criteria, page);
final Specification<Venue> specification = createSpecification(criteria);
return venueRepository.findAll(specification, page);
}
/**
* Return the number of matching entities in the database.
* @param criteria The object which holds all the filters, which the entities should match.
* @return the number of matching entities.
*/
@Transactional(readOnly = true)
public long countByCriteria(VenueCriteria criteria) {
log.debug("count by criteria : {}", criteria);
final Specification<Venue> specification = createSpecification(criteria);
return venueRepository.count(specification);
}
/**
* Function to convert {@link VenueCriteria} to a {@link Specification}
* @param criteria The object which holds all the filters, which the entities should match.
* @return the matching {@link Specification} of the entity.
*/
protected Specification<Venue> createSpecification(VenueCriteria criteria) {
Specification<Venue> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildRangeSpecification(criteria.getId(), Venue_.id));
}
if (criteria.getVenueName() != null) {
specification = specification.and(buildStringSpecification(criteria.getVenueName(), Venue_.venueName));
}
if (criteria.getLocation() != null) {
specification = specification.and(buildSpecification(criteria.getLocation(), Venue_.location));
}
if (criteria.getCapacity() != null) {
specification = specification.and(buildRangeSpecification(criteria.getCapacity(), Venue_.capacity));
}
if (criteria.getUserId() != null) {
specification = specification.and(buildSpecification(criteria.getUserId(),
root -> root.join(Venue_.user, JoinType.LEFT).get(User_.id)));
}
}
return specification;
}
}

View File

@@ -0,0 +1,45 @@
package edu.uoc.evental.service;
import edu.uoc.evental.domain.Venue;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import java.util.Optional;
/**
* Service Interface for managing {@link Venue}.
*/
public interface VenueService {
/**
* Save a venue.
*
* @param venue the entity to save.
* @return the persisted entity.
*/
Venue save(Venue venue);
/**
* Get all the venues.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
Page<Venue> findAll(Pageable pageable);
/**
* Get the "id" venue.
*
* @param id the id of the entity.
* @return the entity.
*/
Optional<Venue> findOne(Long id);
/**
* Delete the "id" venue.
*
* @param id the id of the entity.
*/
void delete(Long id);
}

View File

@@ -0,0 +1,105 @@
package edu.uoc.evental.service.dto;
import java.io.Serializable;
import java.util.Objects;
import io.github.jhipster.service.Criteria;
import io.github.jhipster.service.filter.BooleanFilter;
import io.github.jhipster.service.filter.DoubleFilter;
import io.github.jhipster.service.filter.Filter;
import io.github.jhipster.service.filter.FloatFilter;
import io.github.jhipster.service.filter.IntegerFilter;
import io.github.jhipster.service.filter.LongFilter;
import io.github.jhipster.service.filter.StringFilter;
/**
* Criteria class for the {@link edu.uoc.evental.domain.Artist} entity. This class is used
* in {@link edu.uoc.evental.web.rest.ArtistResource} to receive all the possible filtering options from
* the Http GET request parameters.
* For example the following could be a valid request:
* {@code /artists?id.greaterThan=5&attr1.contains=something&attr2.specified=false}
* As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use
* fix type specific filters.
*/
public class ArtistCriteria implements Serializable, Criteria {
private static final long serialVersionUID = 1L;
private LongFilter id;
private StringFilter artistName;
private LongFilter userId;
public ArtistCriteria() {
}
public ArtistCriteria(ArtistCriteria other) {
this.id = other.id == null ? null : other.id.copy();
this.artistName = other.artistName == null ? null : other.artistName.copy();
this.userId = other.userId == null ? null : other.userId.copy();
}
@Override
public ArtistCriteria copy() {
return new ArtistCriteria(this);
}
public LongFilter getId() {
return id;
}
public void setId(LongFilter id) {
this.id = id;
}
public StringFilter getArtistName() {
return artistName;
}
public void setArtistName(StringFilter artistName) {
this.artistName = artistName;
}
public LongFilter getUserId() {
return userId;
}
public void setUserId(LongFilter userId) {
this.userId = userId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final ArtistCriteria that = (ArtistCriteria) o;
return
Objects.equals(id, that.id) &&
Objects.equals(artistName, that.artistName) &&
Objects.equals(userId, that.userId);
}
@Override
public int hashCode() {
return Objects.hash(
id,
artistName,
userId
);
}
@Override
public String toString() {
return "ArtistCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(artistName != null ? "artistName=" + artistName + ", " : "") +
(userId != null ? "userId=" + userId + ", " : "") +
"}";
}
}

View File

@@ -0,0 +1,280 @@
package edu.uoc.evental.service.dto;
import java.io.Serializable;
import java.util.Objects;
import io.github.jhipster.service.Criteria;
import edu.uoc.evental.domain.enumeration.FeeModel;
import io.github.jhipster.service.filter.BooleanFilter;
import io.github.jhipster.service.filter.DoubleFilter;
import io.github.jhipster.service.filter.Filter;
import io.github.jhipster.service.filter.FloatFilter;
import io.github.jhipster.service.filter.IntegerFilter;
import io.github.jhipster.service.filter.LongFilter;
import io.github.jhipster.service.filter.StringFilter;
import io.github.jhipster.service.filter.BigDecimalFilter;
import io.github.jhipster.service.filter.InstantFilter;
/**
* Criteria class for the {@link edu.uoc.evental.domain.Event} entity. This class is used
* in {@link edu.uoc.evental.web.rest.EventResource} to receive all the possible filtering options from
* the Http GET request parameters.
* For example the following could be a valid request:
* {@code /events?id.greaterThan=5&attr1.contains=something&attr2.specified=false}
* As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use
* fix type specific filters.
*/
public class EventCriteria implements Serializable, Criteria {
/**
* Class for filtering FeeModel
*/
public static class FeeModelFilter extends Filter<FeeModel> {
public FeeModelFilter() {
}
public FeeModelFilter(FeeModelFilter filter) {
super(filter);
}
@Override
public FeeModelFilter copy() {
return new FeeModelFilter(this);
}
}
private static final long serialVersionUID = 1L;
private LongFilter id;
private InstantFilter eventDateTime;
private BigDecimalFilter ticketPrice;
private FeeModelFilter feeModel;
private IntegerFilter feeAmount;
private LongFilter artistUserId;
private LongFilter venueUserId;
private BooleanFilter isConfirmedByArtist;
private BooleanFilter isConfirmedByVenue;
private BooleanFilter isRejected;
private IntegerFilter ticketsSold;
private LongFilter ticketId;
private LongFilter artistId;
private LongFilter venueId;
public EventCriteria() {
}
public EventCriteria(EventCriteria other) {
this.id = other.id == null ? null : other.id.copy();
this.eventDateTime = other.eventDateTime == null ? null : other.eventDateTime.copy();
this.ticketPrice = other.ticketPrice == null ? null : other.ticketPrice.copy();
this.feeModel = other.feeModel == null ? null : other.feeModel.copy();
this.feeAmount = other.feeAmount == null ? null : other.feeAmount.copy();
this.artistUserId = other.artistUserId == null ? null : other.artistUserId.copy();
this.venueUserId = other.venueUserId == null ? null : other.venueUserId.copy();
this.isConfirmedByArtist = other.isConfirmedByArtist == null ? null : other.isConfirmedByArtist.copy();
this.isConfirmedByVenue = other.isConfirmedByVenue == null ? null : other.isConfirmedByVenue.copy();
this.isRejected = other.isRejected == null ? null : other.isRejected.copy();
this.ticketsSold = other.ticketsSold == null ? null : other.ticketsSold.copy();
this.ticketId = other.ticketId == null ? null : other.ticketId.copy();
this.artistId = other.artistId == null ? null : other.artistId.copy();
this.venueId = other.venueId == null ? null : other.venueId.copy();
}
@Override
public EventCriteria copy() {
return new EventCriteria(this);
}
public LongFilter getId() {
return id;
}
public void setId(LongFilter id) {
this.id = id;
}
public InstantFilter getEventDateTime() {
return eventDateTime;
}
public void setEventDateTime(InstantFilter eventDateTime) {
this.eventDateTime = eventDateTime;
}
public BigDecimalFilter getTicketPrice() {
return ticketPrice;
}
public void setTicketPrice(BigDecimalFilter ticketPrice) {
this.ticketPrice = ticketPrice;
}
public FeeModelFilter getFeeModel() {
return feeModel;
}
public void setFeeModel(FeeModelFilter feeModel) {
this.feeModel = feeModel;
}
public IntegerFilter getFeeAmount() {
return feeAmount;
}
public void setFeeAmount(IntegerFilter feeAmount) {
this.feeAmount = feeAmount;
}
public LongFilter getArtistUserId() {
return artistUserId;
}
public void setArtistUserId(LongFilter artistUserId) {
this.artistUserId = artistUserId;
}
public LongFilter getVenueUserId() {
return venueUserId;
}
public void setVenueUserId(LongFilter venueUserId) {
this.venueUserId = venueUserId;
}
public BooleanFilter getIsConfirmedByArtist() {
return isConfirmedByArtist;
}
public void setIsConfirmedByArtist(BooleanFilter isConfirmedByArtist) {
this.isConfirmedByArtist = isConfirmedByArtist;
}
public BooleanFilter getIsConfirmedByVenue() {
return isConfirmedByVenue;
}
public void setIsConfirmedByVenue(BooleanFilter isConfirmedByVenue) {
this.isConfirmedByVenue = isConfirmedByVenue;
}
public BooleanFilter getIsRejected() {
return isRejected;
}
public void setIsRejected(BooleanFilter isRejected) {
this.isRejected = isRejected;
}
public IntegerFilter getTicketsSold() {
return ticketsSold;
}
public void setTicketsSold(IntegerFilter ticketsSold) {
this.ticketsSold = ticketsSold;
}
public LongFilter getTicketId() {
return ticketId;
}
public void setTicketId(LongFilter ticketId) {
this.ticketId = ticketId;
}
public LongFilter getArtistId() {
return artistId;
}
public void setArtistId(LongFilter artistId) {
this.artistId = artistId;
}
public LongFilter getVenueId() {
return venueId;
}
public void setVenueId(LongFilter venueId) {
this.venueId = venueId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final EventCriteria that = (EventCriteria) o;
return
Objects.equals(id, that.id) &&
Objects.equals(eventDateTime, that.eventDateTime) &&
Objects.equals(ticketPrice, that.ticketPrice) &&
Objects.equals(feeModel, that.feeModel) &&
Objects.equals(feeAmount, that.feeAmount) &&
Objects.equals(artistUserId, that.artistUserId) &&
Objects.equals(venueUserId, that.venueUserId) &&
Objects.equals(isConfirmedByArtist, that.isConfirmedByArtist) &&
Objects.equals(isConfirmedByVenue, that.isConfirmedByVenue) &&
Objects.equals(isRejected, that.isRejected) &&
Objects.equals(ticketsSold, that.ticketsSold) &&
Objects.equals(ticketId, that.ticketId) &&
Objects.equals(artistId, that.artistId) &&
Objects.equals(venueId, that.venueId);
}
@Override
public int hashCode() {
return Objects.hash(
id,
eventDateTime,
ticketPrice,
feeModel,
feeAmount,
artistUserId,
venueUserId,
isConfirmedByArtist,
isConfirmedByVenue,
isRejected,
ticketsSold,
ticketId,
artistId,
venueId
);
}
@Override
public String toString() {
return "EventCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(eventDateTime != null ? "eventDateTime=" + eventDateTime + ", " : "") +
(ticketPrice != null ? "ticketPrice=" + ticketPrice + ", " : "") +
(feeModel != null ? "feeModel=" + feeModel + ", " : "") +
(feeAmount != null ? "feeAmount=" + feeAmount + ", " : "") +
(artistUserId != null ? "artistUserId=" + artistUserId + ", " : "") +
(venueUserId != null ? "venueUserId=" + venueUserId + ", " : "") +
(isConfirmedByArtist != null ? "isConfirmedByArtist=" + isConfirmedByArtist + ", " : "") +
(isConfirmedByVenue != null ? "isConfirmedByVenue=" + isConfirmedByVenue + ", " : "") +
(isRejected != null ? "isRejected=" + isRejected + ", " : "") +
(ticketsSold != null ? "ticketsSold=" + ticketsSold + ", " : "") +
(ticketId != null ? "ticketId=" + ticketId + ", " : "") +
(artistId != null ? "artistId=" + artistId + ", " : "") +
(venueId != null ? "venueId=" + venueId + ", " : "") +
"}";
}
}

View File

@@ -0,0 +1,120 @@
package edu.uoc.evental.service.dto;
import java.io.Serializable;
import java.util.Objects;
import io.github.jhipster.service.Criteria;
import io.github.jhipster.service.filter.BooleanFilter;
import io.github.jhipster.service.filter.DoubleFilter;
import io.github.jhipster.service.filter.Filter;
import io.github.jhipster.service.filter.FloatFilter;
import io.github.jhipster.service.filter.IntegerFilter;
import io.github.jhipster.service.filter.LongFilter;
import io.github.jhipster.service.filter.StringFilter;
import io.github.jhipster.service.filter.LocalDateFilter;
/**
* Criteria class for the {@link edu.uoc.evental.domain.FiscalData} entity. This class is used
* in {@link edu.uoc.evental.web.rest.FiscalDataResource} to receive all the possible filtering options from
* the Http GET request parameters.
* For example the following could be a valid request:
* {@code /fiscal-data?id.greaterThan=5&attr1.contains=something&attr2.specified=false}
* As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use
* fix type specific filters.
*/
public class FiscalDataCriteria implements Serializable, Criteria {
private static final long serialVersionUID = 1L;
private LongFilter id;
private StringFilter nif;
private LocalDateFilter birthDate;
private LongFilter userId;
public FiscalDataCriteria() {
}
public FiscalDataCriteria(FiscalDataCriteria other) {
this.id = other.id == null ? null : other.id.copy();
this.nif = other.nif == null ? null : other.nif.copy();
this.birthDate = other.birthDate == null ? null : other.birthDate.copy();
this.userId = other.userId == null ? null : other.userId.copy();
}
@Override
public FiscalDataCriteria copy() {
return new FiscalDataCriteria(this);
}
public LongFilter getId() {
return id;
}
public void setId(LongFilter id) {
this.id = id;
}
public StringFilter getNif() {
return nif;
}
public void setNif(StringFilter nif) {
this.nif = nif;
}
public LocalDateFilter getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDateFilter birthDate) {
this.birthDate = birthDate;
}
public LongFilter getUserId() {
return userId;
}
public void setUserId(LongFilter userId) {
this.userId = userId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final FiscalDataCriteria that = (FiscalDataCriteria) o;
return
Objects.equals(id, that.id) &&
Objects.equals(nif, that.nif) &&
Objects.equals(birthDate, that.birthDate) &&
Objects.equals(userId, that.userId);
}
@Override
public int hashCode() {
return Objects.hash(
id,
nif,
birthDate,
userId
);
}
@Override
public String toString() {
return "FiscalDataCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(nif != null ? "nif=" + nif + ", " : "") +
(birthDate != null ? "birthDate=" + birthDate + ", " : "") +
(userId != null ? "userId=" + userId + ", " : "") +
"}";
}
}

View File

@@ -0,0 +1,35 @@
package edu.uoc.evental.service.dto;
/**
* A DTO representing a password change required data - current and new password.
*/
public class PasswordChangeDTO {
private String currentPassword;
private String newPassword;
public PasswordChangeDTO() {
// Empty constructor needed for Jackson.
}
public PasswordChangeDTO(String currentPassword, String newPassword) {
this.currentPassword = currentPassword;
this.newPassword = newPassword;
}
public String getCurrentPassword() {
return currentPassword;
}
public void setCurrentPassword(String currentPassword) {
this.currentPassword = currentPassword;
}
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
}

View File

@@ -0,0 +1,105 @@
package edu.uoc.evental.service.dto;
import java.io.Serializable;
import java.util.Objects;
import io.github.jhipster.service.Criteria;
import io.github.jhipster.service.filter.BooleanFilter;
import io.github.jhipster.service.filter.DoubleFilter;
import io.github.jhipster.service.filter.Filter;
import io.github.jhipster.service.filter.FloatFilter;
import io.github.jhipster.service.filter.IntegerFilter;
import io.github.jhipster.service.filter.LongFilter;
import io.github.jhipster.service.filter.StringFilter;
/**
* Criteria class for the {@link edu.uoc.evental.domain.Ticket} entity. This class is used
* in {@link edu.uoc.evental.web.rest.TicketResource} to receive all the possible filtering options from
* the Http GET request parameters.
* For example the following could be a valid request:
* {@code /tickets?id.greaterThan=5&attr1.contains=something&attr2.specified=false}
* As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use
* fix type specific filters.
*/
public class TicketCriteria implements Serializable, Criteria {
private static final long serialVersionUID = 1L;
private LongFilter id;
private LongFilter fiscalDataId;
private LongFilter eventId;
public TicketCriteria() {
}
public TicketCriteria(TicketCriteria other) {
this.id = other.id == null ? null : other.id.copy();
this.fiscalDataId = other.fiscalDataId == null ? null : other.fiscalDataId.copy();
this.eventId = other.eventId == null ? null : other.eventId.copy();
}
@Override
public TicketCriteria copy() {
return new TicketCriteria(this);
}
public LongFilter getId() {
return id;
}
public void setId(LongFilter id) {
this.id = id;
}
public LongFilter getFiscalDataId() {
return fiscalDataId;
}
public void setFiscalDataId(LongFilter fiscalDataId) {
this.fiscalDataId = fiscalDataId;
}
public LongFilter getEventId() {
return eventId;
}
public void setEventId(LongFilter eventId) {
this.eventId = eventId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final TicketCriteria that = (TicketCriteria) o;
return
Objects.equals(id, that.id) &&
Objects.equals(fiscalDataId, that.fiscalDataId) &&
Objects.equals(eventId, that.eventId);
}
@Override
public int hashCode() {
return Objects.hash(
id,
fiscalDataId,
eventId
);
}
@Override
public String toString() {
return "TicketCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(fiscalDataId != null ? "fiscalDataId=" + fiscalDataId + ", " : "") +
(eventId != null ? "eventId=" + eventId + ", " : "") +
"}";
}
}

View File

@@ -0,0 +1,196 @@
package edu.uoc.evental.service.dto;
import edu.uoc.evental.config.Constants;
import edu.uoc.evental.domain.Authority;
import edu.uoc.evental.domain.User;
import javax.validation.constraints.*;
import java.time.Instant;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A DTO representing a user, with his authorities.
*/
public class UserDTO {
private Long id;
@NotBlank
@Pattern(regexp = Constants.LOGIN_REGEX)
@Size(min = 1, max = 50)
private String login;
@Size(max = 50)
private String firstName;
@Size(max = 50)
private String lastName;
@Email
@Size(min = 5, max = 254)
private String email;
@Size(max = 256)
private String imageUrl;
private boolean activated = false;
@Size(min = 2, max = 10)
private String langKey;
private String createdBy;
private Instant createdDate;
private String lastModifiedBy;
private Instant lastModifiedDate;
private Set<String> authorities;
public UserDTO() {
// Empty constructor needed for Jackson.
}
public UserDTO(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.email = user.getEmail();
this.activated = user.getActivated();
this.imageUrl = user.getImageUrl();
this.langKey = user.getLangKey();
this.createdBy = user.getCreatedBy();
this.createdDate = user.getCreatedDate();
this.lastModifiedBy = user.getLastModifiedBy();
this.lastModifiedDate = user.getLastModifiedDate();
this.authorities = user.getAuthorities().stream()
.map(Authority::getName)
.collect(Collectors.toSet());
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public boolean isActivated() {
return activated;
}
public void setActivated(boolean activated) {
this.activated = activated;
}
public String getLangKey() {
return langKey;
}
public void setLangKey(String langKey) {
this.langKey = langKey;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Instant getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public Set<String> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<String> authorities) {
this.authorities = authorities;
}
@Override
public String toString() {
return "UserDTO{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated=" + activated +
", langKey='" + langKey + '\'' +
", createdBy=" + createdBy +
", createdDate=" + createdDate +
", lastModifiedBy='" + lastModifiedBy + '\'' +
", lastModifiedDate=" + lastModifiedDate +
", authorities=" + authorities +
"}";
}
}

View File

@@ -0,0 +1,152 @@
package edu.uoc.evental.service.dto;
import java.io.Serializable;
import java.util.Objects;
import io.github.jhipster.service.Criteria;
import edu.uoc.evental.domain.enumeration.Location;
import io.github.jhipster.service.filter.BooleanFilter;
import io.github.jhipster.service.filter.DoubleFilter;
import io.github.jhipster.service.filter.Filter;
import io.github.jhipster.service.filter.FloatFilter;
import io.github.jhipster.service.filter.IntegerFilter;
import io.github.jhipster.service.filter.LongFilter;
import io.github.jhipster.service.filter.StringFilter;
/**
* Criteria class for the {@link edu.uoc.evental.domain.Venue} entity. This class is used
* in {@link edu.uoc.evental.web.rest.VenueResource} to receive all the possible filtering options from
* the Http GET request parameters.
* For example the following could be a valid request:
* {@code /venues?id.greaterThan=5&attr1.contains=something&attr2.specified=false}
* As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use
* fix type specific filters.
*/
public class VenueCriteria implements Serializable, Criteria {
/**
* Class for filtering Location
*/
public static class LocationFilter extends Filter<Location> {
public LocationFilter() {
}
public LocationFilter(LocationFilter filter) {
super(filter);
}
@Override
public LocationFilter copy() {
return new LocationFilter(this);
}
}
private static final long serialVersionUID = 1L;
private LongFilter id;
private StringFilter venueName;
private LocationFilter location;
private IntegerFilter capacity;
private LongFilter userId;
public VenueCriteria() {
}
public VenueCriteria(VenueCriteria other) {
this.id = other.id == null ? null : other.id.copy();
this.venueName = other.venueName == null ? null : other.venueName.copy();
this.location = other.location == null ? null : other.location.copy();
this.capacity = other.capacity == null ? null : other.capacity.copy();
this.userId = other.userId == null ? null : other.userId.copy();
}
@Override
public VenueCriteria copy() {
return new VenueCriteria(this);
}
public LongFilter getId() {
return id;
}
public void setId(LongFilter id) {
this.id = id;
}
public StringFilter getVenueName() {
return venueName;
}
public void setVenueName(StringFilter venueName) {
this.venueName = venueName;
}
public LocationFilter getLocation() {
return location;
}
public void setLocation(LocationFilter location) {
this.location = location;
}
public IntegerFilter getCapacity() {
return capacity;
}
public void setCapacity(IntegerFilter capacity) {
this.capacity = capacity;
}
public LongFilter getUserId() {
return userId;
}
public void setUserId(LongFilter userId) {
this.userId = userId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final VenueCriteria that = (VenueCriteria) o;
return
Objects.equals(id, that.id) &&
Objects.equals(venueName, that.venueName) &&
Objects.equals(location, that.location) &&
Objects.equals(capacity, that.capacity) &&
Objects.equals(userId, that.userId);
}
@Override
public int hashCode() {
return Objects.hash(
id,
venueName,
location,
capacity,
userId
);
}
@Override
public String toString() {
return "VenueCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(venueName != null ? "venueName=" + venueName + ", " : "") +
(location != null ? "location=" + location + ", " : "") +
(capacity != null ? "capacity=" + capacity + ", " : "") +
(userId != null ? "userId=" + userId + ", " : "") +
"}";
}
}

View File

@@ -0,0 +1,4 @@
/**
* Data Transfer Objects.
*/
package edu.uoc.evental.service.dto;

View File

@@ -0,0 +1,79 @@
package edu.uoc.evental.service.impl;
import edu.uoc.evental.service.ArtistService;
import edu.uoc.evental.domain.Artist;
import edu.uoc.evental.repository.ArtistRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* Service Implementation for managing {@link Artist}.
*/
@Service
@Transactional
public class ArtistServiceImpl implements ArtistService {
private final Logger log = LoggerFactory.getLogger(ArtistServiceImpl.class);
private final ArtistRepository artistRepository;
public ArtistServiceImpl(ArtistRepository artistRepository) {
this.artistRepository = artistRepository;
}
/**
* Save a artist.
*
* @param artist the entity to save.
* @return the persisted entity.
*/
@Override
public Artist save(Artist artist) {
log.debug("Request to save Artist : {}", artist);
return artistRepository.save(artist);
}
/**
* Get all the artists.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
@Override
@Transactional(readOnly = true)
public Page<Artist> findAll(Pageable pageable) {
log.debug("Request to get all Artists");
return artistRepository.findAll(pageable);
}
/**
* Get one artist by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Override
@Transactional(readOnly = true)
public Optional<Artist> findOne(Long id) {
log.debug("Request to get Artist : {}", id);
return artistRepository.findById(id);
}
/**
* Delete the artist by id.
*
* @param id the id of the entity.
*/
@Override
public void delete(Long id) {
log.debug("Request to delete Artist : {}", id);
artistRepository.deleteById(id);
}
}

View File

@@ -0,0 +1,79 @@
package edu.uoc.evental.service.impl;
import edu.uoc.evental.service.EventService;
import edu.uoc.evental.domain.Event;
import edu.uoc.evental.repository.EventRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* Service Implementation for managing {@link Event}.
*/
@Service
@Transactional
public class EventServiceImpl implements EventService {
private final Logger log = LoggerFactory.getLogger(EventServiceImpl.class);
private final EventRepository eventRepository;
public EventServiceImpl(EventRepository eventRepository) {
this.eventRepository = eventRepository;
}
/**
* Save a event.
*
* @param event the entity to save.
* @return the persisted entity.
*/
@Override
public Event save(Event event) {
log.debug("Request to save Event : {}", event);
return eventRepository.save(event);
}
/**
* Get all the events.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
@Override
@Transactional(readOnly = true)
public Page<Event> findAll(Pageable pageable) {
log.debug("Request to get all Events");
return eventRepository.findAll(pageable);
}
/**
* Get one event by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Override
@Transactional(readOnly = true)
public Optional<Event> findOne(Long id) {
log.debug("Request to get Event : {}", id);
return eventRepository.findById(id);
}
/**
* Delete the event by id.
*
* @param id the id of the entity.
*/
@Override
public void delete(Long id) {
log.debug("Request to delete Event : {}", id);
eventRepository.deleteById(id);
}
}

View File

@@ -0,0 +1,77 @@
package edu.uoc.evental.service.impl;
import edu.uoc.evental.service.FiscalDataService;
import edu.uoc.evental.domain.FiscalData;
import edu.uoc.evental.repository.FiscalDataRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
/**
* Service Implementation for managing {@link FiscalData}.
*/
@Service
@Transactional
public class FiscalDataServiceImpl implements FiscalDataService {
private final Logger log = LoggerFactory.getLogger(FiscalDataServiceImpl.class);
private final FiscalDataRepository fiscalDataRepository;
public FiscalDataServiceImpl(FiscalDataRepository fiscalDataRepository) {
this.fiscalDataRepository = fiscalDataRepository;
}
/**
* Save a fiscalData.
*
* @param fiscalData the entity to save.
* @return the persisted entity.
*/
@Override
public FiscalData save(FiscalData fiscalData) {
log.debug("Request to save FiscalData : {}", fiscalData);
return fiscalDataRepository.save(fiscalData);
}
/**
* Get all the fiscalData.
*
* @return the list of entities.
*/
@Override
@Transactional(readOnly = true)
public List<FiscalData> findAll() {
log.debug("Request to get all FiscalData");
return fiscalDataRepository.findAll();
}
/**
* Get one fiscalData by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Override
@Transactional(readOnly = true)
public Optional<FiscalData> findOne(Long id) {
log.debug("Request to get FiscalData : {}", id);
return fiscalDataRepository.findById(id);
}
/**
* Delete the fiscalData by id.
*
* @param id the id of the entity.
*/
@Override
public void delete(Long id) {
log.debug("Request to delete FiscalData : {}", id);
fiscalDataRepository.deleteById(id);
}
}

View File

@@ -0,0 +1,79 @@
package edu.uoc.evental.service.impl;
import edu.uoc.evental.service.TicketService;
import edu.uoc.evental.domain.Ticket;
import edu.uoc.evental.repository.TicketRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* Service Implementation for managing {@link Ticket}.
*/
@Service
@Transactional
public class TicketServiceImpl implements TicketService {
private final Logger log = LoggerFactory.getLogger(TicketServiceImpl.class);
private final TicketRepository ticketRepository;
public TicketServiceImpl(TicketRepository ticketRepository) {
this.ticketRepository = ticketRepository;
}
/**
* Save a ticket.
*
* @param ticket the entity to save.
* @return the persisted entity.
*/
@Override
public Ticket save(Ticket ticket) {
log.debug("Request to save Ticket : {}", ticket);
return ticketRepository.save(ticket);
}
/**
* Get all the tickets.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
@Override
@Transactional(readOnly = true)
public Page<Ticket> findAll(Pageable pageable) {
log.debug("Request to get all Tickets");
return ticketRepository.findAll(pageable);
}
/**
* Get one ticket by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Override
@Transactional(readOnly = true)
public Optional<Ticket> findOne(Long id) {
log.debug("Request to get Ticket : {}", id);
return ticketRepository.findById(id);
}
/**
* Delete the ticket by id.
*
* @param id the id of the entity.
*/
@Override
public void delete(Long id) {
log.debug("Request to delete Ticket : {}", id);
ticketRepository.deleteById(id);
}
}

View File

@@ -0,0 +1,79 @@
package edu.uoc.evental.service.impl;
import edu.uoc.evental.service.VenueService;
import edu.uoc.evental.domain.Venue;
import edu.uoc.evental.repository.VenueRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
/**
* Service Implementation for managing {@link Venue}.
*/
@Service
@Transactional
public class VenueServiceImpl implements VenueService {
private final Logger log = LoggerFactory.getLogger(VenueServiceImpl.class);
private final VenueRepository venueRepository;
public VenueServiceImpl(VenueRepository venueRepository) {
this.venueRepository = venueRepository;
}
/**
* Save a venue.
*
* @param venue the entity to save.
* @return the persisted entity.
*/
@Override
public Venue save(Venue venue) {
log.debug("Request to save Venue : {}", venue);
return venueRepository.save(venue);
}
/**
* Get all the venues.
*
* @param pageable the pagination information.
* @return the list of entities.
*/
@Override
@Transactional(readOnly = true)
public Page<Venue> findAll(Pageable pageable) {
log.debug("Request to get all Venues");
return venueRepository.findAll(pageable);
}
/**
* Get one venue by id.
*
* @param id the id of the entity.
* @return the entity.
*/
@Override
@Transactional(readOnly = true)
public Optional<Venue> findOne(Long id) {
log.debug("Request to get Venue : {}", id);
return venueRepository.findById(id);
}
/**
* Delete the venue by id.
*
* @param id the id of the entity.
*/
@Override
public void delete(Long id) {
log.debug("Request to delete Venue : {}", id);
venueRepository.deleteById(id);
}
}

View File

@@ -0,0 +1,81 @@
package edu.uoc.evental.service.mapper;
import edu.uoc.evental.domain.Authority;
import edu.uoc.evental.domain.User;
import edu.uoc.evental.service.dto.UserDTO;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
/**
* Mapper for the entity {@link User} and its DTO called {@link UserDTO}.
*
* Normal mappers are generated using MapStruct, this one is hand-coded as MapStruct
* support is still in beta, and requires a manual step with an IDE.
*/
@Service
public class UserMapper {
public List<UserDTO> usersToUserDTOs(List<User> users) {
return users.stream()
.filter(Objects::nonNull)
.map(this::userToUserDTO)
.collect(Collectors.toList());
}
public UserDTO userToUserDTO(User user) {
return new UserDTO(user);
}
public List<User> userDTOsToUsers(List<UserDTO> userDTOs) {
return userDTOs.stream()
.filter(Objects::nonNull)
.map(this::userDTOToUser)
.collect(Collectors.toList());
}
public User userDTOToUser(UserDTO userDTO) {
if (userDTO == null) {
return null;
} else {
User user = new User();
user.setId(userDTO.getId());
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities());
user.setAuthorities(authorities);
return user;
}
}
private Set<Authority> authoritiesFromStrings(Set<String> authoritiesAsString) {
Set<Authority> authorities = new HashSet<>();
if (authoritiesAsString != null) {
authorities = authoritiesAsString.stream().map(string -> {
Authority auth = new Authority();
auth.setName(string);
return auth;
}).collect(Collectors.toSet());
}
return authorities;
}
public User userFromId(Long id) {
if (id == null) {
return null;
}
User user = new User();
user.setId(id);
return user;
}
}

View File

@@ -0,0 +1,4 @@
/**
* MapStruct mappers for mapping domain objects and Data Transfer Objects.
*/
package edu.uoc.evental.service.mapper;

View File

@@ -0,0 +1,4 @@
/**
* Service layer beans.
*/
package edu.uoc.evental.service;

View File

@@ -0,0 +1,187 @@
package edu.uoc.evental.web.rest;
import edu.uoc.evental.domain.User;
import edu.uoc.evental.repository.UserRepository;
import edu.uoc.evental.security.SecurityUtils;
import edu.uoc.evental.service.MailService;
import edu.uoc.evental.service.UserService;
import edu.uoc.evental.service.dto.PasswordChangeDTO;
import edu.uoc.evental.service.dto.UserDTO;
import edu.uoc.evental.web.rest.errors.*;
import edu.uoc.evental.web.rest.vm.KeyAndPasswordVM;
import edu.uoc.evental.web.rest.vm.ManagedUserVM;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;
/**
* REST controller for managing the current user's account.
*/
@RestController
@RequestMapping("/api")
public class AccountResource {
private static class AccountResourceException extends RuntimeException {
private AccountResourceException(String message) {
super(message);
}
}
private final Logger log = LoggerFactory.getLogger(AccountResource.class);
private final UserRepository userRepository;
private final UserService userService;
private final MailService mailService;
public AccountResource(UserRepository userRepository, UserService userService, MailService mailService) {
this.userRepository = userRepository;
this.userService = userService;
this.mailService = mailService;
}
/**
* {@code POST /register} : register the user.
*
* @param managedUserVM the managed user View Model.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect.
* @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used.
* @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already used.
*/
@PostMapping("/register")
@ResponseStatus(HttpStatus.CREATED)
public void registerAccount(@Valid @RequestBody ManagedUserVM managedUserVM) {
if (!checkPasswordLength(managedUserVM.getPassword())) {
throw new InvalidPasswordException();
}
User user = userService.registerUser(managedUserVM, managedUserVM.getPassword());
mailService.sendActivationEmail(user);
}
/**
* {@code GET /activate} : activate the registered user.
*
* @param key the activation key.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be activated.
*/
@GetMapping("/activate")
public void activateAccount(@RequestParam(value = "key") String key) {
Optional<User> user = userService.activateRegistration(key);
if (!user.isPresent()) {
throw new AccountResourceException("No user was found for this activation key");
}
}
/**
* {@code GET /authenticate} : check if the user is authenticated, and return its login.
*
* @param request the HTTP request.
* @return the login if the user is authenticated.
*/
@GetMapping("/authenticate")
public String isAuthenticated(HttpServletRequest request) {
log.debug("REST request to check if the current user is authenticated");
return request.getRemoteUser();
}
/**
* {@code GET /account} : get the current user.
*
* @return the current user.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user couldn't be returned.
*/
@GetMapping("/account")
public UserDTO getAccount() {
return userService.getUserWithAuthorities()
.map(UserDTO::new)
.orElseThrow(() -> new AccountResourceException("User could not be found"));
}
/**
* {@code POST /account} : update the current user information.
*
* @param userDTO the current user information.
* @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already used.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the user login wasn't found.
*/
@PostMapping("/account")
public void saveAccount(@Valid @RequestBody UserDTO userDTO) {
String userLogin = SecurityUtils.getCurrentUserLogin().orElseThrow(() -> new AccountResourceException("Current user login not found"));
Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail());
if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) {
throw new EmailAlreadyUsedException();
}
Optional<User> user = userRepository.findOneByLogin(userLogin);
if (!user.isPresent()) {
throw new AccountResourceException("User could not be found");
}
userService.updateUser(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(),
userDTO.getLangKey(), userDTO.getImageUrl());
}
/**
* {@code POST /account/change-password} : changes the current user's password.
*
* @param passwordChangeDto current and new password.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the new password is incorrect.
*/
@PostMapping(path = "/account/change-password")
public void changePassword(@RequestBody PasswordChangeDTO passwordChangeDto) {
if (!checkPasswordLength(passwordChangeDto.getNewPassword())) {
throw new InvalidPasswordException();
}
userService.changePassword(passwordChangeDto.getCurrentPassword(), passwordChangeDto.getNewPassword());
}
/**
* {@code POST /account/reset-password/init} : Send an email to reset the password of the user.
*
* @param mail the mail of the user.
*/
@PostMapping(path = "/account/reset-password/init")
public void requestPasswordReset(@RequestBody String mail) {
Optional<User> user = userService.requestPasswordReset(mail);
if (user.isPresent()) {
mailService.sendPasswordResetMail(user.get());
} else {
// Pretend the request has been successful to prevent checking which emails really exist
// but log that an invalid attempt has been made
log.warn("Password reset requested for non existing mail '{}'", mail);
}
}
/**
* {@code POST /account/reset-password/finish} : Finish to reset the password of the user.
*
* @param keyAndPassword the generated key and the new password.
* @throws InvalidPasswordException {@code 400 (Bad Request)} if the password is incorrect.
* @throws RuntimeException {@code 500 (Internal Server Error)} if the password could not be reset.
*/
@PostMapping(path = "/account/reset-password/finish")
public void finishPasswordReset(@RequestBody KeyAndPasswordVM keyAndPassword) {
if (!checkPasswordLength(keyAndPassword.getNewPassword())) {
throw new InvalidPasswordException();
}
Optional<User> user =
userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey());
if (!user.isPresent()) {
throw new AccountResourceException("No user was found for this reset key");
}
}
private static boolean checkPasswordLength(String password) {
return !StringUtils.isEmpty(password) &&
password.length() >= ManagedUserVM.PASSWORD_MIN_LENGTH &&
password.length() <= ManagedUserVM.PASSWORD_MAX_LENGTH;
}
}

View File

@@ -0,0 +1,144 @@
package edu.uoc.evental.web.rest;
import edu.uoc.evental.domain.Artist;
import edu.uoc.evental.service.ArtistService;
import edu.uoc.evental.web.rest.errors.BadRequestAlertException;
import edu.uoc.evental.service.dto.ArtistCriteria;
import edu.uoc.evental.service.ArtistQueryService;
import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing {@link edu.uoc.evental.domain.Artist}.
*/
@RestController
@RequestMapping("/api")
public class ArtistResource {
private final Logger log = LoggerFactory.getLogger(ArtistResource.class);
private static final String ENTITY_NAME = "artist";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final ArtistService artistService;
private final ArtistQueryService artistQueryService;
public ArtistResource(ArtistService artistService, ArtistQueryService artistQueryService) {
this.artistService = artistService;
this.artistQueryService = artistQueryService;
}
/**
* {@code POST /artists} : Create a new artist.
*
* @param artist the artist to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new artist, or with status {@code 400 (Bad Request)} if the artist has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/artists")
public ResponseEntity<Artist> createArtist(@Valid @RequestBody Artist artist) throws URISyntaxException {
log.debug("REST request to save Artist : {}", artist);
if (artist.getId() != null) {
throw new BadRequestAlertException("A new artist cannot already have an ID", ENTITY_NAME, "idexists");
}
Artist result = artistService.save(artist);
return ResponseEntity.created(new URI("/api/artists/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* {@code PUT /artists} : Updates an existing artist.
*
* @param artist the artist to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated artist,
* or with status {@code 400 (Bad Request)} if the artist is not valid,
* or with status {@code 500 (Internal Server Error)} if the artist couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/artists")
public ResponseEntity<Artist> updateArtist(@Valid @RequestBody Artist artist) throws URISyntaxException {
log.debug("REST request to update Artist : {}", artist);
if (artist.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
Artist result = artistService.save(artist);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, artist.getId().toString()))
.body(result);
}
/**
* {@code GET /artists} : get all the artists.
*
* @param pageable the pagination information.
* @param criteria the criteria which the requested entities should match.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of artists in body.
*/
@GetMapping("/artists")
public ResponseEntity<List<Artist>> getAllArtists(ArtistCriteria criteria, Pageable pageable) {
log.debug("REST request to get Artists by criteria: {}", criteria);
Page<Artist> page = artistQueryService.findByCriteria(criteria, pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
* {@code GET /artists/count} : count all the artists.
*
* @param criteria the criteria which the requested entities should match.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body.
*/
@GetMapping("/artists/count")
public ResponseEntity<Long> countArtists(ArtistCriteria criteria) {
log.debug("REST request to count Artists by criteria: {}", criteria);
return ResponseEntity.ok().body(artistQueryService.countByCriteria(criteria));
}
/**
* {@code GET /artists/:id} : get the "id" artist.
*
* @param id the id of the artist to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the artist, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/artists/{id}")
public ResponseEntity<Artist> getArtist(@PathVariable Long id) {
log.debug("REST request to get Artist : {}", id);
Optional<Artist> artist = artistService.findOne(id);
return ResponseUtil.wrapOrNotFound(artist);
}
/**
* {@code DELETE /artists/:id} : delete the "id" artist.
*
* @param id the id of the artist to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/artists/{id}")
public ResponseEntity<Void> deleteArtist(@PathVariable Long id) {
log.debug("REST request to delete Artist : {}", id);
artistService.delete(id);
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build();
}
}

View File

@@ -0,0 +1,79 @@
package edu.uoc.evental.web.rest;
import edu.uoc.evental.service.AuditEventService;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.springframework.boot.actuate.audit.AuditEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.List;
/**
* REST controller for getting the {@link AuditEvent}s.
*/
@RestController
@RequestMapping("/management/audits")
public class AuditResource {
private final AuditEventService auditEventService;
public AuditResource(AuditEventService auditEventService) {
this.auditEventService = auditEventService;
}
/**
* {@code GET /audits} : get a page of {@link AuditEvent}s.
*
* @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent}s in body.
*/
@GetMapping
public ResponseEntity<List<AuditEvent>> getAll(Pageable pageable) {
Page<AuditEvent> page = auditEventService.findAll(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* {@code GET /audits} : get a page of {@link AuditEvent} between the {@code fromDate} and {@code toDate}.
*
* @param fromDate the start of the time period of {@link AuditEvent} to get.
* @param toDate the end of the time period of {@link AuditEvent} to get.
* @param pageable the pagination information.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent} in body.
*/
@GetMapping(params = {"fromDate", "toDate"})
public ResponseEntity<List<AuditEvent>> getByDates(
@RequestParam(value = "fromDate") LocalDate fromDate,
@RequestParam(value = "toDate") LocalDate toDate,
Pageable pageable) {
Instant from = fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
Instant to = toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant();
Page<AuditEvent> page = auditEventService.findByDates(from, to, pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
/**
* {@code GET /audits/:id} : get an {@link AuditEvent} by id.
*
* @param id the id of the entity to get.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the {@link AuditEvent} in body, or status {@code 404 (Not Found)}.
*/
@GetMapping("/{id:.+}")
public ResponseEntity<AuditEvent> get(@PathVariable Long id) {
return ResponseUtil.wrapOrNotFound(auditEventService.find(id));
}
}

View File

@@ -0,0 +1,17 @@
package edu.uoc.evental.web.rest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ClientForwardController {
/**
* Forwards any unmapped paths (except those containing a period) to the client {@code index.html}.
* @return forward to client {@code index.html}.
*/
@GetMapping(value = "/**/{path:[^\\.]*}")
public String forward() {
return "forward:/";
}
}

View File

@@ -0,0 +1,144 @@
package edu.uoc.evental.web.rest;
import edu.uoc.evental.domain.Event;
import edu.uoc.evental.service.EventService;
import edu.uoc.evental.web.rest.errors.BadRequestAlertException;
import edu.uoc.evental.service.dto.EventCriteria;
import edu.uoc.evental.service.EventQueryService;
import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing {@link edu.uoc.evental.domain.Event}.
*/
@RestController
@RequestMapping("/api")
public class EventResource {
private final Logger log = LoggerFactory.getLogger(EventResource.class);
private static final String ENTITY_NAME = "event";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final EventService eventService;
private final EventQueryService eventQueryService;
public EventResource(EventService eventService, EventQueryService eventQueryService) {
this.eventService = eventService;
this.eventQueryService = eventQueryService;
}
/**
* {@code POST /events} : Create a new event.
*
* @param event the event to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new event, or with status {@code 400 (Bad Request)} if the event has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/events")
public ResponseEntity<Event> createEvent(@Valid @RequestBody Event event) throws URISyntaxException {
log.debug("REST request to save Event : {}", event);
if (event.getId() != null) {
throw new BadRequestAlertException("A new event cannot already have an ID", ENTITY_NAME, "idexists");
}
Event result = eventService.save(event);
return ResponseEntity.created(new URI("/api/events/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* {@code PUT /events} : Updates an existing event.
*
* @param event the event to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated event,
* or with status {@code 400 (Bad Request)} if the event is not valid,
* or with status {@code 500 (Internal Server Error)} if the event couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/events")
public ResponseEntity<Event> updateEvent(@Valid @RequestBody Event event) throws URISyntaxException {
log.debug("REST request to update Event : {}", event);
if (event.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
Event result = eventService.save(event);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, event.getId().toString()))
.body(result);
}
/**
* {@code GET /events} : get all the events.
*
* @param pageable the pagination information.
* @param criteria the criteria which the requested entities should match.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of events in body.
*/
@GetMapping("/events")
public ResponseEntity<List<Event>> getAllEvents(EventCriteria criteria, Pageable pageable) {
log.debug("REST request to get Events by criteria: {}", criteria);
Page<Event> page = eventQueryService.findByCriteria(criteria, pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
* {@code GET /events/count} : count all the events.
*
* @param criteria the criteria which the requested entities should match.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body.
*/
@GetMapping("/events/count")
public ResponseEntity<Long> countEvents(EventCriteria criteria) {
log.debug("REST request to count Events by criteria: {}", criteria);
return ResponseEntity.ok().body(eventQueryService.countByCriteria(criteria));
}
/**
* {@code GET /events/:id} : get the "id" event.
*
* @param id the id of the event to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the event, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/events/{id}")
public ResponseEntity<Event> getEvent(@PathVariable Long id) {
log.debug("REST request to get Event : {}", id);
Optional<Event> event = eventService.findOne(id);
return ResponseUtil.wrapOrNotFound(event);
}
/**
* {@code DELETE /events/:id} : delete the "id" event.
*
* @param id the id of the event to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/events/{id}")
public ResponseEntity<Void> deleteEvent(@PathVariable Long id) {
log.debug("REST request to delete Event : {}", id);
eventService.delete(id);
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build();
}
}

View File

@@ -0,0 +1,136 @@
package edu.uoc.evental.web.rest;
import edu.uoc.evental.domain.FiscalData;
import edu.uoc.evental.service.FiscalDataService;
import edu.uoc.evental.web.rest.errors.BadRequestAlertException;
import edu.uoc.evental.service.dto.FiscalDataCriteria;
import edu.uoc.evental.service.FiscalDataQueryService;
import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing {@link edu.uoc.evental.domain.FiscalData}.
*/
@RestController
@RequestMapping("/api")
public class FiscalDataResource {
private final Logger log = LoggerFactory.getLogger(FiscalDataResource.class);
private static final String ENTITY_NAME = "fiscalData";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final FiscalDataService fiscalDataService;
private final FiscalDataQueryService fiscalDataQueryService;
public FiscalDataResource(FiscalDataService fiscalDataService, FiscalDataQueryService fiscalDataQueryService) {
this.fiscalDataService = fiscalDataService;
this.fiscalDataQueryService = fiscalDataQueryService;
}
/**
* {@code POST /fiscal-data} : Create a new fiscalData.
*
* @param fiscalData the fiscalData to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new fiscalData, or with status {@code 400 (Bad Request)} if the fiscalData has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/fiscal-data")
public ResponseEntity<FiscalData> createFiscalData(@Valid @RequestBody FiscalData fiscalData) throws URISyntaxException {
log.debug("REST request to save FiscalData : {}", fiscalData);
if (fiscalData.getId() != null) {
throw new BadRequestAlertException("A new fiscalData cannot already have an ID", ENTITY_NAME, "idexists");
}
FiscalData result = fiscalDataService.save(fiscalData);
return ResponseEntity.created(new URI("/api/fiscal-data/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* {@code PUT /fiscal-data} : Updates an existing fiscalData.
*
* @param fiscalData the fiscalData to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated fiscalData,
* or with status {@code 400 (Bad Request)} if the fiscalData is not valid,
* or with status {@code 500 (Internal Server Error)} if the fiscalData couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/fiscal-data")
public ResponseEntity<FiscalData> updateFiscalData(@Valid @RequestBody FiscalData fiscalData) throws URISyntaxException {
log.debug("REST request to update FiscalData : {}", fiscalData);
if (fiscalData.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
FiscalData result = fiscalDataService.save(fiscalData);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, fiscalData.getId().toString()))
.body(result);
}
/**
* {@code GET /fiscal-data} : get all the fiscalData.
*
* @param criteria the criteria which the requested entities should match.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of fiscalData in body.
*/
@GetMapping("/fiscal-data")
public ResponseEntity<List<FiscalData>> getAllFiscalData(FiscalDataCriteria criteria) {
log.debug("REST request to get FiscalData by criteria: {}", criteria);
List<FiscalData> entityList = fiscalDataQueryService.findByCriteria(criteria);
return ResponseEntity.ok().body(entityList);
}
/**
* {@code GET /fiscal-data/count} : count all the fiscalData.
*
* @param criteria the criteria which the requested entities should match.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body.
*/
@GetMapping("/fiscal-data/count")
public ResponseEntity<Long> countFiscalData(FiscalDataCriteria criteria) {
log.debug("REST request to count FiscalData by criteria: {}", criteria);
return ResponseEntity.ok().body(fiscalDataQueryService.countByCriteria(criteria));
}
/**
* {@code GET /fiscal-data/:id} : get the "id" fiscalData.
*
* @param id the id of the fiscalData to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the fiscalData, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/fiscal-data/{id}")
public ResponseEntity<FiscalData> getFiscalData(@PathVariable Long id) {
log.debug("REST request to get FiscalData : {}", id);
Optional<FiscalData> fiscalData = fiscalDataService.findOne(id);
return ResponseUtil.wrapOrNotFound(fiscalData);
}
/**
* {@code DELETE /fiscal-data/:id} : delete the "id" fiscalData.
*
* @param id the id of the fiscalData to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/fiscal-data/{id}")
public ResponseEntity<Void> deleteFiscalData(@PathVariable Long id) {
log.debug("REST request to delete FiscalData : {}", id);
fiscalDataService.delete(id);
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build();
}
}

View File

@@ -0,0 +1,143 @@
package edu.uoc.evental.web.rest;
import edu.uoc.evental.domain.Ticket;
import edu.uoc.evental.service.TicketService;
import edu.uoc.evental.web.rest.errors.BadRequestAlertException;
import edu.uoc.evental.service.dto.TicketCriteria;
import edu.uoc.evental.service.TicketQueryService;
import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
/**
* REST controller for managing {@link edu.uoc.evental.domain.Ticket}.
*/
@RestController
@RequestMapping("/api")
public class TicketResource {
private final Logger log = LoggerFactory.getLogger(TicketResource.class);
private static final String ENTITY_NAME = "ticket";
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final TicketService ticketService;
private final TicketQueryService ticketQueryService;
public TicketResource(TicketService ticketService, TicketQueryService ticketQueryService) {
this.ticketService = ticketService;
this.ticketQueryService = ticketQueryService;
}
/**
* {@code POST /tickets} : Create a new ticket.
*
* @param ticket the ticket to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new ticket, or with status {@code 400 (Bad Request)} if the ticket has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/tickets")
public ResponseEntity<Ticket> createTicket(@RequestBody Ticket ticket) throws URISyntaxException {
log.debug("REST request to save Ticket : {}", ticket);
if (ticket.getId() != null) {
throw new BadRequestAlertException("A new ticket cannot already have an ID", ENTITY_NAME, "idexists");
}
Ticket result = ticketService.save(ticket);
return ResponseEntity.created(new URI("/api/tickets/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, false, ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* {@code PUT /tickets} : Updates an existing ticket.
*
* @param ticket the ticket to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated ticket,
* or with status {@code 400 (Bad Request)} if the ticket is not valid,
* or with status {@code 500 (Internal Server Error)} if the ticket couldn't be updated.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PutMapping("/tickets")
public ResponseEntity<Ticket> updateTicket(@RequestBody Ticket ticket) throws URISyntaxException {
log.debug("REST request to update Ticket : {}", ticket);
if (ticket.getId() == null) {
throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
}
Ticket result = ticketService.save(ticket);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(applicationName, false, ENTITY_NAME, ticket.getId().toString()))
.body(result);
}
/**
* {@code GET /tickets} : get all the tickets.
*
* @param pageable the pagination information.
* @param criteria the criteria which the requested entities should match.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of tickets in body.
*/
@GetMapping("/tickets")
public ResponseEntity<List<Ticket>> getAllTickets(TicketCriteria criteria, Pageable pageable) {
log.debug("REST request to get Tickets by criteria: {}", criteria);
Page<Ticket> page = ticketQueryService.findByCriteria(criteria, pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
/**
* {@code GET /tickets/count} : count all the tickets.
*
* @param criteria the criteria which the requested entities should match.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and the count in body.
*/
@GetMapping("/tickets/count")
public ResponseEntity<Long> countTickets(TicketCriteria criteria) {
log.debug("REST request to count Tickets by criteria: {}", criteria);
return ResponseEntity.ok().body(ticketQueryService.countByCriteria(criteria));
}
/**
* {@code GET /tickets/:id} : get the "id" ticket.
*
* @param id the id of the ticket to retrieve.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the ticket, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/tickets/{id}")
public ResponseEntity<Ticket> getTicket(@PathVariable Long id) {
log.debug("REST request to get Ticket : {}", id);
Optional<Ticket> ticket = ticketService.findOne(id);
return ResponseUtil.wrapOrNotFound(ticket);
}
/**
* {@code DELETE /tickets/:id} : delete the "id" ticket.
*
* @param id the id of the ticket to delete.
* @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/tickets/{id}")
public ResponseEntity<Void> deleteTicket(@PathVariable Long id) {
log.debug("REST request to delete Ticket : {}", id);
ticketService.delete(id);
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, false, ENTITY_NAME, id.toString())).build();
}
}

Some files were not shown because too many files have changed in this diff Show More