Merge remote-tracking branch 'upstream/master'

This commit is contained in:
mujah 2016-10-30 12:48:35 +08:00
commit 4a35e16e08
67 changed files with 16629 additions and 36 deletions

View File

@ -0,0 +1,33 @@
package com.baeldung.java.networking.udp;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class UDPTest {
EchoClient client = null;
@Before
public void setup() throws IOException {
new EchoServer().start();
client = new EchoClient();
}
@Test
public void whenCanSendAndReceivePacket_thenCorrect1() {
String echo = client.sendEcho("hello server");
assertEquals("hello server", echo);
echo = client.sendEcho("server is working");
assertFalse(echo.equals("hello server"));
}
@After
public void tearDown() {
client.sendEcho("end");
client.close();
}
}

View File

@ -0,0 +1,104 @@
package com.baeldung.java.networking.url;
import static org.junit.Assert.assertEquals;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.Test;
public class UrlTest {
@Test
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com");
assertEquals("http", url.getProtocol());
}
@Test
public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com");
assertEquals("baeldung.com", url.getHost());
}
@Test
public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException {
URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
assertEquals("/articles?topic=java&version=8", url.getFile());
}
@Test
public void givenUrl_whenCanGetFileName_thenCorrect1() throws MalformedURLException {
URL url = new URL("http://baeldung.com/guidelines.txt");
assertEquals("/guidelines.txt", url.getFile());
}
@Test
public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com/articles?topic=java&version=8");
assertEquals("/articles", url.getPath());
}
@Test
public void givenUrl_whenCanGetQueryParams_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com/articles?topic=java");
assertEquals("topic=java", url.getQuery());
}
@Test
public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com");
assertEquals(-1, url.getPort());
assertEquals(80, url.getDefaultPort());
}
@Test
public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com:8090");
assertEquals(8090, url.getPort());
assertEquals(80, url.getDefaultPort());
}
@Test
public void givenBaseUrl_whenCreatesRelativeUrl_thenCorrect() throws MalformedURLException {
URL baseUrl = new URL("http://baeldung.com");
URL relativeUrl = new URL(baseUrl, "a-guide-to-java-sockets");
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
}
@Test
public void givenAbsoluteUrl_whenIgnoresBaseUrl_thenCorrect() throws MalformedURLException {
URL baseUrl = new URL("http://baeldung.com");
URL relativeUrl = new URL(baseUrl, "http://baeldung.com/a-guide-to-java-sockets");
assertEquals("http://baeldung.com/a-guide-to-java-sockets", relativeUrl.toString());
}
@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
String protocol = "http";
String host = "baeldung.com";
String file = "/guidelines.txt";
URL url = new URL(protocol, host, file);
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
}
@Test
public void givenUrlComponents_whenConstructsCompleteUrl_thenCorrect2() throws MalformedURLException {
String protocol = "http";
String host = "baeldung.com";
String file = "/articles?topic=java&version=8";
URL url = new URL(protocol, host, file);
assertEquals("http://baeldung.com/guidelines.txt", url.toString());
}
@Test
public void givenUrlComponentsWithPort_whenConstructsCompleteUrl_thenCorrect() throws MalformedURLException {
String protocol = "http";
String host = "baeldung.com";
int port = 9000;
String file = "/guidelines.txt";
URL url = new URL(protocol, host, port, file);
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
}
}

View File

