diff --git a/algorithms/README.md b/algorithms/README.md
index 3401b6d935..31cb8076d9 100644
--- a/algorithms/README.md
+++ b/algorithms/README.md
@@ -16,3 +16,4 @@
- [Introduction to Minimax Algorithm](http://www.baeldung.com/java-minimax-algorithm)
- [How to Calculate Levenshtein Distance in Java?](http://www.baeldung.com/java-levenshtein-distance)
- [How to Find the Kth Largest Element in Java](http://www.baeldung.com/java-kth-largest-element)
+- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
diff --git a/algorithms/pom.xml b/algorithms/pom.xml
index 2eb8cd42b6..8751cf45c0 100644
--- a/algorithms/pom.xml
+++ b/algorithms/pom.xml
@@ -9,6 +9,7 @@
1.5.0
1.16.12
3.6.1
+ 1.0.1
@@ -39,6 +40,11 @@
jgrapht-core
1.0.1
+
+ pl.allegro.finance
+ tradukisto
+ ${tradukisto.version}
+
org.assertj
assertj-core
@@ -46,7 +52,6 @@
test
-
@@ -77,4 +82,4 @@
-
+
\ No newline at end of file
diff --git a/algorithms/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java b/algorithms/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java
new file mode 100644
index 0000000000..0fe2960f96
--- /dev/null
+++ b/algorithms/src/main/java/com/baeldung/algorithms/numberwordconverter/NumberWordConverter.java
@@ -0,0 +1,75 @@
+package com.baeldung.algorithms.numberwordconverter;
+
+import java.math.BigDecimal;
+
+import pl.allegro.finance.tradukisto.MoneyConverters;
+
+public class NumberWordConverter {
+
+ public static final String INVALID_INPUT_GIVEN = "Invalid input given";
+
+ public static final String[] ones = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
+
+ public static final String[] tens = {
+ "", // 0
+ "", // 1
+ "twenty", // 2
+ "thirty", // 3
+ "forty", // 4
+ "fifty", // 5
+ "sixty", // 6
+ "seventy", // 7
+ "eighty", // 8
+ "ninety" // 9
+ };
+
+ public static String getMoneyIntoWords(String input) {
+ MoneyConverters converter = MoneyConverters.ENGLISH_BANKING_MONEY_VALUE;
+ return converter.asWords(new BigDecimal(input));
+ }
+
+ public static String getMoneyIntoWords(final double money) {
+ long dollar = (long) money;
+ long cents = Math.round((money - dollar) * 100);
+ if (money == 0D) {
+ return "";
+ }
+ if (money < 0) {
+ return INVALID_INPUT_GIVEN;
+ }
+ String dollarPart = "";
+ if (dollar > 0) {
+ dollarPart = convert(dollar) + " dollar" + (dollar == 1 ? "" : "s");
+ }
+ String centsPart = "";
+ if (cents > 0) {
+ if (dollarPart.length() > 0) {
+ centsPart = " and ";
+ }
+ centsPart += convert(cents) + " cent" + (cents == 1 ? "" : "s");
+ }
+ return dollarPart + centsPart;
+ }
+
+ private static String convert(final long n) {
+ if (n < 0) {
+ return INVALID_INPUT_GIVEN;
+ }
+ if (n < 20) {
+ return ones[(int) n];
+ }
+ if (n < 100) {
+ return tens[(int) n / 10] + ((n % 10 != 0) ? " " : "") + ones[(int) n % 10];
+ }
+ if (n < 1000) {
+ return ones[(int) n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100);
+ }
+ if (n < 1_000_000) {
+ return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000);
+ }
+ if (n < 1_000_000_000) {
+ return convert(n / 1_000_000) + " million" + ((n % 1_000_000 != 0) ? " " : "") + convert(n % 1_000_000);
+ }
+ return convert(n / 1_000_000_000) + " billion" + ((n % 1_000_000_000 != 0) ? " " : "") + convert(n % 1_000_000_000);
+ }
+}
\ No newline at end of file
diff --git a/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java b/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java
new file mode 100644
index 0000000000..a4a169f158
--- /dev/null
+++ b/algorithms/src/test/java/com/baeldung/algorithms/moneywords/NumberWordConverterTest.java
@@ -0,0 +1,84 @@
+package com.baeldung.algorithms.moneywords;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+import com.baeldung.algorithms.numberwordconverter.NumberWordConverter;
+
+public class NumberWordConverterTest {
+
+ @Test
+ public void whenMoneyNegative_thenReturnInvalidInput() {
+ assertEquals(NumberWordConverter.INVALID_INPUT_GIVEN, NumberWordConverter.getMoneyIntoWords(-13));
+ }
+
+ @Test
+ public void whenZeroDollarsGiven_thenReturnEmptyString() {
+ assertEquals("", NumberWordConverter.getMoneyIntoWords(0));
+ }
+
+ @Test
+ public void whenOnlyDollarsGiven_thenReturnWords() {
+ assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
+ }
+
+ @Test
+ public void whenOnlyCentsGiven_thenReturnWords() {
+ assertEquals("sixty cents", NumberWordConverter.getMoneyIntoWords(0.6));
+ }
+
+ @Test
+ public void whenAlmostAMillioDollarsGiven_thenReturnWords() {
+ String expectedResult = "nine hundred ninety nine thousand nine hundred ninety nine dollars";
+ assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(999_999));
+ }
+
+ @Test
+ public void whenThirtyMillionDollarsGiven_thenReturnWords() {
+ String expectedResult = "thirty three million three hundred forty eight thousand nine hundred seventy eight dollars";
+ assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(33_348_978));
+ }
+
+ @Test
+ public void whenTwoBillionDollarsGiven_thenReturnWords() {
+ String expectedResult = "two billion one hundred thirty three million two hundred forty seven thousand eight hundred ten dollars";
+ assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(2_133_247_810));
+ }
+
+ @Test
+ public void whenGivenDollarsAndCents_thenReturnWords() {
+ String expectedResult = "nine hundred twenty four dollars and sixty cents";
+ assertEquals(expectedResult, NumberWordConverter.getMoneyIntoWords(924.6));
+ }
+
+ @Test
+ public void whenOneDollarAndNoCents_thenReturnDollarSingular() {
+ assertEquals("one dollar", NumberWordConverter.getMoneyIntoWords(1));
+ }
+
+ @Test
+ public void whenNoDollarsAndOneCent_thenReturnCentSingular() {
+ assertEquals("one cent", NumberWordConverter.getMoneyIntoWords(0.01));
+ }
+
+ @Test
+ public void whenNoDollarsAndTwoCents_thenReturnCentsPlural() {
+ assertEquals("two cents", NumberWordConverter.getMoneyIntoWords(0.02));
+ }
+
+ @Test
+ public void whenNoDollarsAndNinetyNineCents_thenReturnWords() {
+ assertEquals("ninety nine cents", NumberWordConverter.getMoneyIntoWords(0.99));
+ }
+
+ @Test
+ public void whenNoDollarsAndNineFiveNineCents_thenCorrectRounding() {
+ assertEquals("ninety six cents", NumberWordConverter.getMoneyIntoWords(0.959));
+ }
+
+ @Test
+ public void whenGivenDollarsAndCents_thenReturnWordsVersionTwo() {
+ assertEquals("three hundred ten £ 00/100", NumberWordConverter.getMoneyIntoWords("310"));
+ }
+}
diff --git a/apache-curator/pom.xml b/apache-curator/pom.xml
new file mode 100644
index 0000000000..35549861c8
--- /dev/null
+++ b/apache-curator/pom.xml
@@ -0,0 +1,76 @@
+
+ 4.0.0
+ apache-curator
+ 0.0.1-SNAPSHOT
+ jar
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ 4.0.1
+ 3.4.11
+ 2.9.4
+
+
+ 3.6.1
+ 1.7.0
+
+
+
+
+
+
+
+
+ org.apache.curator
+ curator-x-async
+ ${curator.version}
+
+
+ org.apache.zookeeper
+ zookeeper
+
+
+
+
+
+ org.apache.curator
+ curator-recipes
+ ${curator.version}
+
+
+
+ org.apache.zookeeper
+ zookeeper
+ ${zookeeper.version}
+
+
+
+
+ com.fasterxml.jackson.core
+ jackson-databind
+ ${jackson-databind.version}
+
+
+
+
+
+ org.assertj
+ assertj-core
+ ${assertj.version}
+ test
+
+
+
+ com.jayway.awaitility
+ awaitility
+ ${avaitility.version}
+ test
+
+
+
diff --git a/apache-curator/src/main/java/com/baeldung/apache/curator/modeled/HostConfig.java b/apache-curator/src/main/java/com/baeldung/apache/curator/modeled/HostConfig.java
new file mode 100644
index 0000000000..bab7133742
--- /dev/null
+++ b/apache-curator/src/main/java/com/baeldung/apache/curator/modeled/HostConfig.java
@@ -0,0 +1,31 @@
+package com.baeldung.apache.curator.modeled;
+
+public class HostConfig {
+ private String hostname;
+ private int port;
+
+ public HostConfig() {
+
+ }
+
+ public HostConfig(String hostname, int port) {
+ this.hostname = hostname;
+ this.port = port;
+ }
+
+ public int getPort() {
+ return port;
+ }
+
+ public void setPort(int port) {
+ this.port = port;
+ }
+
+ public String getHostname() {
+ return hostname;
+ }
+
+ public void setHostname(String hostname) {
+ this.hostname = hostname;
+ }
+}
diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java
new file mode 100644
index 0000000000..cfac3ee3f2
--- /dev/null
+++ b/apache-curator/src/test/java/com/baeldung/apache/curator/BaseTest.java
@@ -0,0 +1,22 @@
+package com.baeldung.apache.curator;
+
+import org.apache.curator.RetryPolicy;
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.CuratorFrameworkFactory;
+import org.apache.curator.retry.RetryNTimes;
+import org.junit.Before;
+
+public abstract class BaseTest {
+
+ @Before
+ public void setup() {
+ org.apache.log4j.BasicConfigurator.configure();
+ }
+
+ protected CuratorFramework newClient() {
+ int sleepMsBetweenRetries = 100;
+ int maxRetries = 3;
+ RetryPolicy retryPolicy = new RetryNTimes(maxRetries, sleepMsBetweenRetries);
+ return CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryPolicy);
+ }
+}
diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java
new file mode 100644
index 0000000000..d02ef8131d
--- /dev/null
+++ b/apache-curator/src/test/java/com/baeldung/apache/curator/configuration/ConfigurationManagementManualTest.java
@@ -0,0 +1,89 @@
+package com.baeldung.apache.curator.configuration;
+
+import static com.jayway.awaitility.Awaitility.await;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.x.async.AsyncCuratorFramework;
+import org.junit.Test;
+
+import com.baeldung.apache.curator.BaseTest;
+
+public class ConfigurationManagementManualTest extends BaseTest {
+
+ private static final String KEY_FORMAT = "/%s";
+
+ @Test
+ public void givenPath_whenCreateKey_thenValueIsStored() throws Exception {
+ try (CuratorFramework client = newClient()) {
+ client.start();
+ AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
+ String key = getKey();
+ String expected = "my_value";
+
+ // Create key nodes structure
+ client.create()
+ .forPath(key);
+
+ // Set data value for our key
+ async.setData()
+ .forPath(key, expected.getBytes());
+
+ // Get data value
+ AtomicBoolean isEquals = new AtomicBoolean();
+ async.getData()
+ .forPath(key)
+ .thenAccept(
+ data -> isEquals.set(new String(data).equals(expected)));
+
+ await().until(() -> assertThat(isEquals.get()).isTrue());
+ }
+ }
+
+ @Test
+ public void givenPath_whenWatchAKeyAndStoreAValue_thenWatcherIsTriggered()
+ throws Exception {
+ try (CuratorFramework client = newClient()) {
+ client.start();
+ AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
+ String key = getKey();
+ String expected = "my_value";
+
+ // Create key structure
+ async.create()
+ .forPath(key);
+
+ List changes = new ArrayList<>();
+
+ // Watch data value
+ async.watched()
+ .getData()
+ .forPath(key)
+ .event()
+ .thenAccept(watchedEvent -> {
+ try {
+ changes.add(new String(client.getData()
+ .forPath(watchedEvent.getPath())));
+ } catch (Exception e) {
+ // fail ...
+ }
+ });
+
+ // Set data value for our key
+ async.setData()
+ .forPath(key, expected.getBytes());
+
+ await().until(() -> assertThat(changes.size() > 0).isTrue());
+ }
+ }
+
+ private String getKey() {
+ return String.format(KEY_FORMAT, UUID.randomUUID()
+ .toString());
+ }
+}
diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java
new file mode 100644
index 0000000000..61fa1c7c2c
--- /dev/null
+++ b/apache-curator/src/test/java/com/baeldung/apache/curator/connection/ConnectionManagementManualTest.java
@@ -0,0 +1,79 @@
+package com.baeldung.apache.curator.connection;
+
+import static com.jayway.awaitility.Awaitility.await;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.curator.RetryPolicy;
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.CuratorFrameworkFactory;
+import org.apache.curator.retry.RetryNTimes;
+import org.apache.curator.x.async.AsyncCuratorFramework;
+import org.junit.Test;
+
+public class ConnectionManagementManualTest {
+
+ @Test
+ public void givenRunningZookeeper_whenOpenConnection_thenClientIsOpened()
+ throws Exception {
+ int sleepMsBetweenRetries = 100;
+ int maxRetries = 3;
+ RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
+ sleepMsBetweenRetries);
+
+ try (CuratorFramework client = CuratorFrameworkFactory
+ .newClient("127.0.0.1:2181", retryPolicy)) {
+ client.start();
+
+ assertThat(client.checkExists()
+ .forPath("/")).isNotNull();
+ }
+ }
+
+ @Test
+ public void givenRunningZookeeper_whenOpenConnectionUsingAsyncNotBlocking_thenClientIsOpened()
+ throws InterruptedException {
+ int sleepMsBetweenRetries = 100;
+ int maxRetries = 3;
+ RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
+ sleepMsBetweenRetries);
+
+ try (CuratorFramework client = CuratorFrameworkFactory
+ .newClient("127.0.0.1:2181", retryPolicy)) {
+ client.start();
+ AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
+
+ AtomicBoolean exists = new AtomicBoolean(false);
+
+ async.checkExists()
+ .forPath("/")
+ .thenAcceptAsync(s -> exists.set(s != null));
+
+ await().until(() -> assertThat(exists.get()).isTrue());
+ }
+ }
+
+ @Test
+ public void givenRunningZookeeper_whenOpenConnectionUsingAsyncBlocking_thenClientIsOpened()
+ throws InterruptedException {
+ int sleepMsBetweenRetries = 100;
+ int maxRetries = 3;
+ RetryPolicy retryPolicy = new RetryNTimes(maxRetries,
+ sleepMsBetweenRetries);
+
+ try (CuratorFramework client = CuratorFrameworkFactory
+ .newClient("127.0.0.1:2181", retryPolicy)) {
+ client.start();
+ AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
+
+ AtomicBoolean exists = new AtomicBoolean(false);
+
+ async.checkExists()
+ .forPath("/")
+ .thenAccept(s -> exists.set(s != null));
+
+ await().until(() -> assertThat(exists.get()).isTrue());
+ }
+ }
+}
diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java
new file mode 100644
index 0000000000..4400c1d1aa
--- /dev/null
+++ b/apache-curator/src/test/java/com/baeldung/apache/curator/modeled/ModelTypedExamplesManualTest.java
@@ -0,0 +1,49 @@
+package com.baeldung.apache.curator.modeled;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.fail;
+
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.x.async.AsyncCuratorFramework;
+import org.apache.curator.x.async.modeled.JacksonModelSerializer;
+import org.apache.curator.x.async.modeled.ModelSpec;
+import org.apache.curator.x.async.modeled.ModeledFramework;
+import org.apache.curator.x.async.modeled.ZPath;
+import org.junit.Test;
+
+import com.baeldung.apache.curator.BaseTest;
+
+public class ModelTypedExamplesManualTest extends BaseTest {
+
+ @Test
+ public void givenPath_whenStoreAModel_thenNodesAreCreated()
+ throws InterruptedException {
+
+ ModelSpec mySpec = ModelSpec
+ .builder(ZPath.parseWithIds("/config/dev"),
+ JacksonModelSerializer.build(HostConfig.class))
+ .build();
+
+ try (CuratorFramework client = newClient()) {
+ client.start();
+ AsyncCuratorFramework async = AsyncCuratorFramework.wrap(client);
+ ModeledFramework modeledClient = ModeledFramework
+ .wrap(async, mySpec);
+
+ modeledClient.set(new HostConfig("host-name", 8080));
+
+ modeledClient.read()
+ .whenComplete((value, e) -> {
+ if (e != null) {
+ fail("Cannot read host config", e);
+ } else {
+ assertThat(value).isNotNull();
+ assertThat(value.getHostname()).isEqualTo("host-name");
+ assertThat(value.getPort()).isEqualTo(8080);
+ }
+
+ });
+ }
+
+ }
+}
diff --git a/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java b/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java
new file mode 100644
index 0000000000..04f4104e6b
--- /dev/null
+++ b/apache-curator/src/test/java/com/baeldung/apache/curator/recipes/RecipesManualTest.java
@@ -0,0 +1,74 @@
+package com.baeldung.apache.curator.recipes;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.apache.curator.framework.CuratorFramework;
+import org.apache.curator.framework.recipes.leader.LeaderSelector;
+import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
+import org.apache.curator.framework.recipes.locks.InterProcessSemaphoreMutex;
+import org.apache.curator.framework.recipes.shared.SharedCount;
+import org.apache.curator.framework.state.ConnectionState;
+import org.junit.Test;
+
+import com.baeldung.apache.curator.BaseTest;
+
+public class RecipesManualTest extends BaseTest {
+
+ @Test
+ public void givenRunningZookeeper_whenUsingLeaderElection_thenNoErrors() {
+ try (CuratorFramework client = newClient()) {
+ client.start();
+ LeaderSelector leaderSelector = new LeaderSelector(client, "/mutex/select/leader/for/job/A", new LeaderSelectorListener() {
+
+ @Override
+ public void stateChanged(CuratorFramework client, ConnectionState newState) {
+
+ }
+
+ @Override
+ public void takeLeadership(CuratorFramework client) throws Exception {
+ // I'm the leader of the job A !
+ }
+
+ });
+
+ leaderSelector.start();
+
+ // Wait until the job A is done among all the members
+
+ leaderSelector.close();
+ }
+ }
+
+ @Test
+ public void givenRunningZookeeper_whenUsingSharedLock_thenNoErrors() throws Exception {
+ try (CuratorFramework client = newClient()) {
+ client.start();
+ InterProcessSemaphoreMutex sharedLock = new InterProcessSemaphoreMutex(client, "/mutex/process/A");
+
+ sharedLock.acquire();
+
+ // Do process A
+
+ sharedLock.release();
+ }
+ }
+
+ @Test
+ public void givenRunningZookeeper_whenUsingSharedCounter_thenCounterIsIncrement() throws Exception {
+ try (CuratorFramework client = newClient()) {
+ client.start();
+
+ try (SharedCount counter = new SharedCount(client, "/counters/A", 0)) {
+ counter.start();
+
+ counter.setCount(0);
+ counter.setCount(counter.getCount() + 1);
+
+ assertThat(counter.getCount()).isEqualTo(1);
+ }
+
+ }
+ }
+
+}
diff --git a/apache-tika/pom.xml b/apache-tika/pom.xml
new file mode 100644
index 0000000000..34013dee89
--- /dev/null
+++ b/apache-tika/pom.xml
@@ -0,0 +1,25 @@
+
+ 4.0.0
+ com.baeldung
+ apache-tika
+ 0.0.1-SNAPSHOT
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ 1.17
+
+
+
+
+ org.apache.tika
+ tika-parsers
+ ${tika.version}
+
+
+
\ No newline at end of file
diff --git a/apache-tika/src/main/java/com/baeldung/tika/TikaAnalysis.java b/apache-tika/src/main/java/com/baeldung/tika/TikaAnalysis.java
new file mode 100644
index 0000000000..85eafc7c08
--- /dev/null
+++ b/apache-tika/src/main/java/com/baeldung/tika/TikaAnalysis.java
@@ -0,0 +1,67 @@
+package com.baeldung.tika;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.tika.Tika;
+import org.apache.tika.detect.DefaultDetector;
+import org.apache.tika.detect.Detector;
+import org.apache.tika.exception.TikaException;
+import org.apache.tika.metadata.Metadata;
+import org.apache.tika.mime.MediaType;
+import org.apache.tika.parser.AutoDetectParser;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.parser.Parser;
+import org.apache.tika.sax.BodyContentHandler;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+
+public class TikaAnalysis {
+ public static String detectDocTypeUsingDetector(InputStream stream) throws IOException {
+ Detector detector = new DefaultDetector();
+ Metadata metadata = new Metadata();
+
+ MediaType mediaType = detector.detect(stream, metadata);
+ return mediaType.toString();
+ }
+
+ public static String detectDocTypeUsingFacade(InputStream stream) throws IOException {
+ Tika tika = new Tika();
+ String mediaType = tika.detect(stream);
+ return mediaType;
+ }
+
+ public static String extractContentUsingParser(InputStream stream) throws IOException, TikaException, SAXException {
+ Parser parser = new AutoDetectParser();
+ ContentHandler handler = new BodyContentHandler();
+ Metadata metadata = new Metadata();
+ ParseContext context = new ParseContext();
+
+ parser.parse(stream, handler, metadata, context);
+ return handler.toString();
+ }
+
+ public static String extractContentUsingFacade(InputStream stream) throws IOException, TikaException {
+ Tika tika = new Tika();
+ String content = tika.parseToString(stream);
+ return content;
+ }
+
+ public static Metadata extractMetadatatUsingParser(InputStream stream) throws IOException, SAXException, TikaException {
+ Parser parser = new AutoDetectParser();
+ ContentHandler handler = new BodyContentHandler();
+ Metadata metadata = new Metadata();
+ ParseContext context = new ParseContext();
+
+ parser.parse(stream, handler, metadata, context);
+ return metadata;
+ }
+
+ public static Metadata extractMetadatatUsingFacade(InputStream stream) throws IOException, TikaException {
+ Tika tika = new Tika();
+ Metadata metadata = new Metadata();
+
+ tika.parse(stream, metadata);
+ return metadata;
+ }
+}
diff --git a/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java b/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java
new file mode 100644
index 0000000000..f8c2372d1f
--- /dev/null
+++ b/apache-tika/src/test/java/com/baeldung/tika/TikaUnitTest.java
@@ -0,0 +1,79 @@
+package com.baeldung.tika;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.tika.exception.TikaException;
+import org.apache.tika.metadata.Metadata;
+import org.junit.Test;
+import org.xml.sax.SAXException;
+
+public class TikaUnitTest {
+ @Test
+ public void whenUsingDetector_thenDocumentTypeIsReturned() throws IOException {
+ InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.txt");
+ String mediaType = TikaAnalysis.detectDocTypeUsingDetector(stream);
+
+ assertEquals("application/pdf", mediaType);
+
+ stream.close();
+ }
+
+ @Test
+ public void whenUsingFacade_thenDocumentTypeIsReturned() throws IOException {
+ InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.txt");
+ String mediaType = TikaAnalysis.detectDocTypeUsingFacade(stream);
+
+ assertEquals("application/pdf", mediaType);
+
+ stream.close();
+ }
+
+ @Test
+ public void whenUsingParser_thenContentIsReturned() throws IOException, TikaException, SAXException {
+ InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.docx");
+ String content = TikaAnalysis.extractContentUsingParser(stream);
+
+ assertThat(content, containsString("Apache Tika - a content analysis toolkit"));
+ assertThat(content, containsString("detects and extracts metadata and text"));
+
+ stream.close();
+ }
+
+ @Test
+ public void whenUsingFacade_thenContentIsReturned() throws IOException, TikaException {
+ InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.docx");
+ String content = TikaAnalysis.extractContentUsingFacade(stream);
+
+ assertThat(content, containsString("Apache Tika - a content analysis toolkit"));
+ assertThat(content, containsString("detects and extracts metadata and text"));
+
+ stream.close();
+ }
+
+ @Test
+ public void whenUsingParser_thenMetadataIsReturned() throws IOException, TikaException, SAXException {
+ InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.xlsx");
+ Metadata metadata = TikaAnalysis.extractMetadatatUsingParser(stream);
+
+ assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By"));
+ assertEquals("Microsoft Office User", metadata.get("Author"));
+
+ stream.close();
+ }
+
+ @Test
+ public void whenUsingFacade_thenMetadataIsReturned() throws IOException, TikaException {
+ InputStream stream = this.getClass().getClassLoader().getResourceAsStream("tika.xlsx");
+ Metadata metadata = TikaAnalysis.extractMetadatatUsingFacade(stream);
+
+ assertEquals("org.apache.tika.parser.DefaultParser", metadata.get("X-Parsed-By"));
+ assertEquals("Microsoft Office User", metadata.get("Author"));
+
+ stream.close();
+ }
+}
diff --git a/apache-tika/src/test/resources/tika.docx b/apache-tika/src/test/resources/tika.docx
new file mode 100644
index 0000000000..0a01ccef55
Binary files /dev/null and b/apache-tika/src/test/resources/tika.docx differ
diff --git a/apache-tika/src/test/resources/tika.txt b/apache-tika/src/test/resources/tika.txt
new file mode 100644
index 0000000000..26923836de
Binary files /dev/null and b/apache-tika/src/test/resources/tika.txt differ
diff --git a/apache-tika/src/test/resources/tika.xlsx b/apache-tika/src/test/resources/tika.xlsx
new file mode 100644
index 0000000000..110a0b2dd5
Binary files /dev/null and b/apache-tika/src/test/resources/tika.xlsx differ
diff --git a/apache-zookeeper/pom.xml b/apache-zookeeper/pom.xml
index 6d49d74ade..3a6fc1787b 100644
--- a/apache-zookeeper/pom.xml
+++ b/apache-zookeeper/pom.xml
@@ -6,6 +6,12 @@
0.0.1-SNAPSHOT
jar
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
org.apache.zookeeper
diff --git a/aws/src/main/java/com/baeldung/ec2/EC2Application.java b/aws/src/main/java/com/baeldung/ec2/EC2Application.java
new file mode 100644
index 0000000000..6755188fcd
--- /dev/null
+++ b/aws/src/main/java/com/baeldung/ec2/EC2Application.java
@@ -0,0 +1,137 @@
+package com.baeldung.ec2;
+
+import java.util.Arrays;
+
+import com.amazonaws.auth.AWSCredentials;
+import com.amazonaws.auth.AWSStaticCredentialsProvider;
+import com.amazonaws.auth.BasicAWSCredentials;
+import com.amazonaws.regions.Regions;
+import com.amazonaws.services.ec2.AmazonEC2;
+import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
+import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest;
+import com.amazonaws.services.ec2.model.CreateKeyPairRequest;
+import com.amazonaws.services.ec2.model.CreateKeyPairResult;
+import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest;
+import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
+import com.amazonaws.services.ec2.model.DescribeInstancesResult;
+import com.amazonaws.services.ec2.model.DescribeKeyPairsRequest;
+import com.amazonaws.services.ec2.model.DescribeKeyPairsResult;
+import com.amazonaws.services.ec2.model.IpPermission;
+import com.amazonaws.services.ec2.model.IpRange;
+import com.amazonaws.services.ec2.model.MonitorInstancesRequest;
+import com.amazonaws.services.ec2.model.RebootInstancesRequest;
+import com.amazonaws.services.ec2.model.RunInstancesRequest;
+import com.amazonaws.services.ec2.model.StartInstancesRequest;
+import com.amazonaws.services.ec2.model.StopInstancesRequest;
+import com.amazonaws.services.ec2.model.UnmonitorInstancesRequest;
+
+public class EC2Application {
+
+ private static final AWSCredentials credentials;
+
+ static {
+ // put your accesskey and secretkey here
+ credentials = new BasicAWSCredentials(
+ "",
+ ""
+ );
+ }
+
+ public static void main(String[] args) {
+
+ // Set up the client
+ AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
+ .withCredentials(new AWSStaticCredentialsProvider(credentials))
+ .withRegion(Regions.US_EAST_1)
+ .build();
+
+ // Create a security group
+ CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
+ .withDescription("Baeldung Security Group");
+ ec2Client.createSecurityGroup(createSecurityGroupRequest);
+
+ // Allow HTTP and SSH traffic
+ IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");
+
+ IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
+ .withIpProtocol("tcp")
+ .withFromPort(80)
+ .withToPort(80);
+
+ IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
+ .withIpProtocol("tcp")
+ .withFromPort(22)
+ .withToPort(22);
+
+ AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
+ .withGroupName("BaeldungSecurityGroup")
+ .withIpPermissions(ipPermission1, ipPermission2);
+
+ ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);
+
+ // Create KeyPair
+ CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
+ .withKeyName("baeldung-key-pair");
+ CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
+ String privateKey = createKeyPairResult
+ .getKeyPair()
+ .getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key
+
+ // See what key-pairs you've got
+ DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
+ DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);
+
+ // Launch an Amazon Instance
+ RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
+ .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
+ .withMinCount(1)
+ .withMaxCount(1)
+ .withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
+ .withSecurityGroups("BaeldungSecurityGroup");
+
+ String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();
+
+ // Start an Instance
+ StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
+ .withInstanceIds(yourInstanceId);
+
+ ec2Client.startInstances(startInstancesRequest);
+
+ // Monitor Instances
+ MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
+ .withInstanceIds(yourInstanceId);
+
+ ec2Client.monitorInstances(monitorInstancesRequest);
+
+ UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
+ .withInstanceIds(yourInstanceId);
+
+ ec2Client.unmonitorInstances(unmonitorInstancesRequest);
+
+ // Reboot an Instance
+
+ RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
+ .withInstanceIds(yourInstanceId);
+
+ ec2Client.rebootInstances(rebootInstancesRequest);
+
+ // Stop an Instance
+ StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
+ .withInstanceIds(yourInstanceId);
+
+ ec2Client.stopInstances(stopInstancesRequest)
+ .getStoppingInstances()
+ .get(0)
+ .getPreviousState()
+ .getName();
+
+ // Describe an Instance
+ DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
+ DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
+ System.out.println(response.getReservations()
+ .get(0)
+ .getInstances()
+ .get(0)
+ .getKernelId());
+ }
+}
diff --git a/core-groovy/build.gradle b/core-groovy/build.gradle
index b3f33836da..300827ee7c 100644
--- a/core-groovy/build.gradle
+++ b/core-groovy/build.gradle
@@ -8,6 +8,6 @@ repositories {
}
dependencies {
- compile 'org.codehaus.groovy:groovy-all:2.5.0-alpha-1'
+ compile 'org.codehaus.groovy:groovy-all:2.4.13'
testCompile 'org.spockframework:spock-core:1.1-groovy-2.4'
}
diff --git a/core-groovy/pom.xml b/core-groovy/pom.xml
index eb9932e0cf..91cbe66e35 100644
--- a/core-groovy/pom.xml
+++ b/core-groovy/pom.xml
@@ -1,6 +1,5 @@
-
+
4.0.0
core-groovy
@@ -24,17 +23,17 @@
org.codehaus.groovy
groovy
- 2.5.0-alpha-1
+ 2.4.13
org.codehaus.groovy
groovy-all
- 2.5.0-alpha-1
+ 2.4.13
org.codehaus.groovy
groovy-sql
- 2.5.0-alpha-1
+ 2.4.13
org.junit.jupiter
diff --git a/core-groovy/src/main/groovy/com/baeldung/json/JsonParser.groovy b/core-groovy/src/main/groovy/com/baeldung/json/JsonParser.groovy
index 0d7c451972..6cda7c6fbd 100644
--- a/core-groovy/src/main/groovy/com/baeldung/json/JsonParser.groovy
+++ b/core-groovy/src/main/groovy/com/baeldung/json/JsonParser.groovy
@@ -1,6 +1,5 @@
package com.baeldung.json
-import groovy.json.JsonGenerator
import groovy.json.JsonOutput
import groovy.json.JsonParserType
import groovy.json.JsonSlurper
@@ -21,14 +20,6 @@ class JsonParser {
JsonOutput.toJson(account)
}
- String toJson(Account account, String dateFormat, String... fieldsToExclude) {
- JsonGenerator generator = new JsonGenerator.Options()
- .dateFormat(dateFormat)
- .excludeFieldsByName(fieldsToExclude)
- .build()
- generator.toJson(account)
- }
-
String prettyfy(String json) {
JsonOutput.prettyPrint(json)
}
diff --git a/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy b/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy
index fcd51d58bc..c3842340a5 100644
--- a/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy
+++ b/core-groovy/src/test/groovy/com/baeldung/json/JsonParserTest.groovy
@@ -52,20 +52,6 @@ class JsonParserTest extends Specification {
json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}'
}
- def 'Should parse to Json given an Account object, a date format and fields to exclude' () {
- given:
- Account account = new Account(
- id: '123',
- value: 15.6,
- createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018')
- )
- when:
- def json = jsonParser.toJson(account, 'MM/dd/yyyy', 'value')
- then:
- json
- json == '{"createdAt":"01/01/2018","id":"123"}'
- }
-
def 'Should prettify given a json string' () {
given:
String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}'
diff --git a/core-java-8/README.md b/core-java-8/README.md
index 1b5208961d..949577df19 100644
--- a/core-java-8/README.md
+++ b/core-java-8/README.md
@@ -41,3 +41,5 @@
- [Primitive Type Streams in Java 8](http://www.baeldung.com/java-8-primitive-streams)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
+- [Java 8 StringJoiner](http://www.baeldung.com/java-string-joiner)
+- [Introduction to Spliterator in Java](http://www.baeldung.com/java-spliterator)
diff --git a/core-java-8/src/main/java/com/baeldung/findanelement/FindElementInAList.java b/core-java-8/src/main/java/com/baeldung/findanelement/FindElementInAList.java
new file mode 100644
index 0000000000..2f402ee72b
--- /dev/null
+++ b/core-java-8/src/main/java/com/baeldung/findanelement/FindElementInAList.java
@@ -0,0 +1,71 @@
+package com.baeldung.findanelement;
+
+import java.util.List;
+import java.util.ListIterator;
+import org.apache.commons.collections4.IterableUtils;
+import com.google.common.base.Predicate;
+import com.google.common.collect.Iterables;
+
+public class FindElementInAList {
+
+ public T findUsingIndexOf(T element, List list) {
+ int index = list.indexOf(element);
+ if (index >= 0) {
+ return element;
+ }
+ return null;
+ }
+
+ public boolean findUsingListIterator(T element, List list) {
+ ListIterator listIterator = list.listIterator();
+ while (listIterator.hasNext()) {
+ T elementFromList = listIterator.next();
+ if (elementFromList.equals(element)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public boolean findUsingEnhancedForLoop(T element, List list) {
+ for (T elementFromList : list) {
+ if (element.equals(elementFromList)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public T findUsingStream(T element, List list) {
+ return list.stream()
+ .filter(integer -> integer.equals(element))
+ .findFirst()
+ .orElse(null);
+ }
+
+ public T findUsingParallelStream(T element, List list) {
+ return list.parallelStream()
+ .filter(integer -> integer.equals(element))
+ .findAny()
+ .orElse(null);
+ }
+
+ public T findUsingGuava(T element, List list) {
+ T foundElement = Iterables.tryFind(list, new Predicate() {
+ public boolean apply(T input) {
+ return element.equals(input);
+ }
+ }).orNull();
+ return foundElement;
+ }
+
+ public T findUsingApacheCommon(T element, List list) {
+ T foundElement = IterableUtils.find(list, new org.apache.commons.collections4.Predicate() {
+ public boolean evaluate(T input) {
+ return element.equals(input);
+ }
+ });
+ return foundElement;
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/findanelement/FindAnElementTest.java b/core-java-8/src/test/java/com/baeldung/findanelement/FindAnElementTest.java
new file mode 100644
index 0000000000..1fef2d98e7
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/findanelement/FindAnElementTest.java
@@ -0,0 +1,116 @@
+package com.baeldung.findanelement;
+
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+import java.util.ArrayList;
+import java.util.List;
+import org.junit.Test;
+
+public class FindAnElementTest {
+
+ private static List scores = new ArrayList<>();
+ static {
+ scores.add(0);
+ scores.add(1);
+ scores.add(2);
+ }
+
+ private static FindElementInAList findElementInAList = new FindElementInAList<>();
+
+ @Test
+ public void givenElement_whenFoundUsingIndexOf_thenReturnElement() {
+ Integer scoreToFind = 1;
+ Integer score = findElementInAList.findUsingIndexOf(scoreToFind, scores);
+ assertTrue(score.equals(scoreToFind));
+ }
+
+ @Test
+ public void givenElement_whenNotFoundUsingListIterator_thenReturnNull() {
+ boolean found = findElementInAList.findUsingListIterator(5, scores);
+ assertTrue(!found);
+ }
+
+ @Test
+ public void givenElement_whenFoundListIterator_thenReturnElement() {
+ Integer scoreToFind = 1;
+ boolean found = findElementInAList.findUsingListIterator(scoreToFind, scores);
+ assertTrue(found);
+ }
+
+ @Test
+ public void givenElement_whenNotFoundUsingIndexOf_thenReturnNull() {
+ Integer score = findElementInAList.findUsingIndexOf(5, scores);
+ assertNull(score);
+ }
+
+ @Test
+ public void givenElement_whenFoundUsingEnhancedForLoop_thenReturnElement() {
+ Integer scoreToFind = 1;
+ boolean found = findElementInAList.findUsingEnhancedForLoop(scoreToFind, scores);
+ assertTrue(found);
+ }
+
+ @Test
+ public void givenElement_whenNotFoundUsingEnhancedForLoop_thenReturnNull() {
+ Integer scoreToFind = 5;
+ boolean found = findElementInAList.findUsingEnhancedForLoop(scoreToFind, scores);
+ assertTrue(!found);
+ }
+
+ @Test
+ public void givenElement_whenFoundUsingStream_thenReturnElement() {
+ Integer scoreToFind = 1;
+ Integer score = findElementInAList.findUsingStream(scoreToFind, scores);
+ assertTrue(score.equals(scoreToFind));
+ }
+
+ @Test
+ public void givenElement_whenNotFoundUsingStream_thenReturnNull() {
+ Integer scoreToFind = 5;
+ Integer score = findElementInAList.findUsingStream(scoreToFind, scores);
+ assertNull(score);
+ }
+
+ @Test
+ public void givenElement_whenFoundUsingParallelStream_thenReturnElement() {
+ Integer scoreToFind = 1;
+ Integer score = findElementInAList.findUsingParallelStream(scoreToFind, scores);
+ assertTrue(score.equals(scoreToFind));
+ }
+
+ @Test
+ public void givenElement_whenNotFoundUsingParallelStream_thenReturnNull() {
+ Integer scoreToFind = 5;
+ Integer score = findElementInAList.findUsingParallelStream(scoreToFind, scores);
+ assertNull(score);
+ }
+
+ @Test
+ public void givenElement_whenFoundUsingGuava_thenReturnElement() {
+ Integer scoreToFind = 1;
+ Integer score = findElementInAList.findUsingGuava(scoreToFind, scores);
+ assertTrue(score.equals(scoreToFind));
+ }
+
+ @Test
+ public void givenElement_whenNotFoundUsingGuava_thenReturnNull() {
+ Integer scoreToFind = 5;
+ Integer score = findElementInAList.findUsingGuava(scoreToFind, scores);
+ assertNull(score);
+ }
+
+ @Test
+ public void givenElement_whenFoundUsingApacheCommons_thenReturnElement() {
+ Integer scoreToFind = 1;
+ Integer score = findElementInAList.findUsingApacheCommon(scoreToFind, scores);
+ assertTrue(score.equals(scoreToFind));
+ }
+
+ @Test
+ public void givenElement_whenNotFoundUsingApacheCommons_thenReturnNull() {
+ Integer scoreToFind = 5;
+ Integer score = findElementInAList.findUsingApacheCommon(scoreToFind, scores);
+ assertNull(score);
+ }
+
+}
\ No newline at end of file
diff --git a/core-java-8/src/test/java/com/baeldung/math/MathNewMethodsUnitTest.java b/core-java-8/src/test/java/com/baeldung/math/MathNewMethodsUnitTest.java
new file mode 100644
index 0000000000..da96376009
--- /dev/null
+++ b/core-java-8/src/test/java/com/baeldung/math/MathNewMethodsUnitTest.java
@@ -0,0 +1,89 @@
+package com.baeldung.math;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+public class MathNewMethodsUnitTest {
+
+ @Test
+ public void whenAddExactToInteger_thenExpectCorrectArithmeticResult() {
+ assertEquals(150, Math.addExact(100, 50)); // Returns 150
+ }
+
+ @Test
+ public void whenSubstractExactFromInteger_thenExpectCorrectArithmeticResult() {
+ assertEquals(50, Math.subtractExact(100, 50)); // Returns 50
+ }
+
+ @Test
+ public void whenDecrementExactInteger_thenExpectCorrectArithmeticResult() {
+ assertEquals(99, Math.decrementExact(100)); // Returns 99
+ }
+
+ @Test
+ public void whenIncrementExactToInteger_thenExpectCorrectArithmeticResult() {
+ assertEquals(101, Math.incrementExact(100)); // Returns 101
+ }
+
+ @Test
+ public void whenMultiplyExactTwoIntegers_thenExpectCorrectArithmeticResult() {
+ assertEquals(500, Math.multiplyExact(100, 5)); // Returns 500
+ }
+
+ @Test
+ public void whenNegateExactInteger_thenExpectCorrectArithmeticResult() {
+ assertEquals(-100, Math.negateExact(100)); // Returns -100
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenAddToMaxInteger_thenThrowsArithmeticException() {
+ Math.addExact(Integer.MAX_VALUE, 1); // Throws ArithmeticException
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenDecrementMinInteger_thenThrowsArithmeticException() {
+ Math.decrementExact(Integer.MIN_VALUE); // Throws ArithmeticException
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenIncrementMaxLong_thenThrowsArithmeticException() {
+ Math.incrementExact(Long.MAX_VALUE); // Throws ArithmeticException
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenMultiplyMaxLong_thenThrowsArithmeticException() {
+ Math.multiplyExact(Long.MAX_VALUE, 2); // Throws ArithmeticException
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenNegateMinInteger_thenThrowsArithmeticException() {
+ Math.negateExact(Integer.MIN_VALUE); // MinInt value: −2.147.483.648, but MaxInt Value: 2.147.483.647 => Throws ArithmeticException
+ }
+
+ @Test(expected = ArithmeticException.class)
+ public void whenSubstractFromMinInteger_thenThrowsArithmeticException() {
+ Math.subtractExact(Integer.MIN_VALUE, 1);
+ }
+
+ @Test
+ public void whenFloorDivTwoIntegers_thenExpectCorrectArithmeticResult() {
+ assertEquals(3, Math.floorDiv(7, 2)); // Exact quotient is 3.5 so floor(3.5) == 3
+ assertEquals(-4, Math.floorDiv(-7, 2)); // Exact quotient is -3.5 so floor(-3.5) == -4
+ }
+
+ @Test
+ public void whenModDivTwoIntegers_thenExpectCorrectArithmeticResult() {
+ assertEquals(2, Math.floorMod(5, 3)); // Returns 2: floorMod for positive numbers returns the same as % operator
+ assertEquals(1, Math.floorMod(-5, 3)); // Returns 1 and not 2 because floorDiv(-5, 3) is -2 and not -1 and (-2*3) + (1) = -5
+ }
+
+ @Test
+ public void whenNextDownOfDouble_thenExpectCorrectNumber() {
+ double number = 3.0;
+ double expected = 2.999999999999;
+ double delta = 0.00000001;
+ assertEquals(expected, Math.nextDown(number), delta); // The delta defines the accepted error range
+ }
+
+}
diff --git a/core-java-io/.gitignore b/core-java-io/.gitignore
index 3de4cc647e..c61d35324d 100644
--- a/core-java-io/.gitignore
+++ b/core-java-io/.gitignore
@@ -1,26 +1,5 @@
-*.class
-
0.*
-#folders#
-/target
-/neoDb*
-/data
-/src/main/webapp/WEB-INF/classes
-*/META-INF/*
-.resourceCache
-
-# Packaged files #
-*.jar
-*.war
-*.ear
-
# Files generated by integration tests
-*.txt
-backup-pom.xml
-/bin/
-/temp
-
-#IntelliJ specific
-.idea/
-*.iml
\ No newline at end of file
+# *.txt
+/temp
\ No newline at end of file
diff --git a/core-java-io/pom.xml b/core-java-io/pom.xml
index 9aa8743aa6..b9fdca3502 100644
--- a/core-java-io/pom.xml
+++ b/core-java-io/pom.xml
@@ -1,5 +1,4 @@
-
+
4.0.0
com.baeldung
core-java-io
@@ -211,16 +210,6 @@
jmh-generator-annprocess
1.19
-
- org.springframework
- spring-web
- 4.3.4.RELEASE
-
-
- org.springframework.boot
- spring-boot-starter
- 1.5.8.RELEASE
-
org.hsqldb
hsqldb
@@ -264,99 +253,6 @@
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
- copy-dependencies
- prepare-package
-
- copy-dependencies
-
-
- ${project.build.directory}/libs
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-jar-plugin
-
-
-
- true
- libs/
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-assembly-plugin
-
-
- package
-
- single
-
-
- ${project.basedir}
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
- jar-with-dependencies
-
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-shade-plugin
-
-
-
- shade
-
-
- true
-
-
- org.baeldung.executable.ExecutableMavenJar
-
-
-
-
-
-
-
-
- com.jolira
- onejar-maven-plugin
-
-
-
- org.baeldung.executable.ExecutableMavenJar
- true
- ${project.build.finalName}-onejar.${project.packaging}
-
-
- one-jar
-
-
-
-
-
org.springframework.boot
spring-boot-maven-plugin
@@ -384,19 +280,19 @@
-Xmx300m
-XX:+UseParallelGC
-classpath
-
+
com.baeldung.outofmemoryerror.OutOfMemoryGCLimitExceed
-
+
org.apache.maven.plugins
maven-javadoc-plugin
3.0.0-M1
1.8
- 1.8
+ 1.8
@@ -442,7 +338,7 @@
run-benchmarks
-
+
none
exec
@@ -452,7 +348,7 @@
java
-classpath
-
+
org.openjdk.jmh.Main
.*
@@ -490,7 +386,7 @@
1.13
0.6.5
0.9.0
-
+
1.3
4.12
diff --git a/core-java-io/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java b/core-java-io/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java
index 35955032dc..4c35ffdb22 100644
--- a/core-java-io/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java
+++ b/core-java-io/src/main/java/com/baeldung/java/nio2/watcher/DirectoryWatcherExample.java
@@ -10,7 +10,7 @@ import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class DirectoryWatcherExample {
-
+
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(System.getProperty("user.home"));
@@ -25,5 +25,5 @@ public class DirectoryWatcherExample {
watchService.close();
}
-
+
}
diff --git a/core-java-io/src/main/resources/targetFile.tmp b/core-java-io/src/main/resources/targetFile.tmp
deleted file mode 100644
index 20f137b416..0000000000
--- a/core-java-io/src/main/resources/targetFile.tmp
+++ /dev/null
@@ -1,2 +0,0 @@
-line 1
-a second line
\ No newline at end of file
diff --git a/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java b/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java
index 973436a26a..6d96d2fc0b 100644
--- a/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java
+++ b/core-java-io/src/test/java/com/baeldung/copyfiles/FileCopierTest.java
@@ -19,52 +19,51 @@ import org.junit.Test;
import static org.assertj.core.api.Assertions.*;
public class FileCopierTest {
- File original = new File("src/test/resources/original.txt");
+ File original = new File("src/test/resources/original.txt");
- @Before
- public void init() throws IOException {
- if (!original.exists())
- Files.createFile(original.toPath());
- }
+ @Before
+ public void init() throws IOException {
+ if (!original.exists())
+ Files.createFile(original.toPath());
+ }
- @Test
- public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
- File copied = new File("src/test/resources/copiedWithIo.txt");
- try (InputStream in = new BufferedInputStream(new FileInputStream(original));
- OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
- byte[] buffer = new byte[1024];
- int lengthRead;
- while ((lengthRead = in.read(buffer)) > 0) {
- out.write(buffer, 0, lengthRead);
- out.flush();
- }
- }
- assertThat(copied).exists();
- assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
- }
+ @Test
+ public void givenIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
+ File copied = new File("src/test/resources/copiedWithIo.txt");
+ try (InputStream in = new BufferedInputStream(new FileInputStream(original)); OutputStream out = new BufferedOutputStream(new FileOutputStream(copied))) {
+ byte[] buffer = new byte[1024];
+ int lengthRead;
+ while ((lengthRead = in.read(buffer)) > 0) {
+ out.write(buffer, 0, lengthRead);
+ out.flush();
+ }
+ }
+ assertThat(copied).exists();
+ assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
+ }
- @Test
- public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
- File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
- FileUtils.copyFile(original, copied);
- assertThat(copied).exists();
- assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
- }
+ @Test
+ public void givenCommonsIoAPI_whenCopied_thenCopyExistsWithSameContents() throws IOException {
+ File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
+ FileUtils.copyFile(original, copied);
+ assertThat(copied).exists();
+ assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
+ }
- @Test
- public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException {
- Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
- Path originalPath = original.toPath();
- Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
- assertThat(copied).exists();
- assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied)));
- }
+ @Test
+ public void givenNIO2_whenCopied_thenCopyExistsWithSameContents() throws IOException {
+ Path copied = Paths.get("src/test/resources/copiedWithNio.txt");
+ Path originalPath = original.toPath();
+ Files.copy(originalPath, copied, StandardCopyOption.REPLACE_EXISTING);
+ assertThat(copied).exists();
+ assertThat(Files.readAllLines(originalPath).equals(Files.readAllLines(copied)));
+ }
- @Test
- public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException {
- File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
- com.google.common.io.Files.copy(original, copied);
- assertThat(copied).exists();
- assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
- }
+ @Test
+ public void givenGuava_whenCopied_thenCopyExistsWithSameContents() throws IOException {
+ File copied = new File("src/test/resources/copiedWithApacheCommons.txt");
+ com.google.common.io.Files.copy(original, copied);
+ assertThat(copied).exists();
+ assertThat(Files.readAllLines(original.toPath()).equals(Files.readAllLines(copied.toPath())));
+ }
}
diff --git a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java
index ea71d1b5c1..7968967679 100644
--- a/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java
+++ b/core-java-io/src/test/java/com/baeldung/file/FileOperationsManualTest.java
@@ -3,7 +3,6 @@ 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;
diff --git a/core-java-io/src/test/java/com/baeldung/file/FilesTest.java b/core-java-io/src/test/java/com/baeldung/file/FilesTest.java
index c5a5b8a3a1..a35cda8b23 100644
--- a/core-java-io/src/test/java/com/baeldung/file/FilesTest.java
+++ b/core-java-io/src/test/java/com/baeldung/file/FilesTest.java
@@ -42,19 +42,14 @@ public class FilesTest {
CharSink chs = com.google.common.io.Files.asCharSink(file, Charsets.UTF_8, FileWriteMode.APPEND);
chs.write("Spain\r\n");
- assertThat(StreamUtils.getStringFromInputStream(
- new FileInputStream(fileName)))
- .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
+ assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
-
@Test
public void whenAppendToFileUsingFiles_thenCorrect() throws IOException {
Files.write(Paths.get(fileName), "Spain\r\n".getBytes(), StandardOpenOption.APPEND);
- assertThat(StreamUtils.getStringFromInputStream(
- new FileInputStream(fileName)))
- .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
+ assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
@@ -62,9 +57,7 @@ public class FilesTest {
File file = new File(fileName);
FileUtils.writeStringToFile(file, "Spain\r\n", StandardCharsets.UTF_8, true);
- assertThat(StreamUtils.getStringFromInputStream(
- new FileInputStream(fileName)))
- .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
+ assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
@@ -73,9 +66,7 @@ public class FilesTest {
fos.write("Spain\r\n".getBytes());
fos.close();
- assertThat(StreamUtils.getStringFromInputStream(
- new FileInputStream(fileName)))
- .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
+ assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\r\n");
}
@Test
@@ -86,9 +77,6 @@ public class FilesTest {
bw.newLine();
bw.close();
- assertThat(
- StreamUtils.getStringFromInputStream(
- new FileInputStream(fileName)))
- .isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
+ assertThat(StreamUtils.getStringFromInputStream(new FileInputStream(fileName))).isEqualTo("UK\r\n" + "US\r\n" + "Germany\r\n" + "Spain\n");
}
}
\ No newline at end of file
diff --git a/core-java-io/src/test/java/com/baeldung/filesystem/jndi/test/LookupFSJNDIIntegrationTest.java b/core-java-io/src/test/java/com/baeldung/filesystem/jndi/test/LookupFSJNDIIntegrationTest.java
index 330ec3aee3..023a47cb97 100644
--- a/core-java-io/src/test/java/com/baeldung/filesystem/jndi/test/LookupFSJNDIIntegrationTest.java
+++ b/core-java-io/src/test/java/com/baeldung/filesystem/jndi/test/LookupFSJNDIIntegrationTest.java
@@ -35,7 +35,7 @@ public class LookupFSJNDIIntegrationTest {
@Test
public void givenInitialContext_whenLokupFileExists_thenSuccess() {
- File file = fsjndi.getFile(FILENAME);
- assertNotNull("File exists", file);
+ File file = fsjndi.getFile(FILENAME);
+ assertNotNull("File exists", file);
}
}
diff --git a/core-java-io/src/test/java/com/baeldung/java/nio2/PathManualTest.java b/core-java-io/src/test/java/com/baeldung/java/nio2/PathManualTest.java
index acfb2c08e9..969dff1da2 100644
--- a/core-java-io/src/test/java/com/baeldung/java/nio2/PathManualTest.java
+++ b/core-java-io/src/test/java/com/baeldung/java/nio2/PathManualTest.java
@@ -9,7 +9,6 @@ import java.net.URI;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.Date;
import org.junit.Test;
diff --git a/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncFileIntegrationTest.java b/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncFileIntegrationTest.java
index e2f7a0303a..cf37b92565 100644
--- a/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncFileIntegrationTest.java
+++ b/core-java-io/src/test/java/com/baeldung/java/nio2/async/AsyncFileIntegrationTest.java
@@ -17,18 +17,19 @@ import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
public class AsyncFileIntegrationTest {
+
@Test
public void givenPath_whenReadsContentWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
- Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
- AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
+ final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
+ final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
- ByteBuffer buffer = ByteBuffer.allocate(1024);
+ final ByteBuffer buffer = ByteBuffer.allocate(1024);
- Future operation = fileChannel.read(buffer, 0);
+ final Future operation = fileChannel.read(buffer, 0);
operation.get();
- String fileContent = new String(buffer.array()).trim();
+ final String fileContent = new String(buffer.array()).trim();
buffer.clear();
assertEquals(fileContent, "baeldung.com");
@@ -36,18 +37,16 @@ public class AsyncFileIntegrationTest {
@Test
public void givenPath_whenReadsContentWithCompletionHandler_thenCorrect() throws IOException {
- Path path = Paths.get(URI.create(AsyncFileIntegrationTest.class.getResource("/file.txt").toString()));
- AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
+ final Path path = Paths.get(URI.create(this.getClass().getClassLoader().getResource("file.txt").toString()));
+ final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
- ByteBuffer buffer = ByteBuffer.allocate(1024);
+ final ByteBuffer buffer = ByteBuffer.allocate(1024);
fileChannel.read(buffer, 0, buffer, new CompletionHandler() {
-
@Override
public void completed(Integer result, ByteBuffer attachment) {
// result is number of bytes read
// attachment is the buffer
-
}
@Override
@@ -59,42 +58,40 @@ public class AsyncFileIntegrationTest {
@Test
public void givenPathAndContent_whenWritesToFileWithFuture_thenCorrect() throws IOException, ExecutionException, InterruptedException {
- String fileName = "temp";
- Path path = Paths.get(fileName);
- AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
+ final String fileName = "temp";
+ final Path path = Paths.get(fileName);
+ final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
- ByteBuffer buffer = ByteBuffer.allocate(1024);
- long position = 0;
+ final ByteBuffer buffer = ByteBuffer.allocate(1024);
+ final long position = 0;
buffer.put("hello world".getBytes());
buffer.flip();
- Future operation = fileChannel.write(buffer, position);
+ final Future operation = fileChannel.write(buffer, position);
buffer.clear();
operation.get();
- String content = readContent(path);
+ final String content = readContent(path);
assertEquals("hello world", content);
}
@Test
public void givenPathAndContent_whenWritesToFileWithHandler_thenCorrect() throws IOException {
- String fileName = UUID.randomUUID().toString();
- Path path = Paths.get(fileName);
- AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
+ final String fileName = UUID.randomUUID().toString();
+ final Path path = Paths.get(fileName);
+ final AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.DELETE_ON_CLOSE);
- ByteBuffer buffer = ByteBuffer.allocate(1024);
+ final ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.put("hello world".getBytes());
buffer.flip();
fileChannel.write(buffer, 0, buffer, new CompletionHandler() {
-
@Override
public void completed(Integer result, ByteBuffer attachment) {
// result is number of bytes written
// attachment is the buffer
-
}
@Override
@@ -104,23 +101,25 @@ public class AsyncFileIntegrationTest {
});
}
- public static String readContent(Path file) throws ExecutionException, InterruptedException {
+ //
+
+ private String readContent(Path file) throws ExecutionException, InterruptedException {
AsynchronousFileChannel fileChannel = null;
try {
fileChannel = AsynchronousFileChannel.open(file, StandardOpenOption.READ);
} catch (IOException e) {
- // TODO Auto-generated catch block
e.printStackTrace();
}
- ByteBuffer buffer = ByteBuffer.allocate(1024);
+ final ByteBuffer buffer = ByteBuffer.allocate(1024);
- Future operation = fileChannel.read(buffer, 0);
+ final Future operation = fileChannel.read(buffer, 0);
operation.get();
- String fileContent = new String(buffer.array()).trim();
+ final String fileContent = new String(buffer.array()).trim();
buffer.clear();
return fileContent;
}
+
}
\ No newline at end of file
diff --git a/core-java-io/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsIntegrationTest.java b/core-java-io/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsIntegrationTest.java
index 9f84aa60d6..4b6302e93c 100644
--- a/core-java-io/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsIntegrationTest.java
+++ b/core-java-io/src/test/java/com/baeldung/java/nio2/attributes/BasicAttribsIntegrationTest.java
@@ -20,7 +20,6 @@ public class BasicAttribsIntegrationTest {
private static final Logger LOG = LoggerFactory.getLogger(BasicAttribsIntegrationTest.class);
-
private static final String HOME = System.getProperty("user.home");
private static BasicFileAttributes basicAttribs;
diff --git a/core-java-io/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java b/core-java-io/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java
index 7f83e379cd..1f3b380772 100644
--- a/core-java-io/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java
+++ b/core-java-io/src/test/java/com/baeldung/java8/JavaFolderSizeUnitTest.java
@@ -55,12 +55,7 @@ public class JavaFolderSizeUnitTest {
@Test
public void whenGetFolderSizeUsingJava8_thenCorrect() throws IOException {
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(EXPECTED_SIZE, size);
}
@@ -77,12 +72,8 @@ public class JavaFolderSizeUnitTest {
public void whenGetFolderSizeUsingGuava_thenCorrect() {
final File folder = new File(path);
- final Iterable files = com.google.common.io.Files.fileTreeTraverser()
- .breadthFirstTraversal(folder);
- final long size = StreamSupport.stream(files.spliterator(), false)
- .filter(File::isFile)
- .mapToLong(File::length)
- .sum();
+ final Iterable files = com.google.common.io.Files.fileTreeTraverser().breadthFirstTraversal(folder);
+ final long size = StreamSupport.stream(files.spliterator(), false).filter(File::isFile).mapToLong(File::length).sum();
assertEquals(EXPECTED_SIZE, size);
}
diff --git a/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java b/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java
index 0a0993a0d7..bb87529783 100644
--- a/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java
+++ b/core-java-io/src/test/java/com/baeldung/mappedbytebuffer/MappedByteBufferUnitTest.java
@@ -18,14 +18,13 @@ import static org.junit.Assert.assertNotNull;
public class MappedByteBufferUnitTest {
-
@Test
public void givenFileChannel_whenReadToTheMappedByteBuffer_thenShouldSuccess() throws Exception {
- //given
+ // given
CharBuffer charBuffer = null;
Path pathToRead = getFileURIFromResources("fileToRead.txt");
- //when
+ // when
try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToRead, EnumSet.of(StandardOpenOption.READ))) {
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
@@ -34,20 +33,19 @@ public class MappedByteBufferUnitTest {
}
}
- //then
+ // then
assertNotNull(charBuffer);
assertEquals(charBuffer.toString(), "This is a content of the file");
}
@Test
public void givenPath_whenWriteToItUsingMappedByteBuffer_thenShouldSuccessfullyWrite() throws Exception {
- //given
- CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
- Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
+ // given
+ final CharBuffer charBuffer = CharBuffer.wrap("This will be written to the file");
+ final Path pathToWrite = getFileURIFromResources("fileToWriteTo.txt");
- //when
- try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite,
- EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
+ // when
+ try (FileChannel fileChannel = (FileChannel) Files.newByteChannel(pathToWrite, EnumSet.of(StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING))) {
MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, charBuffer.length());
if (mappedByteBuffer != null) {
@@ -55,14 +53,16 @@ public class MappedByteBufferUnitTest {
}
}
- //then
- List fileContent = Files.readAllLines(pathToWrite);
+ // then
+ final List fileContent = Files.readAllLines(pathToWrite);
assertEquals(fileContent.get(0), "This will be written to the file");
}
- private Path getFileURIFromResources(String fileName) throws Exception {
- ClassLoader classLoader = getClass().getClassLoader();
+ //
+
+ private final Path getFileURIFromResources(String fileName) throws Exception {
+ final ClassLoader classLoader = getClass().getClassLoader();
return Paths.get(classLoader.getResource(fileName).toURI());
}
}
diff --git a/core-java-io/src/test/java/com/baeldung/stream/FileCopyTest.java b/core-java-io/src/test/java/com/baeldung/stream/FileCopyTest.java
deleted file mode 100644
index 3b915a3829..0000000000
--- a/core-java-io/src/test/java/com/baeldung/stream/FileCopyTest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package com.baeldung.stream;
-
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.IOException;
-
-import org.junit.Test;
-
-public class FileCopyTest {
-
- @Test
- public void whenUsingStream_thenCopyFile() throws IOException {
- File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt");
- File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt");
- FileCopy.copyFileUsingStream(src, dest);
- assertTrue(dest.exists());
- dest.delete();
- }
-
- @Test
- public void whenUsingFiles_thenCopyFile() throws IOException {
- File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt");
- File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt");
- FileCopy.copyFileUsingJavaFiles(src, dest);
- assertTrue(dest.exists());
- dest.delete();
- }
-
- @Test
- public void whenUsingChannel_thenCopyFile() throws IOException {
- File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt");
- File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt");
- FileCopy.copyFileUsingChannel(src, dest);
- assertTrue(dest.exists());
- dest.delete();
- }
-
- @Test
- public void whenUsingApache_thenCopyFile() throws IOException {
- File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt");
- File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt");
- FileCopy.copyFileUsingApacheCommonsIO(src, dest);
- assertTrue(dest.exists());
- dest.delete();
- }
-}
diff --git a/core-java-io/src/test/java/com/baeldung/stream/FileCopyUnitTest.java b/core-java-io/src/test/java/com/baeldung/stream/FileCopyUnitTest.java
new file mode 100644
index 0000000000..b4641083b9
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/stream/FileCopyUnitTest.java
@@ -0,0 +1,52 @@
+package com.baeldung.stream;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.junit.Test;
+
+public class FileCopyUnitTest {
+
+ @Test
+ public void whenUsingStream_thenCopyFile() throws IOException {
+ final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_stream.txt");
+ final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_stream.txt");
+ FileCopy.copyFileUsingStream(src, dest);
+
+ assertTrue(dest.exists());
+ dest.delete();
+ }
+
+ @Test
+ public void whenUsingFiles_thenCopyFile() throws IOException {
+ final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_files.txt");
+ final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_files.txt");
+ FileCopy.copyFileUsingJavaFiles(src, dest);
+
+ assertTrue(dest.exists());
+ dest.delete();
+ }
+
+ @Test
+ public void whenUsingChannel_thenCopyFile() throws IOException {
+ final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_channel.txt");
+ final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_channel.txt");
+ FileCopy.copyFileUsingChannel(src, dest);
+
+ assertTrue(dest.exists());
+ dest.delete();
+ }
+
+ @Test
+ public void whenUsingApache_thenCopyFile() throws IOException {
+ final File src = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "src" + File.separator + "test_apache.txt");
+ final File dest = new File("src" + File.separator + "test" + File.separator + "resources" + File.separator + "copyTest" + File.separator + "dest" + File.separator + "test_apache.txt");
+ FileCopy.copyFileUsingApacheCommonsIO(src, dest);
+
+ assertTrue(dest.exists());
+ dest.delete();
+ }
+
+}
diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java
index 0e20e75869..f1bea1eefb 100644
--- a/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java
+++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaInputStreamToXUnitTest.java
@@ -152,11 +152,11 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingToFile_thenCorrect() throws IOException {
- final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
+ final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
- final File targetFile = new File("src/main/resources/targetFile.tmp");
+ final File targetFile = new File("src/test/resources/targetFile.tmp");
final OutputStream outStream = new FileOutputStream(targetFile);
outStream.write(buffer);
@@ -166,8 +166,8 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingInProgressToFile_thenCorrect() throws IOException {
- final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
- final File targetFile = new File("src/main/resources/targetFile.tmp");
+ final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
+ final File targetFile = new File("src/test/resources/targetFile.tmp");
final OutputStream outStream = new FileOutputStream(targetFile);
final byte[] buffer = new byte[8 * 1024];
@@ -182,8 +182,8 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingAnInProgressInputStreamToFile_thenCorrect2() throws IOException {
- final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
- final File targetFile = new File("src/main/resources/targetFile.tmp");
+ final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
+ final File targetFile = new File("src/test/resources/targetFile.tmp");
java.nio.file.Files.copy(initialStream, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
@@ -192,11 +192,11 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingInputStreamToFile_thenCorrect3() throws IOException {
- final InputStream initialStream = new FileInputStream(new File("src/main/resources/sample.txt"));
+ final InputStream initialStream = new FileInputStream(new File("src/test/resources/sample.txt"));
final byte[] buffer = new byte[initialStream.available()];
initialStream.read(buffer);
- final File targetFile = new File("src/main/resources/targetFile.tmp");
+ final File targetFile = new File("src/test/resources/targetFile.tmp");
Files.write(buffer, targetFile);
IOUtils.closeQuietly(initialStream);
@@ -204,13 +204,13 @@ public class JavaInputStreamToXUnitTest {
@Test
public final void whenConvertingInputStreamToFile_thenCorrect4() throws IOException {
- final InputStream initialStream = FileUtils.openInputStream(new File("src/main/resources/sample.txt"));
+ final InputStream initialStream = FileUtils.openInputStream(new File("src/test/resources/sample.txt"));
- final File targetFile = new File("src/main/resources/targetFile.tmp");
+ final File targetFile = new File("src/test/resources/targetFile.tmp");
FileUtils.copyInputStreamToFile(initialStream, targetFile);
}
-
+
@Test
public final void givenUsingPlainJava_whenConvertingAnInputStreamToString_thenCorrect() throws IOException {
String originalString = randomAlphabetic(8);
@@ -225,7 +225,7 @@ public class JavaInputStreamToXUnitTest {
buffer.flush();
byte[] byteArray = buffer.toByteArray();
-
+
String text = new String(byteArray, StandardCharsets.UTF_8);
assertThat(text, equalTo(originalString));
}
diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java
index 41d0a8a02a..b56841117e 100644
--- a/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java
+++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaReadFromFileUnitTest.java
@@ -18,7 +18,6 @@ import static org.junit.Assert.assertTrue;
public class JavaReadFromFileUnitTest {
-
private static final Logger LOG = LoggerFactory.getLogger(JavaReadFromFileUnitTest.class);
@Test
@@ -107,11 +106,12 @@ public class JavaReadFromFileUnitTest {
@Test
public void whenReadUTFEncodedFile_thenCorrect() throws IOException {
- final String expected_value = "青空";
+ final String expected_value = "�空";
final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("src/test/resources/test_read7.in"), "UTF-8"));
final String currentLine = reader.readLine();
reader.close();
LOG.debug(currentLine);
+
assertEquals(expected_value, currentLine);
}
diff --git a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java
index f58d66818b..08a4c673cd 100644
--- a/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java
+++ b/core-java-io/src/test/java/org/baeldung/java/io/JavaXToInputStreamUnitTest.java
@@ -68,7 +68,7 @@ public class JavaXToInputStreamUnitTest {
@Test
public final void givenUsingPlainJava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
- final File initialFile = new File("src/main/resources/sample.txt");
+ final File initialFile = new File("src/test/resources/sample.txt");
final InputStream targetStream = new FileInputStream(initialFile);
IOUtils.closeQuietly(targetStream);
@@ -76,7 +76,7 @@ public class JavaXToInputStreamUnitTest {
@Test
public final void givenUsingGuava_whenConvertingFileToInputStream_thenCorrect() throws IOException {
- final File initialFile = new File("src/main/resources/sample.txt");
+ final File initialFile = new File("src/test/resources/sample.txt");
final InputStream targetStream = Files.asByteSource(initialFile).openStream();
IOUtils.closeQuietly(targetStream);
@@ -84,7 +84,7 @@ public class JavaXToInputStreamUnitTest {
@Test
public final void givenUsingCommonsIO_whenConvertingFileToInputStream_thenCorrect() throws IOException {
- final File initialFile = new File("src/main/resources/sample.txt");
+ final File initialFile = new File("src/test/resources/sample.txt");
final InputStream targetStream = FileUtils.openInputStream(initialFile);
IOUtils.closeQuietly(targetStream);
diff --git a/core-java/src/test/resources/fileToWriteTo.txt b/core-java-io/src/test/resources/copiedWithApacheCommons.txt
similarity index 100%
rename from core-java/src/test/resources/fileToWriteTo.txt
rename to core-java-io/src/test/resources/copiedWithApacheCommons.txt
diff --git a/core-java-io/src/test/resources/copiedWithIo.txt b/core-java-io/src/test/resources/copiedWithIo.txt
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/core-java-io/src/test/resources/copiedWithNio.txt b/core-java-io/src/test/resources/copiedWithNio.txt
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/core-java/src/test/resources/copyTest/dest/readme.txt b/core-java-io/src/test/resources/copyTest/dest/readme.txt
similarity index 100%
rename from core-java/src/test/resources/copyTest/dest/readme.txt
rename to core-java-io/src/test/resources/copyTest/dest/readme.txt
diff --git a/core-java/src/test/resources/copyTest/src/test_apache.txt b/core-java-io/src/test/resources/copyTest/src/test_apache.txt
similarity index 100%
rename from core-java/src/test/resources/copyTest/src/test_apache.txt
rename to core-java-io/src/test/resources/copyTest/src/test_apache.txt
diff --git a/core-java/src/test/resources/copyTest/src/test_channel.txt b/core-java-io/src/test/resources/copyTest/src/test_channel.txt
similarity index 100%
rename from core-java/src/test/resources/copyTest/src/test_channel.txt
rename to core-java-io/src/test/resources/copyTest/src/test_channel.txt
diff --git a/core-java/src/test/resources/copyTest/src/test_files.txt b/core-java-io/src/test/resources/copyTest/src/test_files.txt
similarity index 100%
rename from core-java/src/test/resources/copyTest/src/test_files.txt
rename to core-java-io/src/test/resources/copyTest/src/test_files.txt
diff --git a/core-java/src/test/resources/copyTest/src/test_stream.txt b/core-java-io/src/test/resources/copyTest/src/test_stream.txt
similarity index 100%
rename from core-java/src/test/resources/copyTest/src/test_stream.txt
rename to core-java-io/src/test/resources/copyTest/src/test_stream.txt
diff --git a/core-java/src/test/resources/file.txt b/core-java-io/src/test/resources/file.txt
similarity index 100%
rename from core-java/src/test/resources/file.txt
rename to core-java-io/src/test/resources/file.txt
diff --git a/core-java/src/test/resources/fileToRead.txt b/core-java-io/src/test/resources/fileToRead.txt
similarity index 100%
rename from core-java/src/test/resources/fileToRead.txt
rename to core-java-io/src/test/resources/fileToRead.txt
diff --git a/core-java-io/src/test/resources/fileToWriteTo.txt b/core-java-io/src/test/resources/fileToWriteTo.txt
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/core-java-io/src/test/resources/initialFile.txt b/core-java-io/src/test/resources/initialFile.txt
new file mode 100644
index 0000000000..7d572d5b9d
--- /dev/null
+++ b/core-java-io/src/test/resources/initialFile.txt
@@ -0,0 +1 @@
+With Commons IO
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/original.txt b/core-java-io/src/test/resources/original.txt
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/core-java-io/src/test/resources/sample.txt b/core-java-io/src/test/resources/sample.txt
new file mode 100644
index 0000000000..5e1c309dae
--- /dev/null
+++ b/core-java-io/src/test/resources/sample.txt
@@ -0,0 +1 @@
+Hello World
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/targetFile.tmp b/core-java-io/src/test/resources/targetFile.tmp
new file mode 100644
index 0000000000..5e1c309dae
--- /dev/null
+++ b/core-java-io/src/test/resources/targetFile.tmp
@@ -0,0 +1 @@
+Hello World
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/targetFile.txt b/core-java-io/src/test/resources/targetFile.txt
new file mode 100644
index 0000000000..424a8d0d1e
--- /dev/null
+++ b/core-java-io/src/test/resources/targetFile.txt
@@ -0,0 +1 @@
+Some textSome text
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/test_write.txt b/core-java-io/src/test/resources/test_write.txt
new file mode 100644
index 0000000000..a15aad69b5
--- /dev/null
+++ b/core-java-io/src/test/resources/test_write.txt
@@ -0,0 +1 @@
+Some StringProduct name is iPhone and its price is 1000 $
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/test_write_1.txt b/core-java-io/src/test/resources/test_write_1.txt
new file mode 100644
index 0000000000..5727d54bfc
Binary files /dev/null and b/core-java-io/src/test/resources/test_write_1.txt differ
diff --git a/core-java-io/src/test/resources/test_write_2.txt b/core-java-io/src/test/resources/test_write_2.txt
new file mode 100644
index 0000000000..6a87dfc075
Binary files /dev/null and b/core-java-io/src/test/resources/test_write_2.txt differ
diff --git a/core-java-io/src/test/resources/test_write_3.txt b/core-java-io/src/test/resources/test_write_3.txt
new file mode 100644
index 0000000000..5e1c309dae
--- /dev/null
+++ b/core-java-io/src/test/resources/test_write_3.txt
@@ -0,0 +1 @@
+Hello World
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/test_write_4.txt b/core-java-io/src/test/resources/test_write_4.txt
new file mode 100644
index 0000000000..f14fca61f6
Binary files /dev/null and b/core-java-io/src/test/resources/test_write_4.txt differ
diff --git a/core-java-io/src/test/resources/test_write_5.txt b/core-java-io/src/test/resources/test_write_5.txt
new file mode 100644
index 0000000000..5ab2f8a432
--- /dev/null
+++ b/core-java-io/src/test/resources/test_write_5.txt
@@ -0,0 +1 @@
+Hello
\ No newline at end of file
diff --git a/core-java/README.md b/core-java/README.md
index 5be4e12592..b7482b09cc 100644
--- a/core-java/README.md
+++ b/core-java/README.md
@@ -129,3 +129,11 @@
- [A Guide to the finalize Method in Java](http://www.baeldung.com/java-finalize)
- [Compiling Java *.class Files with javac](http://www.baeldung.com/javac)
- [Method Overloading and Overriding in Java](http://www.baeldung.com/java-method-overload-override)
+- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
+- [Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
+- [Java TreeMap vs HashMap](http://www.baeldung.com/java-treemap-vs-hashmap)
+- [A Guide to Iterator in Java](http://www.baeldung.com/java-iterator)
+- [The Trie Data Structure in Java](http://www.baeldung.com/trie-java)
+- [Introduction to Javadoc](http://www.baeldung.com/javadoc)
+- [How to TDD a List Implementation](http://jira.baeldung.com/browse/BAEL-1537)
+
diff --git a/core-java/src/main/java/com/baeldung/array/Find2ndLargestInArray.java b/core-java/src/main/java/com/baeldung/array/Find2ndLargestInArray.java
new file mode 100644
index 0000000000..d424bd429f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/array/Find2ndLargestInArray.java
@@ -0,0 +1,20 @@
+package com.baeldung.array;
+
+public class Find2ndLargestInArray {
+
+ public static int find2ndLargestElement(int[] array) {
+ int maxElement = array[0];
+ int secondLargestElement = -1;
+
+ for (int index = 0; index < array.length; index++) {
+ if (maxElement <= array[index]) {
+ secondLargestElement = maxElement;
+ maxElement = array[index];
+ } else if (secondLargestElement < array[index]) {
+ secondLargestElement = array[index];
+ }
+ }
+ return secondLargestElement;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/array/FindElementInArray.java b/core-java/src/main/java/com/baeldung/array/FindElementInArray.java
new file mode 100644
index 0000000000..6da889fe91
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/array/FindElementInArray.java
@@ -0,0 +1,22 @@
+package com.baeldung.array;
+
+import java.util.Arrays;
+
+public class FindElementInArray {
+
+ public static boolean findGivenElementInArrayWithoutUsingStream(int[] array, int element) {
+ boolean actualResult = false;
+
+ for (int index = 0; index < array.length; index++) {
+ if (element == array[index]) {
+ actualResult = true;
+ break;
+ }
+ }
+ return actualResult;
+ }
+
+ public static boolean findGivenElementInArrayUsingStream(int[] array, int element) {
+ return Arrays.stream(array).filter(x -> element == x).findFirst().isPresent();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java b/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java
new file mode 100644
index 0000000000..e7d7172fdb
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/array/SumAndAverageInArray.java
@@ -0,0 +1,27 @@
+package com.baeldung.array;
+
+import java.util.Arrays;
+
+public class SumAndAverageInArray {
+
+ public static int findSumWithoutUsingStream(int[] array) {
+ int sum = 0;
+ for (int index = 0; index < array.length; index++) {
+ sum += array[index];
+ }
+ return sum;
+ }
+
+ public static int findSumUsingStream(int[] array) {
+ return Arrays.stream(array).sum();
+ }
+
+ public static double findAverageWithoutUsingStream(int[] array) {
+ int sum = findSumWithoutUsingStream(array);
+ return (double) sum / array.length;
+ }
+
+ public static double findAverageUsingStream(int[] array) {
+ return Arrays.stream(array).average().getAsDouble();
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/asciiart/AsciiArt.java b/core-java/src/main/java/com/baeldung/asciiart/AsciiArt.java
new file mode 100644
index 0000000000..081717b4fa
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/asciiart/AsciiArt.java
@@ -0,0 +1,62 @@
+package com.baeldung.asciiart;
+
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.RenderingHints;
+import java.awt.image.BufferedImage;
+
+public class AsciiArt {
+
+ public AsciiArt() {
+ }
+
+ public void drawString(String text, String artChar, Settings settings) {
+ BufferedImage image = getImageIntegerMode(settings.width, settings.height);
+
+ Graphics2D graphics2D = getGraphics2D(image.getGraphics(), settings);
+ graphics2D.drawString(text, 6, ((int) (settings.height * 0.67)));
+
+ for (int y = 0; y < settings.height; y++) {
+ StringBuilder stringBuilder = new StringBuilder();
+
+ for (int x = 0; x < settings.width; x++) {
+ stringBuilder.append(image.getRGB(x, y) == -16777216 ? " " : artChar);
+ }
+
+ if (stringBuilder.toString()
+ .trim()
+ .isEmpty()) {
+ continue;
+ }
+
+ System.out.println(stringBuilder);
+ }
+
+ }
+
+ private BufferedImage getImageIntegerMode(int width, int height) {
+ return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+ }
+
+ private Graphics2D getGraphics2D(Graphics graphics, Settings settings) {
+ graphics.setFont(settings.font);
+
+ Graphics2D graphics2D = (Graphics2D) graphics;
+ graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+
+ return graphics2D;
+ }
+
+ public class Settings {
+ public Font font;
+ public int width;
+ public int height;
+
+ public Settings(Font font, int width, int height) {
+ this.font = font;
+ this.width = width;
+ this.height = height;
+ }
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java b/core-java/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java
new file mode 100644
index 0000000000..5fbd2415c7
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/casting/AnimalFeederGeneric.java
@@ -0,0 +1,24 @@
+package com.baeldung.casting;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class AnimalFeederGeneric {
+ private Class type;
+
+ public AnimalFeederGeneric(Class type) {
+ this.type = type;
+ }
+
+ public List feed(List animals) {
+ List list = new ArrayList();
+ animals.forEach(animal -> {
+ if (type.isInstance(animal)) {
+ T objAsType = type.cast(animal);
+ list.add(objAsType);
+ }
+ });
+ return list;
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/AuthenticationProvider.java b/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/AuthenticationProvider.java
deleted file mode 100644
index 552a7ff6d9..0000000000
--- a/core-java/src/main/java/com/baeldung/designpatterns/chainofresponsibility/AuthenticationProvider.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.baeldung.designpatterns.chainofresponsibility;
-
-public interface AuthenticationProvider {
-
-}
diff --git a/core-java/src/main/java/com/baeldung/java/list/CustomList.java b/core-java/src/main/java/com/baeldung/java/list/CustomList.java
index bc1321b1a3..8b91fca32f 100644
--- a/core-java/src/main/java/com/baeldung/java/list/CustomList.java
+++ b/core-java/src/main/java/com/baeldung/java/list/CustomList.java
@@ -9,6 +9,58 @@ import java.util.ListIterator;
public class CustomList implements List {
private Object[] internal = {};
+ @Override
+ public boolean isEmpty() {
+ // the first cycle
+ // return true;
+
+ // the second cycle
+ // if (internal.length != 0) {
+ // return false;
+ // } else {
+ // return true;
+ // }
+
+ // refactoring
+ return internal.length == 0;
+ }
+
+ @Override
+ public int size() {
+ // the first cycle
+ // if (isEmpty()) {
+ // return 0;
+ // } else {
+ // return internal.length;
+ // }
+
+ // refactoring
+ return internal.length;
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public E get(int index) {
+ // the first cycle
+ // return (E) internal[0];
+
+ // improvement
+ return (E) internal[index];
+ }
+
+ @Override
+ public boolean add(E element) {
+ // the first cycle
+ // internal = new Object[] { element };
+ // return true;
+
+ // the second cycle
+ Object[] temp = Arrays.copyOf(internal, internal.length + 1);
+ temp[internal.length] = element;
+ internal = temp;
+ return true;
+ }
+
@Override
public void add(int index, E element) {
throw new UnsupportedOperationException();
@@ -44,40 +96,8 @@ public class CustomList implements List {
throw new UnsupportedOperationException();
}
- @Override
- public int size() {
- return internal.length;
- }
-
- @Override
- public boolean isEmpty() {
- return internal.length == 0;
- }
-
- @Override
- public boolean add(E element) {
- // the first cycle
- // internal = new Object[1];
- // internal[0] = element;
- // return true;
-
- Object[] temp = new Object[internal.length + 1];
- System.arraycopy(internal, 0, temp, 0, internal.length);
- temp[internal.length] = element;
- internal = temp;
- return true;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public E get(int index) {
- return (E) internal[index];
- }
-
@Override
public boolean contains(Object object) {
- // return false
-
for (Object element : internal) {
if (object.equals(element)) {
return true;
@@ -88,14 +108,6 @@ public class CustomList implements List {
@Override
public boolean containsAll(Collection> collection) {
- // the first cycle
- // for (Object element : collection) {
- // if (element.equals(internal[0])) {
- // return true;
- // }
- // }
- // return false;
-
for (Object element : collection)
if (!contains(element)) {
return false;
@@ -118,12 +130,6 @@ public class CustomList implements List {
@Override
public int indexOf(Object object) {
- // the first cycle
- // if (object.equals(internal[0])) {
- // return 0;
- // }
- // return -1;
-
for (int i = 0; i < internal.length; i++) {
if (object.equals(internal[i])) {
return i;
@@ -134,12 +140,6 @@ public class CustomList implements List {
@Override
public int lastIndexOf(Object object) {
- // the first cycle
- // if (object.equals(internal[0])) {
- // return 0;
- // }
- // return -1;
-
for (int i = internal.length - 1; i >= 0; i--) {
if (object.equals(internal[i])) {
return i;
@@ -151,9 +151,6 @@ public class CustomList implements List {
@SuppressWarnings("unchecked")
@Override
public List subList(int fromIndex, int toIndex) {
- // the first cycle
- // return (List) Arrays.asList(internal);
-
Object[] temp = new Object[toIndex - fromIndex];
System.arraycopy(internal, fromIndex, temp, 0, temp.length);
return (List) Arrays.asList(temp);
@@ -167,16 +164,6 @@ public class CustomList implements List {
@SuppressWarnings("unchecked")
@Override
public T[] toArray(T[] array) {
- // the first cycle
- // array[0] = (T) internal[0];
- // return array;
-
- // the second cycle
- // if (array.length < internal.length) {
- // return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
- // }
- // return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
-
if (array.length < internal.length) {
return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
}
@@ -209,18 +196,12 @@ public class CustomList implements List {
@Override
public boolean hasNext() {
- // the first cycle
- // return true;
-
return index != internal.length;
}
@SuppressWarnings("unchecked")
@Override
public E next() {
- // the first cycle
- // return (E) CustomList.this.internal[0];
-
E element = (E) CustomList.this.internal[index];
index++;
return element;
diff --git a/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java b/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java
index 029a779cdb..561430f66f 100644
--- a/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java
+++ b/core-java/src/main/java/com/baeldung/javadoc/SuperHero.java
@@ -23,9 +23,15 @@ public class SuperHero extends Person {
* @return the amount of health hero has after attack
* @see HERO-402
* @since 1.0
+ * @deprecated As of version 1.1, use . . . instead
+ * @version 1.2
+ * @throws IllegalArgumentException if incomingDamage is negative
*/
- public int successfullyAttacked(int incomingDamage, String damageType) {
+ public int successfullyAttacked(int incomingDamage, String damageType) throws Exception {
// do things
+ if (incomingDamage < 0) {
+ throw new IllegalArgumentException ("Cannot cause negative damage");
+ }
return 0;
}
diff --git a/core-java/src/main/resources/targetFile.tmp b/core-java/src/main/resources/targetFile.tmp
deleted file mode 100644
index 20f137b416..0000000000
--- a/core-java/src/main/resources/targetFile.tmp
+++ /dev/null
@@ -1,2 +0,0 @@
-line 1
-a second line
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java
new file mode 100644
index 0000000000..ec916af092
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/array/Find2ndLargestInArrayTest.java
@@ -0,0 +1,16 @@
+package com.baeldung.array;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class Find2ndLargestInArrayTest {
+ @Test
+ public void givenAnIntArray_thenFind2ndLargestElement() {
+ int[] array = { 1, 3, 24, 16, 87, 20 };
+ int expected2ndLargest = 24;
+
+ int actualSecondLargestElement = Find2ndLargestInArray.find2ndLargestElement(array);
+
+ Assert.assertEquals(expected2ndLargest, actualSecondLargestElement);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java b/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java
new file mode 100644
index 0000000000..ba9188fa7b
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/array/FindElementInArrayTest.java
@@ -0,0 +1,35 @@
+package com.baeldung.array;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class FindElementInArrayTest {
+ @Test
+ public void givenAnIntArray_whenNotUsingStream_thenFindAnElement() {
+ int[] array = { 1, 3, 4, 8, 19, 20 };
+ int element = 19;
+ boolean expectedResult = true;
+ boolean actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
+ Assert.assertEquals(expectedResult, actualResult);
+
+ element = 78;
+ expectedResult = false;
+ actualResult = FindElementInArray.findGivenElementInArrayWithoutUsingStream(array, element);
+ Assert.assertEquals(expectedResult, actualResult);
+ }
+
+ @Test
+ public void givenAnIntArray_whenUsingStream_thenFindAnElement() {
+ int[] array = { 15, 16, 12, 18 };
+ int element = 16;
+ boolean expectedResult = true;
+ boolean actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
+ Assert.assertEquals(expectedResult, actualResult);
+
+ element = 20;
+ expectedResult = false;
+ actualResult = FindElementInArray.findGivenElementInArrayUsingStream(array, element);
+ Assert.assertEquals(expectedResult, actualResult);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java
new file mode 100644
index 0000000000..3385ed690f
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/array/SumAndAverageInArrayTest.java
@@ -0,0 +1,41 @@
+package com.baeldung.array;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class SumAndAverageInArrayTest {
+ @Test
+ public void givenAnIntArray_whenNotUsingStream_thenFindSum() {
+ int[] array = { 1, 3, 4, 8, 19, 20 };
+ int expectedSumOfArray = 55;
+ int actualSumOfArray = SumAndAverageInArray.findSumWithoutUsingStream(array);
+ Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
+ }
+
+ @Test
+ public void givenAnIntArray_whenUsingStream_thenFindSum() {
+ int[] array = { 1, 3, 4, 8, 19, 20 };
+ int expectedSumOfArray = 55;
+ int actualSumOfArray = SumAndAverageInArray.findSumUsingStream(array);
+
+ Assert.assertEquals(expectedSumOfArray, actualSumOfArray);
+ }
+
+ @Test
+ public void givenAnIntArray_whenNotUsingStream_thenFindAverage() {
+ int[] array = { 1, 3, 4, 8, 19, 20 };
+ double expectedAvgOfArray = 9.17;
+ double actualAvgOfArray = SumAndAverageInArray.findAverageWithoutUsingStream(array);
+
+ Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034);
+ }
+
+ @Test
+ public void givenAnIntArray_whenUsingStream_thenFindAverage() {
+ int[] array = { 1, 3, 4, 8, 19, 20 };
+ double expectedAvgOfArray = 9.17;
+ double actualAvgOfArray = SumAndAverageInArray.findAverageUsingStream(array);
+
+ Assert.assertEquals(expectedAvgOfArray, actualAvgOfArray, 0.0034);
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java
new file mode 100644
index 0000000000..103681894e
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/asciiart/AsciiArtTest.java
@@ -0,0 +1,20 @@
+package com.baeldung.asciiart;
+
+import java.awt.Font;
+
+import org.junit.Test;
+
+import com.baeldung.asciiart.AsciiArt.Settings;
+
+public class AsciiArtTest {
+
+ @Test
+ public void givenTextWithAsciiCharacterAndSettings_shouldPrintAsciiArt() {
+ AsciiArt asciiArt = new AsciiArt();
+ String text = "BAELDUNG";
+ Settings settings = asciiArt.new Settings(new Font("SansSerif", Font.BOLD, 24), text.length() * 30, 30); // 30 pixel width per character
+
+ asciiArt.drawString(text, "*", settings);
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/casting/CastingTest.java b/core-java/src/test/java/com/baeldung/casting/CastingTest.java
index 0ca1ce88dc..dd95e0dd80 100644
--- a/core-java/src/test/java/com/baeldung/casting/CastingTest.java
+++ b/core-java/src/test/java/com/baeldung/casting/CastingTest.java
@@ -11,6 +11,7 @@ public class CastingTest {
public void whenPrimitiveConverted_thenValueChanged() {
double myDouble = 1.1;
int myInt = (int) myDouble;
+
assertNotEquals(myDouble, myInt);
}
@@ -55,4 +56,25 @@ public class CastingTest {
animals.add(new Dog());
new AnimalFeeder().uncheckedFeed(animals);
}
+
+ @Test
+ public void whenDowncastToCatWithCastMethod_thenMeowIsCalled() {
+ Animal animal = new Cat();
+ if (Cat.class.isInstance(animal)) {
+ Cat cat = Cat.class.cast(animal);
+ cat.meow();
+ }
+ }
+
+ @Test
+ public void whenParameterCat_thenOnlyCatsFed() {
+ List animals = new ArrayList<>();
+ animals.add(new Cat());
+ animals.add(new Dog());
+ AnimalFeederGeneric catFeeder = new AnimalFeederGeneric(Cat.class);
+ List fedAnimals = catFeeder.feed(animals);
+
+ assertTrue(fedAnimals.size() == 1);
+ assertTrue(fedAnimals.get(0) instanceof Cat);
+ }
}
diff --git a/core-java/src/test/java/com/baeldung/java/list/CustomListUnitTest.java b/core-java/src/test/java/com/baeldung/java/list/CustomListUnitTest.java
index 3ee3195e80..9ea42e88e8 100644
--- a/core-java/src/test/java/com/baeldung/java/list/CustomListUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/java/list/CustomListUnitTest.java
@@ -14,6 +14,58 @@ import java.util.List;
import org.junit.Test;
public class CustomListUnitTest {
+ @Test
+ public void givenEmptyList_whenIsEmpty_thenTrueIsReturned() {
+ List
+
+
+ UTF-8
+ 1.8
+ 8.5.4
+
+
\ No newline at end of file
diff --git a/geotools/src/test/java/com/baeldung/geotools/GeoToolsUnitTest.java b/geotools/src/test/java/com/baeldung/geotools/GeoToolsUnitTest.java
index 053932b2a7..4a63c44c8b 100644
--- a/geotools/src/test/java/com/baeldung/geotools/GeoToolsUnitTest.java
+++ b/geotools/src/test/java/com/baeldung/geotools/GeoToolsUnitTest.java
@@ -3,7 +3,6 @@ package com.baeldung.geotools;
import static org.junit.Assert.assertNotNull;
import org.geotools.feature.DefaultFeatureCollection;
-import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeatureType;
@@ -19,4 +18,5 @@ public class GeoToolsUnitTest {
assertNotNull(collection);
}
+
}
diff --git a/gradle/build.gradle b/gradle/build.gradle
index dcc592a2b4..2e5d984fba 100644
--- a/gradle/build.gradle
+++ b/gradle/build.gradle
@@ -33,3 +33,60 @@ task execSecondTest {
}
println 'This will be executed during the configuration phase as well.'
}
+
+task welcome {
+ doLast {
+ println 'Welcome on the Baeldung!'
+ }
+}
+
+task welcomeWithGroup {
+ group 'Sample category'
+ doLast {
+ println 'Welcome on the Baeldung!'
+ }
+}
+
+task welcomeWithGroupAndDescription {
+ group 'Sample category'
+ description 'Tasks which shows welcome message'
+ doLast {
+ println 'Welcome on the Baeldung!'
+ }
+}
+
+class PrintToolVersionTask extends DefaultTask {
+ String tool
+
+ @TaskAction
+ void printToolVersion() {
+ switch (tool) {
+ case 'java':
+ println System.getProperty("java.version")
+ break
+ case 'groovy':
+ println GroovySystem.version
+ break
+ default:
+ throw new IllegalArgumentException("Unknown tool")
+ }
+ }
+}
+
+task printJavaVersion(type : PrintToolVersionTask) {
+ tool 'java'
+}
+
+task printGroovyVersion(type : PrintToolVersionTask) {
+ tool 'groovy'
+}
+
+import com.baeldung.PrintToolVersionBuildSrcTask
+
+task printJavaVersionBuildSrc(type : PrintToolVersionBuildSrcTask) {
+ tool 'java'
+}
+
+task printGroovyVersionBuildSrc(type : PrintToolVersionBuildSrcTask) {
+ tool 'groovy'
+}
\ No newline at end of file
diff --git a/gradle/buildSrc/src/main/groovy/com/baeldung/PrintToolVersionBuildSrcTask.groovy b/gradle/buildSrc/src/main/groovy/com/baeldung/PrintToolVersionBuildSrcTask.groovy
new file mode 100644
index 0000000000..0fbd71db56
--- /dev/null
+++ b/gradle/buildSrc/src/main/groovy/com/baeldung/PrintToolVersionBuildSrcTask.groovy
@@ -0,0 +1,22 @@
+package com.baeldung
+
+import org.gradle.api.DefaultTask
+import org.gradle.api.tasks.TaskAction
+
+class PrintToolVersionBuildSrcTask extends DefaultTask {
+ String tool
+
+ @TaskAction
+ void printToolVersion() {
+ switch (tool) {
+ case 'java':
+ println System.getProperty("java.version")
+ break
+ case 'groovy':
+ println GroovySystem.version
+ break
+ default:
+ throw new IllegalArgumentException("Unknown tool")
+ }
+ }
+}
\ No newline at end of file
diff --git a/guava/pom.xml b/guava/pom.xml
index aa162b7d1b..ca9e1e528e 100644
--- a/guava/pom.xml
+++ b/guava/pom.xml
@@ -43,13 +43,7 @@
${assertj.version}
test
-
-
- org.hamcrest
- java-hamcrest
- 2.0.0.0
- test
-
+
diff --git a/guest/remote-debugging/pom.xml b/guest/remote-debugging/pom.xml
index d958d4c681..8540347e40 100644
--- a/guest/remote-debugging/pom.xml
+++ b/guest/remote-debugging/pom.xml
@@ -31,7 +31,6 @@
org.springframework.boot
spring-boot-starter-tomcat
- provided
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java
new file mode 100644
index 0000000000..dc5242ee7c
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/lob/HibernateSessionUtil.java
@@ -0,0 +1,61 @@
+package com.baeldung.hibernate.lob;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.net.URL;
+import java.util.Properties;
+
+import org.apache.commons.lang3.StringUtils;
+import org.hibernate.SessionFactory;
+import org.hibernate.boot.Metadata;
+import org.hibernate.boot.MetadataSources;
+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.service.ServiceRegistry;
+
+import com.baeldung.hibernate.lob.model.User;
+
+public class HibernateSessionUtil {
+
+ private static SessionFactory sessionFactory;
+ private static String PROPERTY_FILE_NAME;
+
+ public static SessionFactory getSessionFactory() throws IOException {
+ return getSessionFactory(null);
+ }
+
+ public static SessionFactory getSessionFactory(String propertyFileName) throws IOException {
+ PROPERTY_FILE_NAME = propertyFileName;
+ if (sessionFactory == null) {
+ ServiceRegistry serviceRegistry = configureServiceRegistry();
+ sessionFactory = makeSessionFactory(serviceRegistry);
+ }
+ return sessionFactory;
+ }
+
+ private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
+ MetadataSources metadataSources = new MetadataSources(serviceRegistry);
+ metadataSources.addAnnotatedClass(User.class);
+
+ Metadata metadata = metadataSources.buildMetadata();
+ return metadata.getSessionFactoryBuilder()
+ .build();
+
+ }
+
+ private static ServiceRegistry configureServiceRegistry() throws IOException {
+ Properties properties = getProperties();
+ return new StandardServiceRegistryBuilder().applySettings(properties)
+ .build();
+ }
+
+ private static Properties getProperties() throws IOException {
+ Properties properties = new Properties();
+ URL propertiesURL = Thread.currentThread()
+ .getContextClassLoader()
+ .getResource(StringUtils.defaultString(PROPERTY_FILE_NAME, "hibernate.properties"));
+ try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
+ properties.load(inputStream);
+ }
+ return properties;
+ }
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java b/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java
new file mode 100644
index 0000000000..21f725b388
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/lob/model/User.java
@@ -0,0 +1,46 @@
+package com.baeldung.hibernate.lob.model;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.Lob;
+import javax.persistence.Table;
+
+@Entity
+@Table(name="user")
+public class User {
+
+ @Id
+ private String id;
+
+ @Column(name = "name", columnDefinition="VARCHAR(128)")
+ private String name;
+
+ @Lob
+ @Column(name = "photo", columnDefinition="BLOB")
+ private byte[] photo;
+
+ public String getId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public byte[] getPhoto() {
+ return photo;
+ }
+
+ public void setPhoto(byte[] photo) {
+ this.photo = photo;
+ }
+}
diff --git a/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobTest.java b/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobTest.java
new file mode 100644
index 0000000000..74a94d544b
--- /dev/null
+++ b/hibernate5/src/test/java/com/baeldung/hibernate/lob/LobTest.java
@@ -0,0 +1,61 @@
+package com.baeldung.hibernate.lob;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+
+import org.apache.commons.io.IOUtils;
+import org.hibernate.HibernateException;
+import org.hibernate.Session;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import com.baeldung.hibernate.lob.model.User;
+
+public class LobTest {
+
+ private Session session;
+
+ @Before
+ public void init(){
+ try {
+ session = HibernateSessionUtil.getSessionFactory("hibernate.properties")
+ .openSession();
+ } catch (HibernateException | IOException e) {
+ fail("Failed to initiate Hibernate Session [Exception:" + e.toString() + "]");
+ }
+ }
+
+ @After
+ public void close(){
+ if(session != null) session.close();
+ }
+
+ @Test
+ public void givenValidInsertLobObject_whenQueried_returnSameDataAsInserted(){
+ User user = new User();
+ try(InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("profile.png");) {
+ // Get Image file from the resource
+ if(inputStream == null) fail("Unable to get resources");
+ user.setId("1");
+ user.setName("User");
+ user.setPhoto(IOUtils.toByteArray(inputStream));
+
+ session.persist(user);
+ } catch (IOException e) {
+ fail("Unable to read input stream");
+ }
+
+ User result = session.find(User.class, "1");
+
+ assertNotNull("Query result is null", result);
+ assertEquals("User's name is invalid", user.getName(), result.getName() );
+ assertTrue("User's photo is corrupted", Arrays.equals(user.getPhoto(), result.getPhoto()) );
+ }
+}
diff --git a/hibernate5/src/test/resources/profile.png b/hibernate5/src/test/resources/profile.png
new file mode 100644
index 0000000000..1cd4e978b9
Binary files /dev/null and b/hibernate5/src/test/resources/profile.png differ
diff --git a/hystrix/pom.xml b/hystrix/pom.xml
index 9e4b2bb082..19da678eb7 100644
--- a/hystrix/pom.xml
+++ b/hystrix/pom.xml
@@ -34,7 +34,6 @@
org.springframework.boot
spring-boot-starter-tomcat
- provided
org.springframework.boot
diff --git a/intelliJ/README.md b/intelliJ/README.md
deleted file mode 100644
index ff12555376..0000000000
--- a/intelliJ/README.md
+++ /dev/null
@@ -1 +0,0 @@
-## Relevant articles:
diff --git a/java-lite/README.md b/java-lite/README.md
index bcb84e186e..13dcd5f8c3 100644
--- a/java-lite/README.md
+++ b/java-lite/README.md
@@ -1,2 +1,3 @@
### Relevant Articles:
-- [RESTFul CRUD application with JavaLite] ()
\ No newline at end of file
+
+- [A Guide to JavaLite – Building a RESTful CRUD application](http://www.baeldung.com/javalite-rest)
diff --git a/java-rmi/README.md b/java-rmi/README.md
new file mode 100644
index 0000000000..4d12060395
--- /dev/null
+++ b/java-rmi/README.md
@@ -0,0 +1,3 @@
+### Relevant articles
+
+- [Getting Started with Java RMI](http://www.baeldung.com/java-rmi)
diff --git a/java-spi/exchange-rate-api/pom.xml b/java-spi/exchange-rate-api/pom.xml
new file mode 100644
index 0000000000..27651533a9
--- /dev/null
+++ b/java-spi/exchange-rate-api/pom.xml
@@ -0,0 +1,14 @@
+
+ 4.0.0
+
+ exchange-rate-api
+ jar
+
+
+ com.baeldung
+ java-spi
+ 1.0.0-SNAPSHOT
+
+
+
diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/ExchangeRate.java b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/ExchangeRate.java
new file mode 100644
index 0000000000..afc7ef92ce
--- /dev/null
+++ b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/ExchangeRate.java
@@ -0,0 +1,42 @@
+package com.baeldung.rate;
+
+import com.baeldung.rate.exception.ProviderNotFoundException;
+import com.baeldung.rate.spi.ExchangeRateProvider;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.ServiceLoader;
+
+public final class ExchangeRate {
+
+ private static final String DEFAULT_PROVIDER = "com.baeldung.rate.spi.YahooFinanceExchangeRateProvider";
+
+ //All providers
+ public static List providers() {
+ List services = new ArrayList<>();
+ ServiceLoader loader = ServiceLoader.load(ExchangeRateProvider.class);
+ loader.forEach(exchangeRateProvider -> {
+ services.add(exchangeRateProvider);
+ });
+ return services;
+ }
+
+ //Default provider
+ public static ExchangeRateProvider provider() {
+ return provider(DEFAULT_PROVIDER);
+ }
+
+ //provider by name
+ public static ExchangeRateProvider provider(String providerName) {
+ ServiceLoader loader = ServiceLoader.load(ExchangeRateProvider.class);
+ Iterator it = loader.iterator();
+ while (it.hasNext()) {
+ ExchangeRateProvider provider = it.next();
+ if (providerName.equals(provider.getClass().getName())) {
+ return provider;
+ }
+ }
+ throw new ProviderNotFoundException("Exchange Rate provider " + providerName + " not found");
+ }
+}
diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/Quote.java b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/Quote.java
new file mode 100644
index 0000000000..577af3b618
--- /dev/null
+++ b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/Quote.java
@@ -0,0 +1,44 @@
+package com.baeldung.rate.api;
+
+import java.math.BigDecimal;
+import java.time.LocalDate;
+
+public class Quote {
+ private String currency;
+ private BigDecimal ask;
+ private BigDecimal bid;
+ private LocalDate date;
+ //...
+
+ public String getCurrency() {
+ return currency;
+ }
+
+ public void setCurrency(String currency) {
+ this.currency = currency;
+ }
+
+ public BigDecimal getAsk() {
+ return ask;
+ }
+
+ public void setAsk(BigDecimal ask) {
+ this.ask = ask;
+ }
+
+ public BigDecimal getBid() {
+ return bid;
+ }
+
+ public void setBid(BigDecimal bid) {
+ this.bid = bid;
+ }
+
+ public LocalDate getDate() {
+ return date;
+ }
+
+ public void setDate(LocalDate date) {
+ this.date = date;
+ }
+}
\ No newline at end of file
diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/QuoteManager.java b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/QuoteManager.java
new file mode 100644
index 0000000000..16416eaf65
--- /dev/null
+++ b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/api/QuoteManager.java
@@ -0,0 +1,8 @@
+package com.baeldung.rate.api;
+
+import java.time.LocalDate;
+import java.util.List;
+
+public interface QuoteManager {
+ List getQuotes(String baseCurrency, LocalDate date);
+}
diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/exception/ProviderNotFoundException.java b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/exception/ProviderNotFoundException.java
new file mode 100644
index 0000000000..3a2d92c4fd
--- /dev/null
+++ b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/exception/ProviderNotFoundException.java
@@ -0,0 +1,13 @@
+package com.baeldung.rate.exception;
+
+public class ProviderNotFoundException extends RuntimeException {
+
+ public ProviderNotFoundException() {
+ super();
+ }
+
+ public ProviderNotFoundException(String message) {
+ super(message);
+ }
+
+}
diff --git a/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/spi/ExchangeRateProvider.java b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/spi/ExchangeRateProvider.java
new file mode 100644
index 0000000000..c3157b2b03
--- /dev/null
+++ b/java-spi/exchange-rate-api/src/main/java/com/baeldung/rate/spi/ExchangeRateProvider.java
@@ -0,0 +1,7 @@
+package com.baeldung.rate.spi;
+
+import com.baeldung.rate.api.QuoteManager;
+
+public interface ExchangeRateProvider {
+ QuoteManager create();
+}
\ No newline at end of file
diff --git a/java-spi/exchange-rate-app/pom.xml b/java-spi/exchange-rate-app/pom.xml
new file mode 100644
index 0000000000..7e64cf7438
--- /dev/null
+++ b/java-spi/exchange-rate-app/pom.xml
@@ -0,0 +1,27 @@
+
+ 4.0.0
+
+ exchange-rate-app
+ jar
+
+
+ com.baeldung
+ java-spi
+ 1.0.0-SNAPSHOT
+
+
+
+
+ com.baeldung
+ exchange-rate-api
+ 1.0.0-SNAPSHOT
+
+
+ com.baeldung
+ exchange-rate-impl
+ 1.0.0-SNAPSHOT
+
+
+
+
diff --git a/java-spi/exchange-rate-app/src/main/java/com.baeldung.rate.app/MainApp.java b/java-spi/exchange-rate-app/src/main/java/com.baeldung.rate.app/MainApp.java
new file mode 100644
index 0000000000..fd43ed3a85
--- /dev/null
+++ b/java-spi/exchange-rate-app/src/main/java/com.baeldung.rate.app/MainApp.java
@@ -0,0 +1,21 @@
+package com.baeldung.rate.app;
+
+import com.baeldung.rate.ExchangeRate;
+import com.baeldung.rate.api.Quote;
+
+import java.time.LocalDate;
+import java.util.List;
+
+public class MainApp {
+ public static void main(String... args) {
+ ExchangeRate.providers().forEach(provider -> {
+ System.out.println("Retreiving USD quotes from provider :" + provider);
+ List quotes = provider.create().getQuotes("USD", LocalDate.now());
+ System.out.println(String.format("%14s%12s|%12s", "","Ask", "Bid"));
+ System.out.println("----------------------------------------");
+ quotes.forEach(quote -> {
+ System.out.println("USD --> " + quote.getCurrency() + " : " + String.format("%12f|%12f", quote.getAsk(), quote.getBid()));
+ });
+ });
+ }
+}
diff --git a/java-spi/exchange-rate-impl/pom.xml b/java-spi/exchange-rate-impl/pom.xml
new file mode 100644
index 0000000000..ec22791351
--- /dev/null
+++ b/java-spi/exchange-rate-impl/pom.xml
@@ -0,0 +1,42 @@
+
+ 4.0.0
+
+ exchange-rate-impl
+ jar
+
+
+ com.baeldung
+ java-spi
+ 1.0.0-SNAPSHOT
+
+
+
+
+ com.baeldung
+ exchange-rate-api
+ 1.0.0-SNAPSHOT
+
+
+ com.squareup.okhttp3
+ okhttp
+ 3.10.0
+
+
+ javax.json.bind
+ javax.json.bind-api
+ 1.0
+
+
+ org.eclipse
+ yasson
+ 1.0.1
+
+
+ org.glassfish
+ javax.json
+ 1.1.2
+
+
+
+
diff --git a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponse.java b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponse.java
new file mode 100644
index 0000000000..9ba4fb26b0
--- /dev/null
+++ b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponse.java
@@ -0,0 +1,26 @@
+package com.baeldung.rate.impl;
+
+import com.baeldung.rate.api.Quote;
+
+import java.util.List;
+
+public class QuoteResponse {
+ private List result;
+ private String error;
+
+ public List getResult() {
+ return result;
+ }
+
+ public void setResult(List result) {
+ this.result = result;
+ }
+
+ public String getError() {
+ return error;
+ }
+
+ public void setError(String error) {
+ this.error = error;
+ }
+}
diff --git a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponseWrapper.java b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponseWrapper.java
new file mode 100644
index 0000000000..6d7be086f0
--- /dev/null
+++ b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/QuoteResponseWrapper.java
@@ -0,0 +1,13 @@
+package com.baeldung.rate.impl;
+
+public class QuoteResponseWrapper {
+ private QuoteResponse quoteResponse;
+
+ public QuoteResponse getQuoteResponse() {
+ return quoteResponse;
+ }
+
+ public void setQuoteResponse(QuoteResponse quoteResponse) {
+ this.quoteResponse = quoteResponse;
+ }
+}
diff --git a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooFinanceExchangeRateProvider.java b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooFinanceExchangeRateProvider.java
new file mode 100644
index 0000000000..9a069cfde4
--- /dev/null
+++ b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooFinanceExchangeRateProvider.java
@@ -0,0 +1,13 @@
+package com.baeldung.rate.impl;
+
+import com.baeldung.rate.api.QuoteManager;
+import com.baeldung.rate.spi.ExchangeRateProvider;
+
+public class YahooFinanceExchangeRateProvider implements ExchangeRateProvider {
+
+ @Override
+ public QuoteManager create() {
+ return new YahooQuoteManagerImpl();
+ }
+
+}
\ No newline at end of file
diff --git a/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java
new file mode 100644
index 0000000000..8cc68259be
--- /dev/null
+++ b/java-spi/exchange-rate-impl/src/main/java/com/baeldung/rate/impl/YahooQuoteManagerImpl.java
@@ -0,0 +1,65 @@
+package com.baeldung.rate.impl;
+
+import com.baeldung.rate.api.Quote;
+import com.baeldung.rate.api.QuoteManager;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+import javax.json.bind.JsonbBuilder;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.time.LocalDate;
+import java.util.Currency;
+import java.util.List;
+
+public class YahooQuoteManagerImpl implements QuoteManager {
+
+ static final String URL_PROVIDER = "https://query1.finance.yahoo.com/v7/finance/quote";
+ OkHttpClient client = new OkHttpClient();
+
+ @Override
+ public List getQuotes(String baseCurrency, LocalDate date) {
+
+ StringBuilder sb = new StringBuilder();
+ Currency.getAvailableCurrencies().forEach(currency -> {
+ if (!currency.equals(currency.getCurrencyCode())) {
+ sb.append(baseCurrency).append(currency.getCurrencyCode()).append("=X").append(",");
+ }
+ });
+
+ String value = "";
+ try {
+ value = URLEncoder.encode(sb.toString().substring(0, sb.toString().length() - 1), "UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ e.printStackTrace();
+ }
+ String queryString = String.format("%s=%s", "symbols", value);
+ String response = doGetRequest(queryString);
+ System.out.println(response);
+ return map(response);
+ }
+
+ private List map(String response) {
+ QuoteResponseWrapper qrw = JsonbBuilder.create().fromJson(response, QuoteResponseWrapper.class);
+ return qrw.getQuoteResponse().getResult();
+ }
+
+ String doGetRequest(String queryString) {
+ String fullUrl = URL_PROVIDER + "?" + queryString;
+
+ System.out.println(fullUrl);
+ Request request = new Request.Builder()
+ .url(fullUrl)
+ .build();
+ Response response = null;
+ try {
+ response = client.newCall(request).execute();
+ return response.body().string();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+}
diff --git a/java-spi/exchange-rate-impl/src/main/resources/META-INF/services/com.baeldung.rate.spi.ExchangeRateProvider b/java-spi/exchange-rate-impl/src/main/resources/META-INF/services/com.baeldung.rate.spi.ExchangeRateProvider
new file mode 100644
index 0000000000..67ba8a8227
--- /dev/null
+++ b/java-spi/exchange-rate-impl/src/main/resources/META-INF/services/com.baeldung.rate.spi.ExchangeRateProvider
@@ -0,0 +1 @@
+com.baeldung.rate.impl.YahooFinanceExchangeRateProvider
\ No newline at end of file
diff --git a/java-spi/pom.xml b/java-spi/pom.xml
new file mode 100644
index 0000000000..8eaa184d8d
--- /dev/null
+++ b/java-spi/pom.xml
@@ -0,0 +1,20 @@
+
+ 4.0.0
+
+ java-spi
+ pom
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ exchange-rate-api
+ exchange-rate-impl
+ exchange-rate-app
+
+
+
diff --git a/jenkins/README.md b/jenkins/README.md
new file mode 100644
index 0000000000..da60e556df
--- /dev/null
+++ b/jenkins/README.md
@@ -0,0 +1,3 @@
+## Relevant articles:
+
+- [Writing a Jenkins Plugin](http://www.baeldung.com/jenkins-custom-plugin)
diff --git a/jersey/pom.xml b/jersey/pom.xml
new file mode 100644
index 0000000000..0c8b6b9281
--- /dev/null
+++ b/jersey/pom.xml
@@ -0,0 +1,63 @@
+
+
+ 4.0.0
+
+ com.baeldung
+ jersey
+ 0.0.1-SNAPSHOT
+ war
+
+
+ com.baeldung
+ parent-modules
+ 1.0.0-SNAPSHOT
+
+
+
+ 2.26
+ 1.7.25
+ 3.2.0
+
+
+
+ jersey
+
+
+ maven-war-plugin
+ ${maven-war-plugin.version}
+
+ false
+
+
+
+
+
+
+
+ org.glassfish.jersey.core
+ jersey-server
+ ${jersey.version}
+
+
+ org.glassfish.jersey.core
+ jersey-client
+ ${jersey.version}
+
+
+ org.glassfish.jersey.bundles
+ jaxrs-ri
+ ${jersey.version}
+
+
+ org.slf4j
+ slf4j-api
+ ${slf4j.version}
+
+
+
+
+
+
+
diff --git a/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java b/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java
new file mode 100644
index 0000000000..88ad891411
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/client/JerseyClient.java
@@ -0,0 +1,45 @@
+package com.baeldung.jersey.client;
+
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Response;
+
+import org.glassfish.jersey.client.ClientConfig;
+
+import com.baeldung.jersey.client.filter.RequestClientFilter;
+import com.baeldung.jersey.client.filter.ResponseClientFilter;
+import com.baeldung.jersey.client.interceptor.RequestClientWriterInterceptor;
+
+public class JerseyClient {
+
+ private static final String URI_GREETINGS = "http://localhost:8080/jersey/greetings";
+
+ public static String getHelloGreeting() {
+ return createClient().target(URI_GREETINGS)
+ .request()
+ .get(String.class);
+ }
+
+ public static String getHiGreeting() {
+ return createClient().target(URI_GREETINGS + "/hi")
+ .request()
+ .get(String.class);
+ }
+
+ public static Response getCustomGreeting() {
+ return createClient().target(URI_GREETINGS + "/custom")
+ .request()
+ .post(Entity.text("custom"));
+ }
+
+ private static Client createClient() {
+ ClientConfig config = new ClientConfig();
+ config.register(RequestClientFilter.class);
+ config.register(ResponseClientFilter.class);
+ config.register(RequestClientWriterInterceptor.class);
+
+ return ClientBuilder.newClient(config);
+ }
+
+}
diff --git a/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java b/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java
new file mode 100644
index 0000000000..8c6ac2c5fb
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/client/filter/RequestClientFilter.java
@@ -0,0 +1,24 @@
+package com.baeldung.jersey.client.filter;
+
+import java.io.IOException;
+
+import javax.ws.rs.client.ClientRequestContext;
+import javax.ws.rs.client.ClientRequestFilter;
+import javax.ws.rs.ext.Provider;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Provider
+public class RequestClientFilter implements ClientRequestFilter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(RequestClientFilter.class);
+
+ @Override
+ public void filter(ClientRequestContext requestContext) throws IOException {
+ LOG.info("Request client filter");
+
+ requestContext.setProperty("test", "test client request filter");
+ }
+
+}
diff --git a/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java b/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java
new file mode 100644
index 0000000000..1676fa2094
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/client/filter/ResponseClientFilter.java
@@ -0,0 +1,26 @@
+package com.baeldung.jersey.client.filter;
+
+import java.io.IOException;
+
+import javax.ws.rs.client.ClientRequestContext;
+import javax.ws.rs.client.ClientResponseContext;
+import javax.ws.rs.client.ClientResponseFilter;
+import javax.ws.rs.ext.Provider;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Provider
+public class ResponseClientFilter implements ClientResponseFilter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ResponseClientFilter.class);
+
+ @Override
+ public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException {
+ LOG.info("Response client filter");
+
+ responseContext.getHeaders()
+ .add("X-Test-Client", "Test response client filter");
+ }
+
+}
diff --git a/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java b/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java
new file mode 100644
index 0000000000..7216cf18cc
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/client/interceptor/RequestClientWriterInterceptor.java
@@ -0,0 +1,28 @@
+package com.baeldung.jersey.client.interceptor;
+
+import java.io.IOException;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.ext.Provider;
+import javax.ws.rs.ext.WriterInterceptor;
+import javax.ws.rs.ext.WriterInterceptorContext;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Provider
+public class RequestClientWriterInterceptor implements WriterInterceptor {
+
+ private static final Logger LOG = LoggerFactory.getLogger(RequestClientWriterInterceptor.class);
+
+ @Override
+ public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
+ LOG.info("request writer interceptor in the client side");
+
+ context.getOutputStream()
+ .write(("Message added in the writer interceptor in the client side").getBytes());
+
+ context.proceed();
+ }
+
+}
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java b/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java
new file mode 100644
index 0000000000..d0ea873db1
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/server/Greetings.java
@@ -0,0 +1,32 @@
+package com.baeldung.jersey.server;
+
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+
+import com.baeldung.jersey.server.config.HelloBinding;
+
+@Path("/greetings")
+public class Greetings {
+
+ @GET
+ @HelloBinding
+ public String getHelloGreeting() {
+ return "hello";
+ }
+
+ @GET
+ @Path("/hi")
+ public String getHiGreeting() {
+ return "hi";
+ }
+
+ @POST
+ @Path("/custom")
+ public Response getCustomGreeting(String name) {
+ return Response.status(Status.OK.getStatusCode())
+ .build();
+ }
+}
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java
new file mode 100644
index 0000000000..49b11adeab
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloBinding.java
@@ -0,0 +1,11 @@
+package com.baeldung.jersey.server.config;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+import javax.ws.rs.NameBinding;
+
+@NameBinding
+@Retention(RetentionPolicy.RUNTIME)
+public @interface HelloBinding {
+}
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java
new file mode 100644
index 0000000000..e56cdec140
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/server/config/HelloDynamicBinding.java
@@ -0,0 +1,31 @@
+package com.baeldung.jersey.server.config;
+
+import javax.ws.rs.container.DynamicFeature;
+import javax.ws.rs.container.ResourceInfo;
+import javax.ws.rs.core.FeatureContext;
+import javax.ws.rs.ext.Provider;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.baeldung.jersey.server.Greetings;
+import com.baeldung.jersey.server.filter.ResponseServerFilter;
+
+@Provider
+public class HelloDynamicBinding implements DynamicFeature {
+
+ private static final Logger LOG = LoggerFactory.getLogger(HelloDynamicBinding.class);
+
+ @Override
+ public void configure(ResourceInfo resourceInfo, FeatureContext context) {
+ LOG.info("Hello dynamic binding");
+
+ if (Greetings.class.equals(resourceInfo.getResourceClass()) && resourceInfo.getResourceMethod()
+ .getName()
+ .contains("HiGreeting")) {
+ context.register(ResponseServerFilter.class);
+ }
+
+ }
+
+}
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java b/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java
new file mode 100644
index 0000000000..4670cc291c
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/server/config/ServerConfig.java
@@ -0,0 +1,14 @@
+package com.baeldung.jersey.server.config;
+
+import javax.ws.rs.ApplicationPath;
+
+import org.glassfish.jersey.server.ResourceConfig;
+
+@ApplicationPath("/*")
+public class ServerConfig extends ResourceConfig {
+
+ public ServerConfig() {
+ packages("com.baeldung.jersey.server");
+ }
+
+}
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java b/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java
new file mode 100644
index 0000000000..181fa7f043
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/server/filter/PrematchingRequestFilter.java
@@ -0,0 +1,27 @@
+package com.baeldung.jersey.server.filter;
+
+import java.io.IOException;
+
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.container.PreMatching;
+import javax.ws.rs.ext.Provider;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Provider
+@PreMatching
+public class PrematchingRequestFilter implements ContainerRequestFilter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(PrematchingRequestFilter.class);
+
+ @Override
+ public void filter(ContainerRequestContext ctx) throws IOException {
+ LOG.info("prematching filter");
+ if (ctx.getMethod()
+ .equals("DELETE")) {
+ LOG.info("\"Deleting request");
+ }
+ }
+}
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java b/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java
new file mode 100644
index 0000000000..de0dcbdce7
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/server/filter/ResponseServerFilter.java
@@ -0,0 +1,23 @@
+package com.baeldung.jersey.server.filter;
+
+import java.io.IOException;
+
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerResponseContext;
+import javax.ws.rs.container.ContainerResponseFilter;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ResponseServerFilter implements ContainerResponseFilter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ResponseServerFilter.class);
+
+ @Override
+ public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
+ LOG.info("Response server filter");
+
+ responseContext.getHeaders()
+ .add("X-Test", "Filter test");
+ }
+}
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java b/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java
new file mode 100644
index 0000000000..cb0cd185f7
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/server/filter/RestrictedOperationsRequestFilter.java
@@ -0,0 +1,36 @@
+package com.baeldung.jersey.server.filter;
+
+import java.io.IOException;
+
+import javax.annotation.Priority;
+import javax.ws.rs.Priorities;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.Provider;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.baeldung.jersey.server.config.HelloBinding;
+
+@Provider
+@Priority(Priorities.AUTHORIZATION)
+@HelloBinding
+public class RestrictedOperationsRequestFilter implements ContainerRequestFilter {
+
+ private static final Logger LOG = LoggerFactory.getLogger(RestrictedOperationsRequestFilter.class);
+
+ @Override
+ public void filter(ContainerRequestContext ctx) throws IOException {
+ LOG.info("Restricted operations filter");
+ if (ctx.getLanguage() != null && "EN".equals(ctx.getLanguage()
+ .getLanguage())) {
+ LOG.info("Aborting request");
+ ctx.abortWith(Response.status(Response.Status.FORBIDDEN)
+ .entity("Cannot access")
+ .build());
+ }
+
+ }
+}
diff --git a/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java b/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java
new file mode 100644
index 0000000000..e9cc57fc2a
--- /dev/null
+++ b/jersey/src/main/java/com/baeldung/jersey/server/interceptor/RequestServerReaderInterceptor.java
@@ -0,0 +1,36 @@
+package com.baeldung.jersey.server.interceptor;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.stream.Collectors;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.ext.Provider;
+import javax.ws.rs.ext.ReaderInterceptor;
+import javax.ws.rs.ext.ReaderInterceptorContext;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Provider
+public class RequestServerReaderInterceptor implements ReaderInterceptor {
+
+ private static final Logger LOG = LoggerFactory.getLogger(RequestServerReaderInterceptor.class);
+
+ @Override
+ public Object aroundReadFrom(ReaderInterceptorContext context) throws IOException, WebApplicationException {
+ LOG.info("Request reader interceptor in the server side");
+
+ InputStream is = context.getInputStream();
+ String body = new BufferedReader(new InputStreamReader(is)).lines()
+ .collect(Collectors.joining("\n"));
+
+ context.setInputStream(new ByteArrayInputStream((body + " message added in server reader interceptor").getBytes()));
+
+ return context.proceed();
+ }
+
+}
diff --git a/jersey/src/main/resources/logback.xml b/jersey/src/main/resources/logback.xml
new file mode 100644
index 0000000000..d87a87bf53
--- /dev/null
+++ b/jersey/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %date [%thread] %-5level %logger{36} - %message%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java
new file mode 100644
index 0000000000..72ba4cc5b9
--- /dev/null
+++ b/jersey/src/test/java/com/baeldung/jersey/client/JerseyClientTest.java
@@ -0,0 +1,35 @@
+package com.baeldung.jersey.client;
+
+import javax.ws.rs.core.Response;
+
+import org.junit.Assert;
+import org.junit.Ignore;
+import org.junit.Test;
+
+@Ignore
+public class JerseyClientTest {
+
+ private static int HTTP_OK = 200;
+
+ @Test
+ public void givenGreetingResource_whenCallingHelloGreeting_thenHelloReturned() {
+ String response = JerseyClient.getHelloGreeting();
+
+ Assert.assertEquals("hello", response);
+ }
+
+ @Test
+ public void givenGreetingResource_whenCallingHiGreeting_thenHiReturned() {
+ String response = JerseyClient.getHiGreeting();
+
+ Assert.assertEquals("hi", response);
+ }
+
+ @Test
+ public void givenGreetingResource_whenCallingCustomGreeting_thenCustomGreetingReturned() {
+ Response response = JerseyClient.getCustomGreeting();
+
+ Assert.assertEquals(HTTP_OK, response.getStatus());
+ }
+
+}
diff --git a/jsonld/.gitignore b/jsonld/.gitignore
deleted file mode 100644
index 2af7cefb0a..0000000000
--- a/jsonld/.gitignore
+++ /dev/null
@@ -1,24 +0,0 @@
-target/
-!.mvn/wrapper/maven-wrapper.jar
-
-### STS ###
-.apt_generated
-.classpath
-.factorypath
-.project
-.settings
-.springBeans
-
-### IntelliJ IDEA ###
-.idea
-*.iws
-*.iml
-*.ipr
-
-### NetBeans ###
-nbproject/private/
-build/
-nbbuild/
-dist/
-nbdist/
-.nb-gradle/
\ No newline at end of file
diff --git a/jsonld/.mvn/wrapper/maven-wrapper.jar b/jsonld/.mvn/wrapper/maven-wrapper.jar
deleted file mode 100644
index 5fd4d5023f..0000000000
Binary files a/jsonld/.mvn/wrapper/maven-wrapper.jar and /dev/null differ
diff --git a/jsonld/.mvn/wrapper/maven-wrapper.properties b/jsonld/.mvn/wrapper/maven-wrapper.properties
deleted file mode 100644
index c954cec91c..0000000000
--- a/jsonld/.mvn/wrapper/maven-wrapper.properties
+++ /dev/null
@@ -1 +0,0 @@
-distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
diff --git a/jsonld/README.md b/jsonld/README.md
deleted file mode 100644
index 51ca961bea..0000000000
--- a/jsonld/README.md
+++ /dev/null
@@ -1,22 +0,0 @@
-JSON-LD
-=======
-
-Hypermedia serialization with JSON-LD.
-
-### Requirements
-
-- Maven
-- JDK 8
-- JSON-LD
-
-### Running
-To build and start the server simply type
-
-```bash
-$ mvn clean install
-$ mvn spring-boot:run
-```
-
-Now with default configurations it will be available at: [http://localhost:8080](http://localhost:8080)
-
-Enjoy it :)
\ No newline at end of file
diff --git a/jsonld/mvnw b/jsonld/mvnw
deleted file mode 100755
index a1ba1bf554..0000000000
--- a/jsonld/mvnw
+++ /dev/null
@@ -1,233 +0,0 @@
-#!/bin/sh
-# ----------------------------------------------------------------------------
-# Licensed to the Apache Software Foundation (ASF) under one
-# or more contributor license agreements. See the NOTICE file
-# distributed with this work for additional information
-# regarding copyright ownership. The ASF licenses this file
-# to you under the Apache License, Version 2.0 (the
-# "License"); you may not use this file except in compliance
-# with the License. You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing,
-# software distributed under the License is distributed on an
-# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-# KIND, either express or implied. See the License for the
-# specific language governing permissions and limitations
-# under the License.
-# ----------------------------------------------------------------------------
-
-# ----------------------------------------------------------------------------
-# Maven2 Start Up Batch script
-#
-# Required ENV vars:
-# ------------------
-# JAVA_HOME - location of a JDK home dir
-#
-# Optional ENV vars
-# -----------------
-# M2_HOME - location of maven2's installed home dir
-# MAVEN_OPTS - parameters passed to the Java VM when running Maven
-# e.g. to debug Maven itself, use
-# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
-# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
-# ----------------------------------------------------------------------------
-
-if [ -z "$MAVEN_SKIP_RC" ] ; then
-
- if [ -f /etc/mavenrc ] ; then
- . /etc/mavenrc
- fi
-
- if [ -f "$HOME/.mavenrc" ] ; then
- . "$HOME/.mavenrc"
- fi
-
-fi
-
-# OS specific support. $var _must_ be set to either true or false.
-cygwin=false;
-darwin=false;
-mingw=false
-case "`uname`" in
- CYGWIN*) cygwin=true ;;
- MINGW*) mingw=true;;
- Darwin*) darwin=true
- #
- # Look for the Apple JDKs first to preserve the existing behaviour, and then look
- # for the new JDKs provided by Oracle.
- #
- if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK ] ; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -L /System/Library/Java/JavaVirtualMachines/CurrentJDK ] ; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=/System/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -L "/Library/Java/JavaVirtualMachines/CurrentJDK" ] ; then
- #
- # Oracle JDKs
- #
- export JAVA_HOME=/Library/Java/JavaVirtualMachines/CurrentJDK/Contents/Home
- fi
-
- if [ -z "$JAVA_HOME" ] && [ -x "/usr/libexec/java_home" ]; then
- #
- # Apple JDKs
- #
- export JAVA_HOME=`/usr/libexec/java_home`
- fi
- ;;
-esac
-
-if [ -z "$JAVA_HOME" ] ; then
- if [ -r /etc/gentoo-release ] ; then
- JAVA_HOME=`java-config --jre-home`
- fi
-fi
-
-if [ -z "$M2_HOME" ] ; then
- ## resolve links - $0 may be a link to maven's home
- PRG="$0"
-
- # need this for relative symlinks
- while [ -h "$PRG" ] ; do
- ls=`ls -ld "$PRG"`
- link=`expr "$ls" : '.*-> \(.*\)$'`
- if expr "$link" : '/.*' > /dev/null; then
- PRG="$link"
- else
- PRG="`dirname "$PRG"`/$link"
- fi
- done
-
- saveddir=`pwd`
-
- M2_HOME=`dirname "$PRG"`/..
-
- # make it fully qualified
- M2_HOME=`cd "$M2_HOME" && pwd`
-
- cd "$saveddir"
- # echo Using m2 at $M2_HOME
-fi
-
-# For Cygwin, ensure paths are in UNIX format before anything is touched
-if $cygwin ; then
- [ -n "$M2_HOME" ] &&
- M2_HOME=`cygpath --unix "$M2_HOME"`
- [ -n "$JAVA_HOME" ] &&
- JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
- [ -n "$CLASSPATH" ] &&
- CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
-fi
-
-# For Migwn, ensure paths are in UNIX format before anything is touched
-if $mingw ; then
- [ -n "$M2_HOME" ] &&
- M2_HOME="`(cd "$M2_HOME"; pwd)`"
- [ -n "$JAVA_HOME" ] &&
- JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
- # TODO classpath?
-fi
-
-if [ -z "$JAVA_HOME" ]; then
- javaExecutable="`which javac`"
- if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
- # readlink(1) is not available as standard on Solaris 10.
- readLink=`which readlink`
- if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
- if $darwin ; then
- javaHome="`dirname \"$javaExecutable\"`"
- javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
- else
- javaExecutable="`readlink -f \"$javaExecutable\"`"
- fi
- javaHome="`dirname \"$javaExecutable\"`"
- javaHome=`expr "$javaHome" : '\(.*\)/bin'`
- JAVA_HOME="$javaHome"
- export JAVA_HOME
- fi
- fi
-fi
-
-if [ -z "$JAVACMD" ] ; then
- if [ -n "$JAVA_HOME" ] ; then
- if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
- # IBM's JDK on AIX uses strange locations for the executables
- JAVACMD="$JAVA_HOME/jre/sh/java"
- else
- JAVACMD="$JAVA_HOME/bin/java"
- fi
- else
- JAVACMD="`which java`"
- fi
-fi
-
-if [ ! -x "$JAVACMD" ] ; then
- echo "Error: JAVA_HOME is not defined correctly." >&2
- echo " We cannot execute $JAVACMD" >&2
- exit 1
-fi
-
-if [ -z "$JAVA_HOME" ] ; then
- echo "Warning: JAVA_HOME environment variable is not set."
-fi
-
-CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
-
-# For Cygwin, switch paths to Windows format before running java
-if $cygwin; then
- [ -n "$M2_HOME" ] &&
- M2_HOME=`cygpath --path --windows "$M2_HOME"`
- [ -n "$JAVA_HOME" ] &&
- JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
- [ -n "$CLASSPATH" ] &&
- CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
-fi
-
-# traverses directory structure from process work directory to filesystem root
-# first directory with .mvn subdirectory is considered project base directory
-find_maven_basedir() {
- local basedir=$(pwd)
- local wdir=$(pwd)
- while [ "$wdir" != '/' ] ; do
- if [ -d "$wdir"/.mvn ] ; then
- basedir=$wdir
- break
- fi
- wdir=$(cd "$wdir/.."; pwd)
- done
- echo "${basedir}"
-}
-
-# concatenates all lines of a file
-concat_lines() {
- if [ -f "$1" ]; then
- echo "$(tr -s '\n' ' ' < "$1")"
- fi
-}
-
-export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-$(find_maven_basedir)}
-MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
-
-# Provide a "standardized" way to retrieve the CLI args that will
-# work with both Windows and non-Windows executions.
-MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
-export MAVEN_CMD_LINE_ARGS
-
-WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
-
-exec "$JAVACMD" \
- $MAVEN_OPTS \
- -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
- "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
- ${WRAPPER_LAUNCHER} "$@"
diff --git a/jsonld/mvnw.cmd b/jsonld/mvnw.cmd
deleted file mode 100644
index 2b934e89dd..0000000000
--- a/jsonld/mvnw.cmd
+++ /dev/null
@@ -1,145 +0,0 @@
-@REM ----------------------------------------------------------------------------
-@REM Licensed to the Apache Software Foundation (ASF) under one
-@REM or more contributor license agreements. See the NOTICE file
-@REM distributed with this work for additional information
-@REM regarding copyright ownership. The ASF licenses this file
-@REM to you under the Apache License, Version 2.0 (the
-@REM "License"); you may not use this file except in compliance
-@REM with the License. You may obtain a copy of the License at
-@REM
-@REM http://www.apache.org/licenses/LICENSE-2.0
-@REM
-@REM Unless required by applicable law or agreed to in writing,
-@REM software distributed under the License is distributed on an
-@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-@REM KIND, either express or implied. See the License for the
-@REM specific language governing permissions and limitations
-@REM under the License.
-@REM ----------------------------------------------------------------------------
-
-@REM ----------------------------------------------------------------------------
-@REM Maven2 Start Up Batch script
-@REM
-@REM Required ENV vars:
-@REM JAVA_HOME - location of a JDK home dir
-@REM
-@REM Optional ENV vars
-@REM M2_HOME - location of maven2's installed home dir
-@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
-@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending
-@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
-@REM e.g. to debug Maven itself, use
-@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
-@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
-@REM ----------------------------------------------------------------------------
-
-@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
-@echo off
-@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on'
-@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
-
-@REM set %HOME% to equivalent of $HOME
-if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
-
-@REM Execute a user defined script before this one
-if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
-@REM check for pre script, once with legacy .bat ending and once with .cmd ending
-if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
-if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
-:skipRcPre
-
-@setlocal
-
-set ERROR_CODE=0
-
-@REM To isolate internal variables from possible post scripts, we use another setlocal
-@setlocal
-
-@REM ==== START VALIDATION ====
-if not "%JAVA_HOME%" == "" goto OkJHome
-
-echo.
-echo Error: JAVA_HOME not found in your environment. >&2
-echo Please set the JAVA_HOME variable in your environment to match the >&2
-echo location of your Java installation. >&2
-echo.
-goto error
-
-:OkJHome
-if exist "%JAVA_HOME%\bin\java.exe" goto init
-
-echo.
-echo Error: JAVA_HOME is set to an invalid directory. >&2
-echo JAVA_HOME = "%JAVA_HOME%" >&2
-echo Please set the JAVA_HOME variable in your environment to match the >&2
-echo location of your Java installation. >&2
-echo.
-goto error
-
-@REM ==== END VALIDATION ====
-
-:init
-
-set MAVEN_CMD_LINE_ARGS=%*
-
-@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
-@REM Fallback to current working directory if not found.
-
-set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
-IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
-
-set EXEC_DIR=%CD%
-set WDIR=%EXEC_DIR%
-:findBaseDir
-IF EXIST "%WDIR%"\.mvn goto baseDirFound
-cd ..
-IF "%WDIR%"=="%CD%" goto baseDirNotFound
-set WDIR=%CD%
-goto findBaseDir
-
-:baseDirFound
-set MAVEN_PROJECTBASEDIR=%WDIR%
-cd "%EXEC_DIR%"
-goto endDetectBaseDir
-
-:baseDirNotFound
-set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
-cd "%EXEC_DIR%"
-
-:endDetectBaseDir
-
-IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
-
-@setlocal EnableExtensions EnableDelayedExpansion
-for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
-@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
-
-:endReadAdditionalConfig
-
-SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
-
-set WRAPPER_JAR="".\.mvn\wrapper\maven-wrapper.jar""
-set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
-
-%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CMD_LINE_ARGS%
-if ERRORLEVEL 1 goto error
-goto end
-
-:error
-set ERROR_CODE=1
-
-:end
-@endlocal & set ERROR_CODE=%ERROR_CODE%
-
-if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
-@REM check for post script, once with legacy .bat ending and once with .cmd ending
-if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
-if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
-:skipRcPost
-
-@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
-if "%MAVEN_BATCH_PAUSE%" == "on" pause
-
-if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
-
-exit /B %ERROR_CODE%
\ No newline at end of file
diff --git a/jsonld/pom.xml b/jsonld/pom.xml
deleted file mode 100644
index 1574878667..0000000000
--- a/jsonld/pom.xml
+++ /dev/null
@@ -1,53 +0,0 @@
-
-
- 4.0.0
-
- jsonld
- 0.0.1-SNAPSHOT
- jar
-
- jsonld
- Hypermedia serialization with JSON-LD
-
-
- parent-boot-5
- com.baeldung
- 0.0.1-SNAPSHOT
- ../parent-boot-5
-
-
-
- UTF-8
- UTF-8
- 1.8
- 0.11.1
-
-
-
-
- org.springframework.boot
- spring-boot-starter
-
-
- org.springframework.boot
- spring-boot-starter-test
- test
-
-
-
- com.github.jsonld-java
- jsonld-java
- ${jsonld.version}
-
-
-
-
-
-
- org.springframework.boot
- spring-boot-maven-plugin
-
-
-
-
diff --git a/jsonld/src/main/java/com/baeldung/JsonLdApplication.java b/jsonld/src/main/java/com/baeldung/JsonLdApplication.java
deleted file mode 100644
index 0b8f338127..0000000000
--- a/jsonld/src/main/java/com/baeldung/JsonLdApplication.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.baeldung;
-
-import org.springframework.boot.SpringApplication;
-import org.springframework.boot.autoconfigure.SpringBootApplication;
-
-@SpringBootApplication
-public class JsonLdApplication {
- public static void main(String[] args) {
- SpringApplication.run(JsonLdApplication.class, args);
- }
-}
diff --git a/jsonld/src/main/resources/application.properties b/jsonld/src/main/resources/application.properties
deleted file mode 100644
index b6bfd8f6f3..0000000000
--- a/jsonld/src/main/resources/application.properties
+++ /dev/null
@@ -1,14 +0,0 @@
-# the db host
-spring.data.mongodb.host=localhost
-# the connection port (defaults to 27107)
-spring.data.mongodb.port=27017
-# The database's name
-spring.data.mongodb.database=Jenkins-Pipeline
-
-# Or this
-# spring.data.mongodb.uri=mongodb://localhost/Jenkins-Pipeline
-
-# spring.data.mongodb.username=
-# spring.data.mongodb.password=
-
-spring.data.mongodb.repositories.enabled=true
\ No newline at end of file
diff --git a/jsonld/src/test/java/com/baeldung/JsonLdSerializatorTest.java b/jsonld/src/test/java/com/baeldung/JsonLdSerializatorTest.java
deleted file mode 100644
index 762a4254dc..0000000000
--- a/jsonld/src/test/java/com/baeldung/JsonLdSerializatorTest.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package com.baeldung;
-
-import com.github.jsonldjava.core.JsonLdError;
-import com.github.jsonldjava.core.JsonLdOptions;
-import com.github.jsonldjava.core.JsonLdProcessor;
-import com.github.jsonldjava.utils.JsonUtils;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.junit.Assert.assertNotEquals;
-
-@RunWith(SpringJUnit4ClassRunner.class)
-@SpringBootTest
-public class JsonLdSerializatorTest {
-
- @Test
- public void whenInserting_andCount_thenWeDontGetZero() throws JsonLdError {
- String inputStream = "{name:}";
- Object jsonObject = JsonUtils.fromInputStream(inputStream);
-
- Map context = new HashMap();
- JsonLdOptions options = new JsonLdOptions();
- Object compact = JsonLdProcessor.compact(jsonObject, context, options);
-
- assertNotEquals(0, 0);
- }
-
-}
diff --git a/libraries/README.md b/libraries/README.md
index fbf2b4e876..5e4ef6a898 100644
--- a/libraries/README.md
+++ b/libraries/README.md
@@ -60,6 +60,9 @@
- [Guide to google-http-client](http://www.baeldung.com/google-http-client)
- [Interact with Google Sheets from Java](http://www.baeldung.com/google-sheets-java-client)
- [Programatically Create, Configure, and Run a Tomcat Server] (http://www.baeldung.com/tomcat-programmatic-setup)
+- [A Docker Guide for Java](http://www.baeldung.com/docker-java-api)
+- [Exceptions in Netty](http://www.baeldung.com/netty-exception-handling)
+- [Creating and Configuring Jetty 9 Server in Java](http://www.baeldung.com/jetty-java-programmatic)
diff --git a/libraries/helloWorld.docx b/libraries/helloWorld.docx
index 09e71a4d4e..12eba0a6c8 100644
Binary files a/libraries/helloWorld.docx and b/libraries/helloWorld.docx differ
diff --git a/libraries/log4j.properties b/libraries/log4j.properties
index e69de29bb2..2173c5d96f 100644
--- a/libraries/log4j.properties
+++ b/libraries/log4j.properties
@@ -0,0 +1 @@
+log4j.rootLogger=INFO, stdout
diff --git a/libraries/pom.xml b/libraries/pom.xml
index 64cc9c6a84..e9bfecf527 100644
--- a/libraries/pom.xml
+++ b/libraries/pom.xml
@@ -1,122 +1,17 @@
-
+
+ 4.0.0
+ libraries
+ libraries
+
parent-modules
com.baeldung
1.0.0-SNAPSHOT
- 4.0.0
- libraries
- libraries
-
-
-
- org.apache.maven.plugins
- maven-dependency-plugin
-
-
- org.apache.felix
- maven-bundle-plugin
- 3.3.0
- maven-plugin
-
-
- true
-
-
- maven-failsafe-plugin
- 2.20
-
-
- chromedriver
-
-
-
-
- net.serenity-bdd.maven.plugins
- serenity-maven-plugin
- ${serenity.plugin.version}
-
-
- serenity-reports
- post-integration-test
-
- aggregate
-
-
-
-
-
-
- org.datanucleus
- datanucleus-maven-plugin
- 5.0.2
-
- JDO
- ${basedir}/datanucleus.properties
- ${basedir}/log4j.properties
- true
- false
-
-
-
-
- process-classes
-
- enhance
-
-
-
-
-
-
- org.apache.maven.plugins
- maven-jar-plugin
- 3.0.2
-
-
- **/log4j.properties
-
-
-
- com.baeldung.neuroph.NeurophXOR
-
-
-
-
-
- org.apache.maven.plugins
- maven-surefire-plugin
- 2.18.1
-
-
- test
- test
-
- test
-
-
-
- test/java/com/baeldung/neuroph/XORTest.java
-
-
-
-
-
-
-
- maven-compiler-plugin
- 3.7.0
-
- 1.8
- 1.8
-
-
-
-
+
-
+
org.asynchttpclient
async-http-client
@@ -200,11 +95,11 @@
jetty-servlet
${jetty.version}
-
- org.eclipse.jetty
- jetty-webapp
- ${jetty.version}
-
+
+ org.eclipse.jetty
+ jetty-webapp
+ ${jetty.version}
+
rome
rome
@@ -640,14 +535,14 @@
${googleclient.version}
- com.google.http-client
- google-http-client-jackson2
- ${googleclient.version}
+ com.google.http-client
+ google-http-client-jackson2
+ ${googleclient.version}
- com.google.http-client
- google-http-client-gson
- ${googleclient.version}
+ com.google.http-client
+ google-http-client-gson
+ ${googleclient.version}
org.infinispan
@@ -655,7 +550,7 @@
${infinispan.version}
-
+
com.github.docker-java
docker-java
@@ -680,23 +575,23 @@
jersey-client
1.19.4
-
+
- com.google.api-client
- google-api-client
- ${google-api.version}
+ com.google.api-client
+ google-api-client
+ ${google-api.version}
- com.google.oauth-client
- google-oauth-client-jetty
- ${google-api.version}
+ com.google.oauth-client
+ google-oauth-client-jetty
+ ${google-api.version}
- com.google.apis
- google-api-services-sheets
- ${google-sheets.version}
+ com.google.apis
+ google-api-services-sheets
+ ${google-sheets.version}
org.apache.kafka
@@ -732,6 +627,11 @@
org.milyn
milyn-smooks-all
${smooks.version}
+
+
+ com.mashape.unirest
+ unirest-java
+ ${unirest.version}
@@ -753,6 +653,108 @@
https://repository.apache.org/content/groups/staging
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-dependency-plugin
+
+
+ org.apache.felix
+ maven-bundle-plugin
+ 3.3.0
+ maven-plugin
+
+
+ true
+
+
+ maven-failsafe-plugin
+ 2.20
+
+
+ chromedriver
+
+
+
+
+ net.serenity-bdd.maven.plugins
+ serenity-maven-plugin
+ ${serenity.plugin.version}
+
+
+ serenity-reports
+ post-integration-test
+
+ aggregate
+
+
+
+
+
+
+ org.datanucleus
+ datanucleus-maven-plugin
+ 5.0.2
+
+ JDO
+ ${basedir}/datanucleus.properties
+ ${basedir}/log4j.properties
+ true
+ false
+
+
+
+
+ process-classes
+
+ enhance
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-jar-plugin
+ 3.0.2
+
+
+ **/log4j.properties
+
+
+
+ com.baeldung.neuroph.NeurophXOR
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 2.18.1
+
+
+ **/*IntegrationTest.java
+ **/*LiveTest.java
+
+
+
+
+
+
+ maven-compiler-plugin
+ 3.7.0
+
+ 1.8
+ 1.8
+
+
+
+
+
1.23.0
0.1.0
@@ -817,5 +819,7 @@
8.5.24
2.2.0
9.1.5.Final
+ 1.4.9
+
diff --git a/libraries/src/main/java/com/baeldung/bouncycastle/BouncyCastleCrypto.java b/libraries/src/main/java/com/baeldung/bouncycastle/BouncyCastleCrypto.java
index 5d8a7a6643..d7040407db 100644
--- a/libraries/src/main/java/com/baeldung/bouncycastle/BouncyCastleCrypto.java
+++ b/libraries/src/main/java/com/baeldung/bouncycastle/BouncyCastleCrypto.java
@@ -42,8 +42,7 @@ import org.bouncycastle.util.Store;
public class BouncyCastleCrypto {
- public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey)
- throws CertificateEncodingException, OperatorCreationException, CMSException, IOException {
+ public static byte[] signData(byte[] data, final X509Certificate signingCertificate, final PrivateKey signingKey) throws CertificateEncodingException, OperatorCreationException, CMSException, IOException {
byte[] signedMessage = null;
List certList = new ArrayList();
CMSTypedData cmsData = new CMSProcessableByteArray(data);
@@ -51,17 +50,14 @@ public class BouncyCastleCrypto {
Store certs = new JcaCertStore(certList);
CMSSignedDataGenerator cmsGenerator = new CMSSignedDataGenerator();
ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(signingKey);
- cmsGenerator.addSignerInfoGenerator(
- new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build())
- .build(contentSigner, signingCertificate));
+ cmsGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(contentSigner, signingCertificate));
cmsGenerator.addCertificates(certs);
CMSSignedData cms = cmsGenerator.generate(cmsData, true);
signedMessage = cms.getEncoded();
return signedMessage;
}
- public static boolean verifSignData(final byte[] signedData)
- throws CMSException, IOException, OperatorCreationException, CertificateException {
+ public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException {
ByteArrayInputStream bIn = new ByteArrayInputStream(signedData);
ASN1InputStream aIn = new ASN1InputStream(bIn);
CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));
@@ -81,16 +77,14 @@ public class BouncyCastleCrypto {
return true;
}
- public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate)
- throws CertificateEncodingException, CMSException, IOException {
+ public static byte[] encryptData(final byte[] data, X509Certificate encryptionCertificate) throws CertificateEncodingException, CMSException, IOException {
byte[] encryptedData = null;
if (null != data && null != encryptionCertificate) {
CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
JceKeyTransRecipientInfoGenerator jceKey = new JceKeyTransRecipientInfoGenerator(encryptionCertificate);
cmsEnvelopedDataGenerator.addRecipientInfoGenerator(jceKey);
CMSTypedData msg = new CMSProcessableByteArray(data);
- OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC")
- .build();
+ OutputEncryptor encryptor = new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC).setProvider("BC").build();
CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(msg, encryptor);
encryptedData = cmsEnvelopedData.getEncoded();
}
diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java
index d0362a6c92..849e363c4b 100644
--- a/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java
+++ b/libraries/src/main/java/com/baeldung/bytebuddy/Bar.java
@@ -5,12 +5,17 @@ import net.bytebuddy.implementation.bind.annotation.BindingPriority;
public class Bar {
@BindingPriority(3)
- public static String sayHelloBar() { return "Holla in Bar!"; }
+ public static String sayHelloBar() {
+ return "Holla in Bar!";
+ }
@BindingPriority(2)
- public static String sayBar() { return "bar"; }
-
- public String bar() { return Bar.class.getSimpleName() + " - Bar"; }
+ public static String sayBar() {
+ return "bar";
+ }
+ public String bar() {
+ return Bar.class.getSimpleName() + " - Bar";
+ }
}
diff --git a/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java
index 4be06785b1..9410fc6a13 100644
--- a/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java
+++ b/libraries/src/main/java/com/baeldung/bytebuddy/Foo.java
@@ -2,6 +2,8 @@ package com.baeldung.bytebuddy;
public class Foo {
- public String sayHelloFoo() { return "Hello in Foo!"; }
+ public String sayHelloFoo() {
+ return "Hello in Foo!";
+ }
}
diff --git a/libraries/src/main/java/com/baeldung/caffeine/DataObject.java b/libraries/src/main/java/com/baeldung/caffeine/DataObject.java
index a90b3e9f21..65c4c6919f 100644
--- a/libraries/src/main/java/com/baeldung/caffeine/DataObject.java
+++ b/libraries/src/main/java/com/baeldung/caffeine/DataObject.java
@@ -19,9 +19,7 @@ final class DataObject {
@Override
public String toString() {
- return "DataObject{" +
- "data='" + data + '\'' +
- '}';
+ return "DataObject{" + "data='" + data + '\'' + '}';
}
public static DataObject get(String data) {
diff --git a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java
index f6bd25c0fe..354291ebd7 100644
--- a/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java
+++ b/libraries/src/main/java/com/baeldung/chronicle/queue/ChronicleQueue.java
@@ -7,9 +7,7 @@ import net.openhft.chronicle.ExcerptAppender;
public class ChronicleQueue {
- static void writeToQueue(
- Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue)
- throws IOException {
+ static void writeToQueue(Chronicle chronicle, String stringValue, int intValue, long longValue, double doubleValue) throws IOException {
ExcerptAppender appender = chronicle.createAppender();
appender.startExcerpt();
appender.writeUTF(stringValue);
diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java
index 4a0b59404d..b88ee6624d 100644
--- a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java
+++ b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseEntity.java
@@ -24,7 +24,7 @@ public class CourseEntity {
public void setCodes(List codes) {
this.codes = codes;
}
-
+
public void setStudent(String id, Student student) {
students.put(id, student);
}
diff --git a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java
index 1f566a782a..538fa3accb 100644
--- a/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java
+++ b/libraries/src/main/java/com/baeldung/commons/beanutils/CourseService.java
@@ -8,33 +8,27 @@ import org.apache.commons.beanutils.PropertyUtils;
public class CourseService {
- public static void setValues(Course course, String name, List codes)
- throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
+ public static void setValues(Course course, String name, List codes) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the simple properties
PropertyUtils.setSimpleProperty(course, "name", name);
PropertyUtils.setSimpleProperty(course, "codes", codes);
}
-
- public static void setIndexedValue(Course course, int codeIndex, String code)
- throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
+
+ public static void setIndexedValue(Course course, int codeIndex, String code) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the indexed properties
PropertyUtils.setIndexedProperty(course, "codes[" + codeIndex + "]", code);
}
- public static void setMappedValue(Course course, String enrollId, Student student)
- throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
+ public static void setMappedValue(Course course, String enrollId, Student student) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
// Setting the mapped properties
PropertyUtils.setMappedProperty(course, "enrolledStudent(" + enrollId + ")", student);
}
-
- public static String getNestedValue(Course course, String enrollId, String nestedPropertyName)
- throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
- return (String) PropertyUtils.getNestedProperty(
- course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName);
+
+ public static String getNestedValue(Course course, String enrollId, String nestedPropertyName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
+ return (String) PropertyUtils.getNestedProperty(course, "enrolledStudent(" + enrollId + ")." + nestedPropertyName);
}
-
- public static void copyProperties(Course course, CourseEntity courseEntity)
- throws IllegalAccessException, InvocationTargetException {
+
+ public static void copyProperties(Course course, CourseEntity courseEntity) throws IllegalAccessException, InvocationTargetException {
BeanUtils.copyProperties(course, courseEntity);
}
}
diff --git a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java
index 973e2d498e..0acb222aa1 100644
--- a/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java
+++ b/libraries/src/main/java/com/baeldung/commons/chain/AuditFilter.java
@@ -7,7 +7,7 @@ public class AuditFilter implements Filter {
@Override
public boolean postprocess(Context context, Exception exception) {
- // Send notification to customer & bank.
+ // Send notification to customer & bank.
return false;
}
diff --git a/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java b/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java
index e22f13861e..1c6a8dc4f1 100644
--- a/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java
+++ b/libraries/src/main/java/com/baeldung/commons/collectionutil/Customer.java
@@ -73,7 +73,7 @@ public class Customer implements Comparable {
this.name = name;
this.phone = phone;
}
-
+
public Customer(String name) {
super();
this.name = name;
diff --git a/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java b/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java
index c82798d52d..7f24230c43 100644
--- a/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java
+++ b/libraries/src/main/java/com/baeldung/commons/dbutils/Email.java
@@ -20,7 +20,6 @@ public class Email {
public void setEmployeeId(Integer employeeId) {
this.employeeId = employeeId;
}
-
public String getAddress() {
return address;
diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java
index 35cae7426d..74e775383b 100644
--- a/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java
+++ b/libraries/src/main/java/com/baeldung/commons/lang3/BuilderMethods.java
@@ -26,9 +26,7 @@ public class BuilderMethods {
@Override
public int hashCode() {
- return new HashCodeBuilder().append(this.intValue)
- .append(this.strSample)
- .toHashCode();
+ return new HashCodeBuilder().append(this.intValue).append(this.strSample).toHashCode();
}
@Override
@@ -41,16 +39,12 @@ public class BuilderMethods {
}
final BuilderMethods otherObject = (BuilderMethods) obj;
- return new EqualsBuilder().append(this.intValue, otherObject.intValue)
- .append(this.strSample, otherObject.strSample)
- .isEquals();
+ return new EqualsBuilder().append(this.intValue, otherObject.intValue).append(this.strSample, otherObject.strSample).isEquals();
}
@Override
public String toString() {
- return new ToStringBuilder(this).append("INTVALUE", this.intValue)
- .append("STRINGVALUE", this.strSample)
- .toString();
+ return new ToStringBuilder(this).append("INTVALUE", this.intValue).append("STRINGVALUE", this.strSample).toString();
}
public static void main(final String[] arguments) {
@@ -58,21 +52,21 @@ public class BuilderMethods {
System.out.println(simple1.getName());
System.out.println(simple1.hashCode());
System.out.println(simple1.toString());
-
+
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
-
+
try {
sampleLazyInitializer.get();
} catch (ConcurrentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
-
+
SampleBackgroundInitializer sampleBackgroundInitializer = new SampleBackgroundInitializer();
sampleBackgroundInitializer.start();
-
+
// Proceed with other tasks instead of waiting for the SampleBackgroundInitializer task to finish.
-
+
try {
Object result = sampleBackgroundInitializer.get();
} catch (ConcurrentException e) {
@@ -81,13 +75,13 @@ public class BuilderMethods {
}
}
-class SampleBackgroundInitializer extends BackgroundInitializer{
+class SampleBackgroundInitializer extends BackgroundInitializer {
@Override
protected String initialize() throws Exception {
return null;
}
-
+
// Any complex task that takes some time
-
+
}
diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java b/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java
index 56a49d2659..52c6e9c9aa 100644
--- a/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java
+++ b/libraries/src/main/java/com/baeldung/commons/lang3/SampleLazyInitializer.java
@@ -3,7 +3,7 @@ package com.baeldung.commons.lang3;
import org.apache.commons.lang3.concurrent.LazyInitializer;
public class SampleLazyInitializer extends LazyInitializer {
-
+
@Override
protected SampleObject initialize() {
return new SampleObject();
diff --git a/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java b/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java
index 0e61176732..4595f4c6d0 100644
--- a/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java
+++ b/libraries/src/main/java/com/baeldung/commons/lang3/SampleObject.java
@@ -1,7 +1,7 @@
package com.baeldung.commons.lang3;
public class SampleObject {
-
- //Ignored
+
+ // Ignored
}
diff --git a/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java b/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java
index d9c87b3889..97fbf4adc7 100644
--- a/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java
+++ b/libraries/src/main/java/com/baeldung/docx/Docx4jExample.java
@@ -53,16 +53,12 @@ class Docx4jExample {
File image = new File(imagePath);
byte[] fileContent = Files.readAllBytes(image.toPath());
- BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
- .createImagePart(wordPackage, fileContent);
- Inline inline = imagePart.createImageInline(
- "Baeldung Image", "Alt Text", 1, 2, false);
+ BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wordPackage, fileContent);
+ Inline inline = imagePart.createImageInline("Baeldung Image", "Alt Text", 1, 2, false);
P Imageparagraph = addImageToParagraph(inline);
mainDocumentPart.getContent().add(Imageparagraph);
- int writableWidthTwips = wordPackage.getDocumentModel()
- .getSections().get(0).getPageDimensions()
- .getWritableWidthTwips();
+ int writableWidthTwips = wordPackage.getDocumentModel().getSections().get(0).getPageDimensions().getWritableWidthTwips();
int columnNumber = 3;
Tbl tbl = TblFactory.createTable(3, 3, writableWidthTwips / columnNumber);
List rows = tbl.getContent();
diff --git a/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java b/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java
index 069baeab9f..9d1b011e0e 100644
--- a/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java
+++ b/libraries/src/main/java/com/baeldung/eclipsecollections/ConvertContainerToAnother.java
@@ -2,7 +2,6 @@ package com.baeldung.eclipsecollections;
import java.util.List;
-import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
public class ConvertContainerToAnother {
diff --git a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java
index ebf0fa4d2d..eaa201d1ba 100644
--- a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java
+++ b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaIOMain.java
@@ -7,7 +7,7 @@ import fj.data.IO;
import fj.data.IOFunctions;
public class FunctionalJavaIOMain {
-
+
public static IO printLetters(final String s) {
return () -> {
for (int i = 0; i < s.length(); i++) {
@@ -21,8 +21,7 @@ public class FunctionalJavaIOMain {
F> printLetters = i -> printLetters(i);
- IO lowerCase = IOFunctions
- .stdoutPrintln("What's your first Name ?");
+ IO lowerCase = IOFunctions.stdoutPrintln("What's your first Name ?");
IO input = IOFunctions.stdoutPrint("First Name: ");
@@ -32,14 +31,11 @@ public class FunctionalJavaIOMain {
F toUpperCase = i -> i.toUpperCase();
- F> transformInput = F1Functions
- ., String> o(printLetters).f(toUpperCase);
+ F> transformInput = F1Functions., String> o(printLetters).f(toUpperCase);
- IO readAndPrintResult = IOFunctions.bind(readInput,
- transformInput);
+ IO readAndPrintResult = IOFunctions.bind(readInput, transformInput);
- IO program = IOFunctions.bind(userInput,
- nothing -> readAndPrintResult);
+ IO program = IOFunctions.bind(userInput, nothing -> readAndPrintResult);
IOFunctions.toSafe(program).run();
diff --git a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java
index e4d731454d..c6412f2923 100644
--- a/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java
+++ b/libraries/src/main/java/com/baeldung/fj/FunctionalJavaMain.java
@@ -11,16 +11,16 @@ import fj.function.Integers;
public class FunctionalJavaMain {
public static final F isEven = i -> i % 2 == 0;
-
+
public static void main(String[] args) {
-
+
List fList = List.list(3, 4, 5, 6);
List evenList = fList.map(isEven);
Show.listShow(Show.booleanShow).println(evenList);
-
+
fList = fList.map(i -> i + 1);
Show.listShow(Show.intShow).println(fList);
-
+
Array a = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
Array b = a.filter(Integers.even);
Show.arrayShow(Show.intShow).println(b);
@@ -28,11 +28,11 @@ public class FunctionalJavaMain {
Array array = Array.array("Welcome", "To", "baeldung");
Boolean isExist = array.exists(s -> List.fromString(s).forall(Characters.isLowerCase));
System.out.println(isExist);
-
+
Array intArray = Array.array(17, 44, 67, 2, 22, 80, 1, 27);
int sum = intArray.foldLeft(Integers.add, 0);
System.out.println(sum);
-
+
Option n1 = Option.some(1);
Option n2 = Option.some(2);
diff --git a/libraries/src/main/java/com/baeldung/flink/LineSplitter.java b/libraries/src/main/java/com/baeldung/flink/LineSplitter.java
index 8deeeb01c4..f4e322f1e8 100644
--- a/libraries/src/main/java/com/baeldung/flink/LineSplitter.java
+++ b/libraries/src/main/java/com/baeldung/flink/LineSplitter.java
@@ -13,8 +13,6 @@ public class LineSplitter implements FlatMapFunction> out) {
String[] tokens = value.toLowerCase().split("\\W+");
- Stream.of(tokens)
- .filter(t -> t.length() > 0)
- .forEach(token -> out.collect(new Tuple2<>(token, 1)));
+ Stream.of(tokens).filter(t -> t.length() > 0).forEach(token -> out.collect(new Tuple2<>(token, 1)));
}
}
\ No newline at end of file
diff --git a/libraries/src/main/java/com/baeldung/flink/WordCount.java b/libraries/src/main/java/com/baeldung/flink/WordCount.java
index ab109bdbce..fc5064bafa 100644
--- a/libraries/src/main/java/com/baeldung/flink/WordCount.java
+++ b/libraries/src/main/java/com/baeldung/flink/WordCount.java
@@ -12,9 +12,7 @@ public class WordCount {
public static DataSet> startWordCount(ExecutionEnvironment env, List lines) throws Exception {
DataSet text = env.fromCollection(lines);
- return text.flatMap(new LineSplitter())
- .groupBy(0)
- .aggregate(Aggregations.SUM, 1);
+ return text.flatMap(new LineSplitter()).groupBy(0).aggregate(Aggregations.SUM, 1);
}
}
\ No newline at end of file
diff --git a/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java b/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java
index 650a1d084c..641fae42dd 100644
--- a/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java
+++ b/libraries/src/main/java/com/baeldung/google/sheets/GoogleAuthorizeUtil.java
@@ -20,21 +20,13 @@ import com.google.api.services.sheets.v4.SheetsScopes;
public class GoogleAuthorizeUtil {
public static Credential authorize() throws IOException, GeneralSecurityException {
InputStream in = GoogleAuthorizeUtil.class.getResourceAsStream("/google-sheets-client-secret.json");
- GoogleClientSecrets clientSecrets = GoogleClientSecrets
- .load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
+ GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));
List scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);
- GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow
- .Builder(GoogleNetHttpTransport.newTrustedTransport(),
- JacksonFactory.getDefaultInstance(),
- clientSecrets,
- scopes)
- .setDataStoreFactory(new MemoryDataStoreFactory())
- .setAccessType("offline")
- .build();
- Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
- .authorize("user");
+ GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes).setDataStoreFactory(new MemoryDataStoreFactory())
+ .setAccessType("offline").build();
+ Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
return credential;
}
diff --git a/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java b/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java
index bbce96f389..8a78d50551 100644
--- a/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java
+++ b/libraries/src/main/java/com/baeldung/google/sheets/SheetsServiceUtil.java
@@ -14,10 +14,7 @@ public class SheetsServiceUtil {
public static Sheets getSheetsService() throws IOException, GeneralSecurityException {
Credential credential = GoogleAuthorizeUtil.authorize();
- return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(),
- JacksonFactory.getDefaultInstance(), credential)
- .setApplicationName(APPLICATION_NAME)
- .build();
+ return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName(APPLICATION_NAME).build();
}
}
diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java
index 0618a7294d..fce47c6ada 100644
--- a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java
+++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubExample.java
@@ -4,9 +4,7 @@ import com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
-import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
-import com.google.api.client.http.apache.ApacheHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
@@ -21,30 +19,23 @@ import java.util.concurrent.Future;
public class GitHubExample {
static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
- //static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();
+ // static final HttpTransport HTTP_TRANSPORT = new ApacheHttpTransport();
static final JsonFactory JSON_FACTORY = new JacksonFactory();
- //static final JsonFactory JSON_FACTORY = new GsonFactory();
+ // static final JsonFactory JSON_FACTORY = new GsonFactory();
private static void run() throws Exception {
- HttpRequestFactory requestFactory
- = HTTP_TRANSPORT.createRequestFactory(
- (HttpRequest request) -> {
- request.setParser(new JsonObjectParser(JSON_FACTORY));
- });
+ HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory((HttpRequest request) -> {
+ request.setParser(new JsonObjectParser(JSON_FACTORY));
+ });
GitHubUrl url = new GitHubUrl("https://api.github.com/users");
url.per_page = 10;
url.page = 1;
HttpRequest request = requestFactory.buildGetRequest(url);
- ExponentialBackOff backoff = new ExponentialBackOff.Builder()
- .setInitialIntervalMillis(500)
- .setMaxElapsedTimeMillis(900000)
- .setMaxIntervalMillis(6000)
- .setMultiplier(1.5)
- .setRandomizationFactor(0.5)
- .build();
+ ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build();
request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
- Type type = new TypeToken>() {}.getType();
- List users = (List)request.execute().parseAs(type);
+ Type type = new TypeToken>() {
+ }.getType();
+ List users = (List) request.execute().parseAs(type);
System.out.println(users);
url.appendRawPath("/eugenp");
request = requestFactory.buildGetRequest(url);
diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java
index c44de1e145..ea1b83e9fb 100644
--- a/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java
+++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/GitHubUrl.java
@@ -3,16 +3,16 @@ package com.baeldung.googlehttpclientguide;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.util.Key;
-public class GitHubUrl extends GenericUrl{
+public class GitHubUrl extends GenericUrl {
public GitHubUrl(String encodedUrl) {
super(encodedUrl);
- }
-
+ }
+
@Key
public int per_page;
-
+
@Key
public int page;
-
+
}
diff --git a/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java b/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java
index bf4ee96b25..88361e158e 100644
--- a/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java
+++ b/libraries/src/main/java/com/baeldung/googlehttpclientguide/User.java
@@ -16,7 +16,7 @@ public class User extends GenericJson {
private String blog;
@Key
private String email;
-
+
@Key("subscriptions_url")
private String subscriptionsUrl;
@@ -71,7 +71,6 @@ public class User extends GenericJson {
@Override
public String toString() {
return "User{" + "login=" + login + ", id=" + id + ", url=" + url + ", company=" + company + ", blog=" + blog + ", email=" + email + '}';
- }
-
-
+ }
+
}
diff --git a/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java b/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java
index ff4bc939aa..e8d3b4ff96 100644
--- a/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java
+++ b/libraries/src/main/java/com/baeldung/hikaricp/DataSource.java
@@ -1,9 +1,7 @@
package com.baeldung.hikaricp;
-import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
-import java.util.Properties;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
@@ -14,15 +12,15 @@ public class DataSource {
private static HikariDataSource ds;
static {
-// config = new HikariConfig("datasource.properties");
-
-// Properties props = new Properties();
-// props.setProperty("dataSourceClassName", "org.h2.Driver");
-// props.setProperty("dataSource.user", "");
-// props.setProperty("dataSource.password", "");
-// props.put("dataSource.logWriter", new PrintWriter(System.out));
-// config = new HikariConfig(props);
-
+ // config = new HikariConfig("datasource.properties");
+
+ // Properties props = new Properties();
+ // props.setProperty("dataSourceClassName", "org.h2.Driver");
+ // props.setProperty("dataSource.user", "");
+ // props.setProperty("dataSource.password", "");
+ // props.put("dataSource.logWriter", new PrintWriter(System.out));
+ // config = new HikariConfig(props);
+
config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
config.setUsername("");
config.setPassword("");
@@ -30,13 +28,14 @@ public class DataSource {
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
ds = new HikariDataSource(config);
-
-// ds.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
-// ds.setUsername("");
-// ds.setPassword("");
+
+ // ds.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=runscript from 'classpath:/db.sql'");
+ // ds.setUsername("");
+ // ds.setPassword("");
}
- private DataSource() {}
+ private DataSource() {
+ }
public static Connection getConnection() throws SQLException {
return ds.getConnection();
diff --git a/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java b/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java
index af36ab7508..57d124fd5d 100644
--- a/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java
+++ b/libraries/src/main/java/com/baeldung/hikaricp/HikariCPDemo.java
@@ -12,9 +12,7 @@ public class HikariCPDemo {
public static List fetchData() {
final String SQL_QUERY = "select * from emp";
List employees = null;
- try (Connection con = DataSource.getConnection();
- PreparedStatement pst = con.prepareStatement(SQL_QUERY);
- ResultSet rs = pst.executeQuery();) {
+ try (Connection con = DataSource.getConnection(); PreparedStatement pst = con.prepareStatement(SQL_QUERY); ResultSet rs = pst.executeQuery();) {
employees = new ArrayList();
Employee employee;
while (rs.next()) {
@@ -38,5 +36,5 @@ public class HikariCPDemo {
public static void main(String[] args) {
fetchData();
}
-
+
}
diff --git a/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java b/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java
index 58929c0111..eda511d7a7 100644
--- a/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java
+++ b/libraries/src/main/java/com/baeldung/infinispan/CacheConfiguration.java
@@ -43,8 +43,7 @@ public class CacheConfiguration {
return this.buildCache(PASSIVATING_HELLO_WORLD_CACHE, cacheManager, listener, passivatingConfiguration());
}
- private Cache buildCache(String cacheName, DefaultCacheManager cacheManager,
- CacheListener listener, Configuration configuration) {
+ private Cache buildCache(String cacheName, DefaultCacheManager cacheManager, CacheListener listener, Configuration configuration) {
cacheManager.defineConfiguration(cacheName, configuration);
Cache cache = cacheManager.getCache(cacheName);
@@ -53,32 +52,19 @@ public class CacheConfiguration {
}
private Configuration expiringConfiguration() {
- return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS)
- .build();
+ return new ConfigurationBuilder().expiration().lifespan(1, TimeUnit.SECONDS).build();
}
private Configuration evictingConfiguration() {
- return new ConfigurationBuilder()
- .memory().evictionType(EvictionType.COUNT).size(1)
- .build();
+ return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).build();
}
private Configuration passivatingConfiguration() {
- return new ConfigurationBuilder()
- .memory().evictionType(EvictionType.COUNT).size(1)
- .persistence()
- .passivation(true)
- .addSingleFileStore()
- .purgeOnStartup(true)
- .location(System.getProperty("java.io.tmpdir"))
- .build();
+ return new ConfigurationBuilder().memory().evictionType(EvictionType.COUNT).size(1).persistence().passivation(true).addSingleFileStore().purgeOnStartup(true).location(System.getProperty("java.io.tmpdir")).build();
}
private Configuration transactionalConfiguration() {
- return new ConfigurationBuilder()
- .transaction().transactionMode(TransactionMode.TRANSACTIONAL)
- .lockingMode(LockingMode.PESSIMISTIC)
- .build();
+ return new ConfigurationBuilder().transaction().transactionMode(TransactionMode.TRANSACTIONAL).lockingMode(LockingMode.PESSIMISTIC).build();
}
}
diff --git a/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java b/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java
index 3ecefcc21a..de30cd5c8e 100644
--- a/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java
+++ b/libraries/src/main/java/com/baeldung/infinispan/service/HelloWorldService.java
@@ -15,11 +15,8 @@ public class HelloWorldService {
private final Cache evictingHelloWorldCache;
private final Cache passivatingHelloWorldCache;
- public HelloWorldService(HelloWorldRepository repository, CacheListener listener,
- Cache simpleHelloWorldCache,
- Cache expiringHelloWorldCache,
- Cache evictingHelloWorldCache,
- Cache passivatingHelloWorldCache) {
+ public HelloWorldService(HelloWorldRepository repository, CacheListener listener, Cache simpleHelloWorldCache, Cache expiringHelloWorldCache, Cache evictingHelloWorldCache,
+ Cache passivatingHelloWorldCache) {
this.repository = repository;
@@ -66,7 +63,7 @@ public class HelloWorldService {
public String findEvictingHelloWorld(String key) {
String value = evictingHelloWorldCache.get(key);
- if(value == null) {
+ if (value == null) {
value = repository.getHelloWorld();
evictingHelloWorldCache.put(key, value);
}
diff --git a/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java b/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java
index b0dbf5475f..26862b8d65 100644
--- a/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java
+++ b/libraries/src/main/java/com/baeldung/infinispan/service/TransactionalService.java
@@ -28,8 +28,7 @@ public class TransactionalService {
watch.start();
transactionalCache.put(KEY, howManyVisits);
watch.stop();
- System.out.println("I was able to set HowManyVisits to " + howManyVisits +
- " after waiting " + watch.getTotalTimeSeconds() + " seconds");
+ System.out.println("I was able to set HowManyVisits to " + howManyVisits + " after waiting " + watch.getTotalTimeSeconds() + " seconds");
tm.commit();
return howManyVisits;
@@ -44,8 +43,7 @@ public class TransactionalService {
TransactionManager tm = transactionalCache.getAdvancedCache().getTransactionManager();
tm.begin();
transactionalCache.put(KEY, 1000);
- System.out.println("HowManyVisits should now be 1000, " +
- "but we are holding the transaction");
+ System.out.println("HowManyVisits should now be 1000, " + "but we are holding the transaction");
Thread.sleep(1000L);
tm.rollback();
System.out.println("The slow batch suffered a rollback");
diff --git a/libraries/src/main/java/com/baeldung/javasisst/Point.java b/libraries/src/main/java/com/baeldung/javasisst/Point.java
index 7e5c1cedd5..7f10e8c371 100644
--- a/libraries/src/main/java/com/baeldung/javasisst/Point.java
+++ b/libraries/src/main/java/com/baeldung/javasisst/Point.java
@@ -1,6 +1,5 @@
package com.baeldung.javasisst;
-
public class Point {
public int x = 0;
public int y = 0;
diff --git a/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java b/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java
index fb24d4b85d..780604738e 100644
--- a/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java
+++ b/libraries/src/main/java/com/baeldung/javasisst/ThreeDimensionalPoint.java
@@ -1,6 +1,5 @@
package com.baeldung.javasisst;
-
public class ThreeDimensionalPoint {
public int x = 0;
public int y = 0;
diff --git a/libraries/src/main/java/com/baeldung/javers/Address.java b/libraries/src/main/java/com/baeldung/javers/Address.java
index 14f5907ef6..9b0c119046 100644
--- a/libraries/src/main/java/com/baeldung/javers/Address.java
+++ b/libraries/src/main/java/com/baeldung/javers/Address.java
@@ -1,6 +1,5 @@
package com.baeldung.javers;
-
public class Address {
private String country;
diff --git a/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java b/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java
index 0b4e33fcb5..16be083d83 100644
--- a/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java
+++ b/libraries/src/main/java/com/baeldung/javers/PersonWithAddress.java
@@ -1,6 +1,5 @@
package com.baeldung.javers;
-
import java.util.List;
public class PersonWithAddress {
diff --git a/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java
index ec2c52d3b5..8da601b0cf 100644
--- a/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java
+++ b/libraries/src/main/java/com/baeldung/jdeffered/FilterDemo.java
@@ -7,9 +7,9 @@ import org.jdeferred.impl.DeferredObject;
class FilterDemo {
private static String modifiedMsg;
-
+
static String filter(String msg) {
-
+
Deferred d = new DeferredObject<>();
Promise p = d.promise();
Promise filtered = p.then((result) -> {
diff --git a/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java
index 95250cff76..94fe0b70a6 100644
--- a/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java
+++ b/libraries/src/main/java/com/baeldung/jdeffered/PipeDemo.java
@@ -19,14 +19,11 @@ class PipeDemo {
p.then((DonePipe) result -> {
if (result < 90) {
- return new DeferredObject()
- .resolve(result);
+ return new DeferredObject().resolve(result);
} else {
- return new DeferredObject()
- .reject(new Exception("Unacceptable value"));
+ return new DeferredObject().reject(new Exception("Unacceptable value"));
}
- }).done(r -> status = Result.SUCCESS)
- .fail(r -> status = Result.FAILURE);
+ }).done(r -> status = Result.SUCCESS).fail(r -> status = Result.FAILURE);
d.resolve(num);
diff --git a/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java
index 2a9f83dc35..4efb1ad997 100644
--- a/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java
+++ b/libraries/src/main/java/com/baeldung/jdeffered/PromiseDemo.java
@@ -11,10 +11,7 @@ class PromiseDemo {
Deferred deferred = new DeferredObject<>();
Promise promise = deferred.promise();
- promise.done(result -> System.out.println("Job done"))
- .fail(rejection -> System.out.println("Job fail"))
- .progress(progress -> System.out.println("Job is in progress"))
- .always((state, result, rejection) -> System.out.println("Job execution started"));
+ promise.done(result -> System.out.println("Job done")).fail(rejection -> System.out.println("Job fail")).progress(progress -> System.out.println("Job is in progress")).always((state, result, rejection) -> System.out.println("Job execution started"));
deferred.resolve(jobName);
// deferred.notify("");
diff --git a/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java
index 22fd51ed92..c48b916b4b 100644
--- a/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java
+++ b/libraries/src/main/java/com/baeldung/jdeffered/ThreadSafeDemo.java
@@ -12,9 +12,7 @@ public class ThreadSafeDemo {
DeferredManager dm = new DefaultDeferredManager();
Deferred deferred = new DeferredObject<>();
Promise p1 = deferred.promise();
- Promise p = dm.when(p1)
- .done(r -> System.out.println("done"))
- .fail(r -> System.out.println("fail"));
+ Promise p = dm.when(p1).done(r -> System.out.println("done")).fail(r -> System.out.println("fail"));
synchronized (p) {
while (p.isPending()) {
diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java
index 2abe9bc10f..68a113d6a2 100644
--- a/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java
+++ b/libraries/src/main/java/com/baeldung/jdeffered/manager/DeferredManagerWithExecutorDemo.java
@@ -16,9 +16,7 @@ class DeferredManagerWithExecutorDemo {
Deferred deferred = new DeferredObject<>();
DeferredManager dm = new DefaultDeferredManager(executor);
Promise p1 = deferred.promise(), p2 = deferred.promise(), p3 = deferred.promise();
- dm.when(p1, p2, p3)
- .done(r -> System.out.println("done"))
- .fail(r -> System.out.println("fail"));
+ dm.when(p1, p2, p3).done(r -> System.out.println("done")).fail(r -> System.out.println("fail"));
deferred.resolve("done");
}
}
diff --git a/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java b/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java
index dc2e82495f..e1ffa3b6bc 100644
--- a/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java
+++ b/libraries/src/main/java/com/baeldung/jdeffered/manager/SimpleDeferredManagerDemo.java
@@ -7,8 +7,6 @@ class SimpleDeferredManagerDemo {
public static void initiate() {
DeferredManager dm = new DefaultDeferredManager();
- dm.when(() -> 1)
- .done(r -> System.out.println("done"))
- .fail(Throwable::printStackTrace);
+ dm.when(() -> 1).done(r -> System.out.println("done")).fail(Throwable::printStackTrace);
}
}
diff --git a/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java b/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java
index 387c8c4e00..bd459f963c 100644
--- a/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java
+++ b/libraries/src/main/java/com/baeldung/jdo/GuideToJDO.java
@@ -42,8 +42,8 @@ public class GuideToJDO {
listXMLProducts();
}
- public void CreateH2Properties(){
-
+ public void CreateH2Properties() {
+
pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addClassName("com.baeldung.jdo.Product");
pumd.setExcludeUnlistedClasses();
@@ -51,18 +51,18 @@ public class GuideToJDO {
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:h2:mem:mypersistence");
pumd.addProperty("javax.jdo.option.ConnectionUserName", "sa");
pumd.addProperty("javax.jdo.option.ConnectionPassword", "");
- pumd.addProperty("datanucleus.autoCreateSchema", "true");
-
+ pumd.addProperty("datanucleus.autoCreateSchema", "true");
+
}
-
- public void CreateXMLProperties(){
+
+ public void CreateXMLProperties() {
pumdXML = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumdXML.addClassName("com.baeldung.jdo.ProductXML");
pumdXML.setExcludeUnlistedClasses();
pumdXML.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myPersistence.xml");
- pumdXML.addProperty("datanucleus.autoCreateSchema", "true");
+ pumdXML.addProperty("datanucleus.autoCreateSchema", "true");
}
-
+
public void CreateProducts() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager();
@@ -91,7 +91,7 @@ public class GuideToJDO {
}
@SuppressWarnings("rawtypes")
- public void UpdateProducts(){
+ public void UpdateProducts() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
@@ -105,13 +105,13 @@ public class GuideToJDO {
} finally {
if (tx.isActive()) {
tx.rollback();
- }
+ }
pm.close();
}
}
-
+
@SuppressWarnings("rawtypes")
- public void DeleteProducts(){
+ public void DeleteProducts() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
@@ -125,11 +125,11 @@ public class GuideToJDO {
} finally {
if (tx.isActive()) {
tx.rollback();
- }
+ }
pm.close();
}
}
-
+
@SuppressWarnings({ "rawtypes", "unchecked" })
public void ListProducts() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
@@ -155,9 +155,9 @@ public class GuideToJDO {
pm.close();
}
}
-
+
@SuppressWarnings({ "rawtypes", "unchecked" })
- public void QueryJDOQL (){
+ public void QueryJDOQL() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
@@ -177,7 +177,7 @@ public class GuideToJDO {
LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
}
LOGGER.log(Level.INFO, "--------------------------------------------------------------");
-
+
tx.commit();
} finally {
if (tx.isActive()) {
@@ -187,28 +187,28 @@ public class GuideToJDO {
pm.close();
}
}
-
+
@SuppressWarnings({ "rawtypes", "unchecked" })
- public void QuerySQL (){
+ public void QuerySQL() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try {
tx.begin();
- //SQL :
+ // SQL :
LOGGER.log(Level.INFO, "SQL --------------------------------------------------------------");
Query query = pm.newQuery("javax.jdo.query.SQL", "SELECT * FROM PRODUCT");
query.setClass(Product.class);
List results = query.executeList();
-
+
Iterator iter = results.iterator();
while (iter.hasNext()) {
Product p = iter.next();
LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
}
LOGGER.log(Level.INFO, "--------------------------------------------------------------");
-
+
tx.commit();
} finally {
if (tx.isActive()) {
@@ -218,27 +218,27 @@ public class GuideToJDO {
pm.close();
}
}
-
+
@SuppressWarnings({ "rawtypes", "unchecked" })
- public void QueryJPQL (){
+ public void QueryJPQL() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumd, null);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try {
tx.begin();
- //JPQL :
+ // JPQL :
LOGGER.log(Level.INFO, "JPQL --------------------------------------------------------------");
- Query q = pm.newQuery("JPQL", "SELECT p FROM "+Product.class.getName()+" p WHERE p.name = 'Laptop'");
- List results = (List)q.execute();
-
+ Query q = pm.newQuery("JPQL", "SELECT p FROM " + Product.class.getName() + " p WHERE p.name = 'Laptop'");
+ List results = (List) q.execute();
+
Iterator iter = results.iterator();
while (iter.hasNext()) {
Product p = iter.next();
LOGGER.log(Level.WARNING, "Product name: {0} - Price: {1}", new Object[] { p.name, p.price });
}
LOGGER.log(Level.INFO, "--------------------------------------------------------------");
-
+
tx.commit();
} finally {
if (tx.isActive()) {
@@ -248,18 +248,18 @@ public class GuideToJDO {
pm.close();
}
}
-
- public void persistXML(){
+
+ public void persistXML() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
try {
tx.begin();
- ProductXML productXML = new ProductXML(0,"Tablet", 80.0);
+ ProductXML productXML = new ProductXML(0, "Tablet", 80.0);
pm.makePersistent(productXML);
- ProductXML productXML2 = new ProductXML(1,"Phone", 20.0);
+ ProductXML productXML2 = new ProductXML(1, "Phone", 20.0);
pm.makePersistent(productXML2);
- ProductXML productXML3 = new ProductXML(2,"Laptop", 200.0);
+ ProductXML productXML3 = new ProductXML(2, "Laptop", 200.0);
pm.makePersistent(productXML3);
tx.commit();
} finally {
@@ -269,9 +269,9 @@ public class GuideToJDO {
pm.close();
}
}
-
+
@SuppressWarnings({ "rawtypes", "unchecked" })
- public void listXMLProducts(){
+ public void listXMLProducts() {
PersistenceManagerFactory pmf = new JDOPersistenceManagerFactory(pumdXML, null);
PersistenceManager pm = pmf.getPersistenceManager();
Transaction tx = pm.currentTransaction();
diff --git a/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java b/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java
index 384dde48d1..235142d16e 100644
--- a/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java
+++ b/libraries/src/main/java/com/baeldung/jdo/query/MyApp.java
@@ -26,19 +26,19 @@ public class MyApp {
}
- public static void createTestData(){
- ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut",5);
- ProductItem item2 = new ProductItem("pro2", "price less than 10","InStock", 8);
- ProductItem item3 = new ProductItem("pro3", "price more than 10","SoldOut", 15);
+ public static void createTestData() {
+ ProductItem item1 = new ProductItem("supportedItem", "price less than 10", "SoldOut", 5);
+ ProductItem item2 = new ProductItem("pro2", "price less than 10", "InStock", 8);
+ ProductItem item3 = new ProductItem("pro3", "price more than 10", "SoldOut", 15);
- if( pm != null ){
+ if (pm != null) {
pm.makePersistent(item1);
pm.makePersistent(item2);
- pm.makePersistent(item3);
+ pm.makePersistent(item3);
}
}
- public static void defineDynamicPersistentUnit(){
+ public static void defineDynamicPersistentUnit() {
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addProperty("javax.jdo.option.ConnectionURL", "jdbc:mysql://localhost:3306/jdo_db");
@@ -51,53 +51,45 @@ public class MyApp {
pm = pmf.getPersistenceManager();
}
- public static void queryUsingJDOQL(){
+ public static void queryUsingJDOQL() {
- Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem "
- + "WHERE price < threshold PARAMETERS double threshold");
- List explicitParamResults = (List)query.execute(10);
+ Query query = pm.newQuery("SELECT FROM com.baeldung.jdo.query.ProductItem " + "WHERE price < threshold PARAMETERS double threshold");
+ List explicitParamResults = (List) query.execute(10);
- query = pm.newQuery("SELECT FROM "
- + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
+ query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
query.setParameters("double threshold");
- List explicitParamResults2 = (List)query.execute(10);
+ List explicitParamResults2 = (List) query.execute(10);
- query = pm.newQuery("SELECT FROM "
- + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
- List implicitParamResults = (List)query.execute(10);
+ query = pm.newQuery("SELECT FROM " + "com.baeldung.jdo.query.ProductItem WHERE price < :threshold");
+ List implicitParamResults = (List) query.execute(10);
}
- public static void queryUsingTypedJDOQL(){
-
+ public static void queryUsingTypedJDOQL() {
JDOQLTypedQuery tq = pm.newJDOQLTypedQuery(ProductItem.class);
QProductItem cand = QProductItem.candidate();
- tq=tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro")));
+ tq = tq.filter(cand.price.lt(10).and(cand.name.startsWith("pro")));
List results = tq.executeList();
}
- public static void queryUsingSQL(){
+ public static void queryUsingSQL() {
- Query query = pm.newQuery("javax.jdo.query.SQL","select * from "
- + "product_item where price < ? and status = ?");
+ Query query = pm.newQuery("javax.jdo.query.SQL", "select * from " + "product_item where price < ? and status = ?");
query.setClass(ProductItem.class);
- query.setParameters(10,"InStock");
+ query.setParameters(10, "InStock");
List results = query.executeList();
}
- public static void queryUsingJPQL(){
- Query query = pm.newQuery("JPQL","select i from "
- + "com.baeldung.jdo.query.ProductItem i where i.price < 10"
- + " and i.status = 'InStock'");
+ public static void queryUsingJPQL() {
+ Query query = pm.newQuery("JPQL", "select i from " + "com.baeldung.jdo.query.ProductItem i where i.price < 10" + " and i.status = 'InStock'");
List results = (List) query.execute();
}
- public static void namedQuery(){
- Query query = pm.newNamedQuery(
- ProductItem.class, "PriceBelow10");
+ public static void namedQuery() {
+ Query query = pm.newNamedQuery(ProductItem.class, "PriceBelow10");
List results = query.executeList();
}
diff --git a/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java b/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java
index 52221a7d97..fbe999ba2a 100644
--- a/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java
+++ b/libraries/src/main/java/com/baeldung/jdo/query/ProductItem.java
@@ -1,7 +1,6 @@
package com.baeldung.jdo.query;
import javax.jdo.annotations.IdGeneratorStrategy;
-import javax.jdo.annotations.PersistenceAware;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
@@ -10,25 +9,24 @@ import javax.jdo.annotations.PrimaryKey;
public class ProductItem {
@PrimaryKey
- @Persistent(valueStrategy=IdGeneratorStrategy.INCREMENT)
+ @Persistent(valueStrategy = IdGeneratorStrategy.INCREMENT)
int id;
String name;
String description;
String status;
double price;
- public ProductItem(){
+ public ProductItem() {
}
- public ProductItem(String name,String description,String status,double price){
- this.name=name;
+ public ProductItem(String name, String description, String status, double price) {
+ this.name = name;
this.description = description;
this.status = status;
this.price = price;
}
-
public int getId() {
return id;
}
@@ -40,18 +38,23 @@ public class ProductItem {
public String getName() {
return name;
}
+
public void setName(String name) {
this.name = name;
}
+
public String getDescription() {
return description;
}
+
public void setDescription(String description) {
this.description = description;
}
+
public double getPrice() {
return price;
}
+
public void setPrice(double price) {
this.price = price;
}
@@ -64,5 +67,4 @@ public class ProductItem {
this.status = status;
}
-
}
diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java b/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java
index 53e86524a5..acfc26627a 100644
--- a/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java
+++ b/libraries/src/main/java/com/baeldung/jdo/xml/AnnotadedPerson.java
@@ -1,9 +1,7 @@
package com.baeldung.jdo.xml;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import javax.jdo.annotations.Element;
import javax.jdo.annotations.PersistenceCapable;
@@ -12,10 +10,7 @@ import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
-@PersistenceCapable(
- schema="/myproduct/people",
- table="person"
- )
+@PersistenceCapable(schema = "/myproduct/people", table = "person")
public class AnnotadedPerson {
@XmlAttribute
private long personNum;
@@ -24,12 +19,11 @@ public class AnnotadedPerson {
private String firstName;
private String lastName;
- @XmlElementWrapper(name="phone-numbers")
- @XmlElement(name="phone-number")
- @Element(types=String.class)
+ @XmlElementWrapper(name = "phone-numbers")
+ @XmlElement(name = "phone-number")
+ @Element(types = String.class)
private List phoneNumbers = new ArrayList();
-
public AnnotadedPerson(long personNum, String firstName, String lastName) {
super();
this.personNum = personNum;
diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java b/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java
index 97ec49eec1..c75d3695f7 100644
--- a/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java
+++ b/libraries/src/main/java/com/baeldung/jdo/xml/MyApp.java
@@ -17,35 +17,35 @@ public class MyApp {
private static PersistenceManagerFactory pmf;
private static PersistenceManager pm;
- public static void main( String[] args ) {
-
- //persist product object using dynamic persistence unit
+ public static void main(String[] args) {
+
+ // persist product object using dynamic persistence unit
defineDynamicPersistentUnit();
- Product product = new Product("id1","Sony Discman", "A standard discman from Sony", 49.99);
+ Product product = new Product("id1", "Sony Discman", "A standard discman from Sony", 49.99);
persistObject(product);
closePersistenceManager();
-
- //persist AnnotatedPerson object using named pmf
+
+ // persist AnnotatedPerson object using named pmf
defineNamedPersistenceManagerFactory("XmlDatastore");
- AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320,"annotated","person");
+ AnnotadedPerson annotatedPerson = new AnnotadedPerson(654320, "annotated", "person");
annotatedPerson.getPhoneNumbers().add("999999999");
annotatedPerson.getPhoneNumbers().add("000000000");
persistObject(annotatedPerson);
queryAnnotatedPersonsInXML();
closePersistenceManager();
-
- //persist Person object using PMF created by properties file
+
+ // persist Person object using PMF created by properties file
definePersistenceManagerFactoryUsingPropertiesFile("META-INF\\datanucleus.properties");
- Person person = new Person(654321,"bealdung","author");
+ Person person = new Person(654321, "bealdung", "author");
person.getPhoneNumbers().add("123456789");
person.getPhoneNumbers().add("987654321");
persistObject(person);
queryPersonsInXML();
closePersistenceManager();
- }
+ }
+
+ public static void defineDynamicPersistentUnit() {
- public static void defineDynamicPersistentUnit(){
-
PersistenceUnitMetaData pumd = new PersistenceUnitMetaData("dynamic-unit", "RESOURCE_LOCAL", null);
pumd.addProperty("javax.jdo.option.ConnectionURL", "xml:file:myfile_dynamicPMF.xml");
pumd.addProperty("datanucleus.schema.autoCreateAll", "true");
@@ -55,27 +55,27 @@ public class MyApp {
pm = pmf.getPersistenceManager();
}
- public static void defineNamedPersistenceManagerFactory(String pmfName){
-
+ public static void defineNamedPersistenceManagerFactory(String pmfName) {
+
pmf = JDOHelper.getPersistenceManagerFactory("XmlDatastore");
pm = pmf.getPersistenceManager();
}
- public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath){
-
+ public static void definePersistenceManagerFactoryUsingPropertiesFile(String filePath) {
+
pmf = JDOHelper.getPersistenceManagerFactory(filePath);
pm = pmf.getPersistenceManager();
}
- public static void closePersistenceManager(){
-
- if(pm!=null && !pm.isClosed()){
+ public static void closePersistenceManager() {
+
+ if (pm != null && !pm.isClosed()) {
pm.close();
}
}
- public static void persistObject(Object obj){
-
+ public static void persistObject(Object obj) {
+
Transaction tx = pm.currentTransaction();
try {
@@ -88,18 +88,18 @@ public class MyApp {
}
}
}
-
- public static void queryPersonsInXML(){
-
+
+ public static void queryPersonsInXML() {
+
Query query = pm.newQuery(Person.class);
List result = query.executeList();
- System.out.println("name: "+result.get(0).getFirstName());
+ System.out.println("name: " + result.get(0).getFirstName());
}
-
- public static void queryAnnotatedPersonsInXML(){
-
+
+ public static void queryAnnotatedPersonsInXML() {
+
Query query = pm.newQuery(AnnotadedPerson.class);
List result = query.executeList();
- System.out.println("name: "+result.get(0).getFirstName());
+ System.out.println("name: " + result.get(0).getFirstName());
}
}
diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/Person.java b/libraries/src/main/java/com/baeldung/jdo/xml/Person.java
index e3ec5c6bab..0678201afd 100644
--- a/libraries/src/main/java/com/baeldung/jdo/xml/Person.java
+++ b/libraries/src/main/java/com/baeldung/jdo/xml/Person.java
@@ -1,17 +1,10 @@
package com.baeldung.jdo.xml;
import java.util.ArrayList;
-import java.util.HashMap;
import java.util.List;
-import java.util.Map;
-import javax.jdo.annotations.Element;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;
-import javax.xml.bind.annotation.XmlAttribute;
-import javax.xml.bind.annotation.XmlElement;
-import javax.xml.bind.annotation.XmlElementWrapper;
-
@PersistenceCapable
public class Person {
diff --git a/libraries/src/main/java/com/baeldung/jdo/xml/Product.java b/libraries/src/main/java/com/baeldung/jdo/xml/Product.java
index d8d3bb17b2..1e46f212cb 100644
--- a/libraries/src/main/java/com/baeldung/jdo/xml/Product.java
+++ b/libraries/src/main/java/com/baeldung/jdo/xml/Product.java
@@ -1,9 +1,6 @@
package com.baeldung.jdo.xml;
-import javax.jdo.annotations.IdGeneratorStrategy;
-import javax.jdo.annotations.PersistenceAware;
import javax.jdo.annotations.PersistenceCapable;
-import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
@PersistenceCapable
@@ -14,19 +11,18 @@ public class Product {
String name;
String description;
double price;
-
- public Product(){
-
+
+ public Product() {
+
}
-
- public Product(String id,String name,String description,double price){
+
+ public Product(String id, String name, String description, double price) {
this.id = id;
- this.name=name;
+ this.name = name;
this.description = description;
this.price = price;
}
-
-
+
public String getId() {
return id;
}
@@ -38,21 +34,25 @@ public class Product {
public String getName() {
return name;
}
+
public void setName(String name) {
this.name = name;
}
+
public String getDescription() {
return description;
}
+
public void setDescription(String description) {
this.description = description;
}
+
public double getPrice() {
return price;
}
+
public void setPrice(double price) {
this.price = price;
}
-
-
+
}
diff --git a/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java b/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java
index f1de71beeb..6bc73b055a 100644
--- a/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java
+++ b/libraries/src/main/java/com/baeldung/jetty/BlockingServlet.java
@@ -14,4 +14,3 @@ public class BlockingServlet extends HttpServlet {
response.getWriter().println("{ \"status\": \"ok\"}");
}
}
-
diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java b/libraries/src/main/java/com/baeldung/jetty/JettyServer.java
index 364b05473a..82428642c1 100644
--- a/libraries/src/main/java/com/baeldung/jetty/JettyServer.java
+++ b/libraries/src/main/java/com/baeldung/jetty/JettyServer.java
@@ -21,7 +21,7 @@ class JettyServer {
server = new Server(threadPool);
ServerConnector connector = new ServerConnector(server);
connector.setPort(8090);
- server.setConnectors(new Connector[]{connector});
+ server.setConnectors(new Connector[] { connector });
ServletHandler servletHandler = new ServletHandler();
server.setHandler(servletHandler);
diff --git a/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java b/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java
index 00ba84368a..46a2e8102a 100644
--- a/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java
+++ b/libraries/src/main/java/com/baeldung/jetty/JettyServerFactory.java
@@ -14,81 +14,79 @@ import org.eclipse.jetty.webapp.WebAppContext;
*/
public class JettyServerFactory {
- /**
- * Exposed context of the app.
- */
- public final static String APP_PATH = "/myApp";
-
- /**
- * The server port.
- */
- public final static int SERVER_PORT = 13133;
+ /**
+ * Exposed context of the app.
+ */
+ public final static String APP_PATH = "/myApp";
- /**
- * Private constructor to avoid instantiation.
- */
- private JettyServerFactory() {
- }
+ /**
+ * The server port.
+ */
+ public final static int SERVER_PORT = 13133;
- /**
- * Returns a simple server listening on port 80 with a timeout of 30 seconds
- * for connections and no handlers.
- *
- * @return a server
- */
- public static Server createBaseServer() {
- Server server = new Server();
+ /**
+ * Private constructor to avoid instantiation.
+ */
+ private JettyServerFactory() {
+ }
- // Adds a connector for port 80 with a timeout of 30 seconds.
- ServerConnector connector = new ServerConnector(server);
- connector.setPort(SERVER_PORT);
- connector.setHost("127.0.0.1");
- connector.setIdleTimeout(30000);
- server.addConnector(connector);
+ /**
+ * Returns a simple server listening on port 80 with a timeout of 30 seconds
+ * for connections and no handlers.
+ *
+ * @return a server
+ */
+ public static Server createBaseServer() {
+ Server server = new Server();
- return server;
- }
+ // Adds a connector for port 80 with a timeout of 30 seconds.
+ ServerConnector connector = new ServerConnector(server);
+ connector.setPort(SERVER_PORT);
+ connector.setHost("127.0.0.1");
+ connector.setIdleTimeout(30000);
+ server.addConnector(connector);
- /**
- * Creates a server which delegates the request handling to a web
- * application.
- *
- * @return a server
- */
- public static Server createWebAppServer() {
- // Adds an handler to a server and returns it.
- Server server = createBaseServer();
- String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war")
- .getPath();
- Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH);
- server.setHandler(webAppHandler);
+ return server;
+ }
- return server;
- }
+ /**
+ * Creates a server which delegates the request handling to a web
+ * application.
+ *
+ * @return a server
+ */
+ public static Server createWebAppServer() {
+ // Adds an handler to a server and returns it.
+ Server server = createBaseServer();
+ String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
+ Handler webAppHandler = new WebAppContext(webAppFolderPath, APP_PATH);
+ server.setHandler(webAppHandler);
- /**
- * Creates a server which delegates the request handling to both a logging
- * handler and to a web application, in this order.
- *
- * @return a server
- */
- public static Server createMultiHandlerServer() {
- Server server = createBaseServer();
+ return server;
+ }
- // Creates the handlers and adds them to the server.
- HandlerCollection handlers = new HandlerCollection();
+ /**
+ * Creates a server which delegates the request handling to both a logging
+ * handler and to a web application, in this order.
+ *
+ * @return a server
+ */
+ public static Server createMultiHandlerServer() {
+ Server server = createBaseServer();
- String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war")
- .getPath();
- Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH);
- handlers.addHandler(customRequestHandler);
+ // Creates the handlers and adds them to the server.
+ HandlerCollection handlers = new HandlerCollection();
- Handler loggingRequestHandler = new LoggingRequestHandler();
- handlers.addHandler(loggingRequestHandler);
+ String webAppFolderPath = JettyServerFactory.class.getClassLoader().getResource("jetty-embedded-demo-app.war").getPath();
+ Handler customRequestHandler = new WebAppContext(webAppFolderPath, APP_PATH);
+ handlers.addHandler(customRequestHandler);
- server.setHandler(handlers);
+ Handler loggingRequestHandler = new LoggingRequestHandler();
+ handlers.addHandler(loggingRequestHandler);
- return server;
- }
+ server.setHandler(handlers);
+
+ return server;
+ }
}
\ No newline at end of file
diff --git a/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java b/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java
index a38759c903..a5c6d09c16 100644
--- a/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java
+++ b/libraries/src/main/java/com/baeldung/jetty/LoggingRequestHandler.java
@@ -19,150 +19,149 @@ import org.slf4j.LoggerFactory;
*/
public class LoggingRequestHandler implements Handler {
- /**
- * Logger.
- */
- private final static Logger LOG = LoggerFactory.getLogger(LoggingRequestHandler.class);
+ /**
+ * Logger.
+ */
+ private final static Logger LOG = LoggerFactory.getLogger(LoggingRequestHandler.class);
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.util.component.LifeCycle#addLifeCycleListener(org.
- * eclipse.jetty.util.component.LifeCycle.Listener)
- */
- @Override
- public void addLifeCycleListener(Listener arg0) {
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.util.component.LifeCycle#addLifeCycleListener(org.
+ * eclipse.jetty.util.component.LifeCycle.Listener)
+ */
+ @Override
+ public void addLifeCycleListener(Listener arg0) {
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.util.component.LifeCycle#isFailed()
- */
- @Override
- public boolean isFailed() {
- return false;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.util.component.LifeCycle#isFailed()
+ */
+ @Override
+ public boolean isFailed() {
+ return false;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.util.component.LifeCycle#isRunning()
- */
- @Override
- public boolean isRunning() {
- return true;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.util.component.LifeCycle#isRunning()
+ */
+ @Override
+ public boolean isRunning() {
+ return true;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.util.component.LifeCycle#isStarted()
- */
- @Override
- public boolean isStarted() {
- return true;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.util.component.LifeCycle#isStarted()
+ */
+ @Override
+ public boolean isStarted() {
+ return true;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.util.component.LifeCycle#isStarting()
- */
- @Override
- public boolean isStarting() {
- return false;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.util.component.LifeCycle#isStarting()
+ */
+ @Override
+ public boolean isStarting() {
+ return false;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.util.component.LifeCycle#isStopped()
- */
- @Override
- public boolean isStopped() {
- return false;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.util.component.LifeCycle#isStopped()
+ */
+ @Override
+ public boolean isStopped() {
+ return false;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.util.component.LifeCycle#isStopping()
- */
- @Override
- public boolean isStopping() {
- return false;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.util.component.LifeCycle#isStopping()
+ */
+ @Override
+ public boolean isStopping() {
+ return false;
+ }
- /*
- * (non-Javadoc)
- *
- * @see
- * org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org.
- * eclipse.jetty.util.component.LifeCycle.Listener)
- */
- @Override
- public void removeLifeCycleListener(Listener arg0) {
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see
+ * org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org.
+ * eclipse.jetty.util.component.LifeCycle.Listener)
+ */
+ @Override
+ public void removeLifeCycleListener(Listener arg0) {
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.util.component.LifeCycle#start()
- */
- @Override
- public void start() throws Exception {
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.util.component.LifeCycle#start()
+ */
+ @Override
+ public void start() throws Exception {
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.util.component.LifeCycle#stop()
- */
- @Override
- public void stop() throws Exception {
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.util.component.LifeCycle#stop()
+ */
+ @Override
+ public void stop() throws Exception {
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.server.Handler#destroy()
- */
- @Override
- public void destroy() {
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.server.Handler#destroy()
+ */
+ @Override
+ public void destroy() {
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.server.Handler#getServer()
- */
- @Override
- public Server getServer() {
- return null;
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.server.Handler#getServer()
+ */
+ @Override
+ public Server getServer() {
+ return null;
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
- * org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest,
- * javax.servlet.http.HttpServletResponse)
- */
- @Override
- public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3)
- throws IOException, ServletException {
- LOG.info("Received a new request");
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
+ * org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest,
+ * javax.servlet.http.HttpServletResponse)
+ */
+ @Override
+ public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) throws IOException, ServletException {
+ LOG.info("Received a new request");
+ }
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server.
- * Server)
- */
- @Override
- public void setServer(Server server) {
- }
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server.
+ * Server)
+ */
+ @Override
+ public void setServer(Server server) {
+ }
}
diff --git a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java b/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java
index c5bdeb1013..abb6bf7dd9 100644
--- a/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java
+++ b/libraries/src/main/java/com/baeldung/netty/ChannelHandlerB.java
@@ -5,7 +5,6 @@ import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.logging.Logger;
-
public class ChannelHandlerB extends ChannelInboundHandlerAdapter {
private Logger logger = Logger.getLogger(getClass().getName());
@@ -14,7 +13,7 @@ public class ChannelHandlerB extends ChannelInboundHandlerAdapter {
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
logger.info("Exception Handled in ChannelHandler B");
logger.info(cause.getLocalizedMessage());
- //do more exception handling
+ // do more exception handling
ctx.close();
}
}
diff --git a/libraries/src/main/java/com/baeldung/netty/NettyServerB.java b/libraries/src/main/java/com/baeldung/netty/NettyServerB.java
index c8004623c2..49a6aa6bfd 100644
--- a/libraries/src/main/java/com/baeldung/netty/NettyServerB.java
+++ b/libraries/src/main/java/com/baeldung/netty/NettyServerB.java
@@ -9,7 +9,7 @@ import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
-public class NettyServerB {
+public class NettyServerB {
private int port;
@@ -24,15 +24,11 @@ public class NettyServerB {
try {
ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup)
- .channel(NioServerSocketChannel.class)
- .childHandler(new ChannelInitializer() {
- public void initChannel(SocketChannel ch) throws Exception {
- ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB());
- }
- })
- .option(ChannelOption.SO_BACKLOG, 128)
- .childOption(ChannelOption.SO_KEEPALIVE, true);
+ b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer() {
+ public void initChannel(SocketChannel ch) throws Exception {
+ ch.pipeline().addLast(new ChannelHandlerA(), new ChannelHandlerB());
+ }
+ }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(port).sync(); // (7)
f.channel().closeFuture().sync();
} finally {
diff --git a/libraries/src/main/java/com/baeldung/netty/RequestData.java b/libraries/src/main/java/com/baeldung/netty/RequestData.java
index 402aa1ef91..475c0a4dc1 100644
--- a/libraries/src/main/java/com/baeldung/netty/RequestData.java
+++ b/libraries/src/main/java/com/baeldung/netty/RequestData.java
@@ -22,9 +22,6 @@ public class RequestData {
@Override
public String toString() {
- return "RequestData{" +
- "intValue=" + intValue +
- ", stringValue='" + stringValue + '\'' +
- '}';
+ return "RequestData{" + "intValue=" + intValue + ", stringValue='" + stringValue + '\'' + '}';
}
}
diff --git a/libraries/src/main/java/com/baeldung/netty/ResponseData.java b/libraries/src/main/java/com/baeldung/netty/ResponseData.java
index 51d1adaafb..8849e8a4cb 100644
--- a/libraries/src/main/java/com/baeldung/netty/ResponseData.java
+++ b/libraries/src/main/java/com/baeldung/netty/ResponseData.java
@@ -13,8 +13,6 @@ public class ResponseData {
@Override
public String toString() {
- return "ResponseData{" +
- "intValue=" + intValue +
- '}';
+ return "ResponseData{" + "intValue=" + intValue + '}';
}
}
diff --git a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java
index fb6a01d4c1..4cb11c3c05 100644
--- a/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java
+++ b/libraries/src/main/java/com/baeldung/neuroph/NeurophXOR.java
@@ -41,7 +41,7 @@ public class NeurophXOR {
ConnectionFactory.fullConnect(ann.getLayerAt(1), ann.getLayerAt(2));
ann.addLayer(3, outputLayer);
ConnectionFactory.fullConnect(ann.getLayerAt(2), ann.getLayerAt(3));
- ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount()-1), false);
+ ConnectionFactory.fullConnect(ann.getLayerAt(0), ann.getLayerAt(ann.getLayersCount() - 1), false);
ann.setInputNeurons(inputLayer.getNeurons());
ann.setOutputNeurons(outputLayer.getNeurons());
@@ -55,13 +55,13 @@ public class NeurophXOR {
int outputSize = 1;
DataSet ds = new DataSet(inputSize, outputSize);
- DataSetRow rOne = new DataSetRow(new double[] {0, 1}, new double[] {1});
+ DataSetRow rOne = new DataSetRow(new double[] { 0, 1 }, new double[] { 1 });
ds.addRow(rOne);
- DataSetRow rTwo = new DataSetRow(new double[] {1, 1}, new double[] {0});
+ DataSetRow rTwo = new DataSetRow(new double[] { 1, 1 }, new double[] { 0 });
ds.addRow(rTwo);
- DataSetRow rThree = new DataSetRow(new double[] {0, 0}, new double[] {0});
+ DataSetRow rThree = new DataSetRow(new double[] { 0, 0 }, new double[] { 0 });
ds.addRow(rThree);
- DataSetRow rFour = new DataSetRow(new double[] {1, 0}, new double[] {1});
+ DataSetRow rFour = new DataSetRow(new double[] { 1, 0 }, new double[] { 1 });
ds.addRow(rFour);
BackPropagation backPropagation = new BackPropagation();
diff --git a/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java
index 59e13efaa0..48abe35287 100644
--- a/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java
+++ b/libraries/src/main/java/com/baeldung/noexception/CustomExceptionHandler.java
@@ -11,10 +11,7 @@ public class CustomExceptionHandler extends ExceptionHandler {
@Override
public boolean handle(Throwable throwable) {
- if (throwable.getClass()
- .isAssignableFrom(RuntimeException.class)
- || throwable.getClass()
- .isAssignableFrom(Error.class)) {
+ if (throwable.getClass().isAssignableFrom(RuntimeException.class) || throwable.getClass().isAssignableFrom(Error.class)) {
return false;
} else {
logger.error("Caught Exception ", throwable);
diff --git a/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java b/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java
index eead34af71..b872696510 100644
--- a/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java
+++ b/libraries/src/main/java/com/baeldung/protonpack/StreamUtilsExample.java
@@ -20,18 +20,14 @@ public class StreamUtilsExample {
public void zipAStreamWithIndex() {
Stream source = Stream.of("Foo", "Bar", "Baz");
- List> zipped = StreamUtils
- .zipWithIndex(source)
- .collect(Collectors.toList());
+ List> zipped = StreamUtils.zipWithIndex(source).collect(Collectors.toList());
}
public void zipAPairOfStreams() {
Stream streamA = Stream.of("A", "B", "C");
Stream streamB = Stream.of("Apple", "Banana", "Carrot");
- List zipped = StreamUtils
- .zip(streamA, streamB, (a, b) -> a + " is for " + b)
- .collect(Collectors.toList());
+ List zipped = StreamUtils.zip(streamA, streamB, (a, b) -> a + " is for " + b).collect(Collectors.toList());
}
public void zipThreeStreams() {
@@ -39,9 +35,7 @@ public class StreamUtilsExample {
Stream streamB = Stream.of("aggravating", "banausic", "complaisant");
Stream streamC = Stream.of("Apple", "Banana", "Carrot");
- List zipped = StreamUtils
- .zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c)
- .collect(Collectors.toList());
+ List zipped = StreamUtils.zip(streamA, streamB, streamC, (a, b, c) -> a + " is for " + b + " " + c).collect(Collectors.toList());
}
public void mergeThreeStreams() {
@@ -79,24 +73,16 @@ public class StreamUtilsExample {
public void windowedStream() {
Stream integerStream = Stream.of(1, 2, 3, 4, 5);
- List> windows = StreamUtils
- .windowed(integerStream, 2)
- .collect(toList());
- List> windowsWithSkipIndex = StreamUtils
- .windowed(integerStream, 3, 2)
- .collect(toList());
- List> windowsWithSkipIndexAndAllowLowerSize = StreamUtils
- .windowed(integerStream, 2, 2, true)
- .collect(toList());
+ List> windows = StreamUtils.windowed(integerStream, 2).collect(toList());
+ List> windowsWithSkipIndex = StreamUtils.windowed(integerStream, 3, 2).collect(toList());
+ List> windowsWithSkipIndexAndAllowLowerSize = StreamUtils.windowed(integerStream, 2, 2, true).collect(toList());
}
public void groupRunsStreams() {
Stream integerStream = Stream.of(1, 1, 2, 2, 3, 4, 5);
- List> runs = StreamUtils
- .groupRuns(integerStream)
- .collect(toList());
+ List> runs = StreamUtils.groupRuns(integerStream).collect(toList());
}
public void aggreagateOnBiElementPredicate() {
diff --git a/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java b/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java
index 4757d912f8..b55517b6d1 100644
--- a/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java
+++ b/libraries/src/main/java/com/baeldung/quartz/QuartzExample.java
@@ -19,45 +19,17 @@ public class QuartzExample {
Scheduler sched = schedFact.getScheduler();
- JobDetail job = JobBuilder.newJob(SimpleJob.class)
- .withIdentity("myJob", "group1")
- .usingJobData("jobSays", "Hello World!")
- .usingJobData("myFloatValue", 3.141f)
- .build();
+ JobDetail job = JobBuilder.newJob(SimpleJob.class).withIdentity("myJob", "group1").usingJobData("jobSays", "Hello World!").usingJobData("myFloatValue", 3.141f).build();
- Trigger trigger = TriggerBuilder.newTrigger()
- .withIdentity("myTrigger", "group1")
- .startNow()
- .withSchedule(SimpleScheduleBuilder.simpleSchedule()
- .withIntervalInSeconds(40)
- .repeatForever())
- .build();
+ Trigger trigger = TriggerBuilder.newTrigger().withIdentity("myTrigger", "group1").startNow().withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();
- JobDetail jobA = JobBuilder.newJob(JobA.class)
- .withIdentity("jobA", "group2")
- .build();
+ JobDetail jobA = JobBuilder.newJob(JobA.class).withIdentity("jobA", "group2").build();
- JobDetail jobB = JobBuilder.newJob(JobB.class)
- .withIdentity("jobB", "group2")
- .build();
+ JobDetail jobB = JobBuilder.newJob(JobB.class).withIdentity("jobB", "group2").build();
- Trigger triggerA = TriggerBuilder.newTrigger()
- .withIdentity("triggerA", "group2")
- .startNow()
- .withPriority(15)
- .withSchedule(SimpleScheduleBuilder.simpleSchedule()
- .withIntervalInSeconds(40)
- .repeatForever())
- .build();
+ Trigger triggerA = TriggerBuilder.newTrigger().withIdentity("triggerA", "group2").startNow().withPriority(15).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(40).repeatForever()).build();
- Trigger triggerB = TriggerBuilder.newTrigger()
- .withIdentity("triggerB", "group2")
- .startNow()
- .withPriority(10)
- .withSchedule(SimpleScheduleBuilder.simpleSchedule()
- .withIntervalInSeconds(20)
- .repeatForever())
- .build();
+ Trigger triggerB = TriggerBuilder.newTrigger().withIdentity("triggerB", "group2").startNow().withPriority(10).withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(20).repeatForever()).build();
sched.scheduleJob(job, trigger);
sched.scheduleJob(jobA, triggerA);
diff --git a/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java b/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java
index 554d3b9358..03730ee6e5 100644
--- a/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java
+++ b/libraries/src/main/java/com/baeldung/quartz/SimpleJob.java
@@ -8,8 +8,7 @@ import org.quartz.JobExecutionException;
public class SimpleJob implements Job {
public void execute(JobExecutionContext context) throws JobExecutionException {
- JobDataMap dataMap = context.getJobDetail()
- .getJobDataMap();
+ JobDataMap dataMap = context.getJobDetail().getJobDataMap();
String jobSays = dataMap.getString("jobSays");
float myFloatValue = dataMap.getFloat("myFloatValue");
diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java
index 4e071d3384..2b5c1f6f62 100644
--- a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java
+++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApi.java
@@ -18,7 +18,7 @@ public interface GitHubBasicApi {
*/
@GET("users/{user}/repos")
Call> listRepos(@Path("user") String user);
-
+
/**
* List Contributors of a GitHub Repository
* @param user GitHub Account
@@ -26,8 +26,6 @@ public interface GitHubBasicApi {
* @return GitHub Repository Contributors
*/
@GET("repos/{user}/{repo}/contributors")
- Call> listRepoContributors(
- @Path("user") String user,
- @Path("repo") String repo);
-
+ Call> listRepoContributors(@Path("user") String user, @Path("repo") String repo);
+
}
diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java
index 6b2cd14252..df0d90af7f 100644
--- a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java
+++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicApp.java
@@ -7,8 +7,7 @@ public class GitHubBasicApp {
public static void main(String[] args) throws IOException {
String userName = "eugenp";
- List topContributors = new GitHubBasicService()
- .getTopContributors(userName);
+ List topContributors = new GitHubBasicService().getTopContributors(userName);
topContributors.forEach(System.out::println);
}
}
diff --git a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java
index 20256fb540..ff6ef82183 100644
--- a/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java
+++ b/libraries/src/main/java/com/baeldung/retrofit/basic/GitHubBasicService.java
@@ -16,45 +16,29 @@ class GitHubBasicService {
private GitHubBasicApi gitHubApi;
GitHubBasicService() {
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("https://api.github.com/")
- .addConverterFactory(GsonConverterFactory.create())
- .build();
+ Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).build();
gitHubApi = retrofit.create(GitHubBasicApi.class);
}
List getTopContributors(String userName) throws IOException {
- List repos = gitHubApi
- .listRepos(userName)
- .execute()
- .body();
+ List repos = gitHubApi.listRepos(userName).execute().body();
repos = repos != null ? repos : Collections.emptyList();
- return repos.stream()
- .flatMap(repo -> getContributors(userName, repo))
- .sorted((a, b) -> b.getContributions() - a.getContributions())
- .map(Contributor::getName)
- .distinct()
- .sorted()
- .collect(Collectors.toList());
+ return repos.stream().flatMap(repo -> getContributors(userName, repo)).sorted((a, b) -> b.getContributions() - a.getContributions()).map(Contributor::getName).distinct().sorted().collect(Collectors.toList());
}
private Stream getContributors(String userName, Repository repo) {
List contributors = null;
try {
- contributors = gitHubApi
- .listRepoContributors(userName, repo.getName())
- .execute()
- .body();
+ contributors = gitHubApi.listRepoContributors(userName, repo.getName()).execute().body();
} catch (IOException e) {
e.printStackTrace();
}
contributors = contributors != null ? contributors : Collections.emptyList();
- return contributors.stream()
- .filter(c -> c.getContributions() > 100);
+ return contributors.stream().filter(c -> c.getContributions() > 100);
}
}
diff --git a/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java b/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java
index 2f8697f603..f98b19de96 100644
--- a/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java
+++ b/libraries/src/main/java/com/baeldung/retrofit/models/Contributor.java
@@ -3,28 +3,31 @@ package com.baeldung.retrofit.models;
import com.google.gson.annotations.SerializedName;
public class Contributor {
-
+
@SerializedName("login")
private String name;
-
+
private Integer contributions;
-
+
public String getName() {
return name;
}
+
public void setName(String name) {
this.name = name;
}
+
public Integer getContributions() {
return contributions;
}
+
public void setContributions(Integer contributions) {
this.contributions = contributions;
}
-
+
@Override
public String toString() {
return "Contributer [name=" + name + ", contributions=" + contributions + "]";
}
-
+
}
diff --git a/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java b/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java
index f12fcdf8f2..6bc91eb772 100644
--- a/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java
+++ b/libraries/src/main/java/com/baeldung/retrofit/models/Repository.java
@@ -1,20 +1,23 @@
package com.baeldung.retrofit.models;
public class Repository {
-
+
private String name;
-
+
private String description;
-
+
public String getName() {
return name;
}
+
public void setName(String name) {
this.name = name;
}
+
public String getDescription() {
return description;
}
+
public void setDescription(String description) {
this.description = description;
}
diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java
index 4e40aff448..aa0f550115 100644
--- a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java
+++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApi.java
@@ -18,7 +18,7 @@ public interface GitHubRxApi {
*/
@GET("users/{user}/repos")
Observable> listRepos(@Path("user") String user);
-
+
/**
* List Contributors of a GitHub Repository
* @param user GitHub Account
@@ -26,8 +26,6 @@ public interface GitHubRxApi {
* @return GitHub Repository Contributors
*/
@GET("repos/{user}/{repo}/contributors")
- Observable> listRepoContributors(
- @Path("user") String user,
- @Path("repo") String repo);
-
+ Observable> listRepoContributors(@Path("user") String user, @Path("repo") String repo);
+
}
diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java
index b136a1e40b..4941a65717 100644
--- a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java
+++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxApp.java
@@ -6,7 +6,6 @@ public class GitHubRxApp {
public static void main(String[] args) throws IOException {
String userName = "eugenp";
- new GitHubRxService().getTopContributors(userName)
- .subscribe(System.out::println);
+ new GitHubRxService().getTopContributors(userName).subscribe(System.out::println);
}
}
diff --git a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java
index 2ad50a9f39..f2c5114149 100644
--- a/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java
+++ b/libraries/src/main/java/com/baeldung/retrofit/rx/GitHubRxService.java
@@ -11,23 +11,13 @@ class GitHubRxService {
private GitHubRxApi gitHubApi;
GitHubRxService() {
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("https://api.github.com/")
- .addConverterFactory(GsonConverterFactory.create())
- .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
- .build();
+ Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
gitHubApi = retrofit.create(GitHubRxApi.class);
}
Observable getTopContributors(String userName) {
- return gitHubApi.listRepos(userName)
- .flatMapIterable(x -> x)
- .flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName()))
- .flatMapIterable(x -> x)
- .filter(c -> c.getContributions() > 100)
- .sorted((a, b) -> b.getContributions() - a.getContributions())
- .map(Contributor::getName)
- .distinct();
+ return gitHubApi.listRepos(userName).flatMapIterable(x -> x).flatMap(repo -> gitHubApi.listRepoContributors(userName, repo.getName())).flatMapIterable(x -> x).filter(c -> c.getContributions() > 100)
+ .sorted((a, b) -> b.getContributions() - a.getContributions()).map(Contributor::getName).distinct();
}
}
diff --git a/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java b/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java
index d32891be9e..dc6bfbddb1 100644
--- a/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java
+++ b/libraries/src/main/java/com/baeldung/retrofitguide/GitHubServiceGenerator.java
@@ -13,19 +13,13 @@ public class GitHubServiceGenerator {
private static final String BASE_URL = "https://api.github.com/";
- private static Retrofit.Builder builder
- = new Retrofit.Builder()
- .baseUrl(BASE_URL)
- .addConverterFactory(GsonConverterFactory.create());
+ private static Retrofit.Builder builder = new Retrofit.Builder().baseUrl(BASE_URL).addConverterFactory(GsonConverterFactory.create());
private static Retrofit retrofit = builder.build();
- private static OkHttpClient.Builder httpClient
- = new OkHttpClient.Builder();
+ private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
- private static HttpLoggingInterceptor logging
- = new HttpLoggingInterceptor()
- .setLevel(HttpLoggingInterceptor.Level.BASIC);
+ private static HttpLoggingInterceptor logging = new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC);
public static S createService(Class serviceClass) {
if (!httpClient.interceptors().contains(logging)) {
@@ -43,8 +37,7 @@ public class GitHubServiceGenerator {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
- Request.Builder builder = original.newBuilder()
- .header("Authorization", token);
+ Request.Builder builder = original.newBuilder().header("Authorization", token);
Request request = builder.build();
return chain.proceed(request);
}
diff --git a/libraries/src/main/java/com/baeldung/retrofitguide/Main.java b/libraries/src/main/java/com/baeldung/retrofitguide/Main.java
index 8a674f634b..be7e15e3c9 100644
--- a/libraries/src/main/java/com/baeldung/retrofitguide/Main.java
+++ b/libraries/src/main/java/com/baeldung/retrofitguide/Main.java
@@ -11,15 +11,11 @@ import retrofit2.converter.gson.GsonConverterFactory;
public class Main {
public static void main(String[] args) {
- //Manual creation
+ // Manual creation
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("https://api.github.com/")
- .addConverterFactory(GsonConverterFactory.create())
- .client(httpClient.build())
- .build();
+ Retrofit retrofit = new Retrofit.Builder().baseUrl("https://api.github.com/").addConverterFactory(GsonConverterFactory.create()).client(httpClient.build()).build();
UserService service = retrofit.create(UserService.class);
- //Using GitHubServiceGenerator
+ // Using GitHubServiceGenerator
service = GitHubServiceGenerator.createService(UserService.class);
Call callSync = service.getUser("eugenp");
Call callAsync = service.getUser("eugenp");
diff --git a/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java b/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java
index 208b73d4af..c889871b3d 100644
--- a/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java
+++ b/libraries/src/main/java/com/baeldung/serenity/membership/Commodity.java
@@ -9,7 +9,7 @@ public enum Commodity {
public final int price;
- Commodity(int price){
+ Commodity(int price) {
this.price = price;
}
diff --git a/libraries/src/main/java/com/baeldung/serenity/membership/Member.java b/libraries/src/main/java/com/baeldung/serenity/membership/Member.java
index 6e7c4db08e..f2f443020d 100644
--- a/libraries/src/main/java/com/baeldung/serenity/membership/Member.java
+++ b/libraries/src/main/java/com/baeldung/serenity/membership/Member.java
@@ -12,7 +12,8 @@ public class Member {
private int points;
private Member(int points) {
- if (points < 0) throw new IllegalArgumentException("points must not be negative!");
+ if (points < 0)
+ throw new IllegalArgumentException("points must not be negative!");
this.points = points;
}
@@ -22,9 +23,12 @@ public class Member {
}
public MemberGrade getGrade() {
- if (points < 1000) return Bronze;
- else if (points >= 1000 && points < 5000) return Silver;
- else return Gold;
+ if (points < 1000)
+ return Bronze;
+ else if (points >= 1000 && points < 5000)
+ return Silver;
+ else
+ return Gold;
}
public void spend(int moneySpent) {
diff --git a/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java b/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java
index 7bb6f76495..389749c2ca 100644
--- a/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java
+++ b/libraries/src/main/java/com/baeldung/serenity/membership/MemberGrade.java
@@ -3,7 +3,7 @@ package com.baeldung.serenity.membership;
/**
* @author aiet
*/
-public enum MemberGrade {
+public enum MemberGrade {
Bronze, Silver, Gold;
diff --git a/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java b/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java
index d11f5a29b2..fa317f93b7 100644
--- a/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java
+++ b/libraries/src/main/java/com/baeldung/smooks/converter/OrderConverter.java
@@ -21,7 +21,6 @@ public class OrderConverter {
smooks.close();
}
}
-
public String convertOrderXMLtoEDIFACT(String path) throws IOException, SAXException {
return convertDocumentWithTempalte(path, "/smooks/smooks-transform-edi.xml");
diff --git a/libraries/src/main/java/com/baeldung/smooks/model/Item.java b/libraries/src/main/java/com/baeldung/smooks/model/Item.java
index a7f7783b3f..3e1f4a7ef4 100644
--- a/libraries/src/main/java/com/baeldung/smooks/model/Item.java
+++ b/libraries/src/main/java/com/baeldung/smooks/model/Item.java
@@ -15,7 +15,6 @@ public class Item {
private Double price;
private Integer quantity;
-
public String getCode() {
return code;
}
@@ -42,13 +41,17 @@ public class Item {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
Item item = (Item) o;
- if (code != null ? !code.equals(item.code) : item.code != null) return false;
- if (price != null ? !price.equals(item.price) : item.price != null) return false;
+ if (code != null ? !code.equals(item.code) : item.code != null)
+ return false;
+ if (price != null ? !price.equals(item.price) : item.price != null)
+ return false;
return quantity != null ? quantity.equals(item.quantity) : item.quantity == null;
}
@@ -62,10 +65,6 @@ public class Item {
@Override
public String toString() {
- return "Item{" +
- "code='" + code + '\'' +
- ", price=" + price +
- ", quantity=" + quantity +
- '}';
+ return "Item{" + "code='" + code + '\'' + ", price=" + price + ", quantity=" + quantity + '}';
}
}
diff --git a/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java b/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java
index 31a9e1f43f..827a0fc907 100644
--- a/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java
+++ b/libraries/src/main/java/com/baeldung/smooks/model/Supplier.java
@@ -31,12 +31,15 @@ public class Supplier {
@Override
public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
Supplier supplier = (Supplier) o;
- if (name != null ? !name.equals(supplier.name) : supplier.name != null) return false;
+ if (name != null ? !name.equals(supplier.name) : supplier.name != null)
+ return false;
return phoneNumber != null ? phoneNumber.equals(supplier.phoneNumber) : supplier.phoneNumber == null;
}
diff --git a/libraries/src/main/java/com/baeldung/stm/Account.java b/libraries/src/main/java/com/baeldung/stm/Account.java
index 8b17f87120..4dc2c492df 100644
--- a/libraries/src/main/java/com/baeldung/stm/Account.java
+++ b/libraries/src/main/java/com/baeldung/stm/Account.java
@@ -44,7 +44,6 @@ public class Account {
@Override
public String toString() {
- return StmUtils.atomic((TxnCallable)
- txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn));
+ return StmUtils.atomic((TxnCallable) txn -> "Balance: " + balance.get(txn) + " lastUpdateDate: " + lastUpdate.get(txn));
}
}
\ No newline at end of file
diff --git a/libraries/src/main/java/com/baeldung/streamex/StreamEX.java b/libraries/src/main/java/com/baeldung/streamex/StreamEX.java
index 7cbfec4421..56a3860f05 100644
--- a/libraries/src/main/java/com/baeldung/streamex/StreamEX.java
+++ b/libraries/src/main/java/com/baeldung/streamex/StreamEX.java
@@ -15,69 +15,43 @@ import one.util.streamex.StreamEx;
public class StreamEX {
public static void main(String[] args) {
- //Collector shortcut methods (toList, toSet, groupingBy, joining, etc.)
- List users = Arrays.asList(
- new User("name"), new User(), new User());
- users.stream()
- .map(User::getName)
- .collect(Collectors.toList());
- List userNames = StreamEx.of(users)
- .map(User::getName)
- .toList();
- Map> role2users = StreamEx.of(users)
- .groupingBy(User::getRole);
- StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3"
- //Selecting stream elements of specific type
+ // Collector shortcut methods (toList, toSet, groupingBy, joining, etc.)
+ List users = Arrays.asList(new User("name"), new User(), new User());
+ users.stream().map(User::getName).collect(Collectors.toList());
+ List userNames = StreamEx.of(users).map(User::getName).toList();
+ Map> role2users = StreamEx.of(users).groupingBy(User::getRole);
+ StreamEx.of(1, 2, 3).joining("; "); // "1; 2; 3"
+ // Selecting stream elements of specific type
List usersAndRoles = Arrays.asList(new User(), new Role());
- List roles = IntStreamEx.range(usersAndRoles.size())
- .mapToObj(usersAndRoles::get)
- .select(Role.class)
- .toList();
+ List roles = IntStreamEx.range(usersAndRoles.size()).mapToObj(usersAndRoles::get).select(Role.class).toList();
System.out.println(roles);
- //adding elements to Stream
- List appendedUsers = StreamEx.of(users)
- .map(User::getName)
- .prepend("(none)")
- .append("LAST")
- .toList();
+ // adding elements to Stream
+ List appendedUsers = StreamEx.of(users).map(User::getName).prepend("(none)").append("LAST").toList();
System.out.println(appendedUsers);
- //Removing unwanted elements and using the stream as Iterable:
- for (String line : StreamEx.of(users).map(User::getName)
- .nonNull()) {
+ // Removing unwanted elements and using the stream as Iterable:
+ for (String line : StreamEx.of(users).map(User::getName).nonNull()) {
System.out.println(line);
}
- //Selecting map keys by value predicate:
+ // Selecting map keys by value predicate:
Map nameToRole = new HashMap<>();
nameToRole.put("first", new Role());
nameToRole.put("second", null);
- Set nonNullRoles = StreamEx.
- ofKeys(nameToRole, Objects::nonNull)
- .toSet();
+ Set nonNullRoles = StreamEx.ofKeys(nameToRole, Objects::nonNull).toSet();
System.out.println(nonNullRoles);
- //Operating on key-value pairs:
+ // Operating on key-value pairs:
Map> users2roles = transformMap(role2users);
- Map mapToString = EntryStream.of(users2roles)
- .mapKeys(String::valueOf)
- .mapValues(String::valueOf)
- .toMap();
- //Support of byte/char/short/float types:
- short[] src = {1, 2, 3};
- char[] output = IntStreamEx.of(src)
- .map(x -> x * 5)
- .toCharArray();
+ Map mapToString = EntryStream.of(users2roles).mapKeys(String::valueOf).mapValues(String::valueOf).toMap();
+ // Support of byte/char/short/float types:
+ short[] src = { 1, 2, 3 };
+ char[] output = IntStreamEx.of(src).map(x -> x * 5).toCharArray();
}
public double[] getDiffBetweenPairs(double... numbers) {
- return DoubleStreamEx.of(numbers)
- .pairMap((a, b) -> b - a).toArray();
+ return DoubleStreamEx.of(numbers).pairMap((a, b) -> b - a).toArray();
}
- public static Map> transformMap(
- Map> role2users) {
- Map> users2roles = EntryStream.of(role2users)
- .flatMapValues(List::stream)
- .invert()
- .grouping();
+ public static Map> transformMap(Map> role2users) {
+ Map> users2roles = EntryStream.of(role2users).flatMapValues(List::stream).invert().grouping();
return users2roles;
}
diff --git a/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java
index 430759f3a0..d9097188b3 100644
--- a/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java
+++ b/libraries/src/main/java/com/baeldung/streamutils/CopyStream.java
@@ -9,14 +9,14 @@ import org.apache.commons.io.IOUtils;
import org.springframework.util.StreamUtils;
public class CopyStream {
- public static String getStringFromInputStream(InputStream input) throws IOException {
- StringWriter writer = new StringWriter();
- IOUtils.copy(input, writer, "UTF-8");
- return writer.toString();
- }
+ public static String getStringFromInputStream(InputStream input) throws IOException {
+ StringWriter writer = new StringWriter();
+ IOUtils.copy(input, writer, "UTF-8");
+ return writer.toString();
+ }
- public InputStream getNonClosingInputStream() throws IOException {
- InputStream in = new FileInputStream("src/test/resources/input.txt");
- return StreamUtils.nonClosing(in);
- }
+ public InputStream getNonClosingInputStream() throws IOException {
+ InputStream in = new FileInputStream("src/test/resources/input.txt");
+ return StreamUtils.nonClosing(in);
+ }
}
diff --git a/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java
index 6ee4a1ef3a..1ce67a075a 100644
--- a/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java
+++ b/libraries/src/main/java/com/baeldung/streamutils/DrainStream.java
@@ -5,7 +5,7 @@ import java.io.InputStream;
import org.springframework.util.StreamUtils;
public class DrainStream {
- public InputStream getInputStream() {
- return StreamUtils.emptyInput();
- }
+ public InputStream getInputStream() {
+ return StreamUtils.emptyInput();
+ }
}
diff --git a/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java b/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java
index 4bbf3c03a7..1b48e2d90b 100644
--- a/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java
+++ b/libraries/src/main/java/com/baeldung/tomcat/MyServlet.java
@@ -9,10 +9,7 @@ import java.io.IOException;
/**
* Created by adi on 1/10/18.
*/
-@WebServlet(
- name = "com.baeldung.tomcat.programmatic.MyServlet",
- urlPatterns = {"/my-servlet"}
-)
+@WebServlet(name = "com.baeldung.tomcat.programmatic.MyServlet", urlPatterns = { "/my-servlet" })
public class MyServlet extends HttpServlet {
@Override
diff --git a/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java b/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java
index b84b6b5c6d..6c4fed6d07 100644
--- a/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java
+++ b/libraries/src/main/java/com/baeldung/tomcat/ProgrammaticTomcat.java
@@ -15,29 +15,27 @@ public class ProgrammaticTomcat {
private Tomcat tomcat = null;
- //uncomment for live test
- // public static void main(String[] args) throws LifecycleException, ServletException, URISyntaxException, IOException {
- // startTomcat();
- // }
+ // uncomment for live test
+ // public static void main(String[] args) throws LifecycleException, ServletException, URISyntaxException, IOException {
+ // startTomcat();
+ // }
public void startTomcat() throws LifecycleException {
tomcat = new Tomcat();
tomcat.setPort(8080);
tomcat.setHostname("localhost");
String appBase = ".";
- tomcat
- .getHost()
- .setAppBase(appBase);
+ tomcat.getHost().setAppBase(appBase);
File docBase = new File(System.getProperty("java.io.tmpdir"));
Context context = tomcat.addContext("", docBase.getAbsolutePath());
- //add a servlet
+ // add a servlet
Class servletClass = MyServlet.class;
Tomcat.addServlet(context, servletClass.getSimpleName(), servletClass.getName());
context.addServletMappingDecoded("/my-servlet/*", servletClass.getSimpleName());
- //add a filter and filterMapping
+ // add a filter and filterMapping
Class filterClass = MyFilter.class;
FilterDef myFilterDef = new FilterDef();
myFilterDef.setFilterClass(filterClass.getName());
@@ -50,10 +48,10 @@ public class ProgrammaticTomcat {
context.addFilterMap(myFilterMap);
tomcat.start();
- //uncomment for live test
- // tomcat
- // .getServer()
- // .await();
+ // uncomment for live test
+ // tomcat
+ // .getServer()
+ // .await();
}
public void stopTomcat() throws LifecycleException {
diff --git a/libraries/src/main/java/com/baeldung/yarg/DocumentController.java b/libraries/src/main/java/com/baeldung/yarg/DocumentController.java
index 0e1bbca561..ff0d452108 100644
--- a/libraries/src/main/java/com/baeldung/yarg/DocumentController.java
+++ b/libraries/src/main/java/com/baeldung/yarg/DocumentController.java
@@ -30,25 +30,17 @@ public class DocumentController {
@RequestMapping(path = "/generate/doc", method = RequestMethod.GET)
public void generateDocument(HttpServletResponse response) throws IOException {
ReportBuilder reportBuilder = new ReportBuilder();
- ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder()
- .documentPath("./src/main/resources/Letter.docx")
- .documentName("Letter.docx")
- .outputType(ReportOutputType.docx)
- .readFileFromPath();
+ ReportTemplateBuilder reportTemplateBuilder = new ReportTemplateBuilder().documentPath("./src/main/resources/Letter.docx").documentName("Letter.docx").outputType(ReportOutputType.docx).readFileFromPath();
reportBuilder.template(reportTemplateBuilder.build());
BandBuilder bandBuilder = new BandBuilder();
String json = FileUtils.readFileToString(new File("./src/main/resources/Data.json"));
- ReportBand main = bandBuilder.name("Main")
- .query("Main", "parameter=param1 $.main", "json")
- .build();
+ ReportBand main = bandBuilder.name("Main").query("Main", "parameter=param1 $.main", "json").build();
reportBuilder.band(main);
Report report = reportBuilder.build();
Reporting reporting = new Reporting();
reporting.setFormatterFactory(new DefaultFormatterFactory());
- reporting.setLoaderFactory(
- new DefaultLoaderFactory()
- .setJsonDataLoader(new JsonDataLoader()));
+ reporting.setLoaderFactory(new DefaultLoaderFactory().setJsonDataLoader(new JsonDataLoader()));
response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
reporting.runReport(new RunParams(report).param("param1", json), response.getOutputStream());
}
diff --git a/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java b/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java
index 1398c2ba41..7ff81c20c3 100644
--- a/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java
+++ b/libraries/src/test/java/com/baeldung/asynchttpclient/AsyncHttpClientTestCase.java
@@ -186,17 +186,12 @@ public class AsyncHttpClientTestCase {
WebSocket WEBSOCKET_CLIENT = null;
try {
- WEBSOCKET_CLIENT = Dsl.asyncHttpClient()
- .prepareGet("ws://localhost:5590/websocket")
- .addHeader("header_name", "header_value")
- .addQueryParam("key", "value")
- .setRequestTimeout(5000)
- .execute(wsHandler).get();
+ WEBSOCKET_CLIENT = Dsl.asyncHttpClient().prepareGet("ws://localhost:5590/websocket").addHeader("header_name", "header_value").addQueryParam("key", "value").setRequestTimeout(5000).execute(wsHandler).get();
if (WEBSOCKET_CLIENT.isOpen()) {
WEBSOCKET_CLIENT.sendPingFrame();
WEBSOCKET_CLIENT.sendTextFrame("test message");
- WEBSOCKET_CLIENT.sendBinaryFrame(new byte[]{'t', 'e', 's', 't'});
+ WEBSOCKET_CLIENT.sendBinaryFrame(new byte[] { 't', 'e', 's', 't' });
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
diff --git a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java
index 7ca656efbf..87c0b13bcc 100644
--- a/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java
+++ b/libraries/src/test/java/com/baeldung/awaitility/AsyncServiceLongRunningUnitTest.java
@@ -35,10 +35,7 @@ public class AsyncServiceLongRunningUnitTest {
public void givenAsyncService_whenInitialize_thenInitOccurs2() {
asyncService.initialize();
Callable isInitialized = asyncService::isInitialized;
- await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS)
- .atMost(Duration.FIVE_SECONDS)
- .with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS)
- .until(isInitialized);
+ await().atLeast(Duration.ONE_HUNDRED_MILLISECONDS).atMost(Duration.FIVE_SECONDS).with().pollInterval(Duration.ONE_HUNDRED_MILLISECONDS).until(isInitialized);
}
@Test
@@ -60,9 +57,7 @@ public class AsyncServiceLongRunningUnitTest {
@Test
public void givenAsyncService_whenInitialize_thenInitOccurs3() {
asyncService.initialize();
- await().until(fieldIn(asyncService)
- .ofType(boolean.class)
- .andWithName("initialized"), equalTo(true));
+ await().until(fieldIn(asyncService).ofType(boolean.class).andWithName("initialized"), equalTo(true));
}
@Test
@@ -77,10 +72,6 @@ public class AsyncServiceLongRunningUnitTest {
@Test
public void givenAsyncService_whenGetValue_thenExceptionIgnored() {
asyncService.initialize();
- given().ignoreException(IllegalStateException.class)
- .await()
- .atMost(Duration.FIVE_SECONDS)
- .atLeast(Duration.FIVE_HUNDRED_MILLISECONDS)
- .until(asyncService::getValue, equalTo(0L));
+ given().ignoreException(IllegalStateException.class).await().atMost(Duration.FIVE_SECONDS).atLeast(Duration.FIVE_HUNDRED_MILLISECONDS).until(asyncService::getValue, equalTo(0L));
}
}
diff --git a/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java b/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java
index 3965eeecd4..009119d97a 100644
--- a/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java
+++ b/libraries/src/test/java/com/baeldung/bouncycastle/BouncyCastleLiveTest.java
@@ -28,14 +28,11 @@ public class BouncyCastleLiveTest {
char[] keyPassword = "password".toCharArray();
@Test
- public void givenCryptographicResource_whenOperationSuccess_returnTrue()
- throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException,
- KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException {
+ public void givenCryptographicResource_whenOperationSuccess_returnTrue() throws CertificateException, NoSuchProviderException, NoSuchAlgorithmException, IOException, KeyStoreException, UnrecoverableKeyException, CMSException, OperatorCreationException {
Security.addProvider(new BouncyCastleProvider());
CertificateFactory certFactory = CertificateFactory.getInstance("X.509", "BC");
- X509Certificate certificate = (X509Certificate) certFactory
- .generateCertificate(new FileInputStream(certificatePath));
+ X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(new FileInputStream(certificatePath));
KeyStore keystore = KeyStore.getInstance("PKCS12");
keystore.load(new FileInputStream(privateKeyPath), p12Password);
PrivateKey privateKey = (PrivateKey) keystore.getKey("baeldung", keyPassword);
diff --git a/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java
index 6b7364a0a5..5f721025c3 100644
--- a/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java
+++ b/libraries/src/test/java/com/baeldung/bytebuddy/ByteBuddyUnitTest.java
@@ -21,14 +21,9 @@ public class ByteBuddyUnitTest {
@Test
public void givenObject_whenToString_thenReturnHelloWorldString() throws InstantiationException, IllegalAccessException {
- DynamicType.Unloaded unloadedType = new ByteBuddy()
- .subclass(Object.class)
- .method(ElementMatchers.isToString())
- .intercept(FixedValue.value("Hello World ByteBuddy!"))
- .make();
+ DynamicType.Unloaded unloadedType = new ByteBuddy().subclass(Object.class).method(ElementMatchers.isToString()).intercept(FixedValue.value("Hello World ByteBuddy!")).make();
- Class> dynamicType = unloadedType.load(getClass().getClassLoader())
- .getLoaded();
+ Class> dynamicType = unloadedType.load(getClass().getClassLoader()).getLoaded();
assertEquals(dynamicType.newInstance().toString(), "Hello World ByteBuddy!");
}
@@ -36,12 +31,7 @@ public class ByteBuddyUnitTest {
@Test
public void givenFoo_whenRedefined_thenReturnFooRedefined() throws Exception {
ByteBuddyAgent.install();
- new ByteBuddy()
- .redefine(Foo.class)
- .method(named("sayHelloFoo"))
- .intercept(FixedValue.value("Hello Foo Redefined"))
- .make()
- .load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
+ new ByteBuddy().redefine(Foo.class).method(named("sayHelloFoo")).intercept(FixedValue.value("Hello Foo Redefined")).make().load(Foo.class.getClassLoader(), ClassReloadingStrategy.fromInstalledAgent());
Foo f = new Foo();
assertEquals(f.sayHelloFoo(), "Hello Foo Redefined");
}
@@ -49,34 +39,16 @@ public class ByteBuddyUnitTest {
@Test
public void givenSayHelloFoo_whenMethodDelegation_thenSayHelloBar() throws IllegalAccessException, InstantiationException {
- String r = new ByteBuddy()
- .subclass(Foo.class)
- .method(
- named("sayHelloFoo")
- .and(isDeclaredBy(Foo.class)
- .and(returns(String.class)))
- )
- .intercept(MethodDelegation.to(Bar.class))
- .make()
- .load(getClass().getClassLoader())
- .getLoaded()
- .newInstance()
- .sayHelloFoo();
+ String r = new ByteBuddy().subclass(Foo.class).method(named("sayHelloFoo").and(isDeclaredBy(Foo.class).and(returns(String.class)))).intercept(MethodDelegation.to(Bar.class)).make().load(getClass().getClassLoader()).getLoaded().newInstance()
+ .sayHelloFoo();
assertEquals(r, Bar.sayHelloBar());
}
@Test
public void givenMethodName_whenDefineMethod_thenCreateMethod() throws Exception {
- Class> type = new ByteBuddy()
- .subclass(Object.class)
- .name("MyClassName")
- .defineMethod("custom", String.class, Modifier.PUBLIC)
- .intercept(MethodDelegation.to(Bar.class))
- .defineField("x", String.class, Modifier.PUBLIC)
- .make()
- .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER)
- .getLoaded();
+ Class> type = new ByteBuddy().subclass(Object.class).name("MyClassName").defineMethod("custom", String.class, Modifier.PUBLIC).intercept(MethodDelegation.to(Bar.class)).defineField("x", String.class, Modifier.PUBLIC).make()
+ .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER).getLoaded();
Method m = type.getDeclaredMethod("custom", null);
@@ -85,5 +57,4 @@ public class ByteBuddyUnitTest {
}
-
}
diff --git a/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java b/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java
index 56dbda5974..d523d0ff8b 100644
--- a/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java
+++ b/libraries/src/test/java/com/baeldung/caffeine/CaffeineUnitTest.java
@@ -16,10 +16,7 @@ public class CaffeineUnitTest {
@Test
public void givenCache_whenPopulate_thenValueStored() {
- Cache cache = Caffeine.newBuilder()
- .expireAfterWrite(1, TimeUnit.MINUTES)
- .maximumSize(100)
- .build();
+ Cache cache = Caffeine.newBuilder().expireAfterWrite(1, TimeUnit.MINUTES).maximumSize(100).build();
String key = "A";
DataObject dataObject = cache.getIfPresent(key);
@@ -44,10 +41,7 @@ public class CaffeineUnitTest {
@Test
public void givenLoadingCache_whenGet_thenValuePopulated() {
- LoadingCache cache = Caffeine.newBuilder()
- .maximumSize(100)
- .expireAfterWrite(1, TimeUnit.MINUTES)
- .build(k -> DataObject.get("Data for " + k));
+ LoadingCache cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
String key = "A";
DataObject dataObject = cache.get(key);
@@ -63,10 +57,7 @@ public class CaffeineUnitTest {
@Test
public void givenAsyncLoadingCache_whenGet_thenValuePopulated() {
- AsyncLoadingCache cache = Caffeine.newBuilder()
- .maximumSize(100)
- .expireAfterWrite(1, TimeUnit.MINUTES)
- .buildAsync(k -> DataObject.get("Data for " + k));
+ AsyncLoadingCache cache = Caffeine.newBuilder().maximumSize(100).expireAfterWrite(1, TimeUnit.MINUTES).buildAsync(k -> DataObject.get("Data for " + k));
String key = "A";
cache.get(key).thenAccept(dataObject -> {
@@ -74,16 +65,12 @@ public class CaffeineUnitTest {
assertEquals("Data for " + key, dataObject.getData());
});
- cache.getAll(Arrays.asList("A", "B", "C"))
- .thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size()));
+ cache.getAll(Arrays.asList("A", "B", "C")).thenAccept(dataObjectMap -> assertEquals(3, dataObjectMap.size()));
}
@Test
public void givenLoadingCacheWithSmallSize_whenPut_thenSizeIsConstant() {
- LoadingCache cache = Caffeine.newBuilder()
- .maximumSize(1)
- .refreshAfterWrite(10, TimeUnit.MINUTES)
- .build(k -> DataObject.get("Data for " + k));
+ LoadingCache cache = Caffeine.newBuilder().maximumSize(1).refreshAfterWrite(10, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize());
@@ -99,10 +86,7 @@ public class CaffeineUnitTest {
@Test
public void givenLoadingCacheWithWeigher_whenPut_thenSizeIsConstant() {
- LoadingCache cache = Caffeine.newBuilder()
- .maximumWeight(10)
- .weigher((k,v) -> 5)
- .build(k -> DataObject.get("Data for " + k));
+ LoadingCache cache = Caffeine.newBuilder().maximumWeight(10).weigher((k, v) -> 5).build(k -> DataObject.get("Data for " + k));
assertEquals(0, cache.estimatedSize());
@@ -122,20 +106,11 @@ public class CaffeineUnitTest {
@Test
public void givenTimeEvictionCache_whenTimeLeft_thenValueEvicted() {
- LoadingCache cache = Caffeine.newBuilder()
- .expireAfterAccess(5, TimeUnit.MINUTES)
- .build(k -> DataObject.get("Data for " + k));
+ LoadingCache cache = Caffeine.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
- cache = Caffeine.newBuilder()
- .expireAfterWrite(10, TimeUnit.SECONDS)
- .weakKeys()
- .weakValues()
- .build(k -> DataObject.get("Data for " + k));
+ cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).weakKeys().weakValues().build(k -> DataObject.get("Data for " + k));
- cache = Caffeine.newBuilder()
- .expireAfterWrite(10, TimeUnit.SECONDS)
- .softValues()
- .build(k -> DataObject.get("Data for " + k));
+ cache = Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).softValues().build(k -> DataObject.get("Data for " + k));
cache = Caffeine.newBuilder().expireAfter(new Expiry() {
@Override
@@ -154,17 +129,12 @@ public class CaffeineUnitTest {
}
}).build(k -> DataObject.get("Data for " + k));
- cache = Caffeine.newBuilder()
- .refreshAfterWrite(1, TimeUnit.MINUTES)
- .build(k -> DataObject.get("Data for " + k));
+ cache = Caffeine.newBuilder().refreshAfterWrite(1, TimeUnit.MINUTES).build(k -> DataObject.get("Data for " + k));
}
@Test
public void givenCache_whenStatsEnabled_thenStatsRecorded() {
- LoadingCache cache = Caffeine.newBuilder()
- .maximumSize(100)
- .recordStats()
- .build(k -> DataObject.get("Data for " + k));
+ LoadingCache cache = Caffeine.newBuilder().maximumSize(100).recordStats().build(k -> DataObject.get("Data for " + k));
cache.get("A");
cache.get("A");
diff --git a/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java b/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java
index 1224d73724..080444d7b1 100644
--- a/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java
+++ b/libraries/src/test/java/com/baeldung/cglib/proxy/BeanGeneratorIntegrationTest.java
@@ -1,6 +1,5 @@
package com.baeldung.cglib.proxy;
-
import net.sf.cglib.beans.BeanGenerator;
import org.junit.Test;
@@ -12,21 +11,17 @@ public class BeanGeneratorIntegrationTest {
@Test
public void givenBeanCreator_whenAddProperty_thenClassShouldHaveFieldValue() throws Exception {
- //given
+ // given
BeanGenerator beanGenerator = new BeanGenerator();
- //when
+ // when
beanGenerator.addProperty("name", String.class);
Object myBean = beanGenerator.create();
- Method setter = myBean
- .getClass()
- .getMethod("setName", String.class);
+ Method setter = myBean.getClass().getMethod("setName", String.class);
setter.invoke(myBean, "some string value set by a cglib");
- //then
- Method getter = myBean
- .getClass()
- .getMethod("getName");
+ // then
+ Method getter = myBean.getClass().getMethod("getName");
assertEquals("some string value set by a cglib", getter.invoke(myBean));
}
}
diff --git a/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java b/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java
index 93b34bf92b..fc2f6cc1e1 100644
--- a/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java
+++ b/libraries/src/test/java/com/baeldung/cglib/proxy/MixinUnitTest.java
@@ -14,14 +14,11 @@ public class MixinUnitTest {
@Test
public void givenTwoClasses_whenMixedIntoOne_thenMixinShouldHaveMethodsFromBothClasses() throws Exception {
- //when
- Mixin mixin = Mixin.create(
- new Class[]{Interface1.class, Interface2.class, MixinInterface.class},
- new Object[]{new Class1(), new Class2()}
- );
+ // when
+ Mixin mixin = Mixin.create(new Class[] { Interface1.class, Interface2.class, MixinInterface.class }, new Object[] { new Class1(), new Class2() });
MixinInterface mixinDelegate = (MixinInterface) mixin;
- //then
+ // then
assertEquals("first behaviour", mixinDelegate.first());
assertEquals("second behaviour", mixinDelegate.second());
}
diff --git a/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java b/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java
index c22a148d4f..d5c8a1b589 100644
--- a/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java
+++ b/libraries/src/test/java/com/baeldung/cglib/proxy/ProxyIntegrationTest.java
@@ -10,34 +10,34 @@ import static org.junit.Assert.assertEquals;
public class ProxyIntegrationTest {
@Test
public void givenPersonService_whenSayHello_thenReturnResult() {
- //given
+ // given
PersonService personService = new PersonService();
- //when
+ // when
String res = personService.sayHello("Tom");
- //then
+ // then
assertEquals(res, "Hello Tom");
}
@Test
public void givenEnhancerProxy_whenExtendPersonService_thenInterceptMethod() throws Exception {
- //given
+ // given
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class);
enhancer.setCallback((FixedValue) () -> "Hello Tom!");
PersonService proxy = (PersonService) enhancer.create();
- //when
+ // when
String res = proxy.sayHello(null);
- //then
+ // then
assertEquals("Hello Tom!", res);
}
@Test
public void givenEnhancer_whenExecuteMethodOnProxy_thenInterceptOnlyStringReturnTypeMethod() throws Exception {
- //given
+ // given
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(PersonService.class);
enhancer.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
@@ -48,10 +48,10 @@ public class ProxyIntegrationTest {
}
});
- //when
+ // when
PersonService proxy = (PersonService) enhancer.create();
- //then
+ // then
assertEquals("Hello Tom!", proxy.sayHello(null));
int lengthOfName = proxy.lengthOfName("Mary");
assertEquals(4, lengthOfName);
diff --git a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java
index 9c0a0ac910..00e9500318 100644
--- a/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java
+++ b/libraries/src/test/java/com/baeldung/chronicle/queue/ChronicleQueueIntegrationTest.java
@@ -14,12 +14,12 @@ import net.openhft.chronicle.ExcerptTailer;
import net.openhft.chronicle.tools.ChronicleTools;
public class ChronicleQueueIntegrationTest {
-
+
@Test
public void givenSetOfValues_whenWriteToQueue_thenWriteSuccesfully() throws IOException {
File queueDir = Files.createTempDirectory("chronicle-queue").toFile();
ChronicleTools.deleteOnExit(queueDir.getPath());
-
+
Chronicle chronicle = ChronicleQueueBuilder.indexed(queueDir).build();
String stringVal = "Hello World";
int intVal = 101;
@@ -37,7 +37,7 @@ public class ChronicleQueueIntegrationTest {
}
tailer.finish();
tailer.close();
- chronicle.close();
+ chronicle.close();
}
}
diff --git a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java b/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java
similarity index 86%
rename from libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java
rename to libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java
index 5407477a00..833d91b2c4 100644
--- a/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceTest.java
+++ b/libraries/src/test/java/com/baeldung/commons/beanutils/CourseServiceUnitTest.java
@@ -7,11 +7,10 @@ import java.util.List;
import org.junit.Assert;
import org.junit.Test;
-public class CourseServiceTest {
+public class CourseServiceUnitTest {
@Test
- public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues()
- throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
+ public void givenCourse_whenSetValuesUsingPropertyUtil_thenReturnSetValues() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Course course = new Course();
String name = "Computer Science";
List codes = Arrays.asList("CS", "CS01");
@@ -36,8 +35,7 @@ public class CourseServiceTest {
}
@Test
- public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName()
- throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
+ public void givenCopyProperties_whenCopyCourseToCourseEntity_thenCopyPropertyWithSameName() throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Course course = new Course();
course.setName("Computer Science");
course.setCodes(Arrays.asList("CS"));
diff --git a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java
index aa8b799c9d..f34f431d8e 100644
--- a/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java
+++ b/libraries/src/test/java/com/baeldung/commons/collections/CollectionUtilsGuideTest.java
@@ -1,6 +1,5 @@
package com.baeldung.commons.collections;
-
import com.baeldung.commons.collectionutil.Address;
import com.baeldung.commons.collectionutil.Customer;
import org.apache.commons.collections4.CollectionUtils;
@@ -21,7 +20,6 @@ import static org.junit.Assert.assertTrue;
public class CollectionUtilsGuideTest {
-
Customer customer1 = new Customer(1, "Daniel", 123456l, "locality1", "city1", "1234");
Customer customer4 = new Customer(4, "Bob", 456789l, "locality4", "city4", "4567");
List list1, list2, list3, linkedList1;
@@ -77,8 +75,8 @@ public class CollectionUtilsGuideTest {
}
});
- //filterInverse does the opposite. It removes the element from the list if the Predicate returns true
- //select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection
+ // filterInverse does the opposite. It removes the element from the list if the Predicate returns true
+ // select and selectRejected work the same way except that they do not remove elements from the given collection and return a new collection
assertTrue(isModified && linkedList1.size() == 2);
}
@@ -88,8 +86,8 @@ public class CollectionUtilsGuideTest {
List emptyList = new ArrayList<>();
List nullList = null;
- //Very handy at times where we want to check if a collection is not null and not empty too.
- //isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading
+ // Very handy at times where we want to check if a collection is not null and not empty too.
+ // isNotEmpty does the opposite. Handy because using ! operator on isEmpty makes it missable while reading
assertTrue(CollectionUtils.isNotEmpty(list1));
assertTrue(CollectionUtils.isEmpty(nullList));
assertTrue(CollectionUtils.isEmpty(emptyList));
diff --git a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java
index 4685d84781..988335b7d1 100644
--- a/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java
+++ b/libraries/src/test/java/com/baeldung/commons/collections/MapUtilsTest.java
@@ -1,6 +1,5 @@
package com.baeldung.commons.collections;
-import org.apache.commons.collections4.MapIterator;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.collections4.PredicateUtils;
import org.apache.commons.collections4.TransformerUtils;
@@ -8,35 +7,20 @@ import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Test;
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
-import java.util.Set;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.collection.IsMapContaining.hasEntry;
import static org.hamcrest.collection.IsMapWithSize.aMapWithSize;
import static org.hamcrest.collection.IsMapWithSize.anEmptyMap;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
public class MapUtilsTest {
- private String[][] color2DArray = new String[][]{
- {"RED", "#FF0000"},
- {"GREEN", "#00FF00"},
- {"BLUE", "#0000FF"}
- };
- private String[] color1DArray = new String[]{
- "RED", "#FF0000",
- "GREEN", "#00FF00",
- "BLUE", "#0000FF"
- };
+ private String[][] color2DArray = new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } };
+ private String[] color1DArray = new String[] { "RED", "#FF0000", "GREEN", "#00FF00", "BLUE", "#0000FF" };
private Map colorMap;
@Before
@@ -92,34 +76,26 @@ public class MapUtilsTest {
Map invColorMap = MapUtils.invertMap(this.colorMap);
int size = invColorMap.size();
- Assertions.assertThat(invColorMap)
- .hasSameSizeAs(colorMap)
- .containsKeys(this.colorMap.values().toArray(new String[size]))
- .containsValues(this.colorMap.keySet().toArray(new String[size]));
+ Assertions.assertThat(invColorMap).hasSameSizeAs(colorMap).containsKeys(this.colorMap.values().toArray(new String[size])).containsValues(this.colorMap.keySet().toArray(new String[size]));
}
@Test(expected = IllegalArgumentException.class)
public void whenCreateFixedSizedMapAndAdd_thenMustThrowException() {
- Map rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(
- new HashMap(),
- this.color1DArray));
+ Map rgbMap = MapUtils.fixedSizeMap(MapUtils.putAll(new HashMap(), this.color1DArray));
rgbMap.put("ORANGE", "#FFA500");
}
@Test(expected = IllegalArgumentException.class)
public void whenAddDuplicateToUniqueValuesPredicateMap_thenMustThrowException() {
- Map uniqValuesMap
- = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate());
+ Map uniqValuesMap = MapUtils.predicatedMap(this.colorMap, null, PredicateUtils.uniquePredicate());
uniqValuesMap.put("NEW_RED", "#FF0000");
}
@Test
public void whenCreateLazyMap_theMapIsCreated() {
- Map intStrMap = MapUtils.lazyMap(
- new HashMap(),
- TransformerUtils.stringValueTransformer());
+ Map intStrMap = MapUtils.lazyMap(new HashMap(), TransformerUtils.stringValueTransformer());
assertThat(intStrMap, is(anEmptyMap()));
diff --git a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java
index 7d214bc5c5..aa73ed6109 100644
--- a/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java
+++ b/libraries/src/test/java/com/baeldung/commons/collections/SetUtilsUnitTest.java
@@ -17,8 +17,7 @@ public class SetUtilsUnitTest {
public void givenSetAndPredicate_whenPredicatedSet_thenValidateSet_and_throw_IllegalArgumentException() {
Set sourceSet = new HashSet<>();
sourceSet.addAll(Arrays.asList("London", "Lagos", "Err Source1"));
- Set validatingSet
- = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L"));
+ Set validatingSet = SetUtils.predicatedSet(sourceSet, (s) -> s.startsWith("L"));
validatingSet.add("Err Source2");
}
diff --git a/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java b/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java
index 7a05228e51..c64143cba7 100644
--- a/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java
+++ b/libraries/src/test/java/com/baeldung/commons/collections/orderedmap/OrderedMapUnitTest.java
@@ -14,8 +14,8 @@ import static org.junit.Assert.assertEquals;
public class OrderedMapUnitTest {
- private String[] names = {"Emily", "Mathew", "Rose", "John", "Anna"};
- private Integer[] ages = {37, 28, 40, 36, 21};
+ private String[] names = { "Emily", "Mathew", "Rose", "John", "Anna" };
+ private Integer[] ages = { 37, 28, 40, 36, 21 };
private int RUNNERS_COUNT = names.length;
diff --git a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java
index 55fadcbf85..4408dcc195 100644
--- a/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java
+++ b/libraries/src/test/java/com/baeldung/commons/collections4/BagTests.java
@@ -15,94 +15,88 @@ import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
public class BagTests {
-
+
@Test
public void givenMultipleCopies_whenAdded_theCountIsKept() {
- Bag bag = new HashBag<>(
- Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
-
+ Bag bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
+
assertThat(bag.getCount(1), equalTo(2));
}
-
+
@Test
public void givenBag_whenBagAddAPILikeCollectionAPI_thenFalse() {
Collection collection = new ArrayList<>();
-
+
// Collection contract defines that add() should return true
assertThat(collection.add(9), is(true));
-
+
// Even when element is already in the collection
collection.add(1);
assertThat(collection.add(1), is(true));
-
+
Bag bag = new HashBag<>();
-
+
// Bag returns true on adding a new element
assertThat(bag.add(9), is(true));
-
+
bag.add(1);
// But breaks the contract with false when it has to increment the count
assertThat(bag.add(1), is(not(true)));
}
-
+
@Test
public void givenDecoratedBag_whenBagAddAPILikeCollectionAPI_thenTrue() {
Bag bag = CollectionBag.collectionBag(new HashBag<>());
-
+
bag.add(1);
// This time the behavior is compliant to the Java Collection
assertThat(bag.add(1), is((true)));
}
-
+
@Test
public void givenAdd_whenCountOfElementsDefined_thenCountAreAdded() {
Bag bag = new HashBag<>();
-
+
// Adding 1 for 5 times
bag.add(1, 5);
assertThat(bag.getCount(1), equalTo(5));
}
-
+
@Test
public void givenMultipleCopies_whenRemove_allAreRemoved() {
- Bag bag = new HashBag<>(
- Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
-
+ Bag bag = new HashBag<>(Arrays.asList(new Integer[] { 1, 2, 3, 3, 3, 1, 4 }));
+
// From 3 we delete 1, 2 remain
bag.remove(3, 1);
assertThat(bag.getCount(3), equalTo(2));
-
+
// From 2 we delete all
bag.remove(1);
assertThat(bag.getCount(1), equalTo(0));
}
-
+
@Test
public void givenTree_whenDuplicateElementsAdded_thenSort() {
- TreeBag bag = new TreeBag<>(
- Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }));
-
+ TreeBag bag = new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 }));
+
assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2));
assertThat(bag.last(), equalTo(7));
assertThat(bag.getCount(bag.last()), equalTo(3));
}
-
+
@Test
public void givenDecoratedTree_whenTreeAddAPILikeCollectionAPI_thenTrue() {
- SortedBag bag = CollectionSortedBag
- .collectionSortedBag(new TreeBag<>());
-
+ SortedBag bag = CollectionSortedBag.collectionSortedBag(new TreeBag<>());
+
bag.add(1);
assertThat(bag.add(1), is((true)));
}
-
+
@Test
public void givenSortedBag_whenDuplicateElementsAdded_thenSort() {
- SynchronizedSortedBag bag = SynchronizedSortedBag
- .synchronizedSortedBag(new TreeBag<>(
- Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })));
-
+ SynchronizedSortedBag bag = SynchronizedSortedBag.synchronizedSortedBag(new TreeBag<>(Arrays.asList(new Integer[] { 7, 5, 1, 7, 2, 3, 3, 3, 1, 4, 7 })));
+
assertThat(bag.first(), equalTo(1));
assertThat(bag.getCount(bag.first()), equalTo(2));
assertThat(bag.last(), equalTo(7));
diff --git a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java
index 6f47b89396..6210bb51a9 100644
--- a/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java
+++ b/libraries/src/test/java/com/baeldung/commons/csv/CSVReaderWriterTest.java
@@ -29,10 +29,7 @@ public class CSVReaderWriterTest {
@Test
public void givenCSVFile_whenRead_thenContentsAsExpected() throws IOException {
Reader in = new FileReader("src/test/resources/book.csv");
- Iterable records = CSVFormat.DEFAULT
- .withHeader(HEADERS)
- .withFirstRecordAsHeader()
- .parse(in);
+ Iterable records = CSVFormat.DEFAULT.withHeader(HEADERS).withFirstRecordAsHeader().parse(in);
for (CSVRecord record : records) {
String author = record.get("author");
String title = record.get("title");
@@ -52,9 +49,7 @@ public class CSVReaderWriterTest {
}
});
}
- assertEquals(EXPECTED_FILESTREAM, sw
- .toString()
- .trim());
+ assertEquals(EXPECTED_FILESTREAM, sw.toString().trim());
}
}
diff --git a/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java b/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java
index bc7623589c..02cec7d53a 100644
--- a/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java
+++ b/libraries/src/test/java/com/baeldung/commons/dbutils/DbUtilsUnitTest.java
@@ -47,10 +47,8 @@ public class DbUtilsUnitTest {
List