Skip to content

Commit

Permalink
spring6_springboot3_hibernate6
Browse files Browse the repository at this point in the history
  • Loading branch information
oplekal committed Dec 2, 2024
1 parent 79f4a3f commit 882e131
Show file tree
Hide file tree
Showing 262 changed files with 1,980 additions and 1,797 deletions.
3 changes: 2 additions & 1 deletion .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,8 @@ jobs:

- name: Build
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_USERNAME: ${{ secrets.GITHUB_USERNAME }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
cd eperusteet/eperusteet-service
mvn clean verify -B -Pit
Expand Down
304 changes: 199 additions & 105 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,23 @@ 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(AvailableSettings.ID_DB_STRUCTURE_NAMING_STRATEGY, "legacy");
// 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 +139,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 @@ -23,36 +23,36 @@
import static com.google.common.base.Predicates.not;

@Configuration
@EnableSwagger2
//@EnableSwagger2
@Profile("!test")
public class SwaggerConfig {

@Bean
public Docket api(TypeResolver typeResolver) {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.directModelSubstitute(JsonNode.class, Object.class)
.genericModelSubstitutes(ResponseEntity.class, Optional.class)
.forCodeGeneration(true)
.select()
.apis(not(RequestHandlerSelectors.withClassAnnotation(InternalApi.class)))
.build()
.alternateTypeRules(
AlternateTypeRules.newRule(
typeResolver.resolve(new GenericType<Callable<ResponseEntity<Object>>>() {
}),
typeResolver.resolve(Object.class)));
}
// @Bean
// public Docket api(TypeResolver typeResolver) {
// return new Docket(DocumentationType.SWAGGER_2)
// .apiInfo(apiInfo())
// .directModelSubstitute(JsonNode.class, Object.class)
// .genericModelSubstitutes(ResponseEntity.class, Optional.class)
// .forCodeGeneration(true)
// .select()
// .apis(not(RequestHandlerSelectors.withClassAnnotation(InternalApi.class)))
// .build()
// .alternateTypeRules(
// AlternateTypeRules.newRule(
// typeResolver.resolve(new GenericType<Callable<ResponseEntity<Object>>>() {
// }),
// typeResolver.resolve(Object.class)));
// }

private ApiInfo apiInfo() {
return new ApiInfo(
"ePerusteet rajapinta",
"",
"Spring MVC API based on the swagger 2.0 and 1.2 specification",
null,
null,
"EUPL 1.1",
"http://ec.europa.eu/idabc/eupl",
new ArrayList<>());
}
// private ApiInfo apiInfo() {
// return new ApiInfo(
// "ePerusteet rajapinta",
// "",
// "Spring MVC API based on the swagger 2.0 and 1.2 specification",
// null,
// null,
// "EUPL 1.1",
// "http://ec.europa.eu/idabc/eupl",
// new ArrayList<>());
// }
}
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 @@ -84,10 +73,10 @@ public CasAuthenticator casAuthenticator() {
return new CasAuthenticator(this.webUrlCas, eperusteet_username, eperusteet_password, hostAlb, null, false, null);
}

@Bean
public UserDetailsService userDetailsService() {
return new OphUserDetailsServiceImpl(this.hostAlb, RestClientFactoryImpl.CALLER_ID, casAuthenticator());
}
// @Bean
// public UserDetailsService userDetailsService() {
// return new OphUserDetailsServiceImpl(this.hostAlb, RestClientFactoryImpl.CALLER_ID, casAuthenticator());
// }

@Bean
public ServiceProperties serviceProperties() {
Expand All @@ -101,7 +90,8 @@ public ServiceProperties serviceProperties() {
@Bean
public CasAuthenticationProvider casAuthenticationProvider() {
CasAuthenticationProvider casAuthenticationProvider = new CasAuthenticationProvider();
casAuthenticationProvider.setUserDetailsService(userDetailsService());
// casAuthenticationProvider.setUserDetailsService(userDetailsService());
casAuthenticationProvider.setAuthenticationUserDetailsService(new OphUserDetailsServiceImpl());
casAuthenticationProvider.setServiceProperties(serviceProperties());
casAuthenticationProvider.setTicketValidator(ticketValidator());
casAuthenticationProvider.setKey(this.casKey);
Expand Down Expand Up @@ -147,26 +137,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
Loading

0 comments on commit 882e131

Please sign in to comment.