formatting work
This commit is contained in:
+19
-19
@@ -11,28 +11,28 @@ import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;
|
||||
|
||||
@EnableWebMvc
|
||||
@Configuration
|
||||
@ComponentScan({"com.baeldung.freemarker"})
|
||||
@ComponentScan({ "com.baeldung.freemarker" })
|
||||
public class SpringWebConfig extends WebMvcConfigurerAdapter {
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
|
||||
}
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FreeMarkerViewResolver freemarkerViewResolver() {
|
||||
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
|
||||
resolver.setCache(true);
|
||||
resolver.setPrefix("");
|
||||
resolver.setSuffix(".ftl");
|
||||
return resolver;
|
||||
}
|
||||
@Bean
|
||||
public FreeMarkerViewResolver freemarkerViewResolver() {
|
||||
FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
|
||||
resolver.setCache(true);
|
||||
resolver.setPrefix("");
|
||||
resolver.setSuffix(".ftl");
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public FreeMarkerConfigurer freemarkerConfig() {
|
||||
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
|
||||
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");
|
||||
return freeMarkerConfigurer;
|
||||
}
|
||||
@Bean
|
||||
public FreeMarkerConfigurer freemarkerConfig() {
|
||||
FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
|
||||
freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");
|
||||
return freeMarkerConfigurer;
|
||||
}
|
||||
|
||||
}
|
||||
+12
-12
@@ -4,19 +4,19 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatche
|
||||
|
||||
public class WebConfiguration extends AbstractAnnotationConfigDispatcherServletInitializer {
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
return new Class[] { SpringWebConfig.class };
|
||||
}
|
||||
@Override
|
||||
protected Class<?>[] getServletConfigClasses() {
|
||||
return new Class[] { SpringWebConfig.class };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
return new String[] { "/" };
|
||||
}
|
||||
@Override
|
||||
protected String[] getServletMappings() {
|
||||
return new String[] { "/" };
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return null;
|
||||
}
|
||||
@Override
|
||||
protected Class<?>[] getRootConfigClasses() {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
+24
-26
@@ -16,33 +16,31 @@ import com.baeldung.freemarker.model.Car;
|
||||
@Controller
|
||||
public class SpringController {
|
||||
|
||||
private static List<Car> carList = new ArrayList<Car>();
|
||||
|
||||
@RequestMapping(value = "/", method = RequestMethod.GET)
|
||||
public String home(Locale locale, Model model) {
|
||||
return "redirect:/cars";
|
||||
}
|
||||
|
||||
static {
|
||||
carList.add(new Car("Honda", "Civic"));
|
||||
carList.add(new Car("Toyota", "Camry"));
|
||||
carList.add(new Car("Nissan", "Altima"));
|
||||
}
|
||||
private static List<Car> carList = new ArrayList<Car>();
|
||||
|
||||
@RequestMapping(value = "/", method = RequestMethod.GET)
|
||||
public String home(Locale locale, Model model) {
|
||||
return "redirect:/cars";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/cars", method = RequestMethod.GET)
|
||||
public String init(@ModelAttribute("model") ModelMap model) {
|
||||
model.addAttribute("carList", carList);
|
||||
return "index";
|
||||
}
|
||||
static {
|
||||
carList.add(new Car("Honda", "Civic"));
|
||||
carList.add(new Car("Toyota", "Camry"));
|
||||
carList.add(new Car("Nissan", "Altima"));
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/cars", method = RequestMethod.GET)
|
||||
public String init(@ModelAttribute("model") ModelMap model) {
|
||||
model.addAttribute("carList", carList);
|
||||
return "index";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/add", method = RequestMethod.POST)
|
||||
public String addCar(@ModelAttribute("car") Car car) {
|
||||
if (null != car && null != car.getMake() && null != car.getModel() && !car.getMake().isEmpty() && !car.getModel().isEmpty()) {
|
||||
carList.add(car);
|
||||
}
|
||||
return "redirect:/cars";
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/add", method = RequestMethod.POST)
|
||||
public String addCar(@ModelAttribute("car") Car car) {
|
||||
if (null != car && null != car.getMake() && null != car.getModel()
|
||||
&& !car.getMake().isEmpty() && !car.getModel().isEmpty()) {
|
||||
carList.add(car);
|
||||
}
|
||||
return "redirect:/cars";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2,32 +2,32 @@ package com.baeldung.freemarker.model;
|
||||
|
||||
public class Car {
|
||||
|
||||
private String make;
|
||||
private String model;
|
||||
|
||||
public Car(){
|
||||
|
||||
}
|
||||
|
||||
public Car(String make, String model) {
|
||||
this.make = make;
|
||||
private String make;
|
||||
private String model;
|
||||
|
||||
public Car() {
|
||||
|
||||
}
|
||||
|
||||
public Car(String make, String model) {
|
||||
this.make = make;
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public String getMake() {
|
||||
return make;
|
||||
}
|
||||
public String getMake() {
|
||||
return make;
|
||||
}
|
||||
|
||||
public void setMake(String make) {
|
||||
this.make = make;
|
||||
}
|
||||
public void setMake(String make) {
|
||||
this.make = make;
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+3
-11
@@ -19,21 +19,13 @@ public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAda
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("user1").password("user1Pass")
|
||||
.authorities("ROLE_USER");
|
||||
auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.antMatchers("/securityNone").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
.and()
|
||||
.httpBasic()
|
||||
.authenticationEntryPoint(authenticationEntryPoint);
|
||||
http.authorizeRequests().antMatchers("/securityNone").permitAll().anyRequest().authenticated().and().httpBasic().authenticationEntryPoint(authenticationEntryPoint);
|
||||
|
||||
http.addFilterAfter(new CustomFilter(),
|
||||
BasicAuthenticationFilter.class);
|
||||
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ComponentScan("org.baeldung.security")
|
||||
//@ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
// @ImportResource({ "classpath:webSecurityConfig.xml" })
|
||||
public class SecSecurityConfig {
|
||||
|
||||
public SecSecurityConfig() {
|
||||
|
||||
@@ -9,8 +9,7 @@ import org.springframework.context.annotation.FilterType;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan(excludeFilters =
|
||||
@ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*"))
|
||||
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.baeldung.voter.*"))
|
||||
public class Application extends SpringBootServletInitializer {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import org.springframework.transaction.annotation.Transactional;
|
||||
public interface UserRepository extends JpaRepository<User, Long> {
|
||||
|
||||
User findByUsername(final String username);
|
||||
|
||||
|
||||
@Transactional
|
||||
void removeUserByUsername(String username);
|
||||
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ import javax.persistence.ManyToOne;
|
||||
import javax.persistence.Table;
|
||||
|
||||
@Entity
|
||||
@Table(name="user_table")
|
||||
@Table(name = "user_table")
|
||||
public class User {
|
||||
|
||||
@Id
|
||||
|
||||
+1
-8
@@ -21,13 +21,6 @@ public class MinuteBasedVoter implements AccessDecisionVoter {
|
||||
|
||||
@Override
|
||||
public int vote(Authentication authentication, Object object, Collection collection) {
|
||||
return authentication
|
||||
.getAuthorities()
|
||||
.stream()
|
||||
.map(GrantedAuthority::getAuthority)
|
||||
.filter(r -> "ROLE_USER".equals(r) && LocalDateTime.now().getMinute() % 2 != 0)
|
||||
.findAny()
|
||||
.map(s -> ACCESS_DENIED)
|
||||
.orElseGet(() -> ACCESS_ABSTAIN);
|
||||
return authentication.getAuthorities().stream().map(GrantedAuthority::getAuthority).filter(r -> "ROLE_USER".equals(r) && LocalDateTime.now().getMinute() % 2 != 0).findAny().map(s -> ACCESS_DENIED).orElseGet(() -> ACCESS_ABSTAIN);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ import org.springframework.context.annotation.FilterType;
|
||||
|
||||
@Configuration
|
||||
@EnableAutoConfiguration
|
||||
@ComponentScan(basePackages = {"org.baeldung.voter"})
|
||||
@ComponentScan(basePackages = { "org.baeldung.voter" })
|
||||
public class VoterApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
+4
-25
@@ -24,10 +24,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
// @formatter: off
|
||||
auth.inMemoryAuthentication()
|
||||
.withUser("user").password("pass").roles("USER")
|
||||
.and()
|
||||
.withUser("admin").password("pass").roles("ADMIN");
|
||||
auth.inMemoryAuthentication().withUser("user").password("pass").roles("USER").and().withUser("admin").password("pass").roles("ADMIN");
|
||||
// @formatter: on
|
||||
}
|
||||
|
||||
@@ -36,33 +33,15 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
// @formatter: off
|
||||
http
|
||||
// needed so our login could work
|
||||
.csrf()
|
||||
.disable()
|
||||
.authorizeRequests()
|
||||
.anyRequest()
|
||||
.authenticated()
|
||||
.accessDecisionManager(accessDecisionManager())
|
||||
.antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER")
|
||||
.and()
|
||||
.formLogin()
|
||||
.permitAll()
|
||||
.and()
|
||||
.logout()
|
||||
.permitAll()
|
||||
.deleteCookies("JSESSIONID")
|
||||
.logoutSuccessUrl("/login");
|
||||
.csrf().disable().authorizeRequests().anyRequest().authenticated().accessDecisionManager(accessDecisionManager()).antMatchers("/").hasAnyRole("ROLE_ADMIN", "ROLE_USER").and().formLogin().permitAll().and().logout().permitAll()
|
||||
.deleteCookies("JSESSIONID").logoutSuccessUrl("/login");
|
||||
// @formatter: on
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AccessDecisionManager accessDecisionManager() {
|
||||
// @formatter: off
|
||||
List<AccessDecisionVoter<? extends Object>> decisionVoters =
|
||||
Arrays.asList(
|
||||
new WebExpressionVoter(),
|
||||
new RoleVoter(),
|
||||
new AuthenticatedVoter(),
|
||||
new MinuteBasedVoter());
|
||||
List<AccessDecisionVoter<? extends Object>> decisionVoters = Arrays.asList(new WebExpressionVoter(), new RoleVoter(), new AuthenticatedVoter(), new MinuteBasedVoter());
|
||||
// @formatter: on
|
||||
return new UnanimousBased(decisionVoters);
|
||||
}
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ import org.springframework.context.annotation.ImportResource;
|
||||
* Created by ambrusadrianz on 09/10/2016.
|
||||
*/
|
||||
@Configuration
|
||||
@ImportResource({"classpath:spring-security.xml"})
|
||||
@ImportResource({ "classpath:spring-security.xml" })
|
||||
public class XmlSecurityConfig {
|
||||
public XmlSecurityConfig() {
|
||||
super();
|
||||
|
||||
@@ -15,6 +15,7 @@ public class MyUserLiveTest {
|
||||
|
||||
private final MyUser userJohn = new MyUser("john", "doe", "[email protected]", 11);
|
||||
private String URL_PREFIX = "http://localhost:8082/spring-security-rest-full/auth/api/myusers";
|
||||
|
||||
@Test
|
||||
public void whenGettingListOfUsers_thenCorrect() {
|
||||
final Response response = givenAuth().get(URL_PREFIX);
|
||||
|
||||
@@ -16,11 +16,11 @@ import org.springframework.security.web.authentication.SimpleUrlAuthenticationFa
|
||||
@ComponentScan("org.baeldung.security")
|
||||
public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
// @Autowired
|
||||
// private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
|
||||
// @Autowired
|
||||
// private RestAuthenticationEntryPoint restAuthenticationEntryPoint;
|
||||
|
||||
// @Autowired
|
||||
// private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
|
||||
// @Autowired
|
||||
// private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;
|
||||
|
||||
public SecurityJavaConfig() {
|
||||
super();
|
||||
|
||||
@@ -20,7 +20,7 @@ public class WebConfig extends WebMvcConfigurerAdapter {
|
||||
public WebConfig() {
|
||||
super();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
|
||||
|
||||
+17
-19
@@ -14,26 +14,24 @@ import org.springframework.web.bind.annotation.ResponseBody;
|
||||
@Controller
|
||||
public class AsyncController {
|
||||
|
||||
private static final Logger log = Logger.getLogger(AsyncService.class);
|
||||
private static final Logger log = Logger.getLogger(AsyncService.class);
|
||||
|
||||
@Autowired
|
||||
private AsyncService asyncService;
|
||||
@Autowired
|
||||
private AsyncService asyncService;
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/async")
|
||||
@ResponseBody
|
||||
public Object standardProcessing() throws Exception {
|
||||
log.info("Outside the @Async logic - before the async call: "
|
||||
+ SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||
asyncService.asyncCall();
|
||||
log.info("Inside the @Async logic - after the async call: "
|
||||
+ SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||
return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/async2")
|
||||
@ResponseBody
|
||||
public Callable<Boolean> springMVCAsyncTest() {
|
||||
return asyncService.checkIfPrincipalPropagated();
|
||||
}
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/async")
|
||||
@ResponseBody
|
||||
public Object standardProcessing() throws Exception {
|
||||
log.info("Outside the @Async logic - before the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||
asyncService.asyncCall();
|
||||
log.info("Inside the @Async logic - after the async call: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||
return SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
}
|
||||
|
||||
@RequestMapping(method = RequestMethod.GET, value = "/async2")
|
||||
@ResponseBody
|
||||
public Callable<Boolean> springMVCAsyncTest() {
|
||||
return asyncService.checkIfPrincipalPropagated();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -3,9 +3,9 @@ package org.baeldung.web.service;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
public interface AsyncService {
|
||||
|
||||
void asyncCall();
|
||||
|
||||
Callable<Boolean> checkIfPrincipalPropagated();
|
||||
|
||||
|
||||
void asyncCall();
|
||||
|
||||
Callable<Boolean> checkIfPrincipalPropagated();
|
||||
|
||||
}
|
||||
|
||||
@@ -10,27 +10,25 @@ import org.springframework.stereotype.Service;
|
||||
@Service
|
||||
public class AsyncServiceImpl implements AsyncService {
|
||||
|
||||
private static final Logger log = Logger.getLogger(AsyncService.class);
|
||||
private static final Logger log = Logger.getLogger(AsyncService.class);
|
||||
|
||||
@Async
|
||||
@Override
|
||||
public void asyncCall() {
|
||||
log.info("Inside the @Async logic: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||
}
|
||||
@Async
|
||||
@Override
|
||||
public void asyncCall() {
|
||||
log.info("Inside the @Async logic: " + SecurityContextHolder.getContext().getAuthentication().getPrincipal());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Callable<Boolean> checkIfPrincipalPropagated() {
|
||||
Object before
|
||||
= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
log.info("Before new thread: " + before);
|
||||
@Override
|
||||
public Callable<Boolean> checkIfPrincipalPropagated() {
|
||||
Object before = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
log.info("Before new thread: " + before);
|
||||
|
||||
return new Callable<Boolean>() {
|
||||
public Boolean call() throws Exception {
|
||||
Object after
|
||||
= SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
log.info("New thread: " + after);
|
||||
return before == after;
|
||||
}
|
||||
};
|
||||
}
|
||||
return new Callable<Boolean>() {
|
||||
public Boolean call() throws Exception {
|
||||
Object after = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
|
||||
log.info("New thread: " + after);
|
||||
return before == after;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,27 +22,27 @@ import org.springframework.web.context.WebApplicationContext;
|
||||
|
||||
@RunWith(SpringJUnit4ClassRunner.class)
|
||||
@WebAppConfiguration
|
||||
@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class})
|
||||
@ContextConfiguration(classes = { ClientWebConfig.class, SecurityJavaConfig.class, WebConfig.class })
|
||||
public class AsyncControllerTest {
|
||||
|
||||
@Autowired
|
||||
WebApplicationContext wac;
|
||||
@Autowired
|
||||
MockHttpSession session;
|
||||
|
||||
@Mock
|
||||
AsyncController controller;
|
||||
@Autowired
|
||||
WebApplicationContext wac;
|
||||
@Autowired
|
||||
MockHttpSession session;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
@Mock
|
||||
AsyncController controller;
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||
}
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
public void testAsync() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/async")).andExpect(status().is5xxServerError());
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAsync() throws Exception {
|
||||
mockMvc.perform(MockMvcRequestBuilders.get("/async")).andExpect(status().is5xxServerError());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -10,10 +10,10 @@ import org.springframework.web.multipart.commons.CommonsMultipartResolver;
|
||||
@ComponentScan({ "org.baeldung.web" })
|
||||
public class TestConfig {
|
||||
|
||||
@Bean
|
||||
public MultipartResolver multipartResolver() {
|
||||
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
|
||||
return multipartResolver;
|
||||
}
|
||||
@Bean
|
||||
public MultipartResolver multipartResolver() {
|
||||
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
|
||||
return multipartResolver;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -13,17 +13,11 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth
|
||||
.inMemoryAuthentication()
|
||||
.withUser("admin").password("password").roles("ADMIN");
|
||||
auth.inMemoryAuthentication().withUser("admin").password("password").roles("ADMIN");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.httpBasic().and()
|
||||
.authorizeRequests()
|
||||
.antMatchers("/").hasRole("ADMIN")
|
||||
.anyRequest().authenticated();
|
||||
http.httpBasic().and().authorizeRequests().antMatchers("/").hasRole("ADMIN").anyRequest().authenticated();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,10 +42,10 @@ public class SessionControllerTest {
|
||||
@Test
|
||||
public void testRedisControlsSession() {
|
||||
ResponseEntity<String> result = testRestTemplateWithAuth.getForEntity(testUrl, String.class);
|
||||
assertEquals("hello admin", result.getBody()); //login worked
|
||||
assertEquals("hello admin", result.getBody()); // login worked
|
||||
|
||||
Set<String> redisResult = jedis.keys("*");
|
||||
assertTrue(redisResult.size() > 0); //redis is populated with session data
|
||||
assertTrue(redisResult.size() > 0); // redis is populated with session data
|
||||
|
||||
String sessionCookie = result.getHeaders().get("Set-Cookie").get(0).split(";")[0];
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
@@ -53,12 +53,12 @@ public class SessionControllerTest {
|
||||
HttpEntity<String> httpEntity = new HttpEntity<>(headers);
|
||||
|
||||
result = testRestTemplate.exchange(testUrl, HttpMethod.GET, httpEntity, String.class);
|
||||
assertEquals("hello admin", result.getBody()); //access with session works worked
|
||||
assertEquals("hello admin", result.getBody()); // access with session works worked
|
||||
|
||||
jedis.flushAll(); //clear all keys in redis
|
||||
jedis.flushAll(); // clear all keys in redis
|
||||
|
||||
result = testRestTemplate.exchange(testUrl, HttpMethod.GET, httpEntity, String.class);
|
||||
assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());//access denied after sessions are removed in redis
|
||||
assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());// access denied after sessions are removed in redis
|
||||
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import java.util.concurrent.Executors;
|
||||
@Configuration
|
||||
@EnableAsync
|
||||
@EnableScheduling
|
||||
public class ThreadConfig extends AsyncConfigurerSupport implements SchedulingConfigurer{
|
||||
public class ThreadConfig extends AsyncConfigurerSupport implements SchedulingConfigurer {
|
||||
|
||||
@Autowired
|
||||
private BeanFactory beanFactory;
|
||||
|
||||
@@ -47,71 +47,71 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application
|
||||
this.applicationContext = applicationContext;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver htmlViewResolver() {
|
||||
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
||||
resolver.setTemplateEngine(templateEngine(htmlTemplateResolver()));
|
||||
resolver.setContentType("text/html");
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
resolver.setViewNames(ArrayUtil.array("*.html"));
|
||||
return resolver;
|
||||
}
|
||||
@Bean
|
||||
public ViewResolver htmlViewResolver() {
|
||||
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
||||
resolver.setTemplateEngine(templateEngine(htmlTemplateResolver()));
|
||||
resolver.setContentType("text/html");
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
resolver.setViewNames(ArrayUtil.array("*.html"));
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver javascriptViewResolver() {
|
||||
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
||||
resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver()));
|
||||
resolver.setContentType("application/javascript");
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
resolver.setViewNames(ArrayUtil.array("*.js"));
|
||||
return resolver;
|
||||
}
|
||||
@Bean
|
||||
public ViewResolver javascriptViewResolver() {
|
||||
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
||||
resolver.setTemplateEngine(templateEngine(javascriptTemplateResolver()));
|
||||
resolver.setContentType("application/javascript");
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
resolver.setViewNames(ArrayUtil.array("*.js"));
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ViewResolver plainViewResolver() {
|
||||
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
||||
resolver.setTemplateEngine(templateEngine(plainTemplateResolver()));
|
||||
resolver.setContentType("text/plain");
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
resolver.setViewNames(ArrayUtil.array("*.txt"));
|
||||
return resolver;
|
||||
}
|
||||
@Bean
|
||||
public ViewResolver plainViewResolver() {
|
||||
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
|
||||
resolver.setTemplateEngine(templateEngine(plainTemplateResolver()));
|
||||
resolver.setContentType("text/plain");
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
resolver.setViewNames(ArrayUtil.array("*.txt"));
|
||||
return resolver;
|
||||
}
|
||||
|
||||
private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
|
||||
SpringTemplateEngine engine = new SpringTemplateEngine();
|
||||
engine.addDialect(new LayoutDialect(new GroupingStrategy()));
|
||||
engine.addDialect(new Java8TimeDialect());
|
||||
engine.setTemplateResolver(templateResolver);
|
||||
engine.setTemplateEngineMessageSource(messageSource());
|
||||
return engine;
|
||||
}
|
||||
private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
|
||||
SpringTemplateEngine engine = new SpringTemplateEngine();
|
||||
engine.addDialect(new LayoutDialect(new GroupingStrategy()));
|
||||
engine.addDialect(new Java8TimeDialect());
|
||||
engine.setTemplateResolver(templateResolver);
|
||||
engine.setTemplateEngineMessageSource(messageSource());
|
||||
return engine;
|
||||
}
|
||||
|
||||
private ITemplateResolver htmlTemplateResolver() {
|
||||
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
||||
resolver.setApplicationContext(applicationContext);
|
||||
resolver.setPrefix("/WEB-INF/views/");
|
||||
resolver.setCacheable(false);
|
||||
resolver.setTemplateMode(TemplateMode.HTML);
|
||||
return resolver;
|
||||
}
|
||||
private ITemplateResolver htmlTemplateResolver() {
|
||||
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
||||
resolver.setApplicationContext(applicationContext);
|
||||
resolver.setPrefix("/WEB-INF/views/");
|
||||
resolver.setCacheable(false);
|
||||
resolver.setTemplateMode(TemplateMode.HTML);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
private ITemplateResolver javascriptTemplateResolver() {
|
||||
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
||||
resolver.setApplicationContext(applicationContext);
|
||||
resolver.setPrefix("/WEB-INF/js/");
|
||||
resolver.setCacheable(false);
|
||||
resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
|
||||
return resolver;
|
||||
}
|
||||
private ITemplateResolver javascriptTemplateResolver() {
|
||||
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
||||
resolver.setApplicationContext(applicationContext);
|
||||
resolver.setPrefix("/WEB-INF/js/");
|
||||
resolver.setCacheable(false);
|
||||
resolver.setTemplateMode(TemplateMode.JAVASCRIPT);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
private ITemplateResolver plainTemplateResolver() {
|
||||
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
||||
resolver.setApplicationContext(applicationContext);
|
||||
resolver.setPrefix("/WEB-INF/txt/");
|
||||
resolver.setCacheable(false);
|
||||
resolver.setTemplateMode(TemplateMode.TEXT);
|
||||
return resolver;
|
||||
}
|
||||
private ITemplateResolver plainTemplateResolver() {
|
||||
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
|
||||
resolver.setApplicationContext(applicationContext);
|
||||
resolver.setPrefix("/WEB-INF/txt/");
|
||||
resolver.setCacheable(false);
|
||||
resolver.setTemplateMode(TemplateMode.TEXT);
|
||||
return resolver;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Description("Spring Message Resolver")
|
||||
@@ -121,7 +121,7 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application
|
||||
return messageSource;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Bean
|
||||
public LocaleResolver localeResolver() {
|
||||
SessionLocaleResolver localeResolver = new SessionLocaleResolver();
|
||||
localeResolver.setDefaultLocale(new Locale("en"));
|
||||
@@ -140,12 +140,12 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application
|
||||
registry.addInterceptor(localeChangeInterceptor());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
|
||||
}
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
|
||||
}
|
||||
|
||||
@Override
|
||||
@Override
|
||||
@Description("Custom Conversion Service")
|
||||
public void addFormatters(FormatterRegistry registry) {
|
||||
registry.addFormatter(new NameFormatter());
|
||||
|
||||
+8
-8
@@ -13,13 +13,13 @@ import org.springframework.web.bind.annotation.RequestMethod;
|
||||
@Controller
|
||||
public class DatesController {
|
||||
|
||||
@RequestMapping(value = "/dates", method = RequestMethod.GET)
|
||||
public String getInfo(Model model) {
|
||||
model.addAttribute("standardDate", new Date());
|
||||
model.addAttribute("localDateTime", LocalDateTime.now());
|
||||
model.addAttribute("localDate", LocalDate.now());
|
||||
model.addAttribute("timestamp", Instant.now());
|
||||
return "dates.html";
|
||||
}
|
||||
@RequestMapping(value = "/dates", method = RequestMethod.GET)
|
||||
public String getInfo(Model model) {
|
||||
model.addAttribute("standardDate", new Date());
|
||||
model.addAttribute("localDateTime", LocalDateTime.now());
|
||||
model.addAttribute("localDate", LocalDate.now());
|
||||
model.addAttribute("timestamp", Instant.now());
|
||||
return "dates.html";
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+14
-14
@@ -31,24 +31,24 @@ import com.baeldung.thymeleaf.config.WebMVCSecurity;
|
||||
@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class })
|
||||
public class ExpressionUtilityObjectsControllerIntegrationTest {
|
||||
|
||||
@Autowired
|
||||
WebApplicationContext wac;
|
||||
@Autowired
|
||||
MockHttpSession session;
|
||||
@Autowired
|
||||
WebApplicationContext wac;
|
||||
@Autowired
|
||||
MockHttpSession session;
|
||||
|
||||
private MockMvc mockMvc;
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Autowired
|
||||
private Filter springSecurityFilterChain;
|
||||
@Autowired
|
||||
private Filter springSecurityFilterChain;
|
||||
|
||||
protected RequestPostProcessor testUser() {
|
||||
return user("user1").password("user1Pass").roles("USER");
|
||||
}
|
||||
protected RequestPostProcessor testUser() {
|
||||
return user("user1").password("user1Pass").roles("USER");
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setup() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
|
||||
}
|
||||
@Before
|
||||
public void setup() {
|
||||
mockMvc = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetObjects() throws Exception {
|
||||
|
||||
@@ -25,8 +25,7 @@ public class UserController {
|
||||
myUserService.registerNewUserAccount(accountDto);
|
||||
model.addAttribute("message", "Registration successful");
|
||||
return "index";
|
||||
}
|
||||
catch(final Exception exc){
|
||||
} catch (final Exception exc) {
|
||||
model.addAttribute("message", "Registration failed");
|
||||
|
||||
return "index";
|
||||
|
||||
@@ -29,7 +29,7 @@ public class MyUserDAO {
|
||||
entityManager.persist(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
|
||||
public void removeUserByUsername(String username) {
|
||||
final Query query = entityManager.createQuery("delete from MyUser where username=:username");
|
||||
query.setParameter("username", username);
|
||||
|
||||
@@ -33,8 +33,8 @@ public class MyUserService {
|
||||
final MyUser user = myUserDAO.findByUsername(username);
|
||||
return user;
|
||||
}
|
||||
|
||||
public void removeUserByUsername(String username){
|
||||
|
||||
public void removeUserByUsername(String username) {
|
||||
myUserDAO.removeUserByUsername(username);
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user