diff --git a/apache-cxf/pom.xml b/apache-cxf/pom.xml
index 53d9d4054c..8918fd4450 100644
--- a/apache-cxf/pom.xml
+++ b/apache-cxf/pom.xml
@@ -1,5 +1,5 @@
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
com.baeldung
apache-cxf
@@ -17,6 +17,7 @@
cxf-spring
cxf-jaxrs-implementation
cxf-aegis
+ sse-jaxrs
diff --git a/apache-cxf/sse-jaxrs/pom.xml b/apache-cxf/sse-jaxrs/pom.xml
new file mode 100644
index 0000000000..d4b6c19d03
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/pom.xml
@@ -0,0 +1,21 @@
+
+
+ 4.0.0
+
+ sse-jaxrs
+ pom
+
+
+ com.baeldung
+ apache-cxf
+ 0.0.1-SNAPSHOT
+
+
+
+ sse-jaxrs-server
+ sse-jaxrs-client
+
+
+
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
new file mode 100644
index 0000000000..0f5406fbc7
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/pom.xml
@@ -0,0 +1,62 @@
+
+
+ 4.0.0
+
+
+ com.baeldung
+ sse-jaxrs
+ 0.0.1-SNAPSHOT
+
+
+ sse-jaxrs-client
+
+
+ 3.2.0
+
+
+
+
+
+ org.codehaus.mojo
+ exec-maven-plugin
+ 1.6.0
+
+
+ singleEvent
+
+ java
+
+
+ com.baeldung.sse.jaxrs.client.SseClientApp
+
+
+
+ broadcast
+
+ java
+
+
+ com.baeldung.sse.jaxrs.client.SseClientBroadcastApp
+
+
+
+
+
+
+
+
+
+ org.apache.cxf
+ cxf-rt-rs-client
+ ${cxf-version}
+
+
+ org.apache.cxf
+ cxf-rt-rs-sse
+ ${cxf-version}
+
+
+
+
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java
new file mode 100644
index 0000000000..5d42b3a243
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientApp.java
@@ -0,0 +1,48 @@
+package com.baeldung.sse.jaxrs.client;
+
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.sse.InboundSseEvent;
+import javax.ws.rs.sse.SseEventSource;
+import java.util.function.Consumer;
+
+public class SseClientApp {
+
+ private static final String url = "http://127.0.0.1:9080/sse-jaxrs-server/sse/stock/prices";
+
+ public static void main(String... args) throws Exception {
+
+ Client client = ClientBuilder.newClient();
+ WebTarget target = client.target(url);
+ try (SseEventSource eventSource = SseEventSource.target(target).build()) {
+
+ eventSource.register(onEvent, onError, onComplete);
+ eventSource.open();
+
+ //Consuming events for one hour
+ Thread.sleep(60 * 60 * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ client.close();
+ System.out.println("End");
+ }
+
+ // A new event is received
+ private static Consumer onEvent = (inboundSseEvent) -> {
+ String data = inboundSseEvent.readData();
+ System.out.println(data);
+ };
+
+ //Error
+ private static Consumer onError = (throwable) -> {
+ throwable.printStackTrace();
+ };
+
+ //Connection close and there is nothing to receive
+ private static Runnable onComplete = () -> {
+ System.out.println("Done!");
+ };
+
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java
new file mode 100644
index 0000000000..9afc187a6d
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/java/com/baeldung/sse/jaxrs/client/SseClientBroadcastApp.java
@@ -0,0 +1,52 @@
+package com.baeldung.sse.jaxrs.client;
+
+import javax.ws.rs.client.Client;
+import javax.ws.rs.client.ClientBuilder;
+import javax.ws.rs.client.WebTarget;
+import javax.ws.rs.sse.InboundSseEvent;
+import javax.ws.rs.sse.SseEventSource;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+
+public class SseClientBroadcastApp {
+
+ private static final String subscribeUrl = "http://localhost:9080/sse-jaxrs-server/sse/stock/subscribe";
+
+
+ public static void main(String... args) throws Exception {
+
+ Client client = ClientBuilder.newClient();
+ WebTarget target = client.target(subscribeUrl);
+ try (final SseEventSource eventSource = SseEventSource.target(target)
+ .reconnectingEvery(5, TimeUnit.SECONDS)
+ .build()) {
+ eventSource.register(onEvent, onError, onComplete);
+ eventSource.open();
+ System.out.println("Wainting for incoming event ...");
+
+ //Consuming events for one hour
+ Thread.sleep(60 * 60 * 1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ client.close();
+ System.out.println("End");
+ }
+
+ // A new event is received
+ private static Consumer onEvent = (inboundSseEvent) -> {
+ String data = inboundSseEvent.readData();
+ System.out.println(data);
+ };
+
+ //Error
+ private static Consumer onError = (throwable) -> {
+ throwable.printStackTrace();
+ };
+
+ //Connection close and there is nothing to receive
+ private static Runnable onComplete = () -> {
+ System.out.println("Done!");
+ };
+
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-client/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
new file mode 100644
index 0000000000..46572a2b75
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/pom.xml
@@ -0,0 +1,85 @@
+
+
+ 4.0.0
+
+
+ com.baeldung
+ sse-jaxrs
+ 0.0.1-SNAPSHOT
+
+
+ sse-jaxrs-server
+ war
+
+
+ 2.4.2
+ false
+ 18.0.0.2
+
+
+
+ ${artifactId}
+
+
+ net.wasdev.wlp.maven.plugins
+ liberty-maven-plugin
+ ${liberty-maven-plugin.version}
+
+
+ io.openliberty
+ openliberty-webProfile8
+ ${openliberty-version}
+ zip
+
+ project
+ true
+ src/main/liberty/config/server.xml
+
+
+
+ install-server
+ prepare-package
+
+ install-server
+ create-server
+ install-feature
+
+
+
+ install-apps
+ package
+
+ install-apps
+
+
+
+
+
+
+
+
+
+
+ javax.ws.rs
+ javax.ws.rs-api
+ 2.1
+ provided
+
+
+ javax.enterprise
+ cdi-api
+ 2.0
+ provided
+
+
+ javax.json.bind
+ javax.json.bind-api
+ 1.0
+ provided
+
+
+
+
+
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java
new file mode 100644
index 0000000000..058d19f045
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/AppConfig.java
@@ -0,0 +1,8 @@
+package com.baeldung.sse.jaxrs;
+
+import javax.ws.rs.ApplicationPath;
+import javax.ws.rs.core.Application;
+
+@ApplicationPath("sse")
+public class AppConfig extends Application {
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java
new file mode 100644
index 0000000000..1f60168a1b
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/SseResource.java
@@ -0,0 +1,119 @@
+package com.baeldung.sse.jaxrs;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.inject.Inject;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.sse.OutboundSseEvent;
+import javax.ws.rs.sse.Sse;
+import javax.ws.rs.sse.SseBroadcaster;
+import javax.ws.rs.sse.SseEventSink;
+
+@ApplicationScoped
+@Path("stock")
+public class SseResource {
+
+ @Inject
+ private StockService stockService;
+
+ private Sse sse;
+ private SseBroadcaster sseBroadcaster;
+ private OutboundSseEvent.Builder eventBuilder;
+
+ @Context
+ public void setSse(Sse sse) {
+ this.sse = sse;
+ this.eventBuilder = sse.newEventBuilder();
+ this.sseBroadcaster = sse.newBroadcaster();
+ }
+
+ @GET
+ @Path("prices")
+ @Produces("text/event-stream")
+ public void getStockPrices(@Context SseEventSink sseEventSink,
+ @HeaderParam(HttpHeaders.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastReceivedId) {
+
+ int lastEventId = 1;
+ if (lastReceivedId != -1) {
+ lastEventId = ++lastReceivedId;
+ }
+ boolean running = true;
+ while (running) {
+ Stock stock = stockService.getNextTransaction(lastEventId);
+ if (stock != null) {
+ OutboundSseEvent sseEvent = this.eventBuilder
+ .name("stock")
+ .id(String.valueOf(lastEventId))
+ .mediaType(MediaType.APPLICATION_JSON_TYPE)
+ .data(Stock.class, stock)
+ .reconnectDelay(3000)
+ .comment("price change")
+ .build();
+ sseEventSink.send(sseEvent);
+ lastEventId++;
+ }
+ //Simulate connection close
+ if (lastEventId % 5 == 0) {
+ sseEventSink.close();
+ break;
+ }
+
+ try {
+ //Wait 5 seconds
+ Thread.sleep(5 * 1000);
+ } catch (InterruptedException ex) {
+ // ...
+ }
+ //Simulatae a while boucle break
+ running = lastEventId <= 2000;
+ }
+ sseEventSink.close();
+ }
+
+ @GET
+ @Path("subscribe")
+ @Produces(MediaType.SERVER_SENT_EVENTS)
+ public void listen(@Context SseEventSink sseEventSink) {
+ sseEventSink.send(sse.newEvent("Welcome !"));
+ this.sseBroadcaster.register(sseEventSink);
+ sseEventSink.send(sse.newEvent("You are registred !"));
+ }
+
+ @GET
+ @Path("publish")
+ public void broadcast() {
+ Runnable r = new Runnable() {
+ @Override
+ public void run() {
+ int lastEventId = 0;
+ boolean running = true;
+ while (running) {
+ lastEventId++;
+ Stock stock = stockService.getNextTransaction(lastEventId);
+ if (stock != null) {
+ OutboundSseEvent sseEvent = eventBuilder
+ .name("stock")
+ .id(String.valueOf(lastEventId))
+ .mediaType(MediaType.APPLICATION_JSON_TYPE)
+ .data(Stock.class, stock)
+ .reconnectDelay(3000)
+ .comment("price change")
+ .build();
+ sseBroadcaster.broadcast(sseEvent);
+ }
+ try {
+ //Wait 5 seconds
+ Thread.currentThread().sleep(5 * 1000);
+ } catch (InterruptedException ex) {
+ // ...
+ }
+ //Simulatae a while boucle break
+ running = lastEventId <= 2000;
+ }
+ }
+ };
+ new Thread(r).start();
+ }
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java
new file mode 100644
index 0000000000..a186b32771
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/Stock.java
@@ -0,0 +1,50 @@
+package com.baeldung.sse.jaxrs;
+
+import java.math.BigDecimal;
+import java.time.LocalDateTime;
+
+public class Stock {
+ private Integer id;
+ private String name;
+ private BigDecimal price;
+ LocalDateTime dateTime;
+
+ public Stock(Integer id, String name, BigDecimal price, LocalDateTime dateTime) {
+ this.id = id;
+ this.name = name;
+ this.price = price;
+ this.dateTime = dateTime;
+ }
+
+ public Integer getId() {
+ return id;
+ }
+
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public BigDecimal getPrice() {
+ return price;
+ }
+
+ public void setPrice(BigDecimal price) {
+ this.price = price;
+ }
+
+ public LocalDateTime getDateTime() {
+ return dateTime;
+ }
+
+ public void setDateTime(LocalDateTime dateTime) {
+ this.dateTime = dateTime;
+ }
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java
new file mode 100644
index 0000000000..15818ead5d
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/java/com/baeldung/sse/jaxrs/StockService.java
@@ -0,0 +1,78 @@
+package com.baeldung.sse.jaxrs;
+
+import javax.enterprise.context.ApplicationScoped;
+import javax.enterprise.context.Initialized;
+import javax.enterprise.event.Event;
+import javax.enterprise.event.Observes;
+import javax.inject.Inject;
+import javax.inject.Named;
+import java.math.BigDecimal;
+import java.math.RoundingMode;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicInteger;
+
+@ApplicationScoped
+@Named
+public class StockService {
+
+ private static final BigDecimal UP = BigDecimal.valueOf(1.05f);
+ private static final BigDecimal DOWN = BigDecimal.valueOf(0.95f);
+
+ List stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO");
+ List stocksDB = new ArrayList<>();
+ private AtomicInteger counter = new AtomicInteger(0);
+
+ public void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
+ //Open price
+ System.out.println("@Start Init ...");
+ stockNames.forEach(stockName -> {
+ stocksDB.add(new Stock(counter.incrementAndGet(), stockName, generateOpenPrice(), LocalDateTime.now()));
+ });
+
+ Runnable runnable = new Runnable() {
+ @Override
+ public void run() {
+ //Simulate Change price and put every x seconds
+ while (true) {
+ int indx = new Random().nextInt(stockNames.size());
+ String stockName = stockNames.get(indx);
+ BigDecimal price = getLastPrice(stockName);
+ BigDecimal newprice = changePrice(price);
+ Stock stock = new Stock(counter.incrementAndGet(), stockName, newprice, LocalDateTime.now());
+ stocksDB.add(stock);
+
+ int r = new Random().nextInt(30);
+ try {
+ Thread.currentThread().sleep(r*1000);
+ } catch (InterruptedException ex) {
+ // ...
+ }
+ }
+ }
+ };
+ new Thread(runnable).start();
+ System.out.println("@End Init ...");
+ }
+
+ public Stock getNextTransaction(Integer lastEventId) {
+ return stocksDB.stream().filter(s -> s.getId().equals(lastEventId)).findFirst().orElse(null);
+ }
+
+ BigDecimal generateOpenPrice() {
+ float min = 70;
+ float max = 120;
+ return BigDecimal.valueOf(min + new Random().nextFloat() * (max - min)).setScale(4,RoundingMode.CEILING);
+ }
+
+ BigDecimal changePrice(BigDecimal price) {
+ return Math.random() >= 0.5 ? price.multiply(UP).setScale(4,RoundingMode.CEILING) : price.multiply(DOWN).setScale(4,RoundingMode.CEILING);
+ }
+
+ private BigDecimal getLastPrice(String stockName) {
+ return stocksDB.stream().filter(stock -> stock.getName().equals(stockName)).findFirst().get().getPrice();
+ }
+}
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml
new file mode 100644
index 0000000000..9bf66d7795
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/liberty/config/server.xml
@@ -0,0 +1,7 @@
+
+
+ jaxrs-2.1
+ cdi-2.0
+
+
+
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml
new file mode 100644
index 0000000000..4f0b3cdeeb
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/META-INF/beans.xml
@@ -0,0 +1,6 @@
+
+
\ No newline at end of file
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml
new file mode 100644
index 0000000000..7d900d8ea8
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/resources/logback.xml
@@ -0,0 +1,13 @@
+
+
+
+
+ %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml
new file mode 100644
index 0000000000..b4b8121fdd
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/WEB-INF/web.xml
@@ -0,0 +1,11 @@
+
+
+ Hello Servlet
+
+
+ index.html
+
+
+
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html
new file mode 100644
index 0000000000..9015a7a32c
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/index.html
@@ -0,0 +1 @@
+index
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html
new file mode 100644
index 0000000000..5a46e2a5d3
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse-broadcast.html
@@ -0,0 +1,38 @@
+
+
+
+ Server-Sent Event Broadcasting
+
+
+Stock prices :
+
+
+
+
\ No newline at end of file
diff --git a/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html
new file mode 100644
index 0000000000..8fddae4717
--- /dev/null
+++ b/apache-cxf/sse-jaxrs/sse-jaxrs-server/src/main/webapp/sse.html
@@ -0,0 +1,38 @@
+
+
+
+ Server-Sent Event
+
+
+Stock prices :
+
+
+
+
\ No newline at end of file
diff --git a/core-java-collections/pom.xml b/core-java-collections/pom.xml
index 1290419a6a..92e4278593 100644
--- a/core-java-collections/pom.xml
+++ b/core-java-collections/pom.xml
@@ -53,15 +53,27 @@
${junit.platform.version}
test
+
+ org.openjdk.jmh
+ jmh-core
+ ${openjdk.jmh.version}
+
+
+ org.openjdk.jmh
+ jmh-generator-annprocess
+ ${openjdk.jmh.version}
+
+
+ 1.19
1.2.0
3.5
4.1
4.01
1.7.0
3.6.1
- 9.2.0
+ 7.1.0
diff --git a/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java
new file mode 100644
index 0000000000..921e1608ea
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/performance/CollectionsBenchmark.java
@@ -0,0 +1,59 @@
+package com.baeldung.performance;
+
+import org.openjdk.jmh.annotations.*;
+import org.openjdk.jmh.runner.Runner;
+import org.openjdk.jmh.runner.options.Options;
+import org.openjdk.jmh.runner.options.OptionsBuilder;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+@BenchmarkMode(Mode.AverageTime)
+@OutputTimeUnit(TimeUnit.NANOSECONDS)
+@Warmup(iterations = 5)
+public class CollectionsBenchmark {
+
+ @State(Scope.Thread)
+ public static class MyState {
+ private Set employeeSet = new HashSet<>();
+ private List employeeList = new ArrayList<>();
+
+ private long iterations = 10000;
+
+ private Employee employee = new Employee(100L, "Harry");
+
+ @Setup(Level.Trial)
+ public void setUp() {
+
+ for (long i = 0; i < iterations; i++) {
+ employeeSet.add(new Employee(i, "John"));
+ employeeList.add(new Employee(i, "John"));
+ }
+
+ employeeList.add(employee);
+ employeeSet.add(employee);
+ }
+ }
+
+ @Benchmark
+ public boolean testArrayList(MyState state) {
+ return state.employeeList.contains(state.employee);
+ }
+
+ @Benchmark
+ public boolean testHashSet(MyState state) {
+ return state.employeeSet.contains(state.employee);
+ }
+
+ public static void main(String[] args) throws Exception {
+ Options options = new OptionsBuilder()
+ .include(CollectionsBenchmark.class.getSimpleName()).threads(1)
+ .forks(1).shouldFailOnError(true)
+ .shouldDoGC(true)
+ .jvmArgs("-server").build();
+ new Runner(options).run();
+ }
+}
diff --git a/core-java-collections/src/main/java/com/baeldung/performance/Employee.java b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java
new file mode 100644
index 0000000000..daa68ae2f1
--- /dev/null
+++ b/core-java-collections/src/main/java/com/baeldung/performance/Employee.java
@@ -0,0 +1,31 @@
+package com.baeldung.performance;
+
+public class Employee {
+
+ private Long id;
+ private String name;
+
+ public Employee(Long id, String name) {
+ this.name = name;
+ this.id = id;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ Employee employee = (Employee) o;
+
+ if (!id.equals(employee.id)) return false;
+ return name.equals(employee.name);
+
+ }
+
+ @Override
+ public int hashCode() {
+ int result = id.hashCode();
+ result = 31 * result + name.hashCode();
+ return result;
+ }
+}
diff --git a/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java b/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java
new file mode 100644
index 0000000000..202fe00017
--- /dev/null
+++ b/core-java-collections/src/test/java/com/baeldung/collection/StreamOperateAndRemoveUnitTest.java
@@ -0,0 +1,78 @@
+package com.baeldung.collection;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class StreamOperateAndRemoveUnitTest {
+
+ private List- itemList;
+
+ @Before
+ public void setup() {
+
+ itemList = new ArrayList<>();
+ for (int i = 0; i < 10; i++) {
+ itemList.add(new Item(i));
+ }
+ }
+
+ @Test
+ public void givenAListOf10Items_whenFilteredForQualifiedItems_thenFilteredListContains5Items() {
+
+ final List
- filteredList = itemList.stream().filter(item -> item.isQualified())
+ .collect(Collectors.toList());
+
+ Assert.assertEquals(5, filteredList.size());
+ }
+
+ @Test
+ public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveIf_thenListContains5Items() {
+
+ itemList.stream().filter(item -> item.isQualified()).forEach(item -> item.operate());
+ itemList.removeIf(item -> item.isQualified());
+
+ Assert.assertEquals(5, itemList.size());
+ }
+
+ @Test
+ public void givenAListOf10Items_whenOperateAndRemoveQualifiedItemsUsingRemoveAll_thenListContains5Items() {
+
+ final List
- operatedList = new ArrayList<>();
+ itemList.stream().filter(item -> item.isQualified()).forEach(item -> {
+ item.operate();
+ operatedList.add(item);
+ });
+ itemList.removeAll(operatedList);
+
+ Assert.assertEquals(5, itemList.size());
+ }
+
+ class Item {
+
+ private final Logger logger = LoggerFactory.getLogger(this.getClass().getName());
+
+ private final int value;
+
+ public Item(final int value) {
+
+ this.value = value;
+ }
+
+ public boolean isQualified() {
+
+ return value % 2 == 0;
+ }
+
+ public void operate() {
+
+ logger.info("Even Number: " + this.value);
+ }
+ }
+}
\ No newline at end of file
diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java
new file mode 100644
index 0000000000..45ff486a79
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/fileparser/BufferedReaderExample.java
@@ -0,0 +1,24 @@
+package com.baeldung.fileparser;
+
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+
+public class BufferedReaderExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
+
+ while (br.ready()) {
+ result.add(br.readLine());
+ }
+ return result;
+ }
+
+ }
+
+}
diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java
new file mode 100644
index 0000000000..f9dd2a9ec5
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/fileparser/FileReaderExample.java
@@ -0,0 +1,31 @@
+package com.baeldung.fileparser;
+
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+
+public class FileReaderExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (FileReader f = new FileReader(filename)) {
+ StringBuffer sb = new StringBuffer();
+ while (f.ready()) {
+ char c = (char) f.read();
+ if (c == '\n') {
+ result.add(sb.toString());
+ sb = new StringBuffer();
+ } else {
+ sb.append(c);
+ }
+ }
+ if (sb.length() > 0) {
+ result.add(sb.toString());
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java
new file mode 100644
index 0000000000..8e74f7d386
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/fileparser/FilesReadLinesExample.java
@@ -0,0 +1,18 @@
+package com.baeldung.fileparser;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.List;
+
+public class FilesReadLinesExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ List result = Files.readAllLines(Paths.get(filename));
+
+ return (ArrayList) result;
+ }
+
+}
diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java
new file mode 100644
index 0000000000..25d17af4ea
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerIntExample.java
@@ -0,0 +1,24 @@
+package com.baeldung.fileparser;
+
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Scanner;
+
+public class ScannerIntExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (Scanner s = new Scanner(new FileReader(filename))) {
+
+ while (s.hasNext()) {
+ result.add(s.nextInt());
+ }
+ return result;
+ }
+
+ }
+
+}
diff --git a/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java
new file mode 100644
index 0000000000..ec213c9490
--- /dev/null
+++ b/core-java-io/src/main/java/com/baeldung/fileparser/ScannerStringExample.java
@@ -0,0 +1,24 @@
+package com.baeldung.fileparser;
+
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Scanner;
+
+public class ScannerStringExample {
+
+ protected static ArrayList generateArrayListFromFile(String filename) throws IOException {
+
+ ArrayList result = new ArrayList<>();
+
+ try (Scanner s = new Scanner(new FileReader(filename))) {
+
+ while (s.hasNext()) {
+ result.add(s.nextLine());
+ }
+ return result;
+ }
+
+ }
+
+}
diff --git a/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java
index 47a7973b34..f9a2ce972d 100644
--- a/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java
+++ b/core-java-io/src/test/java/com/baeldung/file/FilenameFilterManualTest.java
@@ -18,7 +18,7 @@ public class FilenameFilterManualTest {
@BeforeClass
public static void setupClass() {
directory = new File(FilenameFilterManualTest.class.getClassLoader()
- .getResource("testFolder")
+ .getResource("fileNameFilterManualTestFolder")
.getFile());
}
diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java
new file mode 100644
index 0000000000..78f900d796
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/fileparser/BufferedReaderUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class BufferedReaderUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java
new file mode 100644
index 0000000000..a38e58d348
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/fileparser/FileReaderUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class FileReaderUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java
new file mode 100644
index 0000000000..c0b742fd47
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/fileparser/FilesReadAllLinesUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class FilesReadAllLinesUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java
new file mode 100644
index 0000000000..0a398ba7c6
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerIntUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ScannerIntUnitTest {
+
+ protected static final String NUMBER_FILENAME = "src/test/resources/sampleNumberFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetIntArrayList() throws IOException {
+ List numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME);
+ assertTrue("File does not has 2 lines", numbers.size() == 2);
+ }
+}
diff --git a/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java
new file mode 100644
index 0000000000..8f9b0a56c0
--- /dev/null
+++ b/core-java-io/src/test/java/com/baeldung/fileparser/ScannerStringUnitTest.java
@@ -0,0 +1,19 @@
+package com.baeldung.fileparser;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.junit.Test;
+
+public class ScannerStringUnitTest {
+
+ protected static final String TEXT_FILENAME = "src/test/resources/sampleTextFile.txt";
+
+ @Test
+ public void whenParsingExistingTextFile_thenGetArrayList() throws IOException {
+ List lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME);
+ assertTrue("File does not has 2 lines", lines.size() == 2);
+ }
+}
diff --git a/core-java-io/src/test/resources/testFolder/people.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json
similarity index 100%
rename from core-java-io/src/test/resources/testFolder/people.json
rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/people.json
diff --git a/core-java-io/src/test/resources/testFolder/students.json b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json
similarity index 100%
rename from core-java-io/src/test/resources/testFolder/students.json
rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/students.json
diff --git a/core-java-io/src/test/resources/testFolder/teachers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml
similarity index 100%
rename from core-java-io/src/test/resources/testFolder/teachers.xml
rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/teachers.xml
diff --git a/core-java-io/src/test/resources/testFolder/workers.xml b/core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml
similarity index 100%
rename from core-java-io/src/test/resources/testFolder/workers.xml
rename to core-java-io/src/test/resources/fileNameFilterManualTestFolder/workers.xml
diff --git a/core-java-io/src/test/resources/sampleNumberFile.txt b/core-java-io/src/test/resources/sampleNumberFile.txt
new file mode 100644
index 0000000000..7787faa3c1
--- /dev/null
+++ b/core-java-io/src/test/resources/sampleNumberFile.txt
@@ -0,0 +1,2 @@
+111
+222
\ No newline at end of file
diff --git a/core-java-io/src/test/resources/sampleTextFile.txt b/core-java-io/src/test/resources/sampleTextFile.txt
new file mode 100644
index 0000000000..75cb50aafa
--- /dev/null
+++ b/core-java-io/src/test/resources/sampleTextFile.txt
@@ -0,0 +1,2 @@
+Hello
+World
\ No newline at end of file
diff --git a/core-java/src/main/java/com/baeldung/binding/Animal.java b/core-java/src/main/java/com/baeldung/binding/Animal.java
new file mode 100644
index 0000000000..12eaa2a7a3
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/binding/Animal.java
@@ -0,0 +1,23 @@
+package com.baeldung.binding;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Created by madhumita.g on 25-07-2018.
+ */
+public class Animal {
+
+ final static Logger logger = LoggerFactory.getLogger(Animal.class);
+
+ public void makeNoise() {
+ logger.info("generic animal noise");
+ }
+
+ public void makeNoise(Integer repetitions) {
+ while(repetitions != 0) {
+ logger.info("generic animal noise countdown " + repetitions);
+ repetitions -= 1;
+ }
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java b/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java
new file mode 100644
index 0000000000..1bd36123e3
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/binding/AnimalActivity.java
@@ -0,0 +1,43 @@
+package com.baeldung.binding;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Created by madhumita.g on 25-07-2018.
+ */
+public class AnimalActivity {
+
+ final static Logger logger = LoggerFactory.getLogger(AnimalActivity.class);
+
+
+ public static void sleep(Animal animal) {
+ logger.info("Animal is sleeping");
+ }
+
+ public static void sleep(Cat cat) {
+ logger.info("Cat is sleeping");
+ }
+
+ public static void main(String[] args) {
+
+ Animal animal = new Animal();
+
+ //calling methods of animal object
+ animal.makeNoise();
+
+ animal.makeNoise(3);
+
+
+ //assigning a dog object to reference of type Animal
+ Animal catAnimal = new Cat();
+
+ catAnimal.makeNoise();
+
+ // calling static function
+ AnimalActivity.sleep(catAnimal);
+
+ return;
+
+ }
+}
diff --git a/core-java/src/main/java/com/baeldung/binding/Cat.java b/core-java/src/main/java/com/baeldung/binding/Cat.java
new file mode 100644
index 0000000000..bbe740e412
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/binding/Cat.java
@@ -0,0 +1,18 @@
+package com.baeldung.binding;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Created by madhumita.g on 25-07-2018.
+ */
+public class Cat extends Animal {
+
+ final static Logger logger = LoggerFactory.getLogger(Cat.class);
+
+ public void makeNoise() {
+
+ logger.info("meow");
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java
index eb8b733f82..48f4b5c02b 100644
--- a/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java
+++ b/core-java/src/main/java/com/baeldung/exceptionhandling/Exceptions.java
@@ -25,11 +25,7 @@ public class Exceptions {
}
public List loadAllPlayers(String playersFile) throws IOException{
- try {
- throw new IOException();
- } catch(IOException ex) {
- throw new IllegalStateException();
- }
+ throw new IOException();
}
public int getPlayerScoreThrows(String playerFile) throws FileNotFoundException {
@@ -163,14 +159,8 @@ public class Exceptions {
}
}
- public void throwAsGotoAntiPattern() {
- try {
- // bunch of code
- throw new MyException();
- // second bunch of code
- } catch ( MyException e ) {
- // third bunch of code
- }
+ public void throwAsGotoAntiPattern() throws MyException {
+ throw new MyException();
}
public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) {
diff --git a/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java b/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java
new file mode 100644
index 0000000000..af0449c0da
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keywords/finalize/FinalizeObject.java
@@ -0,0 +1,18 @@
+package com.baeldung.keywords.finalize;
+
+public class FinalizeObject {
+
+ @Override
+ protected void finalize() throws Throwable {
+ System.out.println("Execute finalize method");
+ super.finalize();
+ }
+
+ public static void main(String[] args) throws Exception {
+ FinalizeObject object = new FinalizeObject();
+ object = null;
+ System.gc();
+ Thread.sleep(1000);
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java
new file mode 100644
index 0000000000..8615c78652
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Child.java
@@ -0,0 +1,15 @@
+package com.baeldung.keywords.finalkeyword;
+
+public final class Child extends Parent {
+
+ @Override
+ void method1(int arg1, final int arg2) {
+ // OK
+ }
+
+/* @Override
+ void method2() {
+ // Compilation error
+ }*/
+
+}
diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java
new file mode 100644
index 0000000000..1530c5037f
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/GrandChild.java
@@ -0,0 +1,5 @@
+package com.baeldung.keywords.finalkeyword;
+
+/*public class GrandChild extends Child {
+ // Compilation error
+}*/
diff --git a/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java
new file mode 100644
index 0000000000..5cd2996e7a
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keywords/finalkeyword/Parent.java
@@ -0,0 +1,23 @@
+package com.baeldung.keywords.finalkeyword;
+
+public class Parent {
+
+ int field1 = 1;
+ final int field2 = 2;
+
+ Parent() {
+ field1 = 2; // OK
+// field2 = 3; // Compilation error
+ }
+
+ void method1(int arg1, final int arg2) {
+ arg1 = 2; // OK
+// arg2 = 3; // Compilation error
+ }
+
+ final void method2() {
+ final int localVar = 2; // OK
+// localVar = 3; // Compilation error
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java b/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java
new file mode 100644
index 0000000000..3c0aee3196
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/keywords/finallykeyword/FinallyExample.java
@@ -0,0 +1,29 @@
+package com.baeldung.keywords.finallykeyword;
+
+public class FinallyExample {
+
+ public static void main(String args[]) throws Exception {
+ try {
+ System.out.println("Execute try block");
+ throw new Exception();
+ } catch (Exception e) {
+ System.out.println("Execute catch block");
+ } finally {
+ System.out.println("Execute finally block");
+ }
+
+ try {
+ System.out.println("Execute try block");
+ } finally {
+ System.out.println("Execute finally block");
+ }
+
+ try {
+ System.out.println("Execute try block");
+ throw new Exception();
+ } finally {
+ System.out.println("Execute finally block");
+ }
+ }
+
+}
diff --git a/core-java/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java b/core-java/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java
new file mode 100644
index 0000000000..ccae942dcc
--- /dev/null
+++ b/core-java/src/main/java/com/baeldung/regexp/datepattern/optmization/OptimizedMatcher.java
@@ -0,0 +1,6 @@
+package com.baeldung.regexp.datepattern.optmization;
+
+public class OptimizedMatcher {
+
+
+}
diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java
new file mode 100644
index 0000000000..41c67ff389
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/binding/AnimalActivityUnitTest.java
@@ -0,0 +1,95 @@
+package com.baeldung.binding;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.LoggingEvent;
+import ch.qos.logback.core.Appender;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.LoggerFactory;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.verify;
+
+/**
+ *https://gist.github.com/bloodredsun/a041de13e57bf3c6c040
+ */
+@RunWith(MockitoJUnitRunner.class)
+
+public class AnimalActivityUnitTest {
+
+ @Mock
+ private Appender mockAppender;
+ @Captor
+ private ArgumentCaptor captorLoggingEvent;
+
+ @Before
+ public void setup() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.addAppender(mockAppender);
+ }
+
+ @After
+ public void teardown() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.detachAppender(mockAppender);
+ }
+
+ @Test
+ public void givenAnimalReference__whenRefersAnimalObject_shouldCallFunctionWithAnimalParam() {
+
+ Animal animal = new Animal();
+
+ AnimalActivity.sleep(animal);
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("Animal is sleeping"));
+ }
+
+ @Test
+ public void givenDogReference__whenRefersCatObject_shouldCallFunctionWithAnimalParam() {
+
+ Cat cat = new Cat();
+
+ AnimalActivity.sleep(cat);
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("Cat is sleeping"));
+ }
+
+ @Test
+ public void givenAnimaReference__whenRefersDogObject_shouldCallFunctionWithAnimalParam() {
+
+ Animal cat = new Cat();
+
+ AnimalActivity.sleep(cat);
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("Animal is sleeping"));
+ }
+}
\ No newline at end of file
diff --git a/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java
new file mode 100644
index 0000000000..a34640b58a
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/binding/AnimalUnitTest.java
@@ -0,0 +1,87 @@
+package com.baeldung.binding;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.LoggingEvent;
+import ch.qos.logback.core.Appender;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.LoggerFactory;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
+import java.util.List;
+
+/**
+ * Created by madhumita.g on 01-08-2018.
+ */
+
+@RunWith(MockitoJUnitRunner.class)
+public class AnimalUnitTest {
+ @Mock
+ private Appender mockAppender;
+ @Captor
+ private ArgumentCaptor captorLoggingEvent;
+
+ @Before
+ public void setup() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.addAppender(mockAppender);
+ }
+
+ @After
+ public void teardown() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.detachAppender(mockAppender);
+ }
+
+ @Test
+ public void whenCalledWithoutParameters_shouldCallFunctionMakeNoiseWithoutParameters() {
+
+ Animal animal = new Animal();
+
+ animal.makeNoise();
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("generic animal noise"));
+ }
+
+ @Test
+ public void whenCalledWithParameters_shouldCallFunctionMakeNoiseWithParameters() {
+
+ Animal animal = new Animal();
+
+ int testValue = 3;
+ animal.makeNoise(testValue);
+
+ verify(mockAppender,times(3)).doAppend(captorLoggingEvent.capture());
+
+ final List loggingEvents = captorLoggingEvent.getAllValues();
+
+ for(LoggingEvent loggingEvent : loggingEvents)
+ {
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("generic animal noise countdown "+testValue));
+
+ testValue--;
+ }
+ }
+
+}
diff --git a/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java
new file mode 100644
index 0000000000..76ccfb7719
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/binding/CatUnitTest.java
@@ -0,0 +1,62 @@
+package com.baeldung.binding;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.spi.LoggingEvent;
+import ch.qos.logback.core.Appender;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Captor;
+import org.mockito.Mock;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.slf4j.LoggerFactory;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.verify;
+
+/**
+ * Created by madhumita.g on 01-08-2018.
+ */
+@RunWith(MockitoJUnitRunner.class)
+public class CatUnitTest {
+
+ @Mock
+ private Appender mockAppender;
+
+ @Captor
+ private ArgumentCaptor captorLoggingEvent;
+
+ @Before
+ public void setup() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.addAppender(mockAppender);
+ }
+
+ @After
+ public void teardown() {
+ final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ logger.detachAppender(mockAppender);
+ }
+
+ @Test
+ public void makeNoiseTest() {
+
+ Cat cat = new Cat();
+
+ cat.makeNoise();
+
+ verify(mockAppender).doAppend(captorLoggingEvent.capture());
+
+ final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
+
+ assertThat(loggingEvent.getLevel(), is(Level.INFO));
+
+ assertThat(loggingEvent.getFormattedMessage(),
+ is("meow"));
+
+ }
+}
diff --git a/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java
index bc012dae6b..b484eecef7 100644
--- a/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java
+++ b/core-java/src/test/java/com/baeldung/java/listInitialization/ListInitializationUnitTest.java
@@ -9,28 +9,15 @@ import java.util.stream.Stream;
import lombok.extern.java.Log;
import org.junit.Assert;
-import org.junit.Rule;
import org.junit.Test;
-import org.junit.rules.ExpectedException;
@Log
public class ListInitializationUnitTest {
- @Rule
- public ExpectedException exception = ExpectedException.none();
-
@Test
public void givenAnonymousInnerClass_thenInitialiseList() {
List cities = new ArrayList() {
- // Inside declaration of the subclass
-
- // You can have multiple initializer block
{
- log.info("Inside the first initializer block.");
- }
-
- {
- log.info("Inside the second initializer block.");
add("New York");
add("Rio");
add("Tokyo");
@@ -47,11 +34,10 @@ public class ListInitializationUnitTest {
Assert.assertTrue(list.contains("foo"));
}
- @Test
+ @Test(expected = UnsupportedOperationException.class)
public void givenArraysAsList_whenAdd_thenUnsupportedException() {
List list = Arrays.asList("foo", "bar");
- exception.expect(UnsupportedOperationException.class);
list.add("baz");
}
diff --git a/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java
new file mode 100644
index 0000000000..f21a755b01
--- /dev/null
+++ b/core-java/src/test/java/com/baeldung/regexp/optmization/OptimizedMatcherUnitTest.java
@@ -0,0 +1,109 @@
+package com.baeldung.regexp.optmization;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Random;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.junit.Assert.assertTrue;
+
+public class OptimizedMatcherUnitTest {
+
+ private long time;
+ private long mstimePreCompiled;
+ private long mstimeNotPreCompiled;
+
+ private String action;
+
+ private List items;
+
+ @Before
+ public void setup() {
+ Random random = new Random();
+ items = new ArrayList();
+ long average = 0;
+
+ for (int i = 0; i < 100000; ++i) {
+ StringBuilder s = new StringBuilder();
+ int characters = random.nextInt(7) + 1;
+ for (int k = 0; k < characters; ++ k) {
+ char c = (char)(random.nextInt('Z' - 'A') + 'A');
+ int rep = random.nextInt(95) + 5;
+ for (int j = 0; j < rep; ++ j)
+ s.append(c);
+ average += rep;
+ }
+ items.add(s.toString());
+ }
+
+ average /= 100000;
+ System.out.println("generated data, average length: " + average);
+ }
+
+
+ @Test
+ public void givenANotPreCompiledAndAPreCompiledPatternA_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
+
+ testPatterns("A*");
+ assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
+ }
+
+ @Test
+ public void givenANotPreCompiledAndAPreCompiledPatternABC_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
+
+ testPatterns("A*B*C*");
+ assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
+ }
+
+ @Test
+ public void givenANotPreCompiledAndAPreCompiledPatternECWF_whenMatcheItems_thenPreCompiledFasterThanNotPreCompiled() {
+
+ testPatterns("E*C*W*F*");
+ assertTrue(mstimePreCompiled < mstimeNotPreCompiled);
+ }
+
+ private void testPatterns(String regex) {
+ time = System.nanoTime();
+ int matched = 0;
+ int unmatched = 0;
+
+ for (String item : this.items) {
+ if (item.matches(regex)) {
+ ++matched;
+ }
+ else {
+ ++unmatched;
+ }
+ }
+
+ this.action = "uncompiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
+
+ this.mstimeNotPreCompiled = (System.nanoTime() - time) / 1000000;
+ System.out.println(this.action + ": " + mstimeNotPreCompiled + "ms");
+
+ time = System.nanoTime();
+
+ Matcher matcher = Pattern.compile(regex).matcher("");
+ matched = 0;
+ unmatched = 0;
+
+ for (String item : this.items) {
+ if (matcher.reset(item).matches()) {
+ ++matched;
+ }
+ else {
+ ++unmatched;
+ }
+ }
+
+ this.action = "compiled: regex=" + regex + " matched=" + matched + " unmatched=" + unmatched;
+
+ this.mstimePreCompiled = (System.nanoTime() - time) / 1000000;
+ System.out.println(this.action + ": " + mstimePreCompiled + "ms");
+ }
+}
diff --git a/core-kotlin/pom.xml b/core-kotlin/pom.xml
index afa7d8a963..a86359c02f 100644
--- a/core-kotlin/pom.xml
+++ b/core-kotlin/pom.xml
@@ -106,22 +106,22 @@
klaxon
${klaxon.version}
-
- io.ktor
- ktor-server-netty
- ${ktor.io.version}
-
-
- io.ktor
- ktor-gson
- ${ktor.io.version}
-
-
- ch.qos.logback
- logback-classic
- 1.2.1
- test
-
+
+ io.ktor
+ ktor-server-netty
+ ${ktor.io.version}
+
+
+ io.ktor
+ ktor-gson
+ ${ktor.io.version}
+
+
+ ch.qos.logback
+ logback-classic
+ 1.2.1
+ test
+
@@ -166,13 +166,13 @@
${java.version}
-
default-compile
none
-
default-testCompile
@@ -224,10 +224,10 @@
UTF-8
- 1.2.51
- 1.2.51
- 1.2.51
- 1.2.51
+ 1.2.60
+ 1.2.60
+ 1.2.60
+ 1.2.60
0.22.5
0.9.2
1.5.0
@@ -235,9 +235,9 @@
3.0.4
0.1.0
3.6.1
- 1.0.0
+ 1.1.1
5.2.0
3.10.0
-
+
\ No newline at end of file
diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt
new file mode 100644
index 0000000000..72b8d330e8
--- /dev/null
+++ b/core-kotlin/src/main/java/com/baeldung/constructor/Car.kt
@@ -0,0 +1,17 @@
+package com.baeldung.constructor
+
+class Car {
+ val id: String
+ val type: String
+
+ constructor(id: String, type: String) {
+ this.id = id
+ this.type = type
+ }
+
+}
+
+fun main(args: Array) {
+ val car = Car("1", "sport")
+ val s= Car("2", "suv")
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt
new file mode 100644
index 0000000000..4483bfcf08
--- /dev/null
+++ b/core-kotlin/src/main/java/com/baeldung/constructor/Employee.kt
@@ -0,0 +1,3 @@
+package com.baeldung.constructor
+
+class Employee(name: String, val salary: Int): Person(name)
\ No newline at end of file
diff --git a/core-kotlin/src/main/java/com/baeldung/constructor/Person.java b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java
new file mode 100644
index 0000000000..57911b24ee
--- /dev/null
+++ b/core-kotlin/src/main/java/com/baeldung/constructor/Person.java
@@ -0,0 +1,19 @@
+package com.baeldung.constructor;
+
+class PersonJava {
+ final String name;
+ final String surname;
+ final Integer age;
+
+ public PersonJava(String name, String surname) {
+ this.name = name;
+ this.surname = surname;
+ this.age = null;
+ }
+
+ public PersonJava(String name, String surname, Integer age) {
+ this.name = name;
+ this.surname = surname;
+ this.age = age;
+ }
+}
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt
new file mode 100644
index 0000000000..3779d74541
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/constructor/Person.kt
@@ -0,0 +1,26 @@
+package com.baeldung.constructor
+
+open class Person(
+ val name: String,
+ val age: Int? = null
+) {
+ val upperCaseName: String = name.toUpperCase()
+
+ init {
+ println("Hello, I'm $name")
+
+ if (age != null && age < 0) {
+ throw IllegalArgumentException("Age cannot be less than zero!")
+ }
+ }
+
+ init {
+ println("upperCaseName is $upperCaseName")
+ }
+
+}
+
+fun main(args: Array) {
+ val person = Person("John")
+ val personWithAge = Person("John", 22)
+}
\ No newline at end of file
diff --git a/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt
new file mode 100644
index 0000000000..ee01c06646
--- /dev/null
+++ b/core-kotlin/src/main/kotlin/com/baeldung/nested/Computer.kt
@@ -0,0 +1,75 @@
+package com.baeldung.nested
+
+import org.slf4j.Logger
+import org.slf4j.LoggerFactory
+
+class Computer(val model: String) {
+
+ companion object {
+ const val originCountry = "China"
+ fun getBuiltDate(): String {
+ return "2018-05-23"
+ }
+
+ val log: Logger = LoggerFactory.getLogger(Computer::class.java)
+ }
+
+ //Nested class
+ class MotherBoard(val manufacturer: String) {
+ fun getInfo() = "Made by $manufacturer installed in $originCountry - ${getBuiltDate()}"
+ }
+
+ //Inner class
+ inner class HardDisk(val sizeInGb: Int) {
+ fun getInfo() = "Installed on ${this@Computer} with $sizeInGb GB"
+ }
+
+ interface Switcher {
+ fun on(): String
+ }
+
+ interface Protector {
+ fun smart()
+ }
+
+ fun powerOn(): String {
+ //Local class
+ var defaultColor = "Blue"
+
+ class Led(val color: String) {
+ fun blink(): String {
+ return "blinking $color"
+ }
+
+ fun changeDefaultPowerOnColor() {
+ defaultColor = "Violet"
+ }
+ }
+
+ val powerLed = Led("Green")
+ log.debug("defaultColor is $defaultColor")
+ powerLed.changeDefaultPowerOnColor()
+ log.debug("defaultColor changed inside Led class to $defaultColor")
+ //Anonymous object
+ val powerSwitch = object : Switcher, Protector {
+ override fun on(): String {
+ return powerLed.blink()
+ }
+
+ override fun smart() {
+ log.debug("Smart protection is implemented")
+ }
+
+ fun changeDefaultPowerOnColor() {
+ defaultColor = "Yellow"
+ }
+ }
+ powerSwitch.changeDefaultPowerOnColor()
+ log.debug("defaultColor changed inside powerSwitch anonymous object to $defaultColor")
+ return powerSwitch.on()
+ }
+
+ override fun toString(): String {
+ return "Computer(model=$model)"
+ }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt
new file mode 100644
index 0000000000..7882d85b3c
--- /dev/null
+++ b/core-kotlin/src/test/kotlin/com/baeldung/nested/ComputerUnitTest.kt
@@ -0,0 +1,28 @@
+package com.baeldung.nested
+
+import org.assertj.core.api.Assertions.assertThat
+import org.junit.jupiter.api.Test
+
+class ComputerUnitTest {
+
+ @Test
+ fun givenComputer_whenPowerOn_thenBlink() {
+ val computer = Computer("Desktop")
+
+ assertThat(computer.powerOn()).isEqualTo("blinking Green")
+ }
+
+ @Test
+ fun givenMotherboard_whenGetInfo_thenGetInstalledAndBuiltDetails() {
+ val motherBoard = Computer.MotherBoard("MotherBoard Inc.")
+
+ assertThat(motherBoard.getInfo()).isEqualTo("Made by MotherBoard Inc. installed in China - 2018-05-23")
+ }
+
+ @Test
+ fun givenHardDisk_whenGetInfo_thenGetComputerModelAndDiskSizeInGb() {
+ val hardDisk = Computer("Desktop").HardDisk(1000)
+
+ assertThat(hardDisk.getInfo()).isEqualTo("Installed on Computer(model=Desktop) with 1000 GB")
+ }
+}
\ No newline at end of file
diff --git a/core-kotlin/src/test/resources/Kotlin.out b/core-kotlin/src/test/resources/Kotlin.out
new file mode 100644
index 0000000000..63d15d2528
--- /dev/null
+++ b/core-kotlin/src/test/resources/Kotlin.out
@@ -0,0 +1,2 @@
+Kotlin
+Concise, Safe, Interoperable, Tool-friendly
\ No newline at end of file
diff --git a/eclipse/formatter.xml b/eclipse/formatter.xml
index 808f65cda9..6887946a4c 100644
--- a/eclipse/formatter.xml
+++ b/eclipse/formatter.xml
@@ -1,297 +1,5 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java b/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java
new file mode 100644
index 0000000000..69a7505316
--- /dev/null
+++ b/guava/src/test/java/org/baeldung/guava/GuavaMapInitializeUnitTest.java
@@ -0,0 +1,30 @@
+package org.baeldung.guava;
+
+import static org.hamcrest.core.IsEqual.equalTo;
+import static org.junit.Assert.*;
+
+import java.util.Map;
+import org.junit.Test;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Maps;
+
+public class GuavaMapInitializeUnitTest {
+
+ @Test
+ public void givenKeyValuesShoudInitializeMap() {
+ Map articles = ImmutableMap.of("Title", "My New Article", "Title2", "Second Article");
+
+ assertThat(articles.get("Title"), equalTo("My New Article"));
+ assertThat(articles.get("Title2"), equalTo("Second Article"));
+
+ }
+
+
+ @Test
+ public void givenKeyValuesShouldCreateMutableMap() {
+ Map articles = Maps.newHashMap(ImmutableMap.of("Title", "My New Article", "Title2", "Second Article"));
+
+ assertThat(articles.get("Title"), equalTo("My New Article"));
+ assertThat(articles.get("Title2"), equalTo("Second Article"));
+ }
+}
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java
new file mode 100644
index 0000000000..4e00be2b5c
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/DirtyDataInspector.java
@@ -0,0 +1,26 @@
+package com.baeldung.hibernate.lifecycle;
+
+import org.hibernate.EmptyInterceptor;
+import org.hibernate.type.Type;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+public class DirtyDataInspector extends EmptyInterceptor {
+ private static final ArrayList dirtyEntities = new ArrayList<>();
+
+ @Override
+ public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) {
+ dirtyEntities.add((FootballPlayer) entity);
+ return true;
+ }
+
+ public static List getDirtyEntities() {
+ return dirtyEntities;
+ }
+
+ public static void clearDirtyEntitites() {
+ dirtyEntities.clear();
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java
new file mode 100644
index 0000000000..49799a5292
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/FootballPlayer.java
@@ -0,0 +1,35 @@
+package com.baeldung.hibernate.lifecycle;
+
+import javax.persistence.*;
+
+@Entity
+@Table(name = "Football_Player")
+public class FootballPlayer {
+ @Id
+ @GeneratedValue
+ private long id;
+
+ @Column
+ private String name;
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ @Override
+ public String toString() {
+ return "FootballPlayer{" + "id=" + id + ", name='" + name + '\'' + '}';
+ }
+}
\ No newline at end of file
diff --git a/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java
new file mode 100644
index 0000000000..a06685fb9c
--- /dev/null
+++ b/hibernate5/src/main/java/com/baeldung/hibernate/lifecycle/HibernateLifecycleUtil.java
@@ -0,0 +1,96 @@
+package com.baeldung.hibernate.lifecycle;
+
+import org.h2.tools.RunScript;
+import org.hibernate.Session;
+import org.hibernate.SessionFactory;
+import org.hibernate.Transaction;
+import org.hibernate.boot.Metadata;
+import org.hibernate.boot.MetadataSources;
+import org.hibernate.boot.SessionFactoryBuilder;
+import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
+import org.hibernate.engine.spi.EntityEntry;
+import org.hibernate.engine.spi.SessionImplementor;
+import org.hibernate.service.ServiceRegistry;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URL;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.stream.Collectors;
+
+public class HibernateLifecycleUtil {
+ private static SessionFactory sessionFactory;
+ private static Connection connection;
+
+ public static void init() throws Exception {
+ Properties hbConfigProp = getHibernateProperties();
+ Class.forName(hbConfigProp.getProperty("hibernate.connection.driver_class"));
+ connection = DriverManager.getConnection(hbConfigProp.getProperty("hibernate.connection.url"), hbConfigProp.getProperty("hibernate.connection.username"), hbConfigProp.getProperty("hibernate.connection.password"));
+
+ try (InputStream h2InitStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("lifecycle-init.sql");
+ InputStreamReader h2InitReader = new InputStreamReader(h2InitStream)) {
+ RunScript.execute(connection, h2InitReader);
+ }
+
+ ServiceRegistry serviceRegistry = configureServiceRegistry();
+ sessionFactory = getSessionFactoryBuilder(serviceRegistry).applyInterceptor(new DirtyDataInspector()).build();
+ }
+
+ public static void tearDown() throws Exception {
+ sessionFactory.close();
+ connection.close();
+ }
+
+ public static SessionFactory getSessionFactory() {
+ return sessionFactory;
+ }
+
+ private static SessionFactoryBuilder getSessionFactoryBuilder(ServiceRegistry serviceRegistry) {
+ MetadataSources metadataSources = new MetadataSources(serviceRegistry);
+ metadataSources.addAnnotatedClass(FootballPlayer.class);
+
+ Metadata metadata = metadataSources.buildMetadata();
+ return metadata.getSessionFactoryBuilder();
+
+ }
+
+ private static ServiceRegistry configureServiceRegistry() throws IOException {
+ Properties properties = getHibernateProperties();
+ return new StandardServiceRegistryBuilder().applySettings(properties).build();
+ }
+
+ private static Properties getHibernateProperties() throws IOException {
+ Properties properties = new Properties();
+ URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties");
+ try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
+ properties.load(inputStream);
+ }
+ return properties;
+ }
+
+ public static List getManagedEntities(Session session) {
+ Map.Entry