Skip to content

Commit 96c05ab

Browse files
committed
Merge remote-tracking branch 'upstream/master'
2 parents 78a130b + 5f9ef96 commit 96c05ab

12 files changed

Lines changed: 346 additions & 1 deletion

File tree

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
package org.baeldung.java.collections;
2+
3+
import static java.util.Arrays.asList;
4+
5+
import java.util.ArrayList;
6+
import java.util.Arrays;
7+
import java.util.Collection;
8+
import java.util.Iterator;
9+
import java.util.List;
10+
import java.util.NoSuchElementException;
11+
import java.util.stream.Collectors;
12+
import java.util.stream.Stream;
13+
14+
import org.junit.Assert;
15+
import org.junit.Test;
16+
17+
import com.google.common.collect.Iterables;
18+
import com.google.common.collect.Lists;
19+
20+
public class CollectionsConcatenateUnitTest {
21+
22+
@Test
23+
public void givenUsingJava8_whenConcatenatingUsingConcat_thenCorrect() {
24+
Collection<String> collectionA = asList("S", "T");
25+
Collection<String> collectionB = asList("U", "V");
26+
Collection<String> collectionC = asList("W", "X");
27+
28+
Stream<String> combinedStream = Stream.concat(Stream.concat(collectionA.stream(), collectionB.stream()), collectionC.stream());
29+
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
30+
31+
Assert.assertEquals(asList("S", "T", "U", "V", "W", "X"), collectionCombined);
32+
}
33+
34+
@Test
35+
public void givenUsingJava8_whenConcatenatingUsingflatMap_thenCorrect() {
36+
Collection<String> collectionA = asList("S", "T");
37+
Collection<String> collectionB = asList("U", "V");
38+
39+
Stream<String> combinedStream = Stream.of(collectionA, collectionB).flatMap(Collection::stream);
40+
Collection<String> collectionCombined = combinedStream.collect(Collectors.toList());
41+
42+
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
43+
}
44+
45+
@Test
46+
public void givenUsingGuava_whenConcatenatingUsingIterables_thenCorrect() {
47+
Collection<String> collectionA = asList("S", "T");
48+
Collection<String> collectionB = asList("U", "V");
49+
50+
Iterable<String> combinedIterables = Iterables.unmodifiableIterable(Iterables.concat(collectionA, collectionB));
51+
Collection<String> collectionCombined = Lists.newArrayList(combinedIterables);
52+
53+
Assert.assertEquals(asList("S", "T", "U", "V"), collectionCombined);
54+
}
55+
56+
@Test
57+
public void givenUsingJava7_whenConcatenatingUsingIterables_thenCorrect() {
58+
Collection<String> collectionA = asList("S", "T");
59+
Collection<String> collectionB = asList("U", "V");
60+
61+
Iterable<String> combinedIterables = concat(collectionA, collectionB);
62+
Collection<String> collectionCombined = makeListFromIterable(combinedIterables);
63+
Assert.assertEquals(Arrays.asList("S", "T", "U", "V"), collectionCombined);
64+
}
65+
66+
public static <E> Iterable<E> concat(Iterable<? extends E> list1, Iterable<? extends E> list2) {
67+
return new Iterable<E>() {
68+
public Iterator<E> iterator() {
69+
return new Iterator<E>() {
70+
protected Iterator<? extends E> listIterator = list1.iterator();
71+
protected Boolean checkedHasNext;
72+
protected E nextValue;
73+
private boolean startTheSecond;
74+
75+
public void theNext() {
76+
if (listIterator.hasNext()) {
77+
checkedHasNext = true;
78+
nextValue = listIterator.next();
79+
} else if (startTheSecond)
80+
checkedHasNext = false;
81+
else {
82+
startTheSecond = true;
83+
listIterator = list2.iterator();
84+
theNext();
85+
}
86+
}
87+
88+
public boolean hasNext() {
89+
if (checkedHasNext == null)
90+
theNext();
91+
return checkedHasNext;
92+
}
93+
94+
public E next() {
95+
if (!hasNext())
96+
throw new NoSuchElementException();
97+
checkedHasNext = null;
98+
return nextValue;
99+
}
100+
101+
public void remove() {
102+
listIterator.remove();
103+
}
104+
};
105+
}
106+
};
107+
}
108+
109+
public static <E> List<E> makeListFromIterable(Iterable<E> iter) {
110+
List<E> list = new ArrayList<E>();
111+
for (E item : iter) {
112+
list.add(item);
113+
}
114+
return list;
115+
}
116+
}

