Skip to content

Commit

Permalink
spring6_springboot3_hibernate6
Browse files Browse the repository at this point in the history
  • Loading branch information
oplekal committed Nov 29, 2024
1 parent 79f4a3f commit 5cad014
Show file tree
Hide file tree
Showing 254 changed files with 1,792 additions and 1,678 deletions.
212 changes: 134 additions & 78 deletions eperusteet/eperusteet-service/pom.xml

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,33 @@
import fi.vm.sade.eperusteet.hibernate.HibernateInterceptor;
import fi.vm.sade.eperusteet.repository.version.JpaWithVersioningRepositoryFactoryBean;
import fi.vm.sade.eperusteet.service.security.PermissionEvaluator;
import jakarta.persistence.EntityManager;
import jakarta.validation.ValidatorFactory;
import org.flywaydb.core.Flyway;
import org.hibernate.jpa.HibernateEntityManager;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.jpa.HibernatePersistenceProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;

import javax.sql.DataSource;
import java.util.HashMap;
Expand All @@ -39,7 +41,7 @@
@EnableAsync
@EnableCaching
@EnableTransactionManagement
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@EnableMethodSecurity(securedEnabled = true)
@EnableAspectJAutoProxy // (proxyTargetClass = true)
@EnableJpaRepositories(basePackages = "fi.vm.sade.eperusteet.repository", repositoryFactoryBeanClass = JpaWithVersioningRepositoryFactoryBean.class)
@PropertySource(
Expand All @@ -52,6 +54,9 @@ public class DefaultConfigs {
@Autowired
private DataSource dataSource;

@Autowired
private ValidatorFactory validatorFactory;

@Bean
public TaskExecutor defaultExecutor() {
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
Expand All @@ -75,10 +80,10 @@ public DefaultMethodSecurityExpressionHandler expressionHandler() {
return expressionHandler;
}

@Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
// @Bean
// public LocalValidatorFactoryBean validator() {
// return new LocalValidatorFactoryBean();
// }

@Bean(initMethod = "migrate")
public Flyway flyway() {
Expand All @@ -89,10 +94,10 @@ public Flyway flyway() {
.load();
}

@Bean
public HibernateInterceptor hibernateInterceptor() {
return new HibernateInterceptor();
}
// @Bean
// public HibernateInterceptor hibernateInterceptor() {
// return new HibernateInterceptor();
// }

@Bean
public ResourceBundleMessageSource messageSource() {
Expand All @@ -109,21 +114,22 @@ public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
entityManagerFactory.setDataSource(dataSource);
entityManagerFactory.setPackagesToScan("fi.vm.sade.eperusteet.domain");
entityManagerFactory.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactory.setEntityManagerInterface(HibernateEntityManager.class);
entityManagerFactory.setEntityManagerInterface(EntityManager.class);
Map<String, Object> props = new HashMap<>();
props.put("hibernate.hbm2ddl.auto", "validate");
props.put("hibernate.show_sql", false);
props.put("hibernate.dialect", "fi.vm.sade.eperusteet.utils.repository.dialect.CustomPostgreSqlDialect");
props.put("javax.persistence.sharedCache.mode", "ENABLE_SELECTIVE");
props.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
props.put("jakarta.persistence.sharedCache.mode", "ENABLE_SELECTIVE");
props.put("org.hibernate.envers.audit_strategy", "org.hibernate.envers.strategy.internal.DefaultAuditStrategy");
props.put("javax.persistence.validation.factory", validator());
// props.put("jakarta.persistence.validation.factory", validator());
props.put(AvailableSettings.JAKARTA_VALIDATION_FACTORY, validatorFactory);
props.put("org.hibernate.envers.revision_listener", "fi.vm.sade.eperusteet.service.impl.AuditRevisionListener");
props.put("hibernate.jdbc.batch_size", 20);
props.put("hibernate.jdbc.fetch_size", 20);
props.put("hibernate.ejb.interceptor", hibernateInterceptor());
// props.put("hibernate.ejb.interceptor", hibernateInterceptor());
props.put("hibernate.id.new_generator_mappings", false);
entityManagerFactory.setJpaPropertyMap(props);
entityManagerFactory.setMappingResources("hibernate-typedefs.hbm.xml");
// entityManagerFactory.setMappingResources("hibernate-typedefs.hbm.xml");
return entityManagerFactory;
}

Expand All @@ -132,4 +138,9 @@ public JpaTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory().getObject());
}

@Bean
public HandlerMappingIntrospector mvcHandlerMappingIntrospector() {
return new HandlerMappingIntrospector();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@
import org.springframework.core.NestedRuntimeException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.lang.Nullable;
import org.springframework.transaction.TransactionSystemException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
Expand All @@ -38,12 +40,12 @@
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.persistence.PersistenceException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import jakarta.persistence.PersistenceException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.ValidationException;
import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
Expand Down Expand Up @@ -71,8 +73,7 @@ public ResponseEntity<Object> handleTransactionExceptions(TransactionSystemExcep
}

@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status,
WebRequest request) {
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
if (ex.getRootCause() != null && ex.getRootCause() instanceof UnrecognizedPropertyException) {
return handleExceptionInternal((UnrecognizedPropertyException) ex.getRootCause(), null, headers, status, request);
} else {
Expand Down Expand Up @@ -123,7 +124,7 @@ private void describe(Map<String, Object> map, String koodi, String selkokieline
}

@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
final Map<String, Object> map = new HashMap<>();
boolean suppresstrace = false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.persistence.EntityManagerFactory;
import jakarta.persistence.EntityManagerFactory;
import java.util.List;

@Configuration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
import fi.vm.sade.java_utils.security.OpintopolkuCasAuthenticationFilter;
import fi.vm.sade.javautils.http.auth.CasAuthenticator;
import fi.vm.sade.javautils.kayttooikeusclient.OphUserDetailsServiceImpl;
import org.jasig.cas.client.session.SingleSignOutFilter;
import org.jasig.cas.client.validation.Cas20ProxyTicketValidator;
import org.jasig.cas.client.validation.TicketValidator;
import org.apereo.cas.client.session.SingleSignOutFilter;
import org.apereo.cas.client.validation.Cas20ProxyTicketValidator;
import org.apereo.cas.client.validation.TicketValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
Expand All @@ -17,35 +17,24 @@
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.cas.ServiceProperties;
import org.springframework.security.cas.authentication.CasAuthenticationProvider;
import org.springframework.security.cas.authentication.CasAuthenticationToken;
import org.springframework.security.cas.web.CasAuthenticationEntryPoint;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.ldap.LdapBindAuthenticationManagerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Profile({"!dev & !test"})
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@EnableMethodSecurity(securedEnabled = true)
@EnableWebSecurity
public class WebSecurityConfiguration {

Expand Down Expand Up @@ -147,26 +136,28 @@ public CasAuthenticationEntryPoint casAuthenticationEntryPoint() {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
requestCache.setMatchingRequestParameterName(null);

http
.csrf().disable()
.authorizeRequests()
.antMatchers("/buildversion.txt").permitAll()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers(HttpMethod.GET, "/").permitAll()
.anyRequest().authenticated()
.and()
.headers(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/buildversion.txt").permitAll()
.requestMatchers(HttpMethod.GET, "/api/**").permitAll()
.requestMatchers(HttpMethod.GET, "/").permitAll()
.anyRequest().authenticated())
.addFilter(casAuthenticationFilter(http))
.exceptionHandling()
.authenticationEntryPoint(casAuthenticationEntryPoint())
.and()
.exceptionHandling(handling -> handling.authenticationEntryPoint(casAuthenticationEntryPoint()))
.addFilterBefore(singleSignOutFilter(), CasAuthenticationFilter.class)
.logout((logout) -> {
logout.logoutUrl("/api/logout");
logout.logoutSuccessUrl("https://" + this.hostVirkailija + "/service-provider-app/saml/logout");
logout.addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(ClearSiteDataHeaderWriter.Directive.ALL)));
logout.invalidateHttpSession(true);
})
.headers().defaultsDisabled().cacheControl();
.requestCache(cache -> cache.requestCache(requestCache));
return http.build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,61 +2,54 @@

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpMethod;
import org.springframework.security.access.vote.AffirmativeBased;
import org.springframework.security.access.vote.RoleVoter;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.cas.web.CasAuthenticationFilter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.HeaderWriterLogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
import org.springframework.security.web.header.writers.ClearSiteDataHeaderWriter;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Profile({"dev"})
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@EnableMethodSecurity(securedEnabled = true)
@EnableWebSecurity
public class WebSecurityConfigurationDev {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
HttpSessionRequestCache requestCache = new HttpSessionRequestCache();
requestCache.setMatchingRequestParameterName(null);

http
.csrf().disable()
.authorizeRequests()
.antMatchers("/buildversion.txt").permitAll()
.antMatchers(HttpMethod.GET, "/api/**").permitAll()
.antMatchers(HttpMethod.POST, "/api/**").permitAll()
.antMatchers(HttpMethod.GET, "/").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers("/buildversion.txt").permitAll()
.requestMatchers(HttpMethod.GET, "/api/**").permitAll()
.requestMatchers(HttpMethod.GET, "/").permitAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults())
.logout(logout -> {
logout.logoutUrl("/api/logout");
logout.logoutSuccessUrl("http://localhost:9001");
logout.addLogoutHandler(new HeaderWriterLogoutHandler(new ClearSiteDataHeaderWriter(ClearSiteDataHeaderWriter.Directive.ALL)));
logout.invalidateHttpSession(true);
})
.headers().defaultsDisabled().cacheControl();
.requestCache(cache -> cache.requestCache(requestCache));

return http.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import fi.vm.sade.eperusteet.domain.yl.LaajaalainenOsaaminen;
import fi.vm.sade.eperusteet.domain.yl.Oppiaine;
import java.util.*;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.envers.Audited;
Expand All @@ -34,8 +34,8 @@ public class AIPEOpetuksenSisalto extends AbstractOppiaineOpetuksenSisalto imple
@OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval = true)
@Getter
@JoinTable(name = "yl_aipe_opetuksensisalto_yl_laajaalainen_osaaminen",
joinColumns = @JoinColumn(name = "yl_aipe_opetuksensisalto_id", insertable = false, updatable = false),
inverseJoinColumns = @JoinColumn(name = "laajaalaisetosaamiset_id", insertable = false, updatable = false))
joinColumns = @JoinColumn(name = "yl_aipe_opetuksensisalto_id"),
inverseJoinColumns = @JoinColumn(name = "laajaalaisetosaamiset_id"))
@OrderBy("jarjestys, id")
private List<LaajaalainenOsaaminen> laajaalaisetosaamiset = new ArrayList<>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.*;
import jakarta.persistence.*;
import java.io.Serializable;
import java.util.Date;

Expand Down
Loading

0 comments on commit 5cad014

Please sign in to comment.