@ -0,0 +1,265 @@
package com.baeldung.java.nio2;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import org.junit.Test;
public class FileTest {
private static final String HOME = System.getProperty("user.home");
// checking file or dir
@Test
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
Path p = Paths.get(HOME);
assertTrue(Files.exists(p));
}
@Test
public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
Path p = Paths.get(HOME + "/inexistent_file.txt");
assertTrue(Files.notExists(p));
}
@Test
public void givenExistentDirPath_whenConfirmsNotRegularFile_thenCorrect() {
Path p = Paths.get(HOME);
assertFalse(Files.isRegularFile(p));
}
@Test
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
Path p = Paths.get(HOME);
assertTrue(Files.isReadable(p));
}
@Test
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
Path p = Paths.get(HOME);
assertTrue(Files.isWritable(p));
}
@Test
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
Path p = Paths.get(HOME);
assertTrue(Files.isExecutable(p));
}
@Test
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
Path p1 = Paths.get(HOME);
Path p2 = Paths.get(HOME);
assertTrue(Files.isSameFile(p1, p2));
}
// reading, writing and creating files
// creating file
@Test
public void givenFilePath_whenCreatesNewFile_thenCorrect() throws IOException {
String fileName = "myfile_" + new Date().getTime() + ".txt";
Path p = Paths.get(HOME + "/" + fileName);
assertFalse(Files.exists(p));
Files.createFile(p);
assertTrue(Files.exists(p));
}
@Test
public void givenDirPath_whenCreatesNewDir_thenCorrect() throws IOException {
String dirName = "myDir_" + new Date().getTime();
Path p = Paths.get(HOME + "/" + dirName);
assertFalse(Files.exists(p));
Files.createDirectory(p);
assertTrue(Files.exists(p));
assertFalse(Files.isRegularFile(p));
assertTrue(Files.isDirectory(p));
}
@Test
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() {
String dirName = "myDir_" + new Date().getTime() + "/subdir";
Path p = Paths.get(HOME + "/" + dirName);
assertFalse(Files.exists(p));
try {
Files.createDirectory(p);
} catch (IOException e) {
assertTrue(e instanceof NoSuchFileException);
}
}
@Test
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
Path dir = Paths.get(HOME + "/myDir_" + new Date().getTime());
Path subdir = dir.resolve("subdir");
assertFalse(Files.exists(dir));
assertFalse(Files.exists(subdir));
Files.createDirectories(subdir);
assertTrue(Files.exists(dir));
assertTrue(Files.exists(subdir));
}
@Test
public void givenFilePath_whenCreatesTempFile_thenCorrect() throws IOException {
String prefix = "log_";
String suffix = ".txt";
Path p = Paths.get(HOME + "/");
p = Files.createTempFile(p, prefix, suffix);
// like log_8821081429012075286.txt
assertTrue(Files.exists(p));
}
@Test
public void givenFilePath_whenCreatesTempFileWithDefaultsNaming_thenCorrect() throws IOException {
Path p = Paths.get(HOME + "/");
p = Files.createTempFile(p, null, null);
// like 8600179353689423985.tmp
System.out.println(p);
assertTrue(Files.exists(p));
}
@Test
public void givenNoFilePath_whenCreatesTempFileInTempDir_thenCorrect() throws IOException {
Path p = Files.createTempFile(null, null);
// like C:\Users\new\AppData\Local\Temp\6100927974988978748.tmp
assertTrue(Files.exists(p));
}
// delete file
@Test
public void givenPath_whenDeletes_thenCorrect() throws IOException {
Path p = Paths.get(HOME + "/fileToDelete.txt");
assertFalse(Files.exists(p));
Files.createFile(p);
assertTrue(Files.exists(p));
Files.delete(p);
assertFalse(Files.exists(p));
}
@Test
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
Path dir = Paths.get(HOME + "/emptyDir" + new Date().getTime());
Files.createDirectory(dir);
assertTrue(Files.exists(dir));
Path file = dir.resolve("file.txt");
Files.createFile(file);
try {
Files.delete(dir);
} catch (IOException e) {
assertTrue(e instanceof DirectoryNotEmptyException);
}
assertTrue(Files.exists(dir));
}
@Test
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
Path p = Paths.get(HOME + "/inexistentFile.txt");
assertFalse(Files.exists(p));
try {
Files.delete(p);
} catch (IOException e) {
assertTrue(e instanceof NoSuchFileException);
}
}
@Test
public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
Path p = Paths.get(HOME + "/inexistentFile.txt");
assertFalse(Files.exists(p));
Files.deleteIfExists(p);
}
// copy file
@Test
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
Files.createDirectory(dir1);
Files.createDirectory(dir2);
Path file1 = dir1.resolve("filetocopy.txt");
Path file2 = dir2.resolve("filetocopy.txt");
Files.createFile(file1);
assertTrue(Files.exists(file1));
assertFalse(Files.exists(file2));
Files.copy(file1, file2);
assertTrue(Files.exists(file2));
}
@Test
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
Files.createDirectory(dir1);
Files.createDirectory(dir2);
Path file1 = dir1.resolve("filetocopy.txt");
Path file2 = dir2.resolve("filetocopy.txt");
Files.createFile(file1);
Files.createFile(file2);
assertTrue(Files.exists(file1));
assertTrue(Files.exists(file2));
try {
Files.copy(file1, file2);
} catch (IOException e) {
assertTrue(e instanceof FileAlreadyExistsException);
}
Files.copy(file1, file2, StandardCopyOption.REPLACE_EXISTING);
}
// moving files
@Test
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
Files.createDirectory(dir1);
Files.createDirectory(dir2);
Path file1 = dir1.resolve("filetocopy.txt");
Path file2 = dir2.resolve("filetocopy.txt");
Files.createFile(file1);
assertTrue(Files.exists(file1));
assertFalse(Files.exists(file2));
Files.move(file1, file2);
assertTrue(Files.exists(file2));
assertFalse(Files.exists(file1));
}
@Test
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
Files.createDirectory(dir1);
Files.createDirectory(dir2);
Path file1 = dir1.resolve("filetocopy.txt");
Path file2 = dir2.resolve("filetocopy.txt");
Files.createFile(file1);
Files.createFile(file2);
assertTrue(Files.exists(file1));
assertTrue(Files.exists(file2));
try {
Files.move(file1, file2);
} catch (IOException e) {
assertTrue(e instanceof FileAlreadyExistsException);
}
Files.move(file1, file2, StandardCopyOption.REPLACE_EXISTING);
assertTrue(Files.exists(file2));
assertFalse(Files.exists(file1));
}
}