‎spring-security-client/README.MD‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,11 @@
1-
###The Course
1+
=========
2+
## Spring Security Authentication/Authorization Example Project
3+
4+
##The Course
25
The "REST With Spring" Classes: http://github.learnspringsecurity.com
6+
7+
### Relevant Articles:
8+
- [Spring Security Manual Authentication](http://www.baeldung.com/spring-security-authentication)
9+
10+
### Build the Project
11+
mvn clean install

‎spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/MvcConfig.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,11 @@
88
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
99
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
1010
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
11+
import org.springframework.context.annotation.Profile;
1112

1213
@Configuration
1314
@EnableWebMvc
15+
@Profile("!manual")
1416
public class MvcConfig extends WebMvcConfigurerAdapter {
1517

1618
public MvcConfig() {
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package org.baeldung.config;
2+
3+
import org.springframework.context.annotation.Configuration;
4+
import org.springframework.context.annotation.Profile;
5+
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
6+
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
7+
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
8+
9+
@Configuration
10+
@EnableWebMvc
11+
@Profile("manual")
12+
public class MvcConfigManual extends WebMvcConfigurerAdapter {
13+
14+
@Override
15+
public void addViewControllers(ViewControllerRegistry registry) {
16+
registry.addViewController("/home").setViewName("home");
17+
registry.addViewController("/").setViewName("home");
18+
registry.addViewController("/hello").setViewName("hello");
19+
registry.addViewController("/login").setViewName("login");
20+
}
21+
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package org.baeldung.config;
2+
3+
import javax.servlet.http.HttpServletRequest;
4+
import javax.servlet.http.HttpServletResponse;
5+
6+
import org.slf4j.Logger;
7+
import org.slf4j.LoggerFactory;
8+
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.security.authentication.AbstractAuthenticationToken;
10+
import org.springframework.security.authentication.AuthenticationManager;
11+
import org.springframework.security.authentication.BadCredentialsException;
12+
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
13+
import org.springframework.security.core.Authentication;
14+
import org.springframework.security.core.context.SecurityContextHolder;
15+
import org.springframework.security.web.authentication.WebAuthenticationDetails;
16+
import org.springframework.stereotype.Controller;
17+
import org.springframework.web.bind.annotation.RequestMapping;
18+
import org.springframework.web.bind.annotation.RequestMethod;
19+
import org.springframework.context.annotation.Profile;
20+
21+
/**
22+
* Manually authenticate a user using Spring Security / Spring Web MVC' (upon successful account registration)
23+
* (http://stackoverflow.com/questions/4664893/how-to-manually-set-an-authenticated-user-in-spring-security-springmvc)
24+
*
25+
* @author jim clayson
26+
*/
27+
@Controller
28+
@Profile("manual")
29+
public class RegistrationController {
30+
private static final Logger logger = LoggerFactory.getLogger(RegistrationController.class);
31+
32+
@Autowired
33+
AuthenticationManager authenticationManager;
34+
35+
/**
36+
* For demo purposes this need only be a GET request method
37+
*
38+
* @param request
39+
* @param response
40+
* @return The view. Page confirming either successful registration (and/or
41+
* successful authentication) or failed registration.
42+
*/
43+
@RequestMapping(value = "/register", method = RequestMethod.GET)
44+
public String registerAndAuthenticate(HttpServletRequest request, HttpServletResponse response) {
45+
logger.debug("registerAndAuthenticate: attempt to register, application should manually authenticate.");
46+
47+
// Mocked values. Potentially could come from an HTML registration form,
48+
// in which case this mapping would match on an HTTP POST, rather than a GET
49+
String username = "user";
50+
String password = "password";
51+
52+
String view = "registrationSuccess";
53+
54+
if (requestQualifiesForManualAuthentication()) {
55+
try {
56+
authenticate(username, password, request, response);
57+
logger.debug("registerAndAuthenticate: authentication completed.");
58+
} catch (BadCredentialsException bce) {
59+
logger.debug("Authentication failure: bad credentials");
60+
bce.printStackTrace();
61+
view = "systemError"; // assume a low-level error, since the registration
62+
// form would have been successfully validated
63+
}
64+
}
65+
66+
return view;
67+
}
68+
69+
private boolean requestQualifiesForManualAuthentication() {
70+
// Some processing to determine that the user requires a Spring Security-recognized,
71+
// application-directed login e.g. successful account registration.
72+
return true;
73+
}
74+
75+
private void authenticate(String username, String password, HttpServletRequest request, HttpServletResponse response) throws BadCredentialsException {
76+
logger.debug("attempting to authenticated, manually ... ");
77+
78+
// create and populate the token
79+
AbstractAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password);
80+
authToken.setDetails(new WebAuthenticationDetails(request));
81+
82+
// This call returns an authentication object, which holds principle and user credentials
83+
Authentication authentication = this.authenticationManager.authenticate(authToken);
84+
85+
// The security context holds the authentication object, and is stored
86+
// in thread local scope.
87+
SecurityContextHolder.getContext().setAuthentication(authentication);
88+
89+
logger.debug("User should now be authenticated.");
90+
}
91+
92+
}

‎spring-security-client/spring-security-thymeleaf-authentication/src/main/java/org/baeldung/config/SecurityConfig.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@
66
import org.springframework.security.config.annotation.web.builders.WebSecurity;
77
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
88
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
9+
import org.springframework.context.annotation.Profile;
910

1011
@Configuration
1112
@EnableWebSecurity
13+
@Profile("!manual")
1214
public class SecurityConfig extends WebSecurityConfigurerAdapter {
1315

1416
@Override
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package org.baeldung.config;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.context.annotation.Profile;
6+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
7+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10+
11+
@Configuration
12+
@EnableWebSecurity
13+
@Profile("manual")
14+
public class WebSecurityConfigManual extends WebSecurityConfigurerAdapter {
15+
16+
@Override
17+
protected void configure(HttpSecurity http) throws Exception {
18+
// @formatter:off
19+
http
20+
.authorizeRequests()
21+
.antMatchers("/", "/home", "/register").permitAll()
22+
.anyRequest().authenticated()
23+
.and()
24+
.formLogin()
25+
.loginPage("/login").permitAll()
26+
.and()
27+
.logout().permitAll();
28+
// @formatter:on
29+
}
30+
31+
@Autowired
32+
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
33+
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
34+
}
35+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<!DOCTYPE html>
2+
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
3+
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
4+
<head>
5+
<title>Hello World!</title>
6+
</head>
7+
<body>
8+
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
9+
<form th:action="@{/logout}" method="post">
10+
<input type="submit" value="Sign Out"/>
11+
</form>
12+
<p>Click <a th:href="@{/home}">here</a> to go to the home page.</p>
13+
14+
</body>
15+
</html>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<!DOCTYPE html>
2+
<html
3+
xmlns="http://www.w3.org/1999/xhtml"
4+
xmlns:th="http://www.thymeleaf.org"
5+
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
6+
<head>
7+
<title>Spring Security Example</title>
8+
</head>
9+
<body>
10+
<h1>Welcome!</h1>
11+
12+
<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
13+
<p sec:authorize="isAnonymous()">Click <a th:href="@{/register}">here</a> to send a dummy registration request, where the application logs you in.</p>
14+
</body>
15+
</html>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<!DOCTYPE html>
2+
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
3+
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
4+
<head>
5+
<title>Spring Security Example </title>
6+
</head>
7+
<body>
8+
<div th:if="${param.error}">
9+
Invalid username and password.
10+
</div>
11+
<div th:if="${param.logout}">
12+
You have been logged out.
13+
</div>
14+
<form th:action="@{/login}" method="post">
15+
<div><label> User Name : <input type="text" name="username"/> </label></div>
16+
<div><label> Password: <input type="password" name="password"/> </label></div>
17+
<div><input type="submit" value="Sign In"/></div>
18+
</form>
19+
<p>Click <a th:href="@{/home}">here</a> to go to the home page.</p>
20+
</body>
21+
</html>

0 commit comments

Comments
 (0)