Merge branch 'master' of https://github.com/eugenp/tutorials
@ -279,6 +279,41 @@
|
|||||||
</plugins>
|
</plugins>
|
||||||
|
|
||||||
</build>
|
</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>
|
<properties>
|
||||||
<!-- persistence -->
|
<!-- persistence -->
|
||||||
|
@ -14,7 +14,6 @@ public class Screenshot {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public void getScreenshot(int timeToWait) throws Exception {
|
public void getScreenshot(int timeToWait) throws Exception {
|
||||||
Thread.sleep(timeToWait);
|
|
||||||
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
|
Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
|
||||||
Robot robot = new Robot();
|
Robot robot = new Robot();
|
||||||
BufferedImage img = robot.createScreenCapture(rectangle);
|
BufferedImage img = robot.createScreenCapture(rectangle);
|
||||||
|
@ -1,7 +1,5 @@
|
|||||||
package org.baeldung.equalshashcode.entities;
|
package org.baeldung.equalshashcode.entities;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.HashSet;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
|
|
||||||
@ -10,7 +8,7 @@ public class ComplexClass {
|
|||||||
private List<?> genericList;
|
private List<?> genericList;
|
||||||
private Set<Integer> integerSet;
|
private Set<Integer> integerSet;
|
||||||
|
|
||||||
public ComplexClass(ArrayList<?> genericArrayList, HashSet<Integer> integerHashSet) {
|
public ComplexClass(List<?> genericArrayList, Set<Integer> integerHashSet) {
|
||||||
super();
|
super();
|
||||||
this.genericList = genericArrayList;
|
this.genericList = genericArrayList;
|
||||||
this.integerSet = integerHashSet;
|
this.integerSet = integerHashSet;
|
||||||
|
1
core-java/src/main/resources/fileTest.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
Hello World from fileTest.txt!!!
|
@ -4,7 +4,7 @@ import org.junit.Test;
|
|||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
public class CharToStringTest {
|
public class CharToStringUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenChar_whenCallingStringValueOf_shouldConvertToString() {
|
public void givenChar_whenCallingStringValueOf_shouldConvertToString() {
|
@ -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.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
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");
|
private final List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
|
||||||
|
|
@ -7,7 +7,7 @@ import java.time.Month;
|
|||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UseLocalDateTimeTest {
|
public class UseLocalDateTimeUnitTest {
|
||||||
|
|
||||||
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
UseLocalDateTime useLocalDateTime = new UseLocalDateTime();
|
||||||
|
|
@ -7,7 +7,7 @@ import java.time.LocalDateTime;
|
|||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UseLocalDateTest {
|
public class UseLocalDateUnitTest {
|
||||||
|
|
||||||
UseLocalDate useLocalDate = new UseLocalDate();
|
UseLocalDate useLocalDate = new UseLocalDate();
|
||||||
|
|
@ -5,7 +5,7 @@ import java.time.LocalTime;
|
|||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UseLocalTimeTest {
|
public class UseLocalTimeUnitTest {
|
||||||
|
|
||||||
UseLocalTime useLocalTime = new UseLocalTime();
|
UseLocalTime useLocalTime = new UseLocalTime();
|
||||||
|
|
@ -6,7 +6,7 @@ import java.time.Period;
|
|||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UsePeriodTest {
|
public class UsePeriodUnitTest {
|
||||||
UsePeriod usingPeriod=new UsePeriod();
|
UsePeriod usingPeriod=new UsePeriod();
|
||||||
|
|
||||||
@Test
|
@Test
|
@ -7,7 +7,7 @@ import java.time.ZonedDateTime;
|
|||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class UseZonedDateTimeTest {
|
public class UseZonedDateTimeUnitTest {
|
||||||
|
|
||||||
UseZonedDateTime zonedDateTime=new UseZonedDateTime();
|
UseZonedDateTime zonedDateTime=new UseZonedDateTime();
|
||||||
|
|
@ -13,7 +13,7 @@ import java.util.function.BiFunction;
|
|||||||
|
|
||||||
import static com.baeldung.doublecolon.ComputerUtils.*;
|
import static com.baeldung.doublecolon.ComputerUtils.*;
|
||||||
|
|
||||||
public class TestComputerUtils {
|
public class ComputerUtilsUnitTest {
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void setup() {
|
public void setup() {
|
@ -7,7 +7,6 @@ import org.slf4j.Logger;
|
|||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
import java.io.UnsupportedEncodingException;
|
import java.io.UnsupportedEncodingException;
|
||||||
import java.net.MalformedURLException;
|
|
||||||
import java.net.URL;
|
import java.net.URL;
|
||||||
import java.net.URLDecoder;
|
import java.net.URLDecoder;
|
||||||
import java.net.URLEncoder;
|
import java.net.URLEncoder;
|
||||||
@ -15,13 +14,13 @@ import java.nio.charset.StandardCharsets;
|
|||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.Map;
|
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";
|
public class EncoderDecoderUnitTest {
|
||||||
private static final Logger LOGGER = LoggerFactory.getLogger(EncoderDecoder.class);
|
|
||||||
|
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) {
|
private String encodeValue(String value) {
|
||||||
String encoded = null;
|
String encoded = null;
|
||||||
@ -46,7 +45,7 @@ public class EncoderDecoder {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenURL_whenAnalyze_thenCorrect() throws Exception {
|
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.getProtocol(), CoreMatchers.is("http"));
|
||||||
Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com"));
|
Assert.assertThat(url.getHost(), CoreMatchers.is("www.baeldung.com"));
|
||||||
@ -60,25 +59,25 @@ public class EncoderDecoder {
|
|||||||
requestParams.put("key2", "value@!$2");
|
requestParams.put("key2", "value@!$2");
|
||||||
requestParams.put("key3", "value%3");
|
requestParams.put("key3", "value%3");
|
||||||
|
|
||||||
String encodedQuery = requestParams.keySet().stream()
|
String encodedURL = requestParams.keySet().stream()
|
||||||
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
|
.map(key -> key + "=" + encodeValue(requestParams.get(key)))
|
||||||
.collect(Collectors.joining("&"));
|
.collect(joining("&", "http://www.baeldung.com?", ""));
|
||||||
String encodedURL = "http://www.baeldung.com?" + encodedQuery;
|
|
||||||
|
|
||||||
Assert.assertThat(URL, CoreMatchers.is(encodedURL));
|
Assert.assertThat(testUrl, CoreMatchers.is(encodedURL));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
|
public void givenRequestParam_whenUTF8Scheme_thenDecodeRequestParams() throws Exception {
|
||||||
URL url = new URL(URL);
|
URL url = new URL(testUrl);
|
||||||
|
|
||||||
String query = url.getQuery();
|
String query = url.getQuery();
|
||||||
|
|
||||||
String decodedQuery = Arrays.stream(query.split("&"))
|
String decodedQuery = Arrays.stream(query.split("&"))
|
||||||
.map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1]))
|
.map(param -> param.split("=")[0] + "=" + decode(param.split("=")[1]))
|
||||||
.collect(Collectors.joining("&"));
|
.collect(joining("&"));
|
||||||
|
|
||||||
Assert.assertEquals(
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -9,7 +9,7 @@ import java.util.List;
|
|||||||
|
|
||||||
import static junit.framework.TestCase.assertTrue;
|
import static junit.framework.TestCase.assertTrue;
|
||||||
|
|
||||||
public class PizzaTest {
|
public class PizzaUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenPizaOrder_whenReady_thenDeliverable() {
|
public void givenPizaOrder_whenReady_thenDeliverable() {
|
@ -1,11 +1,5 @@
|
|||||||
package com.baeldung.file;
|
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.BufferedReader;
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.FileInputStream;
|
import java.io.FileInputStream;
|
||||||
@ -20,7 +14,13 @@ import java.nio.file.Path;
|
|||||||
import java.nio.file.Paths;
|
import java.nio.file.Paths;
|
||||||
import java.util.stream.Stream;
|
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
|
@Test
|
||||||
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
|
public void givenFileName_whenUsingClassloader_thenFileData() throws IOException {
|
||||||
@ -30,15 +30,15 @@ public class FileOperationsTest {
|
|||||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||||
InputStream inputStream = new FileInputStream(file);
|
InputStream inputStream = new FileInputStream(file);
|
||||||
String data = readFromInputStream(inputStream);
|
String data = readFromInputStream(inputStream);
|
||||||
|
|
||||||
Assert.assertEquals(expectedData, data.trim());
|
Assert.assertEquals(expectedData, data.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
|
public void givenFileNameAsAbsolutePath_whenUsingClasspath_thenFileData() throws IOException {
|
||||||
String expectedData = "Hello World from fileTest.txt!!!";
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
Class clazz = FileOperationsTest.class;
|
Class clazz = FileOperationsUnitTest.class;
|
||||||
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
|
InputStream inputStream = clazz.getResourceAsStream("/fileTest.txt");
|
||||||
String data = readFromInputStream(inputStream);
|
String data = readFromInputStream(inputStream);
|
||||||
|
|
||||||
@ -69,44 +69,44 @@ public class FileOperationsTest {
|
|||||||
|
|
||||||
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
Assert.assertThat(data.trim(), CoreMatchers.containsString(expectedData));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
|
public void givenFileName_whenUsingFileUtils_thenFileData() throws IOException {
|
||||||
String expectedData = "Hello World from fileTest.txt!!!";
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
ClassLoader classLoader = getClass().getClassLoader();
|
ClassLoader classLoader = getClass().getClassLoader();
|
||||||
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
File file = new File(classLoader.getResource("fileTest.txt").getFile());
|
||||||
String data = FileUtils.readFileToString(file);
|
String data = FileUtils.readFileToString(file);
|
||||||
|
|
||||||
Assert.assertEquals(expectedData, data.trim());
|
Assert.assertEquals(expectedData, data.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
|
public void givenFilePath_whenUsingFilesReadAllBytes_thenFileData() throws IOException, URISyntaxException {
|
||||||
String expectedData = "Hello World from fileTest.txt!!!";
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||||
|
|
||||||
byte[] fileBytes = Files.readAllBytes(path);
|
byte[] fileBytes = Files.readAllBytes(path);
|
||||||
String data = new String(fileBytes);
|
String data = new String(fileBytes);
|
||||||
|
|
||||||
Assert.assertEquals(expectedData, data.trim());
|
Assert.assertEquals(expectedData, data.trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
|
public void givenFilePath_whenUsingFilesLines_thenFileData() throws IOException, URISyntaxException {
|
||||||
String expectedData = "Hello World from fileTest.txt!!!";
|
String expectedData = "Hello World from fileTest.txt!!!";
|
||||||
|
|
||||||
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
|
||||||
|
|
||||||
StringBuilder data = new StringBuilder();
|
StringBuilder data = new StringBuilder();
|
||||||
Stream<String> lines = Files.lines(path);
|
Stream<String> lines = Files.lines(path);
|
||||||
lines.forEach(line -> data.append(line).append("\n"));
|
lines.forEach(line -> data.append(line).append("\n"));
|
||||||
lines.close();
|
lines.close();
|
||||||
|
|
||||||
Assert.assertEquals(expectedData, data.toString().trim());
|
Assert.assertEquals(expectedData, data.toString().trim());
|
||||||
}
|
}
|
||||||
|
|
||||||
private String readFromInputStream(InputStream inputStream) throws IOException {
|
private String readFromInputStream(InputStream inputStream) throws IOException {
|
||||||
StringBuilder resultStringBuilder = new StringBuilder();
|
StringBuilder resultStringBuilder = new StringBuilder();
|
||||||
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
|
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
|
@ -10,7 +10,7 @@ import java.io.IOException;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertFalse;
|
import static org.junit.Assert.assertFalse;
|
||||||
|
|
||||||
public class UDPTest {
|
public class UDPIntegrationTest {
|
||||||
private EchoClient client;
|
private EchoClient client;
|
||||||
|
|
||||||
@Before
|
@Before
|
@ -0,0 +1,104 @@
|
|||||||
|
package com.baeldung.java.networking.url;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.net.URL;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class UrlUnitTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenCanIdentifyProtocol_thenCorrect() throws MalformedURLException {
|
||||||
|
final URL url = new URL("http://baeldung.com");
|
||||||
|
assertEquals("http", url.getProtocol());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenCanGetHost_thenCorrect() throws MalformedURLException {
|
||||||
|
final URL url = new URL("http://baeldung.com");
|
||||||
|
assertEquals("baeldung.com", url.getHost());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenCanGetFileName_thenCorrect2() throws MalformedURLException {
|
||||||
|
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 {
|
||||||
|
final URL url = new URL("http://baeldung.com/guidelines.txt");
|
||||||
|
assertEquals("/guidelines.txt", url.getFile());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenCanGetPathParams_thenCorrect() throws MalformedURLException {
|
||||||
|
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 {
|
||||||
|
final URL url = new URL("http://baeldung.com/articles?topic=java");
|
||||||
|
assertEquals("topic=java", url.getQuery());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenGetsDefaultPort_thenCorrect() throws MalformedURLException {
|
||||||
|
final URL url = new URL("http://baeldung.com");
|
||||||
|
assertEquals(-1, url.getPort());
|
||||||
|
assertEquals(80, url.getDefaultPort());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenUrl_whenGetsPort_thenCorrect() throws MalformedURLException {
|
||||||
|
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 {
|
||||||
|
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 {
|
||||||
|
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 {
|
||||||
|
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 {
|
||||||
|
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 {
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -6,7 +6,7 @@ import java.io.IOException;
|
|||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class EchoTest {
|
public class NioEchoIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClient_whenServerEchosMessage_thenCorrect() throws IOException, InterruptedException {
|
public void givenClient_whenServerEchosMessage_thenCorrect() throws IOException, InterruptedException {
|
264
core-java/src/test/java/com/baeldung/java/nio2/FileUnitTest.java
Normal file
@ -0,0 +1,264 @@
|
|||||||
|
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.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 FileUnitTest {
|
||||||
|
private static final String HOME = System.getProperty("user.home");
|
||||||
|
|
||||||
|
// checking file or dir
|
||||||
|
@Test
|
||||||
|
public void givenExistentPath_whenConfirmsFileExists_thenCorrect() {
|
||||||
|
final Path p = Paths.get(HOME);
|
||||||
|
assertTrue(Files.exists(p));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNonexistentPath_whenConfirmsFileNotExists_thenCorrect() {
|
||||||
|
final Path p = Paths.get(HOME + "/inexistent_file.txt");
|
||||||
|
assertTrue(Files.notExists(p));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExistentDirPath_whenConfirmsNotRegularFile_thenCorrect() {
|
||||||
|
final Path p = Paths.get(HOME);
|
||||||
|
assertFalse(Files.isRegularFile(p));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExistentDirPath_whenConfirmsReadable_thenCorrect() {
|
||||||
|
final Path p = Paths.get(HOME);
|
||||||
|
assertTrue(Files.isReadable(p));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExistentDirPath_whenConfirmsWritable_thenCorrect() {
|
||||||
|
final Path p = Paths.get(HOME);
|
||||||
|
assertTrue(Files.isWritable(p));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenExistentDirPath_whenConfirmsExecutable_thenCorrect() {
|
||||||
|
final Path p = Paths.get(HOME);
|
||||||
|
assertTrue(Files.isExecutable(p));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenSameFilePaths_whenConfirmsIsSame_thenCorrect() throws IOException {
|
||||||
|
final Path p1 = Paths.get(HOME);
|
||||||
|
final 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 {
|
||||||
|
final String fileName = "myfile_" + new Date().getTime() + ".txt";
|
||||||
|
final 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 {
|
||||||
|
final String dirName = "myDir_" + new Date().getTime();
|
||||||
|
final Path p = Paths.get(HOME + "/" + dirName);
|
||||||
|
assertFalse(Files.exists(p));
|
||||||
|
Files.createDirectory(p);
|
||||||
|
assertTrue(Files.exists(p));
|
||||||
|
assertFalse(Files.isRegularFile(p));
|
||||||
|
assertTrue(Files.isDirectory(p));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirPath_whenFailsToCreateRecursively_thenCorrect() {
|
||||||
|
final String dirName = "myDir_" + new Date().getTime() + "/subdir";
|
||||||
|
final Path p = Paths.get(HOME + "/" + dirName);
|
||||||
|
assertFalse(Files.exists(p));
|
||||||
|
try {
|
||||||
|
Files.createDirectory(p);
|
||||||
|
} catch (final IOException e) {
|
||||||
|
assertTrue(e instanceof NoSuchFileException);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenDirPath_whenCreatesRecursively_thenCorrect() throws IOException {
|
||||||
|
final Path dir = Paths.get(HOME + "/myDir_" + new Date().getTime());
|
||||||
|
final 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 {
|
||||||
|
final String prefix = "log_";
|
||||||
|
final String suffix = ".txt";
|
||||||
|
Path p = Paths.get(HOME + "/");
|
||||||
|
p = Files.createTempFile(p, prefix, suffix);
|
||||||
|
// like log_8821081429012075286.txt
|
||||||
|
assertTrue(Files.exists(p));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFilePath_whenCreatesTempFileWithDefaultsNaming_thenCorrect() throws IOException {
|
||||||
|
Path p = Paths.get(HOME + "/");
|
||||||
|
p = Files.createTempFile(p, null, null);
|
||||||
|
// like 8600179353689423985.tmp
|
||||||
|
System.out.println(p);
|
||||||
|
assertTrue(Files.exists(p));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenNoFilePath_whenCreatesTempFileInTempDir_thenCorrect() throws IOException {
|
||||||
|
final 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 {
|
||||||
|
final Path p = Paths.get(HOME + "/fileToDelete.txt");
|
||||||
|
assertFalse(Files.exists(p));
|
||||||
|
Files.createFile(p);
|
||||||
|
assertTrue(Files.exists(p));
|
||||||
|
Files.delete(p);
|
||||||
|
assertFalse(Files.exists(p));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenFailsToDeleteNonEmptyDir_thenCorrect() throws IOException {
|
||||||
|
final Path dir = Paths.get(HOME + "/emptyDir" + new Date().getTime());
|
||||||
|
Files.createDirectory(dir);
|
||||||
|
assertTrue(Files.exists(dir));
|
||||||
|
final Path file = dir.resolve("file.txt");
|
||||||
|
Files.createFile(file);
|
||||||
|
try {
|
||||||
|
Files.delete(dir);
|
||||||
|
} catch (final IOException e) {
|
||||||
|
assertTrue(e instanceof DirectoryNotEmptyException);
|
||||||
|
}
|
||||||
|
assertTrue(Files.exists(dir));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInexistentFile_whenDeleteFails_thenCorrect() throws IOException {
|
||||||
|
final Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||||
|
assertFalse(Files.exists(p));
|
||||||
|
try {
|
||||||
|
Files.delete(p);
|
||||||
|
} catch (final IOException e) {
|
||||||
|
assertTrue(e instanceof NoSuchFileException);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInexistentFile_whenDeleteIfExistsWorks_thenCorrect() throws IOException {
|
||||||
|
final Path p = Paths.get(HOME + "/inexistentFile.txt");
|
||||||
|
assertFalse(Files.exists(p));
|
||||||
|
Files.deleteIfExists(p);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// copy file
|
||||||
|
@Test
|
||||||
|
public void givenFilePath_whenCopiesToNewLocation_thenCorrect() throws IOException {
|
||||||
|
final Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||||
|
final Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
||||||
|
Files.createDirectory(dir1);
|
||||||
|
Files.createDirectory(dir2);
|
||||||
|
final Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
final Path file2 = dir2.resolve("filetocopy.txt");
|
||||||
|
Files.createFile(file1);
|
||||||
|
assertTrue(Files.exists(file1));
|
||||||
|
assertFalse(Files.exists(file2));
|
||||||
|
Files.copy(file1, file2);
|
||||||
|
assertTrue(Files.exists(file2));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenCopyFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||||
|
final Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||||
|
final Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
||||||
|
Files.createDirectory(dir1);
|
||||||
|
Files.createDirectory(dir2);
|
||||||
|
final Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
final Path file2 = dir2.resolve("filetocopy.txt");
|
||||||
|
Files.createFile(file1);
|
||||||
|
Files.createFile(file2);
|
||||||
|
assertTrue(Files.exists(file1));
|
||||||
|
assertTrue(Files.exists(file2));
|
||||||
|
try {
|
||||||
|
Files.copy(file1, file2);
|
||||||
|
} catch (final IOException e) {
|
||||||
|
assertTrue(e instanceof FileAlreadyExistsException);
|
||||||
|
}
|
||||||
|
Files.copy(file1, file2, StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
}
|
||||||
|
|
||||||
|
// moving files
|
||||||
|
@Test
|
||||||
|
public void givenFilePath_whenMovesToNewLocation_thenCorrect() throws IOException {
|
||||||
|
final Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||||
|
final Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
||||||
|
Files.createDirectory(dir1);
|
||||||
|
Files.createDirectory(dir2);
|
||||||
|
final Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
final Path file2 = dir2.resolve("filetocopy.txt");
|
||||||
|
Files.createFile(file1);
|
||||||
|
assertTrue(Files.exists(file1));
|
||||||
|
assertFalse(Files.exists(file2));
|
||||||
|
Files.move(file1, file2);
|
||||||
|
assertTrue(Files.exists(file2));
|
||||||
|
assertFalse(Files.exists(file1));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenFilePath_whenMoveFailsDueToExistingFile_thenCorrect() throws IOException {
|
||||||
|
final Path dir1 = Paths.get(HOME + "/firstdir_" + new Date().getTime());
|
||||||
|
final Path dir2 = Paths.get(HOME + "/otherdir_" + new Date().getTime());
|
||||||
|
Files.createDirectory(dir1);
|
||||||
|
Files.createDirectory(dir2);
|
||||||
|
final Path file1 = dir1.resolve("filetocopy.txt");
|
||||||
|
final Path file2 = dir2.resolve("filetocopy.txt");
|
||||||
|
Files.createFile(file1);
|
||||||
|
Files.createFile(file2);
|
||||||
|
assertTrue(Files.exists(file1));
|
||||||
|
assertTrue(Files.exists(file2));
|
||||||
|
try {
|
||||||
|
Files.move(file1, file2);
|
||||||
|
} catch (final IOException e) {
|
||||||
|
assertTrue(e instanceof FileAlreadyExistsException);
|
||||||
|
}
|
||||||
|
Files.move(file1, file2, StandardCopyOption.REPLACE_EXISTING);
|
||||||
|
assertTrue(Files.exists(file2));
|
||||||
|
assertFalse(Files.exists(file1));
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,196 @@
|
|||||||
|
package com.baeldung.java.nio2;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
import static org.junit.Assert.assertFalse;
|
||||||
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
|
||||||
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class PathManualTest {
|
||||||
|
|
||||||
|
private static final String HOME = System.getProperty("user.home");
|
||||||
|
|
||||||
|
// creating a path
|
||||||
|
@Test
|
||||||
|
public void givenPathString_whenCreatesPathObject_thenCorrect() {
|
||||||
|
final Path p = Paths.get("/articles/baeldung");
|
||||||
|
assertEquals("\\articles\\baeldung", p.toString());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPathParts_whenCreatesPathObject_thenCorrect() {
|
||||||
|
final Path p = Paths.get("/articles", "baeldung");
|
||||||
|
assertEquals("\\articles\\baeldung", p.toString());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// retrieving path info
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenRetrievesFileName_thenCorrect() {
|
||||||
|
final Path p = Paths.get("/articles/baeldung/logs");
|
||||||
|
assertEquals("logs", p.getFileName().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenRetrievesNameByIndex_thenCorrect() {
|
||||||
|
final 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() {
|
||||||
|
final Path p = Paths.get("/articles/baeldung/logs");
|
||||||
|
assertEquals(3, p.getNameCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenCanRetrieveSubsequenceByIndex_thenCorrect() {
|
||||||
|
final 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() {
|
||||||
|
final Path p1 = Paths.get("/articles/baeldung/logs");
|
||||||
|
final Path p2 = Paths.get("/articles/baeldung");
|
||||||
|
final Path p3 = Paths.get("/articles");
|
||||||
|
final 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() {
|
||||||
|
final Path p1 = Paths.get("/articles/baeldung/logs");
|
||||||
|
final 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() {
|
||||||
|
final Path p = Paths.get("/home/baeldung/articles.html");
|
||||||
|
final URI uri = p.toUri();
|
||||||
|
assertEquals("file:///E:/home/baeldung/articles.html", uri.toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenConvertsToAbsolutePath_thenCorrect() {
|
||||||
|
final Path p = Paths.get("/home/baeldung/articles.html");
|
||||||
|
assertEquals("E:\\home\\baeldung\\articles.html", p.toAbsolutePath().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAbsolutePath_whenRetainsAsAbsolute_thenCorrect() {
|
||||||
|
final 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 {
|
||||||
|
final Path p = Paths.get(HOME);
|
||||||
|
assertEquals(HOME, p.toRealPath().toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenInExistentPath_whenFailsToConvert_thenCorrect() {
|
||||||
|
final Path p = Paths.get("E:\\home\\baeldung\\articles.html");
|
||||||
|
try {
|
||||||
|
p.toRealPath();
|
||||||
|
} catch (final IOException e) {
|
||||||
|
assertTrue(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// joining paths
|
||||||
|
@Test
|
||||||
|
public void givenTwoPaths_whenJoinsAndResolves_thenCorrect() throws IOException {
|
||||||
|
final Path p = Paths.get("/baeldung/articles");
|
||||||
|
assertEquals("\\baeldung\\articles\\java", p.resolve("java").toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenAbsolutePath_whenResolutionRetainsIt_thenCorrect() throws IOException {
|
||||||
|
final 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 {
|
||||||
|
final 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 {
|
||||||
|
final Path p1 = Paths.get("articles");
|
||||||
|
final 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 {
|
||||||
|
final Path p1 = Paths.get("/baeldung");
|
||||||
|
final 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 {
|
||||||
|
final Path p1 = Paths.get("/baeldung/articles");
|
||||||
|
final Path p2 = Paths.get("/baeldung/articles");
|
||||||
|
final Path p3 = Paths.get("/baeldung/authors");
|
||||||
|
|
||||||
|
assertTrue(p1.equals(p2));
|
||||||
|
assertFalse(p1.equals(p3));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenInspectsStart_thenCorrect() {
|
||||||
|
final Path p1 = Paths.get("/baeldung/articles");
|
||||||
|
assertTrue(p1.startsWith("/baeldung"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void givenPath_whenInspectsEnd_thenCorrect() {
|
||||||
|
final Path p1 = Paths.get("/baeldung/articles");
|
||||||
|
assertTrue(p1.endsWith("articles"));
|
||||||
|
}
|
||||||
|
}
|
@ -1,32 +1,35 @@
|
|||||||
package com.baeldung.java.reflection;
|
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.Constructor;
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.lang.reflect.Modifier;
|
import java.lang.reflect.Modifier;
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.Arrays;
|
import java.util.Arrays;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.ArrayList;
|
|
||||||
import static org.junit.Assert.*;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class ReflectionUnitTest {
|
public class ReflectionUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
|
public void givenObject_whenGetsFieldNamesAtRuntime_thenCorrect() {
|
||||||
Object person = new Person();
|
final Object person = new Person();
|
||||||
Field[] fields = person.getClass().getDeclaredFields();
|
final Field[] fields = person.getClass().getDeclaredFields();
|
||||||
|
|
||||||
List<String> actualFieldNames = getFieldNames(fields);
|
final List<String> actualFieldNames = getFieldNames(fields);
|
||||||
|
|
||||||
assertTrue(Arrays.asList("name", "age").containsAll(actualFieldNames));
|
assertTrue(Arrays.asList("name", "age").containsAll(actualFieldNames));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenObject_whenGetsClassName_thenCorrect() {
|
public void givenObject_whenGetsClassName_thenCorrect() {
|
||||||
Object goat = new Goat("goat");
|
final Object goat = new Goat("goat");
|
||||||
Class<?> clazz = goat.getClass();
|
final Class<?> clazz = goat.getClass();
|
||||||
|
|
||||||
assertEquals("Goat", clazz.getSimpleName());
|
assertEquals("Goat", clazz.getSimpleName());
|
||||||
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
|
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
|
||||||
@ -35,7 +38,7 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassName_whenCreatesObject_thenCorrect() throws ClassNotFoundException {
|
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("Goat", clazz.getSimpleName());
|
||||||
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
|
assertEquals("com.baeldung.java.reflection.Goat", clazz.getName());
|
||||||
@ -44,10 +47,10 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenRecognisesModifiers_thenCorrect() throws ClassNotFoundException {
|
||||||
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||||
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
int goatMods = goatClass.getModifiers();
|
final int goatMods = goatClass.getModifiers();
|
||||||
int animalMods = animalClass.getModifiers();
|
final int animalMods = animalClass.getModifiers();
|
||||||
|
|
||||||
assertTrue(Modifier.isPublic(goatMods));
|
assertTrue(Modifier.isPublic(goatMods));
|
||||||
assertTrue(Modifier.isAbstract(animalMods));
|
assertTrue(Modifier.isAbstract(animalMods));
|
||||||
@ -56,20 +59,20 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsPackageInfo_thenCorrect() {
|
public void givenClass_whenGetsPackageInfo_thenCorrect() {
|
||||||
Goat goat = new Goat("goat");
|
final Goat goat = new Goat("goat");
|
||||||
Class<?> goatClass = goat.getClass();
|
final Class<?> goatClass = goat.getClass();
|
||||||
Package pkg = goatClass.getPackage();
|
final Package pkg = goatClass.getPackage();
|
||||||
|
|
||||||
assertEquals("com.baeldung.java.reflection", pkg.getName());
|
assertEquals("com.baeldung.java.reflection", pkg.getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsSuperClass_thenCorrect() {
|
public void givenClass_whenGetsSuperClass_thenCorrect() {
|
||||||
Goat goat = new Goat("goat");
|
final Goat goat = new Goat("goat");
|
||||||
String str = "any string";
|
final String str = "any string";
|
||||||
|
|
||||||
Class<?> goatClass = goat.getClass();
|
final Class<?> goatClass = goat.getClass();
|
||||||
Class<?> goatSuperClass = goatClass.getSuperclass();
|
final Class<?> goatSuperClass = goatClass.getSuperclass();
|
||||||
|
|
||||||
assertEquals("Animal", goatSuperClass.getSimpleName());
|
assertEquals("Animal", goatSuperClass.getSimpleName());
|
||||||
assertEquals("Object", str.getClass().getSuperclass().getSimpleName());
|
assertEquals("Object", str.getClass().getSuperclass().getSimpleName());
|
||||||
@ -78,10 +81,10 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsImplementedInterfaces_thenCorrect() throws ClassNotFoundException {
|
||||||
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||||
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
Class<?>[] goatInterfaces = goatClass.getInterfaces();
|
final Class<?>[] goatInterfaces = goatClass.getInterfaces();
|
||||||
Class<?>[] animalInterfaces = animalClass.getInterfaces();
|
final Class<?>[] animalInterfaces = animalClass.getInterfaces();
|
||||||
|
|
||||||
assertEquals(1, goatInterfaces.length);
|
assertEquals(1, goatInterfaces.length);
|
||||||
assertEquals(1, animalInterfaces.length);
|
assertEquals(1, animalInterfaces.length);
|
||||||
@ -91,8 +94,8 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsConstructor_thenCorrect() throws ClassNotFoundException {
|
||||||
Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
final Class<?> goatClass = Class.forName("com.baeldung.java.reflection.Goat");
|
||||||
Constructor<?>[] constructors = goatClass.getConstructors();
|
final Constructor<?>[] constructors = goatClass.getConstructors();
|
||||||
|
|
||||||
assertEquals(1, constructors.length);
|
assertEquals(1, constructors.length);
|
||||||
assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName());
|
assertEquals("com.baeldung.java.reflection.Goat", constructors[0].getName());
|
||||||
@ -100,10 +103,10 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsFields_thenCorrect() throws ClassNotFoundException {
|
||||||
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
Field[] fields = animalClass.getDeclaredFields();
|
final Field[] fields = animalClass.getDeclaredFields();
|
||||||
|
|
||||||
List<String> actualFields = getFieldNames(fields);
|
final List<String> actualFields = getFieldNames(fields);
|
||||||
|
|
||||||
assertEquals(2, actualFields.size());
|
assertEquals(2, actualFields.size());
|
||||||
assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY")));
|
assertTrue(actualFields.containsAll(Arrays.asList("name", "CATEGORY")));
|
||||||
@ -111,41 +114,41 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsMethods_thenCorrect() throws ClassNotFoundException {
|
||||||
Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
final Class<?> animalClass = Class.forName("com.baeldung.java.reflection.Animal");
|
||||||
Method[] methods = animalClass.getDeclaredMethods();
|
final Method[] methods = animalClass.getDeclaredMethods();
|
||||||
List<String> actualMethods = getMethodNames(methods);
|
final List<String> actualMethods = getMethodNames(methods);
|
||||||
|
|
||||||
assertEquals(4, actualMethods.size());
|
assertEquals(3, actualMethods.size());
|
||||||
assertTrue(actualMethods.containsAll(Arrays.asList("getName", "setName", "getSound")));
|
assertTrue(actualMethods.containsAll(Arrays.asList("getName", "setName", "getSound")));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsAllConstructors_thenCorrect() throws ClassNotFoundException {
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Constructor<?>[] constructors = birdClass.getConstructors();
|
final Constructor<?>[] constructors = birdClass.getConstructors();
|
||||||
|
|
||||||
assertEquals(3, constructors.length);
|
assertEquals(3, constructors.length);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsEachConstructorByParamTypes_thenCorrect() throws Exception {
|
public void givenClass_whenGetsEachConstructorByParamTypes_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();
|
birdClass.getConstructor();
|
||||||
Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
birdClass.getConstructor(String.class);
|
||||||
Constructor<?> cons3 = birdClass.getConstructor(String.class, boolean.class);
|
birdClass.getConstructor(String.class, boolean.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenInstantiatesObjectsAtRuntime_thenCorrect() throws Exception {
|
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();
|
final Constructor<?> cons1 = birdClass.getConstructor();
|
||||||
Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
final Constructor<?> cons2 = birdClass.getConstructor(String.class);
|
||||||
Constructor<?> cons3 = birdClass.getConstructor(String.class, boolean.class);
|
final Constructor<?> cons3 = birdClass.getConstructor(String.class, boolean.class);
|
||||||
|
|
||||||
Bird bird1 = (Bird) cons1.newInstance();
|
final Bird bird1 = (Bird) cons1.newInstance();
|
||||||
Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
|
final Bird bird2 = (Bird) cons2.newInstance("Weaver bird");
|
||||||
Bird bird3 = (Bird) cons3.newInstance("dove", true);
|
final Bird bird3 = (Bird) cons3.newInstance("dove", true);
|
||||||
|
|
||||||
assertEquals("bird", bird1.getName());
|
assertEquals("bird", bird1.getName());
|
||||||
assertEquals("Weaver bird", bird2.getName());
|
assertEquals("Weaver bird", bird2.getName());
|
||||||
@ -156,8 +159,8 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsPublicFields_thenCorrect() throws ClassNotFoundException {
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Field[] fields = birdClass.getFields();
|
final Field[] fields = birdClass.getFields();
|
||||||
assertEquals(1, fields.length);
|
assertEquals(1, fields.length);
|
||||||
assertEquals("CATEGORY", fields[0].getName());
|
assertEquals("CATEGORY", fields[0].getName());
|
||||||
|
|
||||||
@ -165,40 +168,40 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
|
public void givenClass_whenGetsPublicFieldByName_thenCorrect() throws Exception {
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Field field = birdClass.getField("CATEGORY");
|
final Field field = birdClass.getField("CATEGORY");
|
||||||
assertEquals("CATEGORY", field.getName());
|
assertEquals("CATEGORY", field.getName());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsDeclaredFields_thenCorrect() throws ClassNotFoundException {
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Field[] fields = birdClass.getDeclaredFields();
|
final Field[] fields = birdClass.getDeclaredFields();
|
||||||
assertEquals(1, fields.length);
|
assertEquals(1, fields.length);
|
||||||
assertEquals("walks", fields[0].getName());
|
assertEquals("walks", fields[0].getName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
|
public void givenClass_whenGetsFieldsByName_thenCorrect() throws Exception {
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Field field = birdClass.getDeclaredField("walks");
|
final Field field = birdClass.getDeclaredField("walks");
|
||||||
assertEquals("walks", field.getName());
|
assertEquals("walks", field.getName());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassField_whenGetsType_thenCorrect() throws Exception {
|
public void givenClassField_whenGetsType_thenCorrect() throws Exception {
|
||||||
Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks");
|
final Field field = Class.forName("com.baeldung.java.reflection.Bird").getDeclaredField("walks");
|
||||||
Class<?> fieldClass = field.getType();
|
final Class<?> fieldClass = field.getType();
|
||||||
assertEquals("boolean", fieldClass.getSimpleName());
|
assertEquals("boolean", fieldClass.getSimpleName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
|
public void givenClassField_whenSetsAndGetsValue_thenCorrect() throws Exception {
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Bird bird = (Bird) birdClass.newInstance();
|
final Bird bird = (Bird) birdClass.newInstance();
|
||||||
Field field = birdClass.getDeclaredField("walks");
|
final Field field = birdClass.getDeclaredField("walks");
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
|
|
||||||
assertFalse(field.getBoolean(bird));
|
assertFalse(field.getBoolean(bird));
|
||||||
@ -213,8 +216,8 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception {
|
public void givenClassField_whenGetsAndSetsWithNull_thenCorrect() throws Exception {
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Field field = birdClass.getField("CATEGORY");
|
final Field field = birdClass.getField("CATEGORY");
|
||||||
field.setAccessible(true);
|
field.setAccessible(true);
|
||||||
|
|
||||||
assertEquals("domestic", field.get(null));
|
assertEquals("domestic", field.get(null));
|
||||||
@ -222,9 +225,9 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsAllPublicMethods_thenCorrect() throws ClassNotFoundException {
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Method[] methods = birdClass.getMethods();
|
final Method[] methods = birdClass.getMethods();
|
||||||
List<String> methodNames = getMethodNames(methods);
|
final List<String> methodNames = getMethodNames(methods);
|
||||||
|
|
||||||
assertTrue(methodNames.containsAll(Arrays.asList("equals", "notifyAll", "hashCode", "walks", "eats", "toString")));
|
assertTrue(methodNames.containsAll(Arrays.asList("equals", "notifyAll", "hashCode", "walks", "eats", "toString")));
|
||||||
|
|
||||||
@ -232,10 +235,10 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
|
public void givenClass_whenGetsOnlyDeclaredMethods_thenCorrect() throws ClassNotFoundException {
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
List<String> actualMethodNames = getMethodNames(birdClass.getDeclaredMethods());
|
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());
|
assertEquals(expectedMethodNames.size(), actualMethodNames.size());
|
||||||
assertTrue(expectedMethodNames.containsAll(actualMethodNames));
|
assertTrue(expectedMethodNames.containsAll(actualMethodNames));
|
||||||
@ -245,9 +248,9 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception {
|
public void givenMethodName_whenGetsMethod_thenCorrect() throws Exception {
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Method walksMethod = birdClass.getDeclaredMethod("walks");
|
final Method walksMethod = birdClass.getDeclaredMethod("walks");
|
||||||
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
||||||
|
|
||||||
assertFalse(walksMethod.isAccessible());
|
assertFalse(walksMethod.isAccessible());
|
||||||
assertFalse(setWalksMethod.isAccessible());
|
assertFalse(setWalksMethod.isAccessible());
|
||||||
@ -262,17 +265,17 @@ public class ReflectionUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenMethod_whenInvokes_thenCorrect() throws Exception {
|
public void givenMethod_whenInvokes_thenCorrect() throws Exception {
|
||||||
Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
final Class<?> birdClass = Class.forName("com.baeldung.java.reflection.Bird");
|
||||||
Bird bird = (Bird) birdClass.newInstance();
|
final Bird bird = (Bird) birdClass.newInstance();
|
||||||
Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
final Method setWalksMethod = birdClass.getDeclaredMethod("setWalks", boolean.class);
|
||||||
Method walksMethod = birdClass.getDeclaredMethod("walks");
|
final Method walksMethod = birdClass.getDeclaredMethod("walks");
|
||||||
boolean walks = (boolean) walksMethod.invoke(bird);
|
final boolean walks = (boolean) walksMethod.invoke(bird);
|
||||||
|
|
||||||
assertFalse(walks);
|
assertFalse(walks);
|
||||||
assertFalse(bird.walks());
|
assertFalse(bird.walks());
|
||||||
|
|
||||||
setWalksMethod.invoke(bird, true);
|
setWalksMethod.invoke(bird, true);
|
||||||
boolean walks2 = (boolean) walksMethod.invoke(bird);
|
final boolean walks2 = (boolean) walksMethod.invoke(bird);
|
||||||
|
|
||||||
assertTrue(walks2);
|
assertTrue(walks2);
|
||||||
assertTrue(bird.walks());
|
assertTrue(bird.walks());
|
||||||
@ -280,17 +283,19 @@ public class ReflectionUnitTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static List<String> getFieldNames(Field[] fields) {
|
private static List<String> getFieldNames(Field[] fields) {
|
||||||
List<String> fieldNames = new ArrayList<>();
|
final List<String> fieldNames = new ArrayList<>();
|
||||||
for (Field field : fields)
|
for (final Field field : fields) {
|
||||||
fieldNames.add(field.getName());
|
fieldNames.add(field.getName());
|
||||||
|
}
|
||||||
return fieldNames;
|
return fieldNames;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<String> getMethodNames(Method[] methods) {
|
private static List<String> getMethodNames(Method[] methods) {
|
||||||
List<String> methodNames = new ArrayList<>();
|
final List<String> methodNames = new ArrayList<>();
|
||||||
for (Method method : methods)
|
for (final Method method : methods) {
|
||||||
methodNames.add(method.getName());
|
methodNames.add(method.getName());
|
||||||
|
}
|
||||||
return methodNames;
|
return methodNames;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -6,7 +6,7 @@ import org.junit.Test;
|
|||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class Java8DefaultStaticIntefaceMethodsTest {
|
public class Java8DefaultStaticIntefaceMethodsUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() {
|
public void callStaticInterfaceMethdosMethods_whenExpectedResults_thenCorrect() {
|
@ -1,17 +1,26 @@
|
|||||||
package com.baeldung.java8;
|
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.Before;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
public class Java8ExecutorServiceIntegrationTest {
|
||||||
import java.util.List;
|
|
||||||
import java.util.concurrent.*;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
|
|
||||||
|
|
||||||
public class Java8ExecutorServiceTest {
|
|
||||||
|
|
||||||
private Runnable runnableTask;
|
private Runnable runnableTask;
|
||||||
private Callable<String> callableTask;
|
private Callable<String> callableTask;
|
||||||
@ -53,9 +62,7 @@ public class Java8ExecutorServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() {
|
public void creationSubmittingTasksShuttingDownNow_whenShutDownAfterAwating_thenCorrect() {
|
||||||
|
|
||||||
ExecutorService threadPoolExecutor =
|
ExecutorService threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>());
|
||||||
new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS,
|
|
||||||
new LinkedBlockingQueue<>());
|
|
||||||
|
|
||||||
for (int i = 0; i < 100; i++) {
|
for (int i = 0; i < 100; i++) {
|
||||||
threadPoolExecutor.submit(callableTask);
|
threadPoolExecutor.submit(callableTask);
|
||||||
@ -138,8 +145,7 @@ public class Java8ExecutorServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
public void submittingTaskScheduling_whenExecuted_thenCorrect() {
|
public void submittingTaskScheduling_whenExecuted_thenCorrect() {
|
||||||
|
|
||||||
ScheduledExecutorService executorService = Executors
|
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
|
||||||
.newSingleThreadScheduledExecutor();
|
|
||||||
|
|
||||||
Future<String> resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS);
|
Future<String> resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS);
|
||||||
String result = null;
|
String result = null;
|
@ -1,18 +1,20 @@
|
|||||||
package com.baeldung.java8;
|
package com.baeldung.java8;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
import com.baeldung.forkjoin.CustomRecursiveAction;
|
import static org.junit.Assert.assertNotNull;
|
||||||
import com.baeldung.forkjoin.CustomRecursiveTask;
|
import static org.junit.Assert.assertTrue;
|
||||||
import com.baeldung.forkjoin.util.PoolUtil;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.util.Random;
|
import java.util.Random;
|
||||||
import java.util.concurrent.ForkJoinPool;
|
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 int[] arr;
|
||||||
private CustomRecursiveTask customRecursiveTask;
|
private CustomRecursiveTask customRecursiveTask;
|
||||||
@ -27,28 +29,23 @@ public class Java8ForkJoinTest {
|
|||||||
customRecursiveTask = new CustomRecursiveTask(arr);
|
customRecursiveTask = new CustomRecursiveTask(arr);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void callPoolUtil_whenExistsAndExpectedType_thenCorrect() {
|
public void callPoolUtil_whenExistsAndExpectedType_thenCorrect() {
|
||||||
|
|
||||||
ForkJoinPool forkJoinPool = PoolUtil.forkJoinPool;
|
ForkJoinPool forkJoinPool = PoolUtil.forkJoinPool;
|
||||||
ForkJoinPool forkJoinPoolTwo = PoolUtil.forkJoinPool;
|
ForkJoinPool forkJoinPoolTwo = PoolUtil.forkJoinPool;
|
||||||
|
|
||||||
assertNotNull(forkJoinPool);
|
assertNotNull(forkJoinPool);
|
||||||
assertEquals(2, forkJoinPool.getParallelism());
|
assertEquals(2, forkJoinPool.getParallelism());
|
||||||
assertEquals(forkJoinPool, forkJoinPoolTwo);
|
assertEquals(forkJoinPool, forkJoinPoolTwo);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void callCommonPool_whenExistsAndExpectedType_thenCorrect() {
|
public void callCommonPool_whenExistsAndExpectedType_thenCorrect() {
|
||||||
|
|
||||||
ForkJoinPool commonPool = ForkJoinPool.commonPool();
|
ForkJoinPool commonPool = ForkJoinPool.commonPool();
|
||||||
ForkJoinPool commonPoolTwo = ForkJoinPool.commonPool();
|
ForkJoinPool commonPoolTwo = ForkJoinPool.commonPool();
|
||||||
|
|
||||||
assertNotNull(commonPool);
|
assertNotNull(commonPool);
|
||||||
assertEquals(commonPool, commonPoolTwo);
|
assertEquals(commonPool, commonPoolTwo);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -63,7 +60,6 @@ public class Java8ForkJoinTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void executeRecursiveTask_whenExecuted_thenCorrect() {
|
public void executeRecursiveTask_whenExecuted_thenCorrect() {
|
||||||
|
|
||||||
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
|
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
|
||||||
|
|
||||||
forkJoinPool.execute(customRecursiveTask);
|
forkJoinPool.execute(customRecursiveTask);
|
||||||
@ -73,12 +69,10 @@ public class Java8ForkJoinTest {
|
|||||||
forkJoinPool.submit(customRecursiveTask);
|
forkJoinPool.submit(customRecursiveTask);
|
||||||
int resultTwo = customRecursiveTask.join();
|
int resultTwo = customRecursiveTask.join();
|
||||||
assertTrue(customRecursiveTask.isDone());
|
assertTrue(customRecursiveTask.isDone());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void executeRecursiveTaskWithFJ_whenExecuted_thenCorrect() {
|
public void executeRecursiveTaskWithFJ_whenExecuted_thenCorrect() {
|
||||||
|
|
||||||
CustomRecursiveTask customRecursiveTaskFirst = new CustomRecursiveTask(arr);
|
CustomRecursiveTask customRecursiveTaskFirst = new CustomRecursiveTask(arr);
|
||||||
CustomRecursiveTask customRecursiveTaskSecond = new CustomRecursiveTask(arr);
|
CustomRecursiveTask customRecursiveTaskSecond = new CustomRecursiveTask(arr);
|
||||||
CustomRecursiveTask customRecursiveTaskLast = new CustomRecursiveTask(arr);
|
CustomRecursiveTask customRecursiveTaskLast = new CustomRecursiveTask(arr);
|
||||||
@ -95,6 +89,6 @@ public class Java8ForkJoinTest {
|
|||||||
assertTrue(customRecursiveTaskSecond.isDone());
|
assertTrue(customRecursiveTaskSecond.isDone());
|
||||||
assertTrue(customRecursiveTaskLast.isDone());
|
assertTrue(customRecursiveTaskLast.isDone());
|
||||||
assertTrue(result != 0);
|
assertTrue(result != 0);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -11,7 +11,7 @@ import java.util.function.Function;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertNotEquals;
|
import static org.junit.Assert.assertNotEquals;
|
||||||
|
|
||||||
public class Java8FunctionalInteracesLambdasTest {
|
public class Java8FunctionalInteracesLambdasUnitTest {
|
||||||
|
|
||||||
private UseFoo useFoo;
|
private UseFoo useFoo;
|
||||||
|
|
@ -12,7 +12,7 @@ import java.util.stream.Stream;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class Java8MethodReferenceTest {
|
public class Java8MethodReferenceUnitTest {
|
||||||
|
|
||||||
private List<String> list;
|
private List<String> list;
|
||||||
|
|
@ -1,16 +1,23 @@
|
|||||||
package com.baeldung.java8;
|
package com.baeldung.java8;
|
||||||
|
|
||||||
import com.baeldung.java_8_features.*;
|
import static org.junit.Assert.assertEquals;
|
||||||
import org.junit.Before;
|
import static org.junit.Assert.assertFalse;
|
||||||
import org.junit.Test;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
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;
|
private List<String> list;
|
||||||
|
|
||||||
@ -32,7 +39,6 @@ public class Java8OptionalTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void checkOptional_whenAsExpected_thenCorrect() {
|
public void checkOptional_whenAsExpected_thenCorrect() {
|
||||||
|
|
||||||
Optional<String> optionalEmpty = Optional.empty();
|
Optional<String> optionalEmpty = Optional.empty();
|
||||||
assertFalse(optionalEmpty.isPresent());
|
assertFalse(optionalEmpty.isPresent());
|
||||||
|
|
||||||
@ -52,27 +58,19 @@ public class Java8OptionalTest {
|
|||||||
assertTrue(listOptNull.isEmpty());
|
assertTrue(listOptNull.isEmpty());
|
||||||
|
|
||||||
Optional<User> user = Optional.ofNullable(getUser());
|
Optional<User> user = Optional.ofNullable(getUser());
|
||||||
String result = user.map(User::getAddress)
|
String result = user.map(User::getAddress).map(Address::getStreet).orElse("not specified");
|
||||||
.map(Address::getStreet)
|
|
||||||
.orElse("not specified");
|
|
||||||
assertEquals(result, "1st Avenue");
|
assertEquals(result, "1st Avenue");
|
||||||
|
|
||||||
Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
|
Optional<OptionalUser> optionalUser = Optional.ofNullable(getOptionalUser());
|
||||||
String resultOpt = optionalUser.flatMap(OptionalUser::getAddress)
|
String resultOpt = optionalUser.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified");
|
||||||
.flatMap(OptionalAddress::getStreet)
|
|
||||||
.orElse("not specified");
|
|
||||||
assertEquals(resultOpt, "1st Avenue");
|
assertEquals(resultOpt, "1st Avenue");
|
||||||
|
|
||||||
Optional<User> userNull = Optional.ofNullable(getUserNull());
|
Optional<User> userNull = Optional.ofNullable(getUserNull());
|
||||||
String resultNull = userNull.map(User::getAddress)
|
String resultNull = userNull.map(User::getAddress).map(Address::getStreet).orElse("not specified");
|
||||||
.map(Address::getStreet)
|
|
||||||
.orElse("not specified");
|
|
||||||
assertEquals(resultNull, "not specified");
|
assertEquals(resultNull, "not specified");
|
||||||
|
|
||||||
Optional<OptionalUser> optionalUserNull = Optional.ofNullable(getOptionalUserNull());
|
Optional<OptionalUser> optionalUserNull = Optional.ofNullable(getOptionalUserNull());
|
||||||
String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress)
|
String resultOptNull = optionalUserNull.flatMap(OptionalUser::getAddress).flatMap(OptionalAddress::getStreet).orElse("not specified");
|
||||||
.flatMap(OptionalAddress::getStreet)
|
|
||||||
.orElse("not specified");
|
|
||||||
assertEquals(resultOptNull, "not specified");
|
assertEquals(resultOptNull, "not specified");
|
||||||
|
|
||||||
}
|
}
|
@ -17,11 +17,11 @@ import java.util.stream.*;
|
|||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class Java8StreamApiTest {
|
public class Java8StreamApiUnitTest {
|
||||||
|
|
||||||
private long counter;
|
private long counter;
|
||||||
|
|
||||||
private static Logger log = LoggerFactory.getLogger(Java8StreamApiTest.class);
|
private static Logger log = LoggerFactory.getLogger(Java8StreamApiUnitTest.class);
|
||||||
|
|
||||||
private List<Product> productList;
|
private List<Product> productList;
|
||||||
|
|
@ -14,7 +14,7 @@ import java.util.stream.Stream;
|
|||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class Java8StreamsTest {
|
public class Java8StreamsUnitTest {
|
||||||
|
|
||||||
private List<String> list;
|
private List<String> list;
|
||||||
|
|
@ -1,43 +1,43 @@
|
|||||||
package com.baeldung.java8;
|
package com.baeldung.java8;
|
||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
import static org.junit.Assert.assertEquals;
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
import java.io.IOException;
|
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.nio.file.attribute.BasicFileAttributes;
|
||||||
import java.text.DecimalFormat;
|
import java.text.DecimalFormat;
|
||||||
import java.util.concurrent.atomic.AtomicLong;
|
import java.util.concurrent.atomic.AtomicLong;
|
||||||
import java.util.stream.StreamSupport;
|
import java.util.stream.StreamSupport;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import org.apache.commons.io.FileUtils;
|
||||||
|
import org.junit.Before;
|
||||||
public class JavaFolderSizeTest {
|
import org.junit.Test;
|
||||||
|
|
||||||
|
public class JavaFolderSizeUnitTest {
|
||||||
|
private final long EXPECTED_SIZE = 24;
|
||||||
private String path;
|
private String path;
|
||||||
|
|
||||||
@Before
|
@Before
|
||||||
public void init() {
|
public void init() {
|
||||||
final String separator = File.separator;
|
final String separator = File.separator;
|
||||||
path = String.format("src%stest%sresources", separator, separator);
|
path = String.format("src%stest%sresources%stestFolder", separator, separator, separator);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGetFolderSizeRecursive_thenCorrect() {
|
public void whenGetFolderSizeRecursive_thenCorrect() {
|
||||||
final long expectedSize = 136;
|
|
||||||
|
|
||||||
final File folder = new File(path);
|
final File folder = new File(path);
|
||||||
final long size = getFolderSize(folder);
|
final long size = getFolderSize(folder);
|
||||||
|
|
||||||
assertEquals(expectedSize, size);
|
assertEquals(EXPECTED_SIZE, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGetFolderSizeUsingJava7_thenCorrect() throws IOException {
|
public void whenGetFolderSizeUsingJava7_thenCorrect() throws IOException {
|
||||||
final long expectedSize = 136;
|
|
||||||
|
|
||||||
final AtomicLong size = new AtomicLong(0);
|
final AtomicLong size = new AtomicLong(0);
|
||||||
final Path folder = Paths.get(path);
|
final Path folder = Paths.get(path);
|
||||||
|
|
||||||
@ -49,41 +49,33 @@ public class JavaFolderSizeTest {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
assertEquals(expectedSize, size.longValue());
|
assertEquals(EXPECTED_SIZE, size.longValue());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
|
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
|
||||||
final long expectedSize = 136;
|
|
||||||
|
|
||||||
final Path folder = Paths.get(path);
|
final Path folder = Paths.get(path);
|
||||||
final long size = Files.walk(folder).filter(p -> p.toFile().isFile()).mapToLong(p -> p.toFile().length()).sum();
|
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
|
@Test
|
||||||
public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() {
|
public void whenGetFolderSizeUsingApacheCommonsIO_thenCorrect() {
|
||||||
final long expectedSize = 136;
|
|
||||||
|
|
||||||
final File folder = new File(path);
|
final File folder = new File(path);
|
||||||
final long size = FileUtils.sizeOfDirectory(folder);
|
final long size = FileUtils.sizeOfDirectory(folder);
|
||||||
|
|
||||||
assertEquals(expectedSize, size);
|
assertEquals(EXPECTED_SIZE, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenGetFolderSizeUsingGuava_thenCorrect() {
|
public void whenGetFolderSizeUsingGuava_thenCorrect() {
|
||||||
final long expectedSize = 136;
|
|
||||||
|
|
||||||
final File folder = new File(path);
|
final File folder = new File(path);
|
||||||
|
|
||||||
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
|
final Iterable<File> files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
|
||||||
final long size = StreamSupport.stream(files.spliterator(), false)
|
final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
|
||||||
.filter(File::isFile)
|
|
||||||
.mapToLong(File::length).sum();
|
|
||||||
|
|
||||||
assertEquals(expectedSize, size);
|
assertEquals(EXPECTED_SIZE, size);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@ -91,19 +83,19 @@ public class JavaFolderSizeTest {
|
|||||||
final File folder = new File(path);
|
final File folder = new File(path);
|
||||||
final long size = getFolderSize(folder);
|
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 int unitIndex = (int) (Math.log10(size) / 3);
|
||||||
final double unitValue = 1 << (unitIndex * 10);
|
final double unitValue = 1 << (unitIndex * 10);
|
||||||
|
|
||||||
final String readableSize = new DecimalFormat("#,##0.#").format(size / unitValue) + " " + units[unitIndex];
|
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) {
|
private long getFolderSize(final File folder) {
|
||||||
long length = 0;
|
long length = 0;
|
||||||
final File[] files = folder.listFiles();
|
final File[] files = folder.listFiles();
|
||||||
|
|
||||||
for (File file : files) {
|
for (final File file : files) {
|
||||||
if (file.isFile()) {
|
if (file.isFile()) {
|
||||||
length += file.length();
|
length += file.length();
|
||||||
} else {
|
} else {
|
@ -8,7 +8,7 @@ import java.io.StringWriter;
|
|||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.Scanner;
|
import java.util.Scanner;
|
||||||
|
|
||||||
public class JavaTryWithResourcesTest {
|
public class JavaTryWithResourcesUnitTest {
|
||||||
|
|
||||||
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
|
private static final String TEST_STRING_HELLO_WORLD = "Hello World";
|
||||||
private Date resource1Date, resource2Date;
|
private Date resource1Date, resource2Date;
|
@ -7,7 +7,7 @@ import java.io.UnsupportedEncodingException;
|
|||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class ApacheCommonsEncodeDecodeTest {
|
public class ApacheCommonsEncodeDecodeUnitTest {
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
@ -8,7 +8,7 @@ import java.util.UUID;
|
|||||||
|
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class Java8EncodeDecodeTest {
|
public class Java8EncodeDecodeUnitTest {
|
||||||
|
|
||||||
// tests
|
// tests
|
||||||
|
|
@ -1,15 +1,15 @@
|
|||||||
package com.baeldung.socket;
|
package com.baeldung.socket;
|
||||||
|
|
||||||
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
import org.junit.BeforeClass;
|
import org.junit.BeforeClass;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.util.concurrent.Executors;
|
public class EchoIntegrationTest {
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
public class EchoTest {
|
|
||||||
private static final Integer PORT = 4444;
|
private static final Integer PORT = 4444;
|
||||||
|
|
||||||
@BeforeClass
|
@BeforeClass
|
||||||
@ -25,9 +25,15 @@ public class EchoTest {
|
|||||||
client.startConnection("127.0.0.1", PORT);
|
client.startConnection("127.0.0.1", PORT);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@After
|
||||||
|
public void tearDown() {
|
||||||
|
client.stopConnection();
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenClient_whenServerEchosMessage_thenCorrect() {
|
public void givenClient_whenServerEchosMessage_thenCorrect() {
|
||||||
|
|
||||||
String resp1 = client.sendMessage("hello");
|
String resp1 = client.sendMessage("hello");
|
||||||
String resp2 = client.sendMessage("world");
|
String resp2 = client.sendMessage("world");
|
||||||
String resp3 = client.sendMessage("!");
|
String resp3 = client.sendMessage("!");
|
||||||
@ -38,8 +44,4 @@ public class EchoTest {
|
|||||||
assertEquals("good bye", resp4);
|
assertEquals("good bye", resp4);
|
||||||
}
|
}
|
||||||
|
|
||||||
@After
|
|
||||||
public void tearDown() {
|
|
||||||
client.stopConnection();
|
|
||||||
}
|
|
||||||
}
|
}
|
@ -7,7 +7,7 @@ import java.util.concurrent.Executors;
|
|||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
|
|
||||||
public class EchoMultiTest {
|
public class SocketEchoMultiIntegrationTest {
|
||||||
|
|
||||||
private static final Integer PORT = 5555;
|
private static final Integer PORT = 5555;
|
||||||
|
|
@ -1,13 +1,23 @@
|
|||||||
package com.baeldung.threadpool;
|
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 java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
public class CoreThreadPoolIntegrationTest {
|
||||||
|
|
||||||
public class CoreThreadPoolTest {
|
|
||||||
|
|
||||||
@Test(timeout = 1000)
|
@Test(timeout = 1000)
|
||||||
public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {
|
public void whenCallingExecuteWithRunnable_thenRunnableIsExecuted() throws InterruptedException {
|
||||||
@ -132,9 +142,7 @@ public class CoreThreadPoolTest {
|
|||||||
@Test
|
@Test
|
||||||
public void whenUsingForkJoinPool_thenSumOfTreeElementsIsCalculatedCorrectly() {
|
public void whenUsingForkJoinPool_thenSumOfTreeElementsIsCalculatedCorrectly() {
|
||||||
|
|
||||||
TreeNode tree = new TreeNode(5,
|
TreeNode tree = new TreeNode(5, new TreeNode(3), new TreeNode(2, new TreeNode(2), new TreeNode(8)));
|
||||||
new TreeNode(3), new TreeNode(2,
|
|
||||||
new TreeNode(2), new TreeNode(8)));
|
|
||||||
|
|
||||||
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
|
ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
|
||||||
int sum = forkJoinPool.invoke(new CountingTask(tree));
|
int sum = forkJoinPool.invoke(new CountingTask(tree));
|
||||||
@ -142,5 +150,4 @@ public class CoreThreadPoolTest {
|
|||||||
assertEquals(20, sum);
|
assertEquals(20, sum);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
@ -16,7 +16,7 @@ import org.junit.Test;
|
|||||||
import static org.junit.Assert.assertEquals;
|
import static org.junit.Assert.assertEquals;
|
||||||
import static org.junit.Assert.assertTrue;
|
import static org.junit.Assert.assertTrue;
|
||||||
|
|
||||||
public class GuavaThreadPoolTest {
|
public class GuavaThreadPoolIntegrationTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenExecutingTaskWithDirectExecutor_thenTheTaskIsExecutedInTheCurrentThread() {
|
public void whenExecutingTaskWithDirectExecutor_thenTheTaskIsExecutedInTheCurrentThread() {
|
@ -1,19 +1,22 @@
|
|||||||
package com.baeldung.util;
|
package com.baeldung.util;
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
import java.time.*;
|
|
||||||
import java.time.temporal.ChronoField;
|
|
||||||
|
|
||||||
import static org.junit.Assert.assertEquals;
|
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"));
|
private static final Clock clock = Clock.fixed(Instant.parse("2016-10-09T15:10:30.00Z"), ZoneId.of("UTC"));
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReturnCurrentDate() {
|
public void shouldReturnCurrentDate() {
|
||||||
|
|
||||||
final LocalDate now = LocalDate.now(clock);
|
final LocalDate now = LocalDate.now(clock);
|
||||||
|
|
||||||
assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
|
assertEquals(9, now.get(ChronoField.DAY_OF_MONTH));
|
||||||
@ -23,7 +26,6 @@ public class CurrentDateTimeTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReturnCurrentTime() {
|
public void shouldReturnCurrentTime() {
|
||||||
|
|
||||||
final LocalTime now = LocalTime.now(clock);
|
final LocalTime now = LocalTime.now(clock);
|
||||||
|
|
||||||
assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
|
assertEquals(15, now.get(ChronoField.HOUR_OF_DAY));
|
||||||
@ -33,9 +35,9 @@ public class CurrentDateTimeTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void shouldReturnCurrentTimestamp() {
|
public void shouldReturnCurrentTimestamp() {
|
||||||
|
|
||||||
final Instant now = Instant.now(clock);
|
final Instant now = Instant.now(clock);
|
||||||
|
|
||||||
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
|
assertEquals(clock.instant().getEpochSecond(), now.getEpochSecond());
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -1,13 +1,17 @@
|
|||||||
package org.baeldung.core.exceptions;
|
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.apache.log4j.Logger;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.io.*;
|
public class FileNotFoundExceptionUnitTest {
|
||||||
|
|
||||||
public class FileNotFoundExceptionTest {
|
private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionUnitTest.class);
|
||||||
|
|
||||||
private static final Logger LOG = Logger.getLogger(FileNotFoundExceptionTest.class);
|
|
||||||
|
|
||||||
private String fileName = Double.toString(Math.random());
|
private String fileName = Double.toString(Math.random());
|
||||||
|
|
@ -2,22 +2,22 @@ package org.baeldung.equalshashcode.entities;
|
|||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class ComplexClassTest {
|
public class ComplexClassUnitTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testEqualsAndHashcodes() {
|
public void testEqualsAndHashcodes() {
|
||||||
|
List<String> strArrayList = new ArrayList<String>();
|
||||||
ArrayList<String> strArrayList = new ArrayList<String>();
|
|
||||||
strArrayList.add("abc");
|
strArrayList.add("abc");
|
||||||
strArrayList.add("def");
|
strArrayList.add("def");
|
||||||
ComplexClass aObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
|
ComplexClass aObject = new ComplexClass(strArrayList, new HashSet<Integer>(45, 67));
|
||||||
ComplexClass bObject = 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("lmn");
|
||||||
strArrayListD.add("pqr");
|
strArrayListD.add("pqr");
|
||||||
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67));
|
ComplexClass dObject = new ComplexClass(strArrayListD, new HashSet<Integer>(45, 67));
|
@ -7,6 +7,7 @@ import java.util.Scanner;
|
|||||||
|
|
||||||
import org.apache.commons.io.FileUtils;
|
import org.apache.commons.io.FileUtils;
|
||||||
import org.apache.commons.io.LineIterator;
|
import org.apache.commons.io.LineIterator;
|
||||||
|
import org.junit.Ignore;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
@ -14,6 +15,7 @@ import org.slf4j.LoggerFactory;
|
|||||||
import com.google.common.base.Charsets;
|
import com.google.common.base.Charsets;
|
||||||
import com.google.common.io.Files;
|
import com.google.common.io.Files;
|
||||||
|
|
||||||
|
@Ignore("need large file for testing")
|
||||||
public class JavaIoUnitTest {
|
public class JavaIoUnitTest {
|
||||||
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
protected final Logger logger = LoggerFactory.getLogger(getClass());
|
||||||
|
|
||||||
|
@ -12,7 +12,7 @@ import static org.hamcrest.CoreMatchers.equalTo;
|
|||||||
import static org.hamcrest.core.IsNot.not;
|
import static org.hamcrest.core.IsNot.not;
|
||||||
import static org.junit.Assert.*;
|
import static org.junit.Assert.*;
|
||||||
|
|
||||||
public class ArrayListTest {
|
public class ArrayListUnitTest {
|
||||||
|
|
||||||
private List<String> stringsToSearch;
|
private List<String> stringsToSearch;
|
||||||
|
|
@ -46,7 +46,7 @@ public class JavaFileUnitTest {
|
|||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
|
public final void givenUsingJDK6_whenMovingFile_thenCorrect() throws IOException {
|
||||||
final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt");
|
final File fileToMove = new File("src/test/resources/toMoveFile_jdk6.txt");
|
||||||
fileToMove.exists();
|
fileToMove.createNewFile();// .exists();
|
||||||
final File destDir = new File("src/test/resources/");
|
final File destDir = new File("src/test/resources/");
|
||||||
destDir.mkdir();
|
destDir.mkdir();
|
||||||
|
|
||||||
@ -68,7 +68,7 @@ public class JavaFileUnitTest {
|
|||||||
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
|
public final void givenUsingGuava_whenMovingFile_thenCorrect() throws IOException {
|
||||||
final File fileToMove = new File("src/test/resources/fileToMove.txt");
|
final File fileToMove = new File("src/test/resources/fileToMove.txt");
|
||||||
fileToMove.createNewFile();
|
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());
|
final File targetFile = new File(destDir, fileToMove.getName());
|
||||||
com.google.common.io.Files.createParentDirs(targetFile);
|
com.google.common.io.Files.createParentDirs(targetFile);
|
||||||
com.google.common.io.Files.move(fileToMove, targetFile);
|
com.google.common.io.Files.move(fileToMove, targetFile);
|
||||||
@ -76,13 +76,14 @@ public class JavaFileUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingApache_whenMovingFile_thenCorrect() throws IOException {
|
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
|
@Test
|
||||||
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
|
public final void givenUsingApache_whenMovingFileApproach2_thenCorrect() throws IOException {
|
||||||
FileUtils.touch(new File("src/test/resources/fileToMove.txt"));
|
FileUtils.touch(new File("src/test/resources/fileToMove_apache.txt"));
|
||||||
FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove.txt"), FileUtils.getFile("src/main/resources/"), true);
|
FileUtils.moveFileToDirectory(FileUtils.getFile("src/test/resources/fileToMove_apache.txt"), FileUtils.getFile("src/main/resources/"), true);
|
||||||
}
|
}
|
||||||
|
|
||||||
// delete a file
|
// delete a file
|
||||||
@ -99,7 +100,7 @@ public class JavaFileUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public final void givenUsingJDK7nio2_whenDeletingAFile_thenCorrect() throws IOException {
|
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");
|
final Path fileToDeletePath = Paths.get("src/test/resources/fileToDelete_jdk7.txt");
|
||||||
Files.delete(fileToDeletePath);
|
Files.delete(fileToDeletePath);
|
||||||
@ -117,7 +118,7 @@ public class JavaFileUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void givenUsingCommonsIo_whenDeletingAFileV2_thenCorrect() throws IOException {
|
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"));
|
FileUtils.forceDelete(FileUtils.getFile("src/test/resources/fileToDelete.txt"));
|
||||||
}
|
}
|
||||||
|
@ -111,11 +111,11 @@ public class JavaReadFromFileUnitTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
|
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 BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
|
||||||
final String currentLine = reader.readLine();
|
final String currentLine = reader.readLine();
|
||||||
reader.close();
|
reader.close();
|
||||||
|
System.out.println(currentLine);
|
||||||
assertEquals(expected_value, currentLine);
|
assertEquals(expected_value, currentLine);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -143,8 +143,9 @@ public class JavaReadFromFileUnitTest {
|
|||||||
final FileChannel channel = reader.getChannel();
|
final FileChannel channel = reader.getChannel();
|
||||||
|
|
||||||
int bufferSize = 1024;
|
int bufferSize = 1024;
|
||||||
if (bufferSize > channel.size())
|
if (bufferSize > channel.size()) {
|
||||||
bufferSize = (int) channel.size();
|
bufferSize = (int) channel.size();
|
||||||
|
}
|
||||||
final ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
final ByteBuffer buff = ByteBuffer.allocate(bufferSize);
|
||||||
channel.read(buff);
|
channel.read(buff);
|
||||||
buff.flip();
|
buff.flip();
|
||||||
|
1
core-java/src/test/resources/testFolder/sample_file_1.in
Normal file
@ -0,0 +1 @@
|
|||||||
|
Hello world
|
1
core-java/src/test/resources/testFolder/sample_file_2.in
Normal file
@ -0,0 +1 @@
|
|||||||
|
Hello world !
|
@ -1,7 +1,10 @@
|
|||||||
package org.baeldung.gson.entities;
|
package org.baeldung.gson.entities;
|
||||||
|
|
||||||
|
import java.text.DateFormat;
|
||||||
|
import java.text.SimpleDateFormat;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.TimeZone;
|
||||||
|
|
||||||
public class ActorGson {
|
public class ActorGson {
|
||||||
|
|
||||||
@ -18,7 +21,7 @@ public class ActorGson {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "ActorGson [imdbId=" + imdbId + ", dateOfBirth=" + dateOfBirth + ", filmography=" + filmography + "]";
|
return "ActorGson [imdbId=" + imdbId + ", dateOfBirth=" + formatDateOfBirth() + ", filmography=" + filmography + "]";
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getImdbId() {
|
public String getImdbId() {
|
||||||
@ -45,5 +48,10 @@ public class ActorGson {
|
|||||||
this.filmography = filmography;
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -1,27 +1,33 @@
|
|||||||
package org.baeldung.gson.serialization;
|
package org.baeldung.gson.serialization;
|
||||||
|
|
||||||
import com.google.gson.*;
|
|
||||||
import org.baeldung.gson.entities.ActorGson;
|
|
||||||
|
|
||||||
import java.lang.reflect.Type;
|
import java.lang.reflect.Type;
|
||||||
import java.text.ParseException;
|
import java.text.ParseException;
|
||||||
import java.text.SimpleDateFormat;
|
import java.text.SimpleDateFormat;
|
||||||
import java.util.ArrayList;
|
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> {
|
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
|
@Override
|
||||||
public ActorGson deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
|
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");
|
final JsonElement jsonImdbId = jsonObject.get("imdbId");
|
||||||
JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth");
|
final JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth");
|
||||||
JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography");
|
final JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography");
|
||||||
|
|
||||||
ArrayList<String> filmList = new ArrayList<String>();
|
final ArrayList<String> filmList = new ArrayList<String>();
|
||||||
if (jsonFilmography != null) {
|
if (jsonFilmography != null) {
|
||||||
for (int i = 0; i < jsonFilmography.size(); i++) {
|
for (int i = 0; i < jsonFilmography.size(); i++) {
|
||||||
filmList.add(jsonFilmography.get(i).getAsString());
|
filmList.add(jsonFilmography.get(i).getAsString());
|
||||||
@ -31,7 +37,7 @@ public class ActorGsonDeserializer implements JsonDeserializer<ActorGson> {
|
|||||||
ActorGson actorGson = null;
|
ActorGson actorGson = null;
|
||||||
try {
|
try {
|
||||||
actorGson = new ActorGson(jsonImdbId.getAsString(), sdf.parse(jsonDateOfBirth.getAsString()), filmList);
|
actorGson = new ActorGson(jsonImdbId.getAsString(), sdf.parse(jsonDateOfBirth.getAsString()), filmList);
|
||||||
} catch (ParseException e) {
|
} catch (final ParseException e) {
|
||||||
// TODO Auto-generated catch block
|
// TODO Auto-generated catch block
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
|
@ -1,38 +1,40 @@
|
|||||||
package org.baeldung.gson.deserialization;
|
package org.baeldung.gson.deserialization;
|
||||||
|
|
||||||
import com.google.gson.Gson;
|
import java.text.ParseException;
|
||||||
import com.google.gson.GsonBuilder;
|
|
||||||
import org.baeldung.gson.entities.ActorGson;
|
import org.baeldung.gson.entities.ActorGson;
|
||||||
import org.baeldung.gson.entities.Movie;
|
import org.baeldung.gson.entities.Movie;
|
||||||
import org.baeldung.gson.serialization.ActorGsonDeserializer;
|
import org.baeldung.gson.serialization.ActorGsonDeserializer;
|
||||||
import org.junit.Assert;
|
import org.junit.Assert;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
import java.text.ParseException;
|
import com.google.gson.Gson;
|
||||||
|
import com.google.gson.GsonBuilder;
|
||||||
|
|
||||||
public class GsonDeserializeTest {
|
public class GsonDeserializeTest {
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenSimpleDeserialize_thenCorrect() throws ParseException {
|
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);
|
Assert.assertEquals(outputMovie.toString(), expectedOutput);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void whenCustomDeserialize_thenCorrect() throws ParseException {
|
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);
|
Assert.assertEquals(outputMovie.toString(), expectedOutput);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -141,12 +141,52 @@
|
|||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>${maven-surefire-plugin.version}</version>
|
<version>${maven-surefire-plugin.version}</version>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<exclude>**/*LiveTest.java</exclude>
|
||||||
|
</excludes>
|
||||||
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
</plugins>
|
</plugins>
|
||||||
|
|
||||||
</build>
|
</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>
|
<properties>
|
||||||
<!-- persistence -->
|
<!-- persistence -->
|
||||||
<hibernate.version>4.3.11.Final</hibernate.version>
|
<hibernate.version>4.3.11.Final</hibernate.version>
|
||||||
|
@ -51,7 +51,7 @@ public class HttpAsyncClientLiveTest {
|
|||||||
@Test
|
@Test
|
||||||
public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
|
public void whenUseHttpAsyncClient_thenCorrect() throws InterruptedException, ExecutionException, IOException {
|
||||||
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
|
final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
|
||||||
// client.start();
|
client.start();
|
||||||
final HttpGet request = new HttpGet(HOST);
|
final HttpGet request = new HttpGet(HOST);
|
||||||
|
|
||||||
final Future<HttpResponse> future = client.execute(request, null);
|
final Future<HttpResponse> future = client.execute(request, null);
|
||||||
|
@ -28,15 +28,17 @@ import org.apache.http.impl.client.CloseableHttpClient;
|
|||||||
import org.apache.http.impl.client.HttpClientBuilder;
|
import org.apache.http.impl.client.HttpClientBuilder;
|
||||||
import org.junit.After;
|
import org.junit.After;
|
||||||
import org.junit.Before;
|
import org.junit.Before;
|
||||||
|
import org.junit.Ignore;
|
||||||
import org.junit.Test;
|
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 SERVER = "http://echo.200please.com";
|
||||||
private static final String TEXTFILENAME = "temp.txt";
|
private static final String TEXTFILENAME = "temp.txt";
|
||||||
private static final String IMAGEFILENAME = "image.jpg";
|
private static final String IMAGEFILENAME = "image.jpg";
|
||||||
private static final String ZIPFILENAME = "zipFile.zip";
|
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 CloseableHttpClient client;
|
||||||
private HttpPost post;
|
private HttpPost post;
|
||||||
private BufferedReader rd;
|
private BufferedReader rd;
|
@ -27,9 +27,11 @@ import org.apache.http.impl.auth.BasicScheme;
|
|||||||
import org.apache.http.impl.client.CloseableHttpClient;
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||||||
import org.apache.http.impl.client.HttpClients;
|
import org.apache.http.impl.client.HttpClients;
|
||||||
import org.apache.http.message.BasicNameValuePair;
|
import org.apache.http.message.BasicNameValuePair;
|
||||||
|
import org.junit.Ignore;
|
||||||
import org.junit.Test;
|
import org.junit.Test;
|
||||||
|
|
||||||
public class HttpClientPostingTest {
|
@Ignore("need spring-rest module running")
|
||||||
|
public class HttpClientPostingLiveTest {
|
||||||
private static final String SAMPLE_URL = "http://localhost:8080/spring-rest/users";
|
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 URL_SECURED_BY_BASIC_AUTHENTICATION = "http://browserspy.dk/password-ok.php";
|
||||||
private static final String DEFAULT_USER = "test";
|
private static final String DEFAULT_USER = "test";
|
@ -19,6 +19,7 @@ class FirstTest {
|
|||||||
.sum() > 5, "Sum should be greater than 5");
|
.sum() > 5, "Sum should be greater than 5");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Disabled("test to show MultipleFailuresError")
|
||||||
@Test
|
@Test
|
||||||
void groupAssertions() {
|
void groupAssertions() {
|
||||||
int[] numbers = {0, 1, 2, 3, 4};
|
int[] numbers = {0, 1, 2, 3, 4};
|
||||||
|
@ -53,7 +53,7 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.seleniumhq.selenium</groupId>
|
<groupId>org.seleniumhq.selenium</groupId>
|
||||||
<artifactId>selenium-java</artifactId>
|
<artifactId>selenium-java</artifactId>
|
||||||
<version>2.53.1</version>
|
<version>3.0.1</version>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>junit</groupId>
|
<groupId>junit</groupId>
|
||||||
|
@ -15,6 +15,7 @@ public class SeleniumExample {
|
|||||||
private String url = "http://www.baeldung.com/";
|
private String url = "http://www.baeldung.com/";
|
||||||
|
|
||||||
public SeleniumExample() {
|
public SeleniumExample() {
|
||||||
|
System.setProperty("webdriver.firefox.marionette", "C:\\selenium\\geckodriver.exe");
|
||||||
webDriver = new FirefoxDriver();
|
webDriver = new FirefoxDriver();
|
||||||
webDriver.manage().window().maximize();
|
webDriver.manage().window().maximize();
|
||||||
webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
|
webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
|
||||||
@ -29,16 +30,20 @@ public class SeleniumExample {
|
|||||||
return webDriver.getTitle();
|
return webDriver.getTitle();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void getAboutBaeldungPage() throws Exception {
|
public void getAboutBaeldungPage() {
|
||||||
closeOverlay();
|
closeOverlay();
|
||||||
clickAboutLink();
|
clickAboutLink();
|
||||||
clickAboutUsLink();
|
clickAboutUsLink();
|
||||||
}
|
}
|
||||||
|
|
||||||
private void closeOverlay() throws Exception {
|
private void closeOverlay() {
|
||||||
List<WebElement> webElementList = webDriver.findElements(By.tagName("a"));
|
List<WebElement> webElementList = webDriver.findElements(By.tagName("a"));
|
||||||
if (webElementList != null && !webElementList.isEmpty() && webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().isPresent()) {
|
try {
|
||||||
webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().orElseThrow(NoSuchElementException::new).click();
|
if (webElementList != null && !webElementList.isEmpty()) {
|
||||||
|
webElementList.stream().filter(webElement -> "Close".equalsIgnoreCase(webElement.getAttribute("title"))).findAny().orElseThrow(NoSuchElementException::new).click();
|
||||||
|
}
|
||||||
|
} catch (NoSuchElementException exception) {
|
||||||
|
exception.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,6 +3,9 @@ server.port=8082
|
|||||||
|
|
||||||
eureka.instance.hostname=localhost
|
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.register-with-eureka=false
|
||||||
eureka.client.fetch-registry=false
|
eureka.client.fetch-registry=false
|
||||||
|
|
||||||
|
spring.redis.host=localhost
|
||||||
|
spring.redis.port=6379
|
@ -3,8 +3,21 @@ server.port=8080
|
|||||||
|
|
||||||
eureka.client.region = default
|
eureka.client.region = default
|
||||||
eureka.client.registryFetchIntervalSeconds = 5
|
eureka.client.registryFetchIntervalSeconds = 5
|
||||||
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka/
|
|
||||||
|
management.security.sessions=always
|
||||||
|
|
||||||
zuul.routes.resource.path=/resource/**
|
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
|
@ -2,7 +2,16 @@ spring.application.name=resource
|
|||||||
server.port=8083
|
server.port=8083
|
||||||
|
|
||||||
resource.returnString=hello cloud
|
resource.returnString=hello cloud
|
||||||
|
resource.user.returnString=hello cloud user
|
||||||
|
resource.admin.returnString=hello cloud admin
|
||||||
|
|
||||||
eureka.client.region = default
|
eureka.client.region = default
|
||||||
eureka.client.registryFetchIntervalSeconds = 5
|
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
|
||||||
|
@ -28,6 +28,10 @@
|
|||||||
<artifactId>spring-boot-starter-test</artifactId>
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
@ -48,6 +52,15 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
</plugin>
|
</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>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
@ -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.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
@ -5,4 +5,4 @@ spring.cloud.config.server.git.uri=file:///${user.home}/application-config
|
|||||||
|
|
||||||
eureka.client.region = default
|
eureka.client.region = default
|
||||||
eureka.client.registryFetchIntervalSeconds = 5
|
eureka.client.registryFetchIntervalSeconds = 5
|
||||||
eureka.client.serviceUrl.defaultZone=http://localhost:8082/eureka
|
eureka.client.serviceUrl.defaultZone=http://discUser:discPassword@localhost:8082/eureka/
|
@ -28,6 +28,20 @@
|
|||||||
<artifactId>spring-boot-starter-test</artifactId>
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</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>
|
</dependencies>
|
||||||
|
|
||||||
<dependencyManagement>
|
<dependencyManagement>
|
||||||
@ -48,6 +62,15 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
</plugin>
|
</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>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
</project>
|
</project>
|
@ -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.SpringApplication;
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -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 {
|
||||||
|
}
|
@ -1,2 +1,4 @@
|
|||||||
spring.cloud.config.name=discovery
|
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
|
@ -27,6 +27,21 @@
|
|||||||
<groupId>org.springframework.cloud</groupId>
|
<groupId>org.springframework.cloud</groupId>
|
||||||
<artifactId>spring-cloud-starter-zuul</artifactId>
|
<artifactId>spring-cloud-starter-zuul</artifactId>
|
||||||
</dependency>
|
</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>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
@ -52,6 +67,15 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
</plugin>
|
</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>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
</project>
|
</project>
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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();
|
||||||
|
}
|
||||||
|
}
|
@ -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 {
|
||||||
|
}
|
@ -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;
|
||||||
|
}
|
||||||
|
}
|
@ -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);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,5 +1,7 @@
|
|||||||
spring.cloud.config.name=gateway
|
spring.cloud.config.name=gateway
|
||||||
spring.cloud.config.discovery.service-id=config
|
spring.cloud.config.discovery.service-id=config
|
||||||
spring.cloud.config.discovery.enabled=true
|
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/
|
After Width: | Height: | Size: 83 KiB |
After Width: | Height: | Size: 362 KiB |
After Width: | Height: | Size: 4.1 KiB |
After Width: | Height: | Size: 109 KiB |
After Width: | Height: | Size: 8.9 KiB |
After Width: | Height: | Size: 1.4 KiB |
After Width: | Height: | Size: 3.7 KiB |
After Width: | Height: | Size: 6.1 KiB |
@ -27,6 +27,21 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
<artifactId>spring-boot-starter-web</artifactId>
|
||||||
</dependency>
|
</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>
|
<dependency>
|
||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
@ -52,6 +67,15 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||||
</plugin>
|
</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>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
</project>
|
</project>
|
@ -1,4 +1,4 @@
|
|||||||
package com.baeldung.spring.cloud.integration.resource;
|
package com.baeldung.spring.cloud.bootstrap.resource;
|
||||||
|
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.boot.SpringApplication;
|
import org.springframework.boot.SpringApplication;
|
||||||
@ -18,8 +18,24 @@ public class ResourceApplication {
|
|||||||
@Value("${resource.returnString}")
|
@Value("${resource.returnString}")
|
||||||
private String returnString;
|
private String returnString;
|
||||||
|
|
||||||
|
@Value("${resource.user.returnString}")
|
||||||
|
private String userReturnString;
|
||||||
|
|
||||||
|
@Value("${resource.admin.returnString}")
|
||||||
|
private String adminReturnString;
|
||||||
|
|
||||||
@RequestMapping("/hello/cloud")
|
@RequestMapping("/hello/cloud")
|
||||||
public String getString() {
|
public String getString() {
|
||||||
return returnString;
|
return returnString;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@RequestMapping("/hello/user")
|
||||||
|
public String getUserString() {
|
||||||
|
return userReturnString;
|
||||||
|
}
|
||||||
|
|
||||||
|
@RequestMapping("/hello/admin")
|
||||||
|
public String getAdminString() {
|
||||||
|
return adminReturnString;
|
||||||
|
}
|
||||||
}
|
}
|
@ -0,0 +1,33 @@
|
|||||||
|
package com.baeldung.spring.cloud.bootstrap.resource;
|
||||||
|
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
|
||||||
|
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||||
|
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
|
||||||
|
|
||||||
|
@EnableWebSecurity
|
||||||
|
@Configuration
|
||||||
|
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
public void configureGlobal1(AuthenticationManagerBuilder auth) throws Exception {
|
||||||
|
//try in memory auth with no users to support the case that this will allow for users that are logged in to go anywhere
|
||||||
|
auth.inMemoryAuthentication();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
protected void configure(HttpSecurity http) throws Exception {
|
||||||
|
http.httpBasic()
|
||||||
|
.disable()
|
||||||
|
.authorizeRequests()
|
||||||
|
.antMatchers("/hello/cloud").permitAll()
|
||||||
|
.antMatchers("/hello/user").hasAnyRole("USER", "ADMIN")
|
||||||
|
.antMatchers("/hello/admin").hasRole("ADMIN")
|
||||||
|
.anyRequest().authenticated()
|
||||||
|
.and()
|
||||||
|
.csrf()
|
||||||
|
.disable();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,10 @@
|
|||||||
|
package com.baeldung.spring.cloud.bootstrap.resource;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
|
||||||
|
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableRedisHttpSession
|
||||||
|
public class SessionConfig extends AbstractHttpSessionApplicationInitializer {
|
||||||
|
}
|
@ -1,5 +1,7 @@
|
|||||||
spring.cloud.config.name=resource
|
spring.cloud.config.name=resource
|
||||||
spring.cloud.config.discovery.service-id=config
|
spring.cloud.config.discovery.service-id=config
|
||||||
spring.cloud.config.discovery.enabled=true
|
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/
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
server.port=8888
|
server.port=8888
|
||||||
spring.cloud.config.server.git.uri=https://github.com/eugenp/tutorials/tree/master/spring-cloud-config/client-config
|
spring.cloud.config.server.git.uri=https://github.com/spring-cloud-samples/config-repo
|
||||||
spring.cloud.config.server.git.clone-on-start=false
|
spring.cloud.config.server.git.clone-on-start=true
|
||||||
security.user.name=root
|
security.user.name=root
|
||||||
security.user.password=s3cr3t
|
security.user.password=s3cr3t
|
||||||
encrypt.key-store.location=classpath:/config-server.jks
|
encrypt.key-store.location=classpath:/config-server.jks
|
||||||
|