View File

@ -0,0 +1,197 @@
package com.baeldung.java.nio2;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import org.junit.Test;
public class PathTest {
private static final String HOME = System.getProperty("user.home");
// creating a path
@Test
public void givenPathString_whenCreatesPathObject_thenCorrect() {
Path p = Paths.get("/articles/baeldung");
assertEquals("\\articles\\baeldung", p.toString());
}
@Test
public void givenPathParts_whenCreatesPathObject_thenCorrect() {
Path p = Paths.get("/articles", "baeldung");
assertEquals("\\articles\\baeldung", p.toString());
}
// retrieving path info
@Test
public void givenPath_whenRetrievesFileName_thenCorrect() {
Path p = Paths.get("/articles/baeldung/logs");
assertEquals("logs", p.getFileName().toString());
}
@Test
public void givenPath_whenRetrievesNameByIndex_thenCorrect() {
Path p = Paths.get("/articles/baeldung/logs");
assertEquals("articles", p.getName(0).toString());
assertEquals("baeldung", p.getName(1).toString());
assertEquals("logs", p.getName(2).toString());
}
@Test
public void givenPath_whenCountsParts_thenCorrect() {
Path p = Paths.get("/articles/baeldung/logs");
assertEquals(3, p.getNameCount());
}
@Test
public void givenPath_whenCanRetrieveSubsequenceByIndex_thenCorrect() {
Path p = Paths.get("/articles/baeldung/logs");
assertEquals("articles", p.subpath(0, 1).toString());
assertEquals("articles\\baeldung", p.subpath(0, 2).toString());
assertEquals("articles\\baeldung\\logs", p.subpath(0, 3).toString());
assertEquals("baeldung", p.subpath(1, 2).toString());
assertEquals("baeldung\\logs", p.subpath(1, 3).toString());
assertEquals("logs", p.subpath(2, 3).toString());
}
@Test
public void givenPath_whenRetrievesParent_thenCorrect() {
Path p1 = Paths.get("/articles/baeldung/logs");
Path p2 = Paths.get("/articles/baeldung");
Path p3 = Paths.get("/articles");
Path p4 = Paths.get("/");
assertEquals("\\articles\\baeldung", p1.getParent().toString());
assertEquals("\\articles", p2.getParent().toString());
assertEquals("\\", p3.getParent().toString());
assertEquals(null, p4.getParent());
}
@Test
public void givenPath_whenRetrievesRoot_thenCorrect() {
Path p1 = Paths.get("/articles/baeldung/logs");
Path p2 = Paths.get("c:/articles/baeldung/logs");
assertEquals("\\", p1.getRoot().toString());
assertEquals("c:\\", p2.getRoot().toString());
}
// removing redundancies from path
@Test
public void givenPath_whenRemovesRedundancies_thenCorrect1() {
Path p = Paths.get("/home/./baeldung/articles");
p = p.normalize();
assertEquals("\\home\\baeldung\\articles", p.toString());
}
@Test
public void givenPath_whenRemovesRedundancies_thenCorrect2() {
Path p = Paths.get("/home/baeldung/../articles");
p = p.normalize();
assertEquals("\\home\\articles", p.toString());
}
// converting a path
@Test
public void givenPath_whenConvertsToBrowseablePath_thenCorrect() {
Path p = Paths.get("/home/baeldung/articles.html");
URI uri = p.toUri();
assertEquals("file:///E:/home/baeldung/articles.html", uri.toString());
}
@Test
public void givenPath_whenConvertsToAbsolutePath_thenCorrect() {
Path p = Paths.get("/home/baeldung/articles.html");
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
}
@Test
public void givenAbsolutePath_whenRetainsAsAbsolute_thenCorrect() {
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
}
@Test
public void givenExistingPath_whenGetsRealPathToFile_thenCorrect() throws IOException {
Path p = Paths.get(HOME);
assertEquals(HOME, p.toRealPath().toString());
}
@Test
public void givenInExistentPath_whenFailsToConvert_thenCorrect() {
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
try {
p.toRealPath();
} catch (IOException e) {
assertTrue(true);
}
}
// joining paths
@Test
public void givenTwoPaths_whenJoinsAndResolves_thenCorrect() throws IOException {
Path p = Paths.get("/baeldung/articles");
assertEquals("\\baeldung\\articles\\java", p.resolve("java").toString());
}
@Test
public void givenAbsolutePath_whenResolutionRetainsIt_thenCorrect() throws IOException {
Path p = Paths.get("/baeldung/articles");
assertEquals("C:\\baeldung\\articles\\java", p.resolve("C:\\baeldung\\articles\\java").toString());
}
@Test
public void givenPathWithRoot_whenResolutionRetainsIt_thenCorrect2() throws IOException {
Path p = Paths.get("/baeldung/articles");
assertEquals("\\java", p.resolve("/java").toString());
}
// creating a path between 2 paths
@Test
public void givenSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
Path p1 = Paths.get("articles");
Path p2 = Paths.get("authors");
assertEquals("..\\authors", p1.relativize(p2).toString());
assertEquals("..\\articles", p2.relativize(p1).toString());
}
@Test
public void givenNonSiblingPaths_whenCreatesPathToOther_thenCorrect() throws IOException {
Path p1 = Paths.get("/baeldung");
Path p2 = Paths.get("/baeldung/authors/articles");
assertEquals("authors\\articles", p1.relativize(p2).toString());
assertEquals("..\\..", p2.relativize(p1).toString());
}
// comparing 2 paths
@Test
public void givenTwoPaths_whenTestsEquality_thenCorrect() throws IOException {
Path p1 = Paths.get("/baeldung/articles");
Path p2 = Paths.get("/baeldung/articles");
Path p3 = Paths.get("/baeldung/authors");
assertTrue(p1.equals(p2));
assertFalse(p1.equals(p3));
}
@Test
public void givenPath_whenInspectsStart_thenCorrect() {
Path p1 = Paths.get("/baeldung/articles");
assertTrue(p1.startsWith("/baeldung"));
}
@Test
public void givenPath_whenInspectsEnd_thenCorrect() {
Path p1 = Paths.get("/baeldung/articles");
assertTrue(p1.endsWith("articles"));
}
}

