Merge remote-tracking branch 'upstream/master' into craedel-log4j2

This commit is contained in:
Christian Rädel 2016-11-01 02:33:26 +01:00
commit fe01c870db
143 changed files with 17141 additions and 532 deletions

View File

@ -97,6 +97,14 @@
<version>8.0.2</version>
</dependency>
<dependency>
<groupId>org.dbdoclet</groupId>
<artifactId>herold</artifactId>
<version>6.1.0</version>
<scope>system</scope>
<systemPath>${basedir}/src/test/resources/jars/herold.jar</systemPath>
</dependency>
<dependency>
<groupId>net.sf.jtidy</groupId>
<artifactId>jtidy</artifactId>
@ -132,7 +140,8 @@
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
@ -141,6 +150,42 @@
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<exclude>**/*LiveTest.java</exclude>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>

View File

@ -25,7 +25,7 @@ import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.tidy.Tidy;
public class ApacheFOPConvertHTMLTest {
public class ApacheFOPConvertHTMLIntegrationTest {
private String inputFile = "src/test/resources/input.html";
private String style = "src/test/resources/xhtml2fo.xsl";
private String style1 = "src/test/resources/docbook-xsl/fo/docbook.xsl";

View File

@ -30,7 +30,7 @@ import org.dbdoclet.trafo.script.Script;
import org.junit.Test;
import org.w3c.dom.Document;
public class ApacheFOPHeroldTest {
public class ApacheFOPHeroldLiveTest {
private String[] inputUrls = {// @formatter:off
"http://www.baeldung.com/2011/10/20/bootstraping-a-web-application-with-spring-3-1-and-java-based-configuration-part-1/",
"http://www.baeldung.com/2011/10/25/building-a-restful-web-service-with-spring-3-1-and-java-based-configuration-part-2/",

View File

@ -279,6 +279,41 @@
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- persistence -->

View File

@ -14,7 +14,6 @@ public class Screenshot {
}
public void getScreenshot(int timeToWait) throws Exception {
Thread.sleep(timeToWait);
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(rectangle);

View File

@ -1,7 +1,5 @@
package org.baeldung.equalshashcode.entities;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@ -10,7 +8,7 @@ public class ComplexClass {
private List<?> genericList;
private Set<Integer> integerSet;
public ComplexClass(ArrayList<?> genericArrayList, HashSet<Integer> integerHashSet) {
public ComplexClass(List<?> genericArrayList, Set<Integer> integerHashSet) {
super();
this.genericList = genericArrayList;
this.integerSet = integerHashSet;

View File

@ -0,0 +1 @@
Hello World from fileTest.txt!!!

View File

@ -4,7 +4,7 @@ import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class CharToStringTest {
public class CharToStringUnitTest {
@Test
public void givenChar_whenCallingStringValueOf_shouldConvertToString() {

View File

@ -36,7 +36,7 @@ import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class Java8CollectorsTest {
public class Java8CollectorsUnitTest {
private final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");

View File

@ -7,7 +7,7 @@ import java.time.Month;
import org.junit.Assert;
import org.junit.Test;
public class UseLocalDateTimeTest {
public class UseLocalDateTimeUnitTest {
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();

View File

@ -7,7 +7,7 @@ import java.time.LocalDateTime;
import org.junit.Assert;
import org.junit.Test;
public class UseLocalDateTest {
public class UseLocalDateUnitTest {
UseLocalDate useLocalDate = new UseLocalDate();

View File

@ -5,7 +5,7 @@ import java.time.LocalTime;
import org.junit.Assert;
import org.junit.Test;
public class UseLocalTimeTest {
public class UseLocalTimeUnitTest {
UseLocalTime useLocalTime = new UseLocalTime();

View File

@ -6,7 +6,7 @@ import java.time.Period;
import org.junit.Assert;
import org.junit.Test;
public class UsePeriodTest {
public class UsePeriodUnitTest {
UsePeriod usingPeriod=new UsePeriod();
@Test

View File

@ -7,7 +7,7 @@ import java.time.ZonedDateTime;
import org.junit.Assert;
import org.junit.Test;
public class UseZonedDateTimeTest {
public class UseZonedDateTimeUnitTest {
UseZonedDateTime zonedDateTime=new UseZonedDateTime();

View File

@ -13,7 +13,7 @@ import java.util.function.BiFunction;
import static com.baeldung.doublecolon.ComputerUtils.*;
public class TestComputerUtils {
public class ComputerUtilsUnitTest {
@Before
public void setup() {

View File

@ -7,7 +7,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
@ -15,13 +14,13 @@ import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class EncoderDecoder {
import static java.util.stream.Collectors.joining;
private static final String URL = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoder.class);
public class EncoderDecoderUnitTest {
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoderUnitTest.class);
private static final String testUrl = "http://www.baeldung.com?key1=value+1&key2=value%40%21%242&key3=value%253";
private String encodeValue(String value) {
String encoded = null;
@ -46,7 +45,7 @@ public class EncoderDecoder {
@Test
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
URL url = new URL(URL);
URL url = new URL(testUrl);
Assert.assertThat(url.getProtocol(), CoreMatchers.is("http"));
Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com"));
@ -60,25 +59,25 @@ public class EncoderDecoder {
requestParams.put("key2", "value@!$2");
requestParams.put("key3", "value%3");
String encodedQuery = requestParams.keySet().stream()
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
.collect(Collectors.joining("&"));
String encodedURL = "http://www.baeldung.com?" + encodedQuery;
String encodedURL = requestParams.keySet().stream()
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
.collect(joining("&", "http://www.baeldung.com?", ""));
Assert.assertThat(URL, CoreMatchers.is(encodedURL));
Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
}
@Test
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
URL url = new URL(URL);
URL url = new URL(testUrl);
String query = url.getQuery();
String decodedQuery = Arrays.stream(query.split("&"))
.map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1]))
.collect(Collectors.joining("&"));
.map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1]))
.collect(joining("&"));
Assert.assertEquals(
"http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
"http://www.baeldung.com?key1=value 1&key2=value@!$2&key3=value%3", url.getProtocol() + "://" + url.getHost() + "?" + decodedQuery);
}
}

View File

@ -9,7 +9,7 @@ import java.util.List;
import static junit.framework.TestCase.assertTrue;
public class PizzaTest {
public class PizzaUnitTest {
@Test
public void givenPizaOrder_whenReady_thenDeliverable() {

View File

@ -1,11 +1,5 @@
package com.baeldung.file;
import org.apache.commons.io.FileUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
@ -20,7 +14,13 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class FileOperationsTest {
import org.apache.commons.io.FileUtils;
import org.hamcrest.CoreMatchers;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
public class FileOperationsUnitTest {
@Test
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
@ -30,15 +30,15 @@ public class FileOperationsTest {
File file = new File(classLoader.getResource("fileTest.txt").getFile());
InputStream inputStream = new FileInputStream(file);
String data = readFromInputStream(inputStream);
Assert.assertEquals(expectedData, data.trim());
}
@Test
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
String expectedData = "Hello World from fileTest.txt!!!";
Class clazz = FileOperationsTest.class;
Class clazz = FileOperationsUnitTest.class;
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
String data = readFromInputStream(inputStream);
@ -69,44 +69,44 @@ public class FileOperationsTest {
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
}
@Test
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
String expectedData = "Hello World from fileTest.txt!!!";
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileTest.txt").getFile());
String data = FileUtils.readFileToString(file);
Assert.assertEquals(expectedData, data.trim());
}
@Test
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
String expectedData = "Hello World from fileTest.txt!!!";
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
byte[] fileBytes = Files.readAllBytes(path);
String data = new String(fileBytes);
Assert.assertEquals(expectedData, data.trim());
}
@Test
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
String expectedData = "Hello World from fileTest.txt!!!";
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
StringBuilder data = new StringBuilder();
Stream<String> lines = Files.lines(path);
lines.forEach(line -> data.append(line).append("\n"));
lines.close();
Assert.assertEquals(expectedData, data.toString().trim());
}
private String readFromInputStream(InputStream inputStream) throws IOException {
StringBuilder resultStringBuilder = new StringBuilder();
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {

View File

@ -10,7 +10,7 @@ import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class UDPTest {
public class UDPIntegrationTest {
private EchoClient client;
@Before

View File

@ -7,97 +7,97 @@ import java.net.URL;
import org.junit.Test;
public class UrlTest {
public class UrlUnitTest {
@Test
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException {
URL url = new URL("http://baeldung.com");
final 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");
final 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");
final 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");
final 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");
final 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");
final 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");
final 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");
final 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");
final URL baseUrl = new URL("http://baeldung.com");
final 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");
final URL baseUrl = new URL("http://baeldung.com");
final 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);
final String protocol = "http";
final String host = "baeldung.com";
final String file = "/guidelines.txt";
final 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());
final String protocol = "http";
final String host = "baeldung.com";
final String file = "/articles?topic=java&version=8";
final URL url = new URL(protocol, host, file);
assertEquals("http://baeldung.com/articles?topic=java&version=8", 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);
final String protocol = "http";
final String host = "baeldung.com";
final int port = 9000;
final String file = "/guidelines.txt";
final URL url = new URL(protocol, host, port, file);
assertEquals("http://baeldung.com:9000/guidelines.txt", url.toString());
}

View File

@ -6,7 +6,7 @@ import java.io.IOException;
import org.junit.Test;
public class EchoTest {
public class NioEchoIntegrationTest {
@Test
public void givenClient_whenServerEchosMessage_thenCorrect() throws IOException, InterruptedException {

View File

@ -0,0 +1,250 @@
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(expected = NoSuchFileException.class)
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() throws IOException {
String dirName = "myDir_" + new Date().getTime() + "/subdir";
Path p = Paths.get(HOME + "/" + dirName);
assertFalse(Files.exists(p));
Files.createDirectory(p);
}
@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
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(expected = DirectoryNotEmptyException.class)
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);
Files.delete(dir);
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(expected = FileAlreadyExistsException.class)
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));
Files.copy(file1, file2);
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(expected = FileAlreadyExistsException.class)
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));
Files.move(file1, file2);
Files.move(file1, file2, StandardCopyOption.REPLACE_EXISTING);
assertTrue(Files.exists(file2));
assertFalse(Files.exists(file1));
}
}

View File

@ -0,0 +1,195 @@
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.NoSuchFileException;
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(expected = NoSuchFileException.class)
public void givenInExistentPath_whenFailsToConvert_thenCorrect() throws IOException {
Path p = Paths.get("E:\\home\\baeldung\\articles.html");
p.toRealPath();
}
// 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

@ -1,32 +1,35 @@
package com.baeldung.java.reflection;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import static org.junit.Assert.*;
import org.junit.Test;
public class ReflectionUnitTest {
@Test
public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
Object person = new Person();
Field[] fields = person.getClass().getDeclaredFields();
final Object person = new Person();
final Field[] fields = person.getClass().getDeclaredFields();
List<String> actualFieldNames = getFieldNames(fields);
final List<String> actualFieldNames = getFieldNames(fields);
assertTrue(Arrays.asList("name", "age").containsAll(actualFieldNames));
}
@Test
public void givenObject_whenGetsClassName_thenCorrect() {
Object goat = new Goat("goat");
Class<?> clazz = goat.getClass();
final Object goat = new Goat("goat");
final Class<?> clazz = goat.getClass();
assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
@ -35,7 +38,7 @@ public class ReflectionUnitTest {
@Test
public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException {
Class<?> clazz = Class.forName("com.baeldung.java.reflection.Goat");
final Class<?> clazz = Class.forName("com.baeldung.java.reflection.Goat");
assertEquals("Goat", clazz.getSimpleName());
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
@ -44,10 +47,10 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException {
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
int goatMods = goatClass.getModifiers();
int animalMods = animalClass.getModifiers();
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final int goatMods = goatClass.getModifiers();
final int animalMods = animalClass.getModifiers();
assertTrue(Modifier.isPublic(goatMods));
assertTrue(Modifier.isAbstract(animalMods));
@ -56,20 +59,20 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsPackageInfo_thenCorrect() {
Goat goat = new Goat("goat");
Class<?> goatClass = goat.getClass();
Package pkg = goatClass.getPackage();
final Goat goat = new Goat("goat");
final Class<?> goatClass = goat.getClass();
final Package pkg = goatClass.getPackage();
assertEquals("com.baeldung.java.reflection", pkg.getName());
}
@Test
public void givenClass_whenGetsSuperClass_thenCorrect() {
Goat goat = new Goat("goat");
String str = "any string";
final Goat goat = new Goat("goat");
final String str = "any string";
Class<?> goatClass = goat.getClass();
Class<?> goatSuperClass = goatClass.getSuperclass();
final Class<?> goatClass = goat.getClass();
final Class<?> goatSuperClass = goatClass.getSuperclass();
assertEquals("Animal", goatSuperClass.getSimpleName());
assertEquals("Object", str.getClass().getSuperclass().getSimpleName());
@ -78,10 +81,10 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
Class<?>[] goatInterfaces = goatClass.getInterfaces();
Class<?>[] animalInterfaces = animalClass.getInterfaces();
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Class<?>[] goatInterfaces = goatClass.getInterfaces();
final Class<?>[] animalInterfaces = animalClass.getInterfaces();
assertEquals(1, goatInterfaces.length);
assertEquals(1, animalInterfaces.length);
@ -91,8 +94,8 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException {
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
Constructor<?>[] constructors = goatClass.getConstructors();
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
final Constructor<?>[] constructors = goatClass.getConstructors();
assertEquals(1, constructors.length);
assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName());
@ -100,10 +103,10 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException {
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
Field[] fields = animalClass.getDeclaredFields();
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Field[] fields = animalClass.getDeclaredFields();
List<String> actualFields = getFieldNames(fields);
final List<String> actualFields = getFieldNames(fields);
assertEquals(2, actualFields.size());
assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY")));
@ -111,41 +114,41 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
Method[] methods = animalClass.getDeclaredMethods();
List<String> actualMethods = getMethodNames(methods);
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
final Method[] methods = animalClass.getDeclaredMethods();
final List<String> actualMethods = getMethodNames(methods);
assertEquals(4, actualMethods.size());
assertEquals(3, actualMethods.size());
assertTrue(actualMethods.containsAll(Arrays.asList("getName", "setName", "getSound")));
}
@Test
public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Constructor<?>[] constructors = birdClass.getConstructors();
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Constructor<?>[] constructors = birdClass.getConstructors();
assertEquals(3, constructors.length);
}
@Test
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Constructor<?> cons1 = birdClass.getConstructor();
Constructor<?> cons2 = birdClass.getConstructor(String.class);
Constructor<?> cons3 = birdClass.getConstructor(String.class, boolean.class);
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
birdClass.getConstructor();
birdClass.getConstructor(String.class);
birdClass.getConstructor(String.class, boolean.class);
}
@Test
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Constructor<?> cons1 = birdClass.getConstructor();
Constructor<?> cons2 = birdClass.getConstructor(String.class);
Constructor<?> cons3 = birdClass.getConstructor(String.class, boolean.class);
final Constructor<?> cons1 = birdClass.getConstructor();
final Constructor<?> cons2 = birdClass.getConstructor(String.class);
final Constructor<?> cons3 = birdClass.getConstructor(String.class, boolean.class);
Bird bird1 = (Bird) cons1.newInstance();
Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
Bird bird3 = (Bird) cons3.newInstance("dove", true);
final Bird bird1 = (Bird) cons1.newInstance();
final Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
final Bird bird3 = (Bird) cons3.newInstance("dove", true);
assertEquals("bird", bird1.getName());
assertEquals("Weaver bird", bird2.getName());
@ -156,8 +159,8 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Field[] fields = birdClass.getFields();
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field[] fields = birdClass.getFields();
assertEquals(1, fields.length);
assertEquals("CATEGORY", fields[0].getName());
@ -165,40 +168,40 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Field field = birdClass.getField("CATEGORY");
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field field = birdClass.getField("CATEGORY");
assertEquals("CATEGORY", field.getName());
}
@Test
public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Field[] fields = birdClass.getDeclaredFields();
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field[] fields = birdClass.getDeclaredFields();
assertEquals(1, fields.length);
assertEquals("walks", fields[0].getName());
}
@Test
public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Field field = birdClass.getDeclaredField("walks");
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field field = birdClass.getDeclaredField("walks");
assertEquals("walks", field.getName());
}
@Test
public void givenClassField_whenGetsType_thenCorrect() throws Exception {
Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks");
Class<?> fieldClass = field.getType();
final Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks");
final Class<?> fieldClass = field.getType();
assertEquals("boolean", fieldClass.getSimpleName());
}
@Test
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Bird bird = (Bird) birdClass.newInstance();
Field field = birdClass.getDeclaredField("walks");
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Bird bird = (Bird) birdClass.newInstance();
final Field field = birdClass.getDeclaredField("walks");
field.setAccessible(true);
assertFalse(field.getBoolean(bird));
@ -213,8 +216,8 @@ public class ReflectionUnitTest {
@Test
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Field field = birdClass.getField("CATEGORY");
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Field field = birdClass.getField("CATEGORY");
field.setAccessible(true);
assertEquals("domestic", field.get(null));
@ -222,9 +225,9 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Method[] methods = birdClass.getMethods();
List<String> methodNames = getMethodNames(methods);
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Method[] methods = birdClass.getMethods();
final List<String> methodNames = getMethodNames(methods);
assertTrue(methodNames.containsAll(Arrays.asList("equals", "notifyAll", "hashCode", "walks", "eats", "toString")));
@ -232,10 +235,10 @@ public class ReflectionUnitTest {
@Test
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
final List<String> expectedMethodNames = Arrays.asList("setWalks", "walks", "getSound", "eats");
assertEquals(expectedMethodNames.size(), actualMethodNames.size());
assertTrue(expectedMethodNames.containsAll(actualMethodNames));
@ -245,9 +248,9 @@ public class ReflectionUnitTest {
@Test
public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Method walksMethod = birdClass.getDeclaredMethod("walks");
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Method walksMethod = birdClass.getDeclaredMethod("walks");
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
assertFalse(walksMethod.isAccessible());
assertFalse(setWalksMethod.isAccessible());
@ -262,17 +265,17 @@ public class ReflectionUnitTest {
@Test
public void givenMethod_whenInvokes_thenCorrect() throws Exception {
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
Bird bird = (Bird) birdClass.newInstance();
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
Method walksMethod = birdClass.getDeclaredMethod("walks");
boolean walks = (boolean) walksMethod.invoke(bird);
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
final Bird bird = (Bird) birdClass.newInstance();
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
final Method walksMethod = birdClass.getDeclaredMethod("walks");
final boolean walks = (boolean) walksMethod.invoke(bird);
assertFalse(walks);
assertFalse(bird.walks());
setWalksMethod.invoke(bird, true);
boolean walks2 = (boolean) walksMethod.invoke(bird);
final boolean walks2 = (boolean) walksMethod.invoke(bird);
assertTrue(walks2);
assertTrue(bird.walks());
@ -280,17 +283,19 @@ public class ReflectionUnitTest {
}
private static List<String> getFieldNames(Field[] fields) {
List<String> fieldNames = new ArrayList<>();
for (Field field : fields)
final List<String> fieldNames = new ArrayList<>();
for (final Field field : fields) {
fieldNames.add(field.getName());
}
return fieldNames;
}
private static List<String> getMethodNames(Method[] methods) {
List<String> methodNames = new ArrayList<>();
for (Method method : methods)
final List<String> methodNames = new ArrayList<>();
for (final Method method : methods) {
methodNames.add(method.getName());
}
return methodNames;
}

View File

@ -6,7 +6,7 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class Java8DefaultStaticIntefaceMethodsTest {
public class Java8DefaultStaticIntefaceMethodsUnitTest {
@Test
public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() {

View File

@ -1,17 +1,26 @@
package com.baeldung.java8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import static org.junit.Assert.*;
public class Java8ExecutorServiceTest {
public class Java8ExecutorServiceIntegrationTest {
private Runnable runnableTask;
private Callable<String> callableTask;
@ -53,9 +62,7 @@ public class Java8ExecutorServiceTest {
@Test
public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() {
ExecutorService threadPoolExecutor =
new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>());
ExecutorService threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
for (int i = 0; i < 100; i++) {
threadPoolExecutor.submit(callableTask);
@ -138,8 +145,7 @@ public class Java8ExecutorServiceTest {
@Test
public void submittingTaskScheduling_whenExecuted_thenCorrect() {
ScheduledExecutorService executorService = Executors
.newSingleThreadScheduledExecutor();
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
Future<String> resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS);
String result = null;

View File

@ -1,18 +1,20 @@
package com.baeldung.java8;
import com.baeldung.forkjoin.CustomRecursiveAction;
import com.baeldung.forkjoin.CustomRecursiveTask;
import com.baeldung.forkjoin.util.PoolUtil;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class Java8ForkJoinTest {
import com.baeldung.forkjoin.CustomRecursiveAction;
import com.baeldung.forkjoin.CustomRecursiveTask;
import com.baeldung.forkjoin.util.PoolUtil;
public class Java8ForkJoinIntegrationTest {
private int[] arr;
private CustomRecursiveTask customRecursiveTask;
@ -27,28 +29,23 @@ public class Java8ForkJoinTest {
customRecursiveTask = new CustomRecursiveTask(arr);
}
@Test
public void callPoolUtil_whenExistsAndExpectedType_thenCorrect() {
ForkJoinPool forkJoinPool = PoolUtil.forkJoinPool;
ForkJoinPool forkJoinPoolTwo = PoolUtil.forkJoinPool;
assertNotNull(forkJoinPool);
assertEquals(2, forkJoinPool.getParallelism());
assertEquals(forkJoinPool, forkJoinPoolTwo);
}
@Test
public void callCommonPool_whenExistsAndExpectedType_thenCorrect() {
ForkJoinPool commonPool = ForkJoinPool.commonPool();
ForkJoinPool commonPoolTwo = ForkJoinPool.commonPool();
assertNotNull(commonPool);
assertEquals(commonPool, commonPoolTwo);
}
@Test
@ -63,7 +60,6 @@ public class Java8ForkJoinTest {
@Test
public void executeRecursiveTask_whenExecuted_thenCorrect() {
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
forkJoinPool.execute(customRecursiveTask);
@ -73,12 +69,10 @@ public class Java8ForkJoinTest {
forkJoinPool.submit(customRecursiveTask);
int resultTwo = customRecursiveTask.join();
assertTrue(customRecursiveTask.isDone());
}
@Test
public void executeRecursiveTaskWithFJ_whenExecuted_thenCorrect() {
CustomRecursiveTask customRecursiveTaskFirst = new CustomRecursiveTask(arr);
CustomRecursiveTask customRecursiveTaskSecond = new CustomRecursiveTask(arr);
CustomRecursiveTask customRecursiveTaskLast = new CustomRecursiveTask(arr);
@ -95,6 +89,6 @@ public class Java8ForkJoinTest {
assertTrue(customRecursiveTaskSecond.isDone());
assertTrue(customRecursiveTaskLast.isDone());
assertTrue(result != 0);
}
}

View File

@ -11,7 +11,7 @@ import java.util.function.Function;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
public class Java8FunctionalInteracesLambdasTest {
public class Java8FunctionalInteracesLambdasUnitTest {
private UseFoo useFoo;

View File

@ -12,7 +12,7 @@ import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class Java8MethodReferenceTest {
public class Java8MethodReferenceUnitTest {
private List<String> list;

View File

@ -1,16 +1,23 @@
package com.baeldung.java8;
import com.baeldung.java_8_features.*;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class Java8OptionalTest {
import com.baeldung.java_8_features.Address;
import com.baeldung.java_8_features.CustomException;
import com.baeldung.java_8_features.OptionalAddress;
import com.baeldung.java_8_features.OptionalUser;
import com.baeldung.java_8_features.User;
public class Java8OptionalUnitTest {
private List<String> list;
@ -32,7 +39,6 @@ public class Java8OptionalTest {
@Test
public void checkOptional_whenAsExpected_thenCorrect() {
Optional<String> optionalEmpty = Optional.empty();
assertFalse(optionalEmpty.isPresent());
@ -52,27 +58,19 @@ public class Java8OptionalTest {
assertTrue(listOptNull.isEmpty());
Optional<User> user = Optional.ofNullable(getUser());
String result = user.map(User::getAddress)
.map(Address::getStreet)
.orElse("not specified");
String result = user.map(User::getAddress).map(Address::getStreet).orElse("not specified");
assertEquals(result, "1st Avenue");
Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
String resultOpt = optionalUser.flatMap(OptionalUser::getAddress)
.flatMap(OptionalAddress::getStreet)
.orElse("not specified");
String resultOpt = optionalUser.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified");
assertEquals(resultOpt, "1st Avenue");
Optional<User> userNull = Optional.ofNullable(getUserNull());
String resultNull = userNull.map(User::getAddress)
.map(Address::getStreet)
.orElse("not specified");
String resultNull = userNull.map(User::getAddress).map(Address::getStreet).orElse("not specified");
assertEquals(resultNull, "not specified");
Optional<OptionalUser> optionalUserNull = Optional.ofNullable(getOptionalUserNull());
String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress)
.flatMap(OptionalAddress::getStreet)
.orElse("not specified");
String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified");
assertEquals(resultOptNull, "not specified");
}

View File

@ -17,11 +17,11 @@ import java.util.stream.*;
import static org.junit.Assert.*;
public class Java8StreamApiTest {
public class Java8StreamApiUnitTest {
private long counter;
private static Logger log = LoggerFactory.getLogger(Java8StreamApiTest.class);
private static Logger log = LoggerFactory.getLogger(Java8StreamApiUnitTest.class);
private List<Product> productList;

View File

@ -14,7 +14,7 @@ import java.util.stream.Stream;
import static org.junit.Assert.*;
public class Java8StreamsTest {
public class Java8StreamsUnitTest {
private List<String> list;

View File

@ -1,43 +1,43 @@
package com.baeldung.java8;
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.text.DecimalFormat;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.StreamSupport;
import static org.junit.Assert.assertEquals;
public class JavaFolderSizeTest {
import org.apache.commons.io.FileUtils;
import org.junit.Before;
import org.junit.Test;
public class JavaFolderSizeUnitTest {
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
public void whenGetFolderSizeRecursive_thenCorrect() {
final long expectedSize = 136;
final File folder = new File(path);
final long size = getFolderSize(folder);
assertEquals(expectedSize, size);
assertEquals(EXPECTED_SIZE, size);
}
@Test
public void whenGetFolderSizeUsingJava7_thenCorrect() throws IOException {
final long expectedSize = 136;
final AtomicLong size = new AtomicLong(0);
final Path folder = Paths.get(path);
@ -49,41 +49,33 @@ public class JavaFolderSizeTest {
}
});
assertEquals(expectedSize, size.longValue());
assertEquals(EXPECTED_SIZE, size.longValue());
}
@Test
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
final long expectedSize = 136;
final Path folder = Paths.get(path);
final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
assertEquals(expectedSize, size);
assertEquals(EXPECTED_SIZE, size);
}
@Test
public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() {
final long expectedSize = 136;
final File folder = new File(path);
final long size = FileUtils.sizeOfDirectory(folder);
assertEquals(expectedSize, size);
assertEquals(EXPECTED_SIZE, size);
}
@Test
public void whenGetFolderSizeUsingGuava_thenCorrect() {
final long expectedSize = 136;
final File folder = new File(path);
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
final long size = StreamSupport.stream(files.spliterator(), false)
.filter(File::isFile)
.mapToLong(File::length).sum();
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
assertEquals(expectedSize, size);
assertEquals(EXPECTED_SIZE, size);
}
@Test
@ -91,19 +83,19 @@ public class JavaFolderSizeTest {
final File folder = new File(path);
final long size = getFolderSize(folder);
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
final int unitIndex = (int) (Math.log10(size) / 3);
final double unitValue = 1 << (unitIndex * 10);
final String readableSize = new DecimalFormat("#,##0.#").format(size / unitValue) + " " + units[unitIndex];
assertEquals("136 B", readableSize);
assertEquals(EXPECTED_SIZE + " B", readableSize);
}
private long getFolderSize(final File folder) {
long length = 0;
final File[] files = folder.listFiles();
for (File file : files) {
for (final File file : files) {
if (file.isFile()) {
length += file.length();
} else {

View File

@ -8,7 +8,7 @@ import java.io.StringWriter;
import java.util.Date;
import java.util.Scanner;
public class JavaTryWithResourcesTest {
public class JavaTryWithResourcesUnitTest {
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
private Date resource1Date, resource2Date;

View File

@ -7,7 +7,7 @@ import java.io.UnsupportedEncodingException;
import static org.junit.Assert.*;
public class ApacheCommonsEncodeDecodeTest {
public class ApacheCommonsEncodeDecodeUnitTest {
// tests

View File

@ -8,7 +8,7 @@ import java.util.UUID;
import static org.junit.Assert.*;
public class Java8EncodeDecodeTest {
public class Java8EncodeDecodeUnitTest {
// tests

View File

@ -1,15 +1,15 @@
package com.baeldung.socket;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.Executors;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.concurrent.Executors;
import static org.junit.Assert.assertEquals;
public class EchoTest {
public class EchoIntegrationTest {
private static final Integer PORT = 4444;
@BeforeClass
@ -25,9 +25,15 @@ public class EchoTest {
client.startConnection("127.0.0.1", PORT);
}
@After
public void tearDown() {
client.stopConnection();
}
//
@Test
public void givenClient_whenServerEchosMessage_thenCorrect() {
String resp1 = client.sendMessage("hello");
String resp2 = client.sendMessage("world");
String resp3 = client.sendMessage("!");
@ -38,8 +44,4 @@ public class EchoTest {
assertEquals("good bye", resp4);
}
@After
public void tearDown() {
client.stopConnection();
}
}

View File

@ -7,7 +7,7 @@ import java.util.concurrent.Executors;
import static org.junit.Assert.assertEquals;
public class EchoMultiTest {
public class SocketEchoMultiIntegrationTest {
private static final Integer PORT = 5555;

View File

@ -1,13 +1,23 @@
package com.baeldung.threadpool;
import java.util.concurrent.*;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class CoreThreadPoolTest {
public class CoreThreadPoolIntegrationTest {
@Test(timeout = 1000)
public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {
@ -132,9 +142,7 @@ public class CoreThreadPoolTest {
@Test
public void whenUsingForkJoinPool_thenSumOfTreeElementsIsCalculatedCorrectly() {
TreeNode tree = new TreeNode(5,
new TreeNode(3), new TreeNode(2,
new TreeNode(2), new TreeNode(8)));
TreeNode tree = new TreeNode(5, new TreeNode(3), new TreeNode(2, new TreeNode(2), new TreeNode(8)));
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
int sum = forkJoinPool.invoke(new CountingTask(tree));
@ -142,5 +150,4 @@ public class CoreThreadPoolTest {
assertEquals(20, sum);
}
}

View File

@ -16,7 +16,7 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class GuavaThreadPoolTest {
public class GuavaThreadPoolIntegrationTest {
@Test
public void whenExecutingTaskWithDirectExecutor_thenTheTaskIsExecutedInTheCurrentThread() {

View File

@ -1,19 +1,22 @@
package com.baeldung.util;
import org.junit.Test;
import java.time.*;
import java.time.temporal.ChronoField;
import static org.junit.Assert.assertEquals;
public class CurrentDateTimeTest {
import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import org.junit.Test;
public class CurrentDateTimeUnitTest {
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
@Test
public void shouldReturnCurrentDate() {
final LocalDate now = LocalDate.now(clock);
assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
@ -23,7 +26,6 @@ public class CurrentDateTimeTest {
@Test
public void shouldReturnCurrentTime() {
final LocalTime now = LocalTime.now(clock);
assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
@ -33,9 +35,9 @@ public class CurrentDateTimeTest {
@Test
public void shouldReturnCurrentTimestamp() {
final Instant now = Instant.now(clock);
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
}
}

View File

@ -1,13 +1,17 @@
package org.baeldung.core.exceptions;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.junit.Test;
import java.io.*;
public class FileNotFoundExceptionUnitTest {
public class FileNotFoundExceptionTest {
private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionTest.class);
private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionUnitTest.class);
private String fileName = Double.toString(Math.random());

View File

@ -2,22 +2,22 @@ package org.baeldung.equalshashcode.entities;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
public class ComplexClassTest {
public class ComplexClassUnitTest {
@Test
public void testEqualsAndHashcodes() {
ArrayList<String> strArrayList = new ArrayList<String>();
List<String> strArrayList = new ArrayList<String>();
strArrayList.add("abc");
strArrayList.add("def");
ComplexClass aObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
ComplexClass bObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
ArrayList<String> strArrayListD = new ArrayList<String>();
List<String> strArrayListD = new ArrayList<String>();
strArrayListD.add("lmn");
strArrayListD.add("pqr");
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67));

View File

@ -7,6 +7,7 @@ import java.util.Scanner;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.junit.Ignore;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -14,6 +15,7 @@ import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
@Ignore("need large file for testing")
public class JavaIoUnitTest {
protected final Logger logger = LoggerFactory.getLogger(getClass());

View File

@ -90,7 +90,6 @@ public class JavaTimerLongRunningUnitTest {
@Override
public void run() {
System.out.println("Task performed on " + new Date());
// TODO: stop the thread
}
};
final Timer timer = new Timer("Timer");

View File

@ -12,7 +12,7 @@ import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.*;
public class ArrayListTest {
public class ArrayListUnitTest {
private List<String> stringsToSearch;

View File

@ -46,7 +46,7 @@ public class JavaFileUnitTest {
@Test
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt");
fileToMove.exists();
fileToMove.createNewFile();// .exists();
final File destDir = new File("src/test/resources/");
destDir.mkdir();
@ -68,7 +68,7 @@ public class JavaFileUnitTest {
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
final File fileToMove = new File("src/test/resources/fileToMove.txt");
fileToMove.createNewFile();
final File destDir = new File("src/test/resources/");
final File destDir = new File("src/main/resources/");
final File targetFile = new File(destDir, fileToMove.getName());
com.google.common.io.Files.createParentDirs(targetFile);
com.google.common.io.Files.move(fileToMove, targetFile);
@ -76,13 +76,14 @@ public class JavaFileUnitTest {
@Test
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
FileUtils.moveFile(FileUtils.getFile("src/test/resources/fileToMove.txt"), FileUtils.getFile("src/test/resources/fileMoved.txt"));
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"));
}
@Test
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
FileUtils.touch(new File("src/test/resources/fileToMove.txt"));
FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove.txt"), FileUtils.getFile("src/main/resources/"), true);
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true);
}
// delete a file
@ -99,7 +100,7 @@ public class JavaFileUnitTest {
@Test
public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
// Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt"));
Files.createFile(Paths.get("src/test/resources/fileToDelete_jdk7.txt"));
final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt");
Files.delete(fileToDeletePath);
@ -117,7 +118,7 @@ public class JavaFileUnitTest {
@Test
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
// FileUtils.touch(new File("src/test/resources/fileToDelete.txt"));
FileUtils.touch(new File("src/test/resources/fileToDelete.txt"));
FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt"));
}

View File

@ -111,11 +111,11 @@ public class JavaReadFromFileUnitTest {
@Test
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
final String expected_value = "�空";
final String expected_value = "青空";
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
final String currentLine = reader.readLine();
reader.close();
System.out.println(currentLine);
assertEquals(expected_value, currentLine);
}
@ -143,8 +143,9 @@ public class JavaReadFromFileUnitTest {
final FileChannel channel = reader.getChannel();
int bufferSize = 1024;
if (bufferSize > channel.size())
if (bufferSize > channel.size()) {
bufferSize = (int) channel.size();
}
final ByteBuffer buff = ByteBuffer.allocate(bufferSize);
channel.read(buff);
buff.flip();

View File

@ -0,0 +1 @@
Hello world

View File

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

View File

@ -1,7 +1,10 @@
package org.baeldung.gson.entities;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
public class ActorGson {
@ -18,7 +21,7 @@ public class ActorGson {
@Override
public String toString() {
return "ActorGson [imdbId=" + imdbId + ", dateOfBirth=" + dateOfBirth + ", filmography=" + filmography + "]";
return "ActorGson [imdbId=" + imdbId + ", dateOfBirth=" + formatDateOfBirth() + ", filmography=" + filmography + "]";
}
public String getImdbId() {
@ -45,5 +48,10 @@ public class ActorGson {
this.filmography = filmography;
}
private String formatDateOfBirth() {
final DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss zzz yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
return formatter.format(dateOfBirth);
}
}

View File

@ -1,27 +1,33 @@
package org.baeldung.gson.serialization;
import com.google.gson.*;
import org.baeldung.gson.entities.ActorGson;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import org.baeldung.gson.entities.ActorGson;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
public class ActorGsonDeserializer implements JsonDeserializer<ActorGson> {
private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
@Override
public ActorGson deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
final JsonObject jsonObject = json.getAsJsonObject();
JsonElement jsonImdbId = jsonObject.get("imdbId");
JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth");
JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography");
final JsonElement jsonImdbId = jsonObject.get("imdbId");
final JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth");
final JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography");
ArrayList<String> filmList = new ArrayList<String>();
final ArrayList<String> filmList = new ArrayList<String>();
if (jsonFilmography != null) {
for (int i = 0; i < jsonFilmography.size(); i++) {
filmList.add(jsonFilmography.get(i).getAsString());
@ -31,7 +37,7 @@ public class ActorGsonDeserializer implements JsonDeserializer<ActorGson> {
ActorGson actorGson = null;
try {
actorGson = new ActorGson(jsonImdbId.getAsString(), sdf.parse(jsonDateOfBirth.getAsString()), filmList);
} catch (ParseException e) {
} catch (final ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

View File

@ -1,38 +1,40 @@
package org.baeldung.gson.deserialization;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.text.ParseException;
import org.baeldung.gson.entities.ActorGson;
import org.baeldung.gson.entities.Movie;
import org.baeldung.gson.serialization.ActorGsonDeserializer;
import org.junit.Assert;
import org.junit.Test;
import java.text.ParseException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class GsonDeserializeTest {
@Test
public void whenSimpleDeserialize_thenCorrect() throws ParseException {
String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
final String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"Tue Sep 21 11:00:00 GMT 1982\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
Movie outputMovie = new Gson().fromJson(jsonInput, Movie.class);
final Gson gson = new GsonBuilder().setDateFormat("EEE MMM dd hh:mm:ss zzz yyyy").create();
String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 04:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]";
final Movie outputMovie = gson.fromJson(jsonInput, Movie.class);
final String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]";
Assert.assertEquals(outputMovie.toString(), expectedOutput);
}
@Test
public void whenCustomDeserialize_thenCorrect() throws ParseException {
String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
final String jsonInput = "{\"imdbId\":\"tt0472043\",\"actors\":" + "[{\"imdbId\":\"nm2199632\",\"dateOfBirth\":\"1982-09-21T12:00:00+01:00\",\"filmography\":" + "[\"Apocalypto\",\"Beatdown\",\"Wind Walkers\"]}]}";
Gson gson = new GsonBuilder().registerTypeAdapter(ActorGson.class, new ActorGsonDeserializer()).create();
final Gson gson = new GsonBuilder().registerTypeAdapter(ActorGson.class, new ActorGsonDeserializer()).create();
Movie outputMovie = gson.fromJson(jsonInput, Movie.class);
final Movie outputMovie = gson.fromJson(jsonInput, Movie.class);
String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 12:00:00 PDT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]";
final String expectedOutput = "Movie [imdbId=tt0472043, director=null, actors=[ActorGson [imdbId=nm2199632, dateOfBirth=Tue Sep 21 11:00:00 GMT 1982, filmography=[Apocalypto, Beatdown, Wind Walkers]]]]";
Assert.assertEquals(outputMovie.toString(), expectedOutput);
}
}

View File

@ -141,12 +141,52 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>live</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*ManualTest.java</exclude>
</excludes>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<properties>
<!-- persistence -->
<hibernate.version>4.3.11.Final</hibernate.version>

View File

@ -51,7 +51,7 @@ public class HttpAsyncClientLiveTest {
@Test
public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
// client.start();
client.start();
final HttpGet request = new HttpGet(HOST);
final Future<HttpResponse> future = client.execute(request, null);

View File

@ -28,15 +28,17 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
public class HttpClientMultipartTest {
@Ignore("Server is not available")
public class HttpClientMultipartLiveTest {
private static final String SERVER = "http://echo.200please.com";
private static final String TEXTFILENAME = "temp.txt";
private static final String IMAGEFILENAME = "image.jpg";
private static final String ZIPFILENAME = "zipFile.zip";
private static final Logger LOGGER = Logger.getLogger("org.baeldung.httpclient.HttpClientMultipartTest");
private static final Logger LOGGER = Logger.getLogger("org.baeldung.httpclient.HttpClientMultipartLiveTest");
private CloseableHttpClient client;
private HttpPost post;
private BufferedReader rd;

View File

@ -29,7 +29,10 @@ import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.junit.Test;
public class HttpClientPostingTest {
/*
* NOTE : Need module spring-rest to be running
*/
public class HttpClientPostingLiveTest {
private static final String SAMPLE_URL = "http://localhost:8080/spring-rest/users";
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
private static final String DEFAULT_USER = "test";

View File

@ -1,28 +1,35 @@
package org.baeldung.httpclient;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.*;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.junit.Test;
/**
* This test requires a localhost server over HTTPS <br>
@ -96,7 +103,7 @@ public class HttpsClientSslLiveTest {
@Test
public final void givenIgnoringCertificates_whenHttpsUrlIsConsumed_thenCorrect() throws IOException {
TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
final TrustStrategy acceptingTrustStrategy = (certificate, authType) -> true;
SSLContext sslContext = null;
try {
@ -106,8 +113,8 @@ public class HttpsClientSslLiveTest {
e.printStackTrace();
}
CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
final HttpGet httpGet = new HttpGet("https://sesar3.geoinfogeochem.org/sample/igsn/ODP000002");
final CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
final HttpGet httpGet = new HttpGet(HOST_WITH_SSL);
httpGet.setHeader("Accept", "application/xml");
final HttpResponse response = client.execute(httpGet);

View File

@ -1,5 +1,8 @@
package org.baeldung.httpclient.base;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
@ -11,9 +14,9 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
/*
* NOTE : Need module spring-security-rest-basic-auth to be running
*/
public class HttpClientSandboxLiveTest {
@Test
@ -22,10 +25,10 @@ public class HttpClientSandboxLiveTest {
final AuthScope authscp = new AuthScope("localhost", 8080);
credentialsProvider.setCredentials(authscp, new UsernamePasswordCredentials("user1", "user1Pass"));
CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
final CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
final HttpGet httpGet = new HttpGet("http://localhost:8080/spring-security-rest-basic-auth/api/foos/1");
CloseableHttpResponse response = client.execute(httpGet);
final CloseableHttpResponse response = client.execute(httpGet);
System.out.println(response.getStatusLine());

View File

@ -30,6 +30,10 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/*
* NOTE : Need module spring-security-rest-basic-auth to be running
*/
public class HttpClientAuthLiveTest {
private static final String URL_SECURED_BY_BASIC_AUTHENTICATION = "http://localhost:8081/spring-security-rest-basic-auth/api/foos/1";

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};

73
pom.xml
View File

@ -14,24 +14,25 @@
</properties>
<modules>
<module>assertj</module>
<module>annotations</module>
<module>apache-cxf</module>
<!-- <module>apache-fop</module> --> <!-- TODO: has a compilation issue -->
<module>apache-fop</module> <!-- TODO: has a compilation issue -->
<module>assertj</module>
<module>autovalue</module>
<module>cdi</module>
<!-- <module>core-java-9</module> -->
<module>core-java</module>
<module>couchbase-sdk</module>
<!-- <module>core-java-9</module> -->
<module>dozer</module>
<module>deltaspike</module>
<module>dozer</module>
<module>patterns</module>
<module>feign</module>
<module>flyway</module>
<!-- <module>gatling</module> --> <!-- not meant to run as part of the standard build -->
<module>flyway</module>
<module>gson</module>
<module>guava</module>
@ -39,56 +40,66 @@
<module>guava19</module>
<module>handling-spring-static-resources</module>
<module>hazelcast</module>
<module>httpclient</module>
<module>hystrix</module>
<module>immutables</module>
<module>jackson</module>
<module>java-cassandra</module>
<module>javaxval</module>
<module>jjwt</module>
<module>jpa-storedprocedure</module>
<module>json</module>
<module>json-path</module>
<module>junit5</module>
<module>jee7</module>
<!-- <module>jpa-storedprocedure</module> -->
<module>jjwt</module>
<module>jpa-storedprocedure</module>
<module>jsf</module>
<module>json-path</module>
<module>json</module>
<module>junit5</module>
<module>log4j</module>
<module>lombok</module>
<module>mapstruct</module>
<module>mockito</module>
<module>mocks</module>
<module>testing</module>
<module>orika</module>
<module>patterns</module>
<module>querydsl</module>
<!-- <module>raml</module> -->
<module>redis</module>
<module>rest-assured</module>
<module>rest-testing</module>
<module>resteasy</module>
<module>selenium-junit-testng</module>
<module>spring-akka</module>
<module>spring-all</module>
<module>spring-akka</module>
<module>spring-apache-camel</module>
<module>spring-autowire</module>
<module>spring-batch</module>
<module>spring-boot</module>
<module>spring-cloud-data-flow</module>
<module>spring-cloud</module>
<module>spring-core</module>
<module>spring-cucumber</module>
<module>spring-data-cassandra</module>
<module>spring-data-couchbase-2</module>
<module>spring-data-dynamodb</module>
<module>spring-data-elasticsearch</module>
<module>spring-data-neo4j</module>
<module>spring-data-mongodb</module>
<module>spring-data-neo4j</module>
<module>spring-data-redis</module>
<module>spring-data-rest</module>
<!--<module>spring-dispatcher-servlet</module>-->
<module>spring-exceptions</module>
<module>spring-freemarker</module>
<module>spring-hibernate3</module>
<module>spring-hibernate4</module>
<module>spring-integration</module>
<module>spring-jms</module>
<module>spring-jooq</module>
<module>spring-jpa</module>
@ -96,18 +107,16 @@
<module>spring-mockito</module>
<module>spring-mvc-java</module>
<module>spring-mvc-no-xml</module>
<module>spring-mvc-xml</module>
<module>spring-mvc-tiles</module>
<module>spring-mvc-velocity</module>
<module>spring-mvc-web-vs-initializer</module>
<module>spring-mvc-xml</module>
<module>spring-openid</module>
<module>spring-protobuf</module>
<module>spring-quartz</module>
<module>spring-spel</module>
<module>spring-rest</module>
<module>spring-rest-angular</module>
<module>spring-rest-docs</module>
<module>spring-cloud</module>
<module>spring-cloud-data-flow</module>
<module>spring-rest</module>
<module>spring-security-basic-auth</module>
<module>spring-security-custom-permission</module>
<module>spring-security-mvc-custom</module>
@ -116,26 +125,24 @@
<module>spring-security-mvc-login</module>
<module>spring-security-mvc-persisted-remember-me</module>
<module>spring-security-mvc-session</module>
<module>spring-security-rest</module>
<module>spring-security-rest-basic-auth</module>
<module>spring-security-rest-custom</module>
<module>spring-security-rest-digest-auth</module>
<module>spring-security-rest-full</module>
<module>spring-security-rest</module>
<module>spring-security-x509</module>
<module>spring-spel</module>
<module>spring-thymeleaf</module>
<module>spring-userservice</module>
<module>spring-zuul</module>
<module>spring-mvc-velocity</module>
<module>jsf</module>
<module>xml</module>
<module>xmlunit2</module>
<module>lombok</module>
<module>redis</module>
<module>testing</module>
<module>wicket</module>
<module>xml</module>
<module>xmlunit2</module>
<module>xstream</module>
<module>java-cassandra</module>
<module>annotations</module>
</modules>
</project>

View File

@ -53,7 +53,7 @@
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.1</version>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>

View File

@ -15,6 +15,7 @@ public class SeleniumExample {
private String url = "http://www.baeldung.com/";
public SeleniumExample() {
System.setProperty("webdriver.firefox.marionette", "C:\\selenium\\geckodriver.exe");
webDriver = new FirefoxDriver();
webDriver.manage().window().maximize();
webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
@ -29,16 +30,20 @@ public class SeleniumExample {
return webDriver.getTitle();
}
public void getAboutBaeldungPage() throws Exception {
public void getAboutBaeldungPage() {
closeOverlay();
clickAboutLink();
clickAboutUsLink();
}
private void closeOverlay() throws Exception {
private void closeOverlay() {
List<WebElement> webElementList = webDriver.findElements(By.tagName("a"));
if (webElementList != null && !webElementList.isEmpty() && webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().isPresent()) {
webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().orElseThrow(NoSuchElementException::new).click();
try {
if (webElementList != null && !webElementList.isEmpty()) {
webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().orElseThrow(NoSuchElementException::new).click();
}
} catch (NoSuchElementException exception) {
exception.printStackTrace();
}
}

View File

@ -9,11 +9,11 @@
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/test-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>

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

Some files were not shown because too many files have changed in this diff Show More