View File

@ -19,13 +19,13 @@ import org.junit.Before;
import org.junit.Test;
public class JavaFolderSizeUnitTest {
private final long EXPECTED_SIZE = 381;
private final long EXPECTED_SIZE = 24;
private String path;
@Before
public void init() {
final String separator = File.separator;
path = String.format("src%stest%sresources", separator, separator);
path = String.format("src%stest%sresources%stestFolder", separator, separator, separator);
}
@Test

View File

@ -76,6 +76,7 @@ public class JavaFileUnitTest {
@Test
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/test/resources/fileMoved_apache2.txt"));
}

View File

@ -0,0 +1 @@
Hello world

View File

@ -0,0 +1 @@
Hello world !

View File

@ -19,6 +19,7 @@ class FirstTest {
.sum() > 5, "Sum should be greater than 5");
}
@Disabled("test to show MultipleFailuresError")
@Test
void groupAssertions() {
int[] numbers = {0, 1, 2, 3, 4};

View File

@ -3,6 +3,9 @@ server.port=8082
eureka.instance.hostname=localhost
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/
eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
spring.redis.host=localhost
spring.redis.port=6379

View File

@ -3,8 +3,21 @@ server.port=8080
eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/
management.security.sessions=always
zuul.routes.resource.path=/resource/**
hystrix.command.resource.execution.isolation.thread.timeoutInMilliseconds: 5000
zuul.routes.resource.sensitive-headers=Set-Cookie,Authorization
hystrix.command.resource.execution.isolation.thread.timeoutInMilliseconds=600000
zuul.routes.discovery.path=/discovery/**
zuul.routes.discovery.sensitive-headers=Set-Cookie,Authorization
zuul.routes.discovery.url=http://localhost:8082
hystrix.command.discovery.execution.isolation.thread.timeoutInMilliseconds=600000
logging.level.org.springframework.web.=debug
logging.level.org.springframework.security=debug
logging.level.org.springframework.cloud.netflix.zuul=debug
spring.redis.host=localhost
spring.redis.port=6379

View File

@ -2,7 +2,16 @@ spring.application.name=resource
server.port=8083
resource.returnString=hello cloud
resource.user.returnString=hello cloud user
resource.admin.returnString=hello cloud admin
eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/
management.security.sessions=never
logging.level.org.springframework.web.=debug
logging.level.org.springframework.security=debug
spring.redis.host=localhost
spring.redis.port=6379

View File

@ -28,6 +28,10 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
@ -48,6 +52,15 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.cloud.integration.config;
package com.baeldung.spring.cloud.bootstrap.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@ -0,0 +1,29 @@
package com.baeldung.spring.cloud.bootstrap.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication().withUser("configUser").password("configPassword").roles("SYSTEM");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().hasRole("SYSTEM")
.and()
.httpBasic()
.and()
.csrf()
.disable();
}
}

View File

@ -5,4 +5,4 @@ spring.cloud.config.server.git.uri=file:///${user.home}/application-config
eureka.client.region = default
eureka.client.registryFetchIntervalSeconds = 5
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka
eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/

View File

@ -28,6 +28,20 @@
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
@ -48,6 +62,15 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.cloud.integration.discovery;
package com.baeldung.spring.cloud.bootstrap.discovery;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

View File

@ -0,0 +1,65 @@
package com.baeldung.spring.cloud.bootstrap.discovery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.http.SessionCreationPolicy;
@Configuration
@EnableWebSecurity
@Order(1)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication().withUser("discUser").password("discPassword").roles("SYSTEM");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
.and()
.requestMatchers()
.antMatchers("/eureka/**")
.and()
.authorizeRequests()
.antMatchers("/eureka/**").hasRole("SYSTEM")
.anyRequest().denyAll()
.and()
.httpBasic()
.and()
.csrf()
.disable();
}
@Configuration
//no order tag means this is the last security filter to be evaluated
public static class AdminSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication();
}
@Override protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.httpBasic()
.disable()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/").hasRole("ADMIN")
.antMatchers("/info","/health").authenticated()
.anyRequest().denyAll()
.and()
.csrf()
.disable();
}
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.spring.cloud.bootstrap.discovery;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
@EnableRedisHttpSession
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
}

View File

@ -1,2 +1,4 @@
spring.cloud.config.name=discovery
spring.cloud.config.uri=http://localhost:8081
spring.cloud.config.uri=http://localhost:8081
spring.cloud.config.username=configUser
spring.cloud.config.password=configPassword

View File

@ -27,6 +27,21 @@
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@ -52,6 +67,15 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,40 @@
package com.baeldung.spring.cloud.bootstrap.gateway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClientSpecification;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
@Autowired(required = false)
private List<RibbonClientSpecification> configurations = new ArrayList<>();
@Bean
@LoadBalanced RestTemplate restTemplate(){
return new RestTemplate();
}
@Bean
public SpringClientFactory springClientFactory() {
SpringClientFactory factory = new SpringClientFactory();
factory.setConfigurations(this.configurations);
return factory;
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.spring.cloud.bootstrap.gateway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER")
.and()
.withUser("admin").password("admin").roles("ADMIN");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/resource/hello/cloud").permitAll()
.antMatchers("/eureka/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.logout().permitAll()
.logoutSuccessUrl("/resource/hello/cloud").permitAll()
.and()
.csrf()
.disable();
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.spring.cloud.bootstrap.gateway;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.RedisFlushMode;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
@Configuration
@EnableRedisHttpSession(redisFlushMode = RedisFlushMode.IMMEDIATE)
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
}

View File

@ -0,0 +1,47 @@
package com.baeldung.spring.cloud.bootstrap.gateway.filter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.Session;
import org.springframework.session.SessionRepository;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpSession;
@Component
public class SessionSavingZuulPreFilter extends ZuulFilter {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private SessionRepository repository;
@Override public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext context = RequestContext.getCurrentContext();
HttpSession httpSession = context.getRequest().getSession();
Session session = repository.getSession(httpSession.getId());
context.addZuulRequestHeader("Cookie", "SESSION=" + httpSession.getId());
log.info("ZuulPreFilter session proxy: {}", session.getId());
return null;
}
@Override public String filterType() {
return "pre";
}
@Override public int filterOrder() {
return 0;
}
}

View File

@ -1,15 +0,0 @@
package com.baeldung.spring.cloud.integration.resource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}

View File

@ -1,5 +1,7 @@
spring.cloud.config.name=gateway
spring.cloud.config.discovery.service-id=config
spring.cloud.config.discovery.enabled=true
spring.cloud.config.username=configUser
spring.cloud.config.password=configPassword
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/
eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 83 KiB

File diff suppressed because it is too large Load Diff

After

Width:  |  Height:  |  Size: 362 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

File diff suppressed because one or more lines are too long

View File

@ -27,6 +27,21 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
@ -52,6 +67,15 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.cloud.integration.resource;
package com.baeldung.spring.cloud.bootstrap.resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
@ -18,8 +18,24 @@ public class ResourceApplication {
@Value("${resource.returnString}")
private String returnString;
@Value("${resource.user.returnString}")
private String userReturnString;
@Value("${resource.admin.returnString}")
private String adminReturnString;
@RequestMapping("/hello/cloud")
public String getString() {
return returnString;
}
@RequestMapping("/hello/user")
public String getUserString() {
return userReturnString;
}
@RequestMapping("/hello/admin")
public String getAdminString() {
return adminReturnString;
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.spring.cloud.bootstrap.resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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;
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal1(AuthenticationManagerBuilder auth) throws Exception {
//try in memory auth with no users to support the case that this will allow for users that are logged in to go anywhere
auth.inMemoryAuthentication();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.disable()
.authorizeRequests()
.antMatchers("/hello/cloud").permitAll()
.antMatchers("/hello/user").hasAnyRole("USER", "ADMIN")
.antMatchers("/hello/admin").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.csrf()
.disable();
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.spring.cloud.bootstrap.resource;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
@Configuration
@EnableRedisHttpSession
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
}

View File

@ -1,5 +1,7 @@
spring.cloud.config.name=resource
spring.cloud.config.discovery.service-id=config
spring.cloud.config.discovery.enabled=true
spring.cloud.config.username=configUser
spring.cloud.config.password=configPassword
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/
eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.data.es.config;
package com.baeldung.spring.data.dynamodb.config;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
@ -11,7 +11,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
@Configuration
@EnableDynamoDBRepositories(basePackages = "com.baeldung.spring.data.es.repositories")
@EnableDynamoDBRepositories(basePackages = "com.baeldung.spring.data.dynamodb.repositories")
public class DynamoDBConfig {
@Value("${amazon.dynamodb.endpoint}")

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.data.es.model;
package com.baeldung.spring.data.dynamodb.model;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAttribute;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBAutoGeneratedKey;

View File

@ -1,6 +1,6 @@
package com.baeldung.spring.data.es.repositories;
package com.baeldung.spring.data.dynamodb.repositories;
import com.baeldung.spring.data.es.model.ProductInfo;
import com.baeldung.spring.data.dynamodb.model.ProductInfo;
import org.socialsignin.spring.data.dynamodb.repository.EnableScan;
import org.springframework.data.repository.CrudRepository;

View File

@ -1,4 +1,4 @@
package com.baeldung.spring.data.es.repository;
package com.baeldung.spring.data.dynamodb.repository;
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
@ -6,9 +6,10 @@ import com.amazonaws.services.dynamodbv2.model.CreateTableRequest;
import com.amazonaws.services.dynamodbv2.model.ProvisionedThroughput;
import com.amazonaws.services.dynamodbv2.model.ResourceInUseException;
import com.baeldung.Application;
import com.baeldung.spring.data.es.model.ProductInfo;
import com.baeldung.spring.data.es.repositories.ProductInfoRepository;
import com.baeldung.spring.data.dynamodb.model.ProductInfo;
import com.baeldung.spring.data.dynamodb.repositories.ProductInfoRepository;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -43,6 +44,7 @@ public class ProductInfoRepositoryIntegrationTest {
private static final String EXPECTED_PRICE = "50";
@Before
@Ignore //TODO Remove Ignore annotations when running locally with Local DynamoDB instance
public void setup() throws Exception {
try {
@ -62,6 +64,7 @@ public class ProductInfoRepositoryIntegrationTest {
}
@Test
@Ignore //TODO Remove Ignore annotations when running locally with Local DynamoDB instance
public void givenItemWithExpectedCost_whenRunFindAll_thenItemIsFound() {
ProductInfo productInfo = new ProductInfo(EXPECTED_COST, EXPECTED_PRICE);

View File

@ -0,0 +1,18 @@
package org.baeldung.security.filter;
import org.springframework.web.filter.GenericFilterBean;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
public class CustomFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung.security.filter.configuration;
import org.baeldung.security.filter.CustomFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
@Configuration
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterAfter(new CustomFilter(), BasicAuthenticationFilter.class);
}
}

View File

@ -12,6 +12,7 @@
<http-basic entry-point-ref="myBasicAuthenticationEntryPoint"/>
<custom-filter after="BASIC_AUTH_FILTER" ref="myFilter" />
</http>
<authentication-manager>
@ -22,4 +23,6 @@
</authentication-provider>
</authentication-manager>
<beans:bean id="myFilter" class="org.baeldung.security.filter.CustomFilter"/>
</beans:beans>