Merge branch 'master' of https://github.com/eugenp/tutorials into task/BAEL-8143

This commit is contained in:
Dhawal Kapil 2018-08-14 08:48:19 +05:30
commit aa28e56545
88 changed files with 2268 additions and 380 deletions

View File

@ -1,5 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId>
@ -17,6 +17,7 @@
<module>cxf-spring</module>
<module>cxf-jaxrs-implementation</module>
<module>cxf-aegis</module>
<module>sse-jaxrs</module>
</modules>
<build>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>sse-jaxrs</artifactId>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>apache-cxf</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<modules>
<module>sse-jaxrs-server</module>
<module>sse-jaxrs-client</module>
</modules>
</project>

View File

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>sse-jaxrs</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>sse-jaxrs-client</artifactId>
<properties>
<cxf-version>3.2.0</cxf-version>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
<execution>
<id>singleEvent</id>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.baeldung.sse.jaxrs.client.SseClientApp</mainClass>
</configuration>
</execution>
<execution>
<id>broadcast</id>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.baeldung.sse.jaxrs.client.SseClientBroadcastApp</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-client</artifactId>
<version>${cxf-version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-sse</artifactId>
<version>${cxf-version}</version>
</dependency>
</dependencies>
</project>

View File

@ -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<InboundSseEvent> onEvent = (inboundSseEvent) -> {
String data = inboundSseEvent.readData();
System.out.println(data);
};
//Error
private static Consumer<Throwable> onError = (throwable) -> {
throwable.printStackTrace();
};
//Connection close and there is nothing to receive
private static Runnable onComplete = () -> {
System.out.println("Done!");
};
}

View File

@ -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<InboundSseEvent> onEvent = (inboundSseEvent) -> {
String data = inboundSseEvent.readData();
System.out.println(data);
};
//Error
private static Consumer<Throwable> onError = (throwable) -> {
throwable.printStackTrace();
};
//Connection close and there is nothing to receive
private static Runnable onComplete = () -> {
System.out.println("Done!");
};
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>sse-jaxrs</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>sse-jaxrs-server</artifactId>
<packaging>war</packaging>
<properties>
<liberty-maven-plugin.version>2.4.2</liberty-maven-plugin.version>
<failOnMissingWebXml>false</failOnMissingWebXml>
<openliberty-version>18.0.0.2</openliberty-version>
</properties>
<build>
<finalName>${artifactId}</finalName>
<plugins>
<plugin>
<groupId>net.wasdev.wlp.maven.plugins</groupId>
<artifactId>liberty-maven-plugin</artifactId>
<version>${liberty-maven-plugin.version}</version>
<configuration>
<assemblyArtifact>
<groupId>io.openliberty</groupId>
<artifactId>openliberty-webProfile8</artifactId>
<version>${openliberty-version}</version>
<type>zip</type>
</assemblyArtifact>
<installAppPackages>project</installAppPackages>
<looseApplication>true</looseApplication>
<configFile>src/main/liberty/config/server.xml</configFile>
</configuration>
<executions>
<execution>
<id>install-server</id>
<phase>prepare-package</phase>
<goals>
<goal>install-server</goal>
<goal>create-server</goal>
<goal>install-feature</goal>
</goals>
</execution>
<execution>
<id>install-apps</id>
<phase>package</phase>
<goals>
<goal>install-apps</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.json.bind</groupId>
<artifactId>javax.json.bind-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@ -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 {
}

View File

@ -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();
}
}

View File

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

View File

@ -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<String> stockNames = Arrays.asList("GOOG", "IBM", "MS", "GOOG", "YAHO");
List<Stock> 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();
}
}

View File

@ -0,0 +1,7 @@
<server description="OpenLiberty Server">
<featureManager>
<feature>jaxrs-2.1</feature>
<feature>cdi-2.0</feature>
</featureManager>
<httpEndpoint httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint" host="*"/>
</server>

View File

@ -0,0 +1,6 @@
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
bean-discovery-mode="all">
</beans>

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>Hello Servlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

View File

@ -0,0 +1 @@
index

View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html>
<head>
<title>Server-Sent Event Broadcasting</title>
</head>
<body>
<h2>Stock prices :</h2>
<div>
<ul id="data">
</ul>
</div>
<script>
var source = new EventSource('sse/stock/subscribe');
source.onopen = function(event) {
console.log(event);
};
source.addEventListener("stock", function(event) {
append(event.data);
}, false);
source.onmessage = function(event) {
append(event.data);
};
source.onerror = function(event) {
console.log(event);
};
function append(data) {
var ul = document.getElementById("data");
var li = document.createElement("li");
li.appendChild(document.createTextNode(data));
ul.insertBefore(li, ul.childNodes[0]);
};
</script>
</body>
</html>

View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html>
<head>
<title>Server-Sent Event</title>
</head>
<body>
<h2>Stock prices :</h2>
<div>
<ul id="data">
</ul>
</div>
<script>
var source = new EventSource('sse/stock/prices');
source.onopen = function(event) {
console.log(event);
};
source.addEventListener("stock", function(event) {
append(event.data);
}, false);
source.onmessage = function(event) {
append(event.data);
};
source.onerror = function(event) {
console.log(event);
};
function append(data) {
var ul = document.getElementById("data");
var li = document.createElement("li");
li.appendChild(document.createTextNode(data));
ul.insertBefore(li, ul.childNodes[0]);
};
</script>
</body>
</html>

View File

@ -53,15 +53,27 @@
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${openjdk.jmh.version}</version>
</dependency>
</dependencies>
<properties>
<openjdk.jmh.version>1.19</openjdk.jmh.version>
<junit.platform.version>1.2.0</junit.platform.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-collections4.version>4.1</commons-collections4.version>
<collections-generic.version>4.01</collections-generic.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.6.1</assertj.version>
<eclipse.collections.version>9.2.0</eclipse.collections.version>
<eclipse.collections.version>7.1.0</eclipse.collections.version>
</properties>
</project>

View File

@ -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<Employee> employeeSet = new HashSet<>();
private List<Employee> 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();
}
}

View File

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

View File

@ -0,0 +1,26 @@
package com.baeldung.collection;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import org.junit.Assert;
import org.junit.Test;
public class CollectionsEmpty {
@Test
public void givenArrayList_whenAddingElement_addsNewElement() {
ArrayList<String> mutableList = new ArrayList<>();
mutableList.add("test");
Assert.assertEquals(mutableList.size(), 1);
Assert.assertEquals(mutableList.get(0), "test");
}
@Test(expected = UnsupportedOperationException.class)
public void givenCollectionsEmptyList_whenAddingElement_throwsUnsupportedOperationException() {
List<String> immutableList = Collections.emptyList();
immutableList.add("test");
}
}

View File

@ -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<String> generateArrayListFromFile(String filename) throws IOException {
ArrayList<String> result = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
while (br.ready()) {
result.add(br.readLine());
}
return result;
}
}
}

View File

@ -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<String> generateArrayListFromFile(String filename) throws IOException {
ArrayList<String> 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;
}
}

View File

@ -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<String> generateArrayListFromFile(String filename) throws IOException {
List<String> result = Files.readAllLines(Paths.get(filename));
return (ArrayList<String>) result;
}
}

View File

@ -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<Integer> generateArrayListFromFile(String filename) throws IOException {
ArrayList<Integer> result = new ArrayList<>();
try (Scanner s = new Scanner(new FileReader(filename))) {
while (s.hasNext()) {
result.add(s.nextInt());
}
return result;
}
}
}

View File

@ -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<String> generateArrayListFromFile(String filename) throws IOException {
ArrayList<String> result = new ArrayList<>();
try (Scanner s = new Scanner(new FileReader(filename))) {
while (s.hasNext()) {
result.add(s.nextLine());
}
return result;
}
}
}

View File

@ -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<String> lines = BufferedReaderExample.generateArrayListFromFile(TEXT_FILENAME);
assertTrue("File does not has 2 lines", lines.size() == 2);
}
}

View File

@ -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<String> lines = FileReaderExample.generateArrayListFromFile(TEXT_FILENAME);
assertTrue("File does not has 2 lines", lines.size() == 2);
}
}

View File

@ -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<String> lines = FilesReadLinesExample.generateArrayListFromFile(TEXT_FILENAME);
assertTrue("File does not has 2 lines", lines.size() == 2);
}
}

View File

@ -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<Integer> numbers = ScannerIntExample.generateArrayListFromFile(NUMBER_FILENAME);
assertTrue("File does not has 2 lines", numbers.size() == 2);
}
}

View File

@ -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<String> lines = ScannerStringExample.generateArrayListFromFile(TEXT_FILENAME);
assertTrue("File does not has 2 lines", lines.size() == 2);
}
}

View File

@ -0,0 +1,2 @@
111
222

View File

@ -0,0 +1,2 @@
Hello
World

View File

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

View File

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

View File

@ -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");
}
}

View File

@ -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<LoggingEvent> 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"));
}
}

View File

@ -0,0 +1,86 @@
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 AnimalUnitTest {
@Mock
private Appender mockAppender;
@Captor
private ArgumentCaptor<LoggingEvent> 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).doAppend(captorLoggingEvent.capture());
final LoggingEvent loggingEvent = captorLoggingEvent.getValue();
while (testValue != 0) {
assertThat(loggingEvent.getLevel(), is(Level.INFO));
assertThat(loggingEvent.getFormattedMessage(),
is("generic animal noise countdown 3\n"
+ "generic animal noise countdown 2\n"
+ "generic animal noise countdown 1\n"));
testValue-=1;
}
}
}

View File

@ -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<LoggingEvent> 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"));
}
}

View File

@ -106,22 +106,22 @@
<artifactId>klaxon</artifactId>
<version>${klaxon.version}</version>
</dependency>
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-netty</artifactId>
<version>${ktor.io.version}</version>
</dependency>
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-gson</artifactId>
<version>${ktor.io.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-server-netty</artifactId>
<version>${ktor.io.version}</version>
</dependency>
<dependency>
<groupId>io.ktor</groupId>
<artifactId>ktor-gson</artifactId>
<version>${ktor.io.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -166,13 +166,13 @@
<target>${java.version}</target>
</configuration>
<executions>
<!-- Replacing default-compile as it is treated specially
<!-- Replacing default-compile as it is treated specially
by maven -->
<execution>
<id>default-compile</id>
<phase>none</phase>
</execution>
<!-- Replacing default-testCompile as it is treated specially
<!-- Replacing default-testCompile as it is treated specially
by maven -->
<execution>
<id>default-testCompile</id>
@ -224,10 +224,10 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<kotlin-maven-plugin.version>1.2.51</kotlin-maven-plugin.version>
<kotlin-test-junit.version>1.2.51</kotlin-test-junit.version>
<kotlin-stdlib.version>1.2.51</kotlin-stdlib.version>
<kotlin-reflect.version>1.2.51</kotlin-reflect.version>
<kotlin-maven-plugin.version>1.2.60</kotlin-maven-plugin.version>
<kotlin-test-junit.version>1.2.60</kotlin-test-junit.version>
<kotlin-stdlib.version>1.2.60</kotlin-stdlib.version>
<kotlin-reflect.version>1.2.60</kotlin-reflect.version>
<kotlinx.version>0.22.5</kotlinx.version>
<ktor.io.version>0.9.2</ktor.io.version>
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
@ -235,9 +235,9 @@
<klaxon.version>3.0.4</klaxon.version>
<khttp.version>0.1.0</khttp.version>
<commons-math3.version>3.6.1</commons-math3.version>
<junit.platform.version>1.0.0</junit.platform.version>
<junit.platform.version>1.1.1</junit.platform.version>
<junit.vintage.version>5.2.0</junit.vintage.version>
<assertj.version>3.10.0</assertj.version>
</properties>
</project>
</project>

View File

@ -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<String>) {
val car = Car("1", "sport")
val s= Car("2", "suv")
}

View File

@ -0,0 +1,3 @@
package com.baeldung.constructor
class Employee(name: String, val salary: Int): Person(name)

View File

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

View File

@ -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<String>) {
val person = Person("John")
val personWithAge = Person("John", 22)
}

View File

@ -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)"
}
}

View File

@ -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")
}
}

View File

@ -0,0 +1,2 @@
Kotlin
Concise, Safe, Interoperable, Tool-friendly

View File

@ -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<String, String> 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<String, String> 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"));
}
}

View File

@ -33,6 +33,20 @@
<artifactId>json</artifactId>
<version>20171018</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://search.maven.org/search?q=g:org.glassfish%20AND%20a:javax.json&core=gav -->
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<properties>

View File

@ -0,0 +1,95 @@
package com.baeldung.jsonpointer;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonPointer;
import javax.json.JsonReader;
import javax.json.JsonString;
import javax.json.JsonStructure;
public class JsonPointerCrud {
private JsonStructure jsonStructure = null;
public JsonPointerCrud(String fileName) throws IOException {
try (JsonReader reader = Json.createReader(Files.newBufferedReader(Paths.get(fileName)))) {
jsonStructure = reader.read();
} catch (FileNotFoundException e) {
System.out.println("Error to open json file: " + e.getMessage());
}
}
public JsonPointerCrud(InputStream stream) {
JsonReader reader = Json.createReader(stream);
jsonStructure = reader.read();
reader.close();
}
public JsonStructure insert(String key, String value) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
JsonString jsonValue = Json.createValue(value);
jsonStructure = jsonPointer.add(jsonStructure, jsonValue);
return jsonStructure;
}
public JsonStructure update(String key, String newValue) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
JsonString jsonNewValue = Json.createValue(newValue);
jsonStructure = jsonPointer.replace(jsonStructure, jsonNewValue);
return jsonStructure;
}
public JsonStructure delete(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
jsonPointer.getValue(jsonStructure);
jsonStructure = jsonPointer.remove(jsonStructure);
return jsonStructure;
}
public String fetchValueFromKey(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
JsonString jsonString = (JsonString) jsonPointer.getValue(jsonStructure);
return jsonString.getString();
}
public String fetchListValues(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure);
return jsonObject.toString();
}
public String fetchFullJSON() {
JsonPointer jsonPointer = Json.createPointer("");
JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure);
return jsonObject.toString();
}
public boolean check(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
boolean found = jsonPointer.containsValue(jsonStructure);
return found;
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.jsonpointer;
import static org.junit.Assert.*;
import org.junit.Test;
public class JsonPointerCrudUnitTest {
@Test
public void testJsonPointerCrudForAddress() {
JsonPointerCrud jsonPointerCrud = new JsonPointerCrud(JsonPointerCrudUnitTest.class.getResourceAsStream("/address.json"));
assertFalse(jsonPointerCrud.check("city"));
// insert a value
jsonPointerCrud.insert("city", "Rio de Janeiro");
assertTrue(jsonPointerCrud.check("city"));
// fetch full json
String fullJSON = jsonPointerCrud.fetchFullJSON();
assertTrue(fullJSON.contains("name"));
assertTrue(fullJSON.contains("city"));
// fetch value
String cityName = jsonPointerCrud.fetchValueFromKey("city");
assertEquals(cityName, "Rio de Janeiro");
// update value
jsonPointerCrud.update("city", "Sao Paulo");
// fetch value
cityName = jsonPointerCrud.fetchValueFromKey("city");
assertEquals(cityName, "Sao Paulo");
// delete
jsonPointerCrud.delete("city");
assertFalse(jsonPointerCrud.check("city"));
}
@Test
public void testJsonPointerCrudForBooks() {
JsonPointerCrud jsonPointerCrud = new JsonPointerCrud(JsonPointerCrudUnitTest.class.getResourceAsStream("/books.json"));
// fetch value
String book = jsonPointerCrud.fetchListValues("books/1");
assertEquals(book, "{\"title\":\"Title 2\",\"author\":\"John Doe\"}");
}
}

View File

@ -0,0 +1,4 @@
{
"name": "Customer 01",
"street name": "Street 01"
}

View File

@ -0,0 +1,7 @@
{
"library": "My Personal Library",
"books": [
{ "title":"Title 1", "author":"Jane Doe" },
{ "title":"Title 2", "author":"John Doe" }
]
}

View File

@ -94,6 +94,24 @@
</filesets>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>${maven.build.helper.version}</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/another-src</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
@ -102,6 +120,7 @@
<maven.failsafe.version>2.21.0</maven.failsafe.version>
<maven.verifier.version>1.1</maven.verifier.version>
<maven.clean.version>3.0.0</maven.clean.version>
<maven.build.helper.version>3.0.0</maven.build.helper.version>
<resources.name>Baeldung</resources.name>
</properties>

View File

@ -0,0 +1,10 @@
package com.baeldung.maven.plugins;
public class Foo {
public static String foo() {
return "foo";
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.maven.plugins;
public class MultipleSrcFolders {
public static void callFoo() {
Foo.foo();
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.state;
public class DeliveredState implements PackageState {
@Override
public void next(Package pkg) {
pkg.setState(new ReceivedState());
}
@Override
public void prev(Package pkg) {
pkg.setState(new OrderedState());
}
@Override
public void printStatus() {
System.out.println("Package delivered to post office, not received yet.");
}
@Override
public String toString() {
return "DeliveredState{}";
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.state;
public class OrderedState implements PackageState {
@Override
public void next(Package pkg) {
pkg.setState(new DeliveredState());
}
@Override
public void prev(Package pkg) {
System.out.println("The package is in it's root state.");
}
@Override
public void printStatus() {
System.out.println("Package ordered, not delivered to the office yet.");
}
@Override
public String toString() {
return "OrderedState{}";
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.state;
public class Package {
private PackageState state = new OrderedState();
public PackageState getState() {
return state;
}
public void setState(PackageState state) {
this.state = state;
}
public void previousState() {
state.prev(this);
}
public void nextState() {
state.next(this);
}
public void printStatus() {
state.printStatus();
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.state;
public interface PackageState {
void next(Package pkg);
void prev(Package pkg);
void printStatus();
}

View File

@ -0,0 +1,24 @@
package com.baeldung.state;
public class ReceivedState implements PackageState {
@Override
public void next(Package pkg) {
System.out.println("This package is already received by a client.");
}
@Override
public void prev(Package pkg) {
pkg.setState(new DeliveredState());
}
@Override
public void printStatus() {
System.out.println("Package was received by client.");
}
@Override
public String toString() {
return "ReceivedState{}";
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.state;
public class StateDemo {
public static void main(String[] args) {
Package pkg = new Package();
pkg.printStatus();
pkg.nextState();
pkg.printStatus();
pkg.nextState();
pkg.printStatus();
pkg.nextState();
pkg.printStatus();
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.state;
import com.baeldung.state.Package;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.instanceOf;
import org.junit.Test;
public class StatePatternUnitTest {
@Test
public void givenNewPackage_whenPackageReceived_thenStateReceived() {
Package pkg = new Package();
assertThat(pkg.getState(), instanceOf(OrderedState.class));
pkg.nextState();
assertThat(pkg.getState(), instanceOf(DeliveredState.class));
pkg.nextState();
assertThat(pkg.getState(), instanceOf(ReceivedState.class));
}
@Test
public void givenDeliveredPackage_whenPrevState_thenStateOrdered() {
Package pkg = new Package();
pkg.setState(new DeliveredState());
pkg.previousState();
assertThat(pkg.getState(), instanceOf(OrderedState.class));
}
}

View File

@ -177,46 +177,12 @@
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>dynamodb-local</id>
<name>DynamoDB Local Release Repository</name>
<url>${dynamodblocal.repository.url}</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties>
<!-- The main class to start by executing java -jar -->

View File

@ -587,7 +587,6 @@
<module>apache-meecrowave</module>
<module>spring-reactive-kotlin</module>
<module>jnosql</module>
<module>sse-jaxrs</module>
<module>spring-boot-angular-ecommerce</module>
</modules>

View File

@ -134,31 +134,9 @@
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties>
<jayway-rest-assured.version>2.9.0</jayway-rest-assured.version>
<kotlin.version>1.1.2</kotlin.version>
</properties>
</project>

View File

@ -112,27 +112,6 @@
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties>
<reactor-spring.version>1.0.1.RELEASE</reactor-spring.version>
<johnzon.version>1.1.3</johnzon.version>

View File

@ -79,25 +79,4 @@
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>

View File

@ -149,6 +149,12 @@
<artifactId>rome</artifactId>
<version>${rome.version}</version>
</dependency>
<dependency>
<groupId>de.codecentric</groupId>
<artifactId>chaos-monkey-spring-boot</artifactId>
<version>${chaos.monkey.version}</version>
</dependency>
</dependencies>
<build>
@ -219,6 +225,7 @@
<tomee-servlet-api.version>8.5.11</tomee-servlet-api.version>
<togglz.version>2.4.1.Final</togglz.version>
<rome.version>1.9.0</rome.version>
<chaos.monkey.version>2.0.0</chaos.monkey.version>
<graphql-spring-boot-starter.version>3.6.0</graphql-spring-boot-starter.version>
<graphql-java-tools.version>3.2.0</graphql-java-tools.version>
<guava.version>18.0</guava.version>

View File

@ -0,0 +1,15 @@
package com.baeldung.chaosmonkey;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* Created by adi on 8/2/18.
*/
@SpringBootApplication(scanBasePackages = { "com.baeldung.chaosmonkey" })
public class SpringBootChaosMonkeyApp {
public static void main(String[] args) {
SpringApplication.run(SpringBootChaosMonkeyApp.class, args);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.chaosmonkey.controller;
import com.baeldung.chaosmonkey.service.PermissionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* Created by adi on 8/2/18.
*/
@RestController
@RequestMapping("/permissions")
public class PermissionsController {
@Autowired private PermissionsService permissionsService;
@GetMapping
public List<String> getAllPermissions() {
return permissionsService.getAllPermissions();
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.chaosmonkey.service;
import org.springframework.stereotype.Service;
import java.util.Arrays;
import java.util.List;
/**
* Created by adi on 8/2/18.
*/
@Service
public class PermissionsService {
public List<String> getAllPermissions() {
return Arrays.asList("CREATE", "READ", "UPDATE", "DELETE");
}
}

View File

@ -43,3 +43,34 @@ servlet.mapping=/dispatcherExampleURL
#spring.banner.image.invert= //TODO
contactInfoType=email
#chaos monkey for spring boot props
management.endpoint.chaosmonkey.enabled=true
management.endpoint.chaosmonkeyjmx.enabled=true
spring.profiles.active=chaos-monkey
#Determine whether should execute or not
chaos.monkey.enabled=true
#How many requests are to be attacked. 1: attack each request; 5: each 5th request is attacked
chaos.monkey.assaults.level=1
#Minimum latency in ms added to the request
chaos.monkey.assaults.latencyRangeStart=3000
#Maximum latency in ms added to the request
chaos.monkey.assaults.latencyRangeEnd=15000
#Latency assault active
chaos.monkey.assaults.latencyActive=true
#Exception assault active
chaos.monkey.assaults.exceptionsActive=false
#AppKiller assault active
chaos.monkey.assaults.killApplicationActive=false
#Controller watcher active
chaos.monkey.watcher.controller=false
#RestController watcher active
chaos.monkey.watcher.restController=false
#Service watcher active
chaos.monkey.watcher.service=true
#Repository watcher active
chaos.monkey.watcher.repository=false
#Component watcher active
chaos.monkey.watcher.component=false

View File

@ -28,7 +28,7 @@
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
@ -54,27 +54,8 @@
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<properties>
<cloud.version>2.0.0.RC2</cloud.version>
<cloud.version>2.0.1.RELEASE</cloud.version>
<hibernate-validator.version>6.0.2.Final</hibernate-validator.version>
</properties>

View File

@ -38,25 +38,6 @@
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<properties>
<spring-cloud-dependencies.version>Brixton.SR7</spring-cloud-dependencies.version>
</properties>

View File

@ -51,27 +51,6 @@
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties>
<spring-security-oauth2.version>2.2.1.RELEASE</spring-security-oauth2.version>
<spring-security-jwt.version>1.0.9.RELEASE</spring-security-jwt.version>

View File

@ -1,5 +1,5 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>spring-thymeleaf</artifactId>
@ -8,8 +8,9 @@
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<artifactId>parent-spring-5</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-spring-5</relativePath>
</parent>
<dependencies>
@ -17,7 +18,7 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<version>${spring.version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
@ -29,19 +30,38 @@
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${spring-data.version}</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springframework-security.version}</version>
<version>${spring-security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springframework-security.version}</version>
<version>${spring-security.version}</version>
</dependency>
<!-- Thymeleaf -->
<dependency>
<groupId>org.thymeleaf</groupId>
@ -50,10 +70,9 @@
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<artifactId>thymeleaf-spring5</artifactId>
<version>${org.thymeleaf-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/nz.net.ultraq.thymeleaf/thymeleaf-layout-dialect -->
<dependency>
<groupId>nz.net.ultraq.thymeleaf</groupId>
<artifactId>thymeleaf-layout-dialect</artifactId>
@ -64,60 +83,29 @@
<artifactId>thymeleaf-extras-java8time</artifactId>
<version>${org.thymeleaf.extras-version}</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-version}</version>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- Validation -->
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${javax.validation-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<!-- test scoped -->
<!-- test scoped -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.security/spring-security-test -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>${springframework-security.version}</version>
<version>${spring-security.version}</version>
<scope>test</scope>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.0.1.RELEASE</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> -->
<!-- Spring data -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${springFramework-data.version}</version>
</dependency>
</dependencies>
@ -131,7 +119,7 @@
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
@ -151,7 +139,7 @@
</configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
@ -176,22 +164,14 @@
</build>
<properties>
<!-- spring -->
<org.springframework-version>4.3.4.RELEASE</org.springframework-version>
<springframework-security.version>4.2.0.RELEASE</springframework-security.version>
<springFramework-data.version>2.0.7.RELEASE</springFramework-data.version>
<javax.servlet-version>3.1.0</javax.servlet-version>
<!-- thymeleaf -->
<spring-data.version>2.0.9.RELEASE</spring-data.version>
<org.thymeleaf-version>3.0.9.RELEASE</org.thymeleaf-version>
<org.thymeleaf.extras-version>3.0.0.RELEASE</org.thymeleaf.extras-version>
<thymeleaf-layout-dialect.version>2.1.2</thymeleaf-layout-dialect.version>
<!-- validation -->
<javax.validation-version>1.1.0.Final</javax.validation-version>
<hibernate-validator.version>5.3.3.Final</hibernate-validator.version>
<org.hibernate-version>5.2.5.Final</org.hibernate-version>
<org.thymeleaf.extras-version>3.0.1.RELEASE</org.thymeleaf.extras-version>
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
<javax.validation-version>2.0.1.Final</javax.validation-version>
<hibernate-validator.version>6.0.11.Final</hibernate-validator.version>
<!-- Maven plugins -->
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
<tomcat7-maven-plugin.version>2.2</tomcat7-maven-plugin.version>
</properties>

View File

@ -2,6 +2,9 @@ package com.baeldung.thymeleaf.config;
import java.util.Locale;
import nz.net.ultraq.thymeleaf.LayoutDialect;
import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
@ -15,23 +18,20 @@ import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.spring5.ISpringTemplateEngine;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
import com.baeldung.thymeleaf.formatter.NameFormatter;
import com.baeldung.thymeleaf.utils.ArrayUtil;
import nz.net.ultraq.thymeleaf.LayoutDialect;
import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy;
@Configuration
@EnableWebMvc
@ComponentScan({ "com.baeldung.thymeleaf" })
@ -39,10 +39,11 @@ import nz.net.ultraq.thymeleaf.decorators.strategies.GroupingStrategy;
* Java configuration file that is used for Spring MVC and Thymeleaf
* configurations
*/
public class WebMVCConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
public class WebMVCConfig implements WebMvcConfigurer, ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@ -77,7 +78,7 @@ public class WebMVCConfig extends WebMvcConfigurerAdapter implements Application
return resolver;
}
private TemplateEngine templateEngine(ITemplateResolver templateResolver) {
private ISpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.addDialect(new LayoutDialect(new GroupingStrategy()));
engine.addDialect(new Java8TimeDialect());

View File

@ -27,7 +27,7 @@ public class WebMVCSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user1").password("user1Pass").authorities("ROLE_USER");
auth.inMemoryAuthentication().withUser("user1").password("{noop}user1Pass").authorities("ROLE_USER");
}
@Override

View File

@ -1,10 +1,22 @@
package com.baeldung.thymeleaf.controller;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.servlet.Filter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.RequestPostProcessor;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
@ -15,21 +27,6 @@ import com.baeldung.thymeleaf.config.WebApp;
import com.baeldung.thymeleaf.config.WebMVCConfig;
import com.baeldung.thymeleaf.config.WebMVCSecurity;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import javax.servlet.Filter;
import static org.hamcrest.Matchers.containsString;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { WebApp.class, WebMVCConfig.class, WebMVCSecurity.class, InitSecurity.class })

View File

@ -0,0 +1,48 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parallel-tests-junit</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>math-test-functions</artifactId>
<name>math-test-functions</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<configuration>
<parallel>all</parallel>
<threadCount>10</threadCount>
<threadCountSuites>2</threadCountSuites>
<threadCountClasses>2</threadCountClasses>
<threadCountMethods>6</threadCountMethods>
<parallelTestTimeoutInSeconds>3.5</parallelTestTimeoutInSeconds>
<parallelTestTimeoutForcedInSeconds>5</parallelTestTimeoutForcedInSeconds>
<perCoreThreadCount>true</perCoreThreadCount>
<includes>
<include>FunctionTestSuite.class</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,29 +1,28 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class MathFunctionTest {
@Test
public void test_addingIntegers_returnsSum() throws InterruptedException {
assertEquals(22, Math.addExact(10, 12));
}
@Test
public void test_multiplyingIntegers_returnsProduct() {
assertEquals(120, Math.multiplyExact(10, 12));
}
@Test
public void test_subtractingIntegers_returnsDifference() {
assertEquals(2, Math.subtractExact(12, 10));
}
@Test
public void test_minimumInteger() {
assertEquals(10, Math.min(10, 12));
}
}
package com.baeldung;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ArithmeticFunctionTest {
@Test
public void test_addingIntegers_returnsSum() {
assertEquals(22, Math.addExact(10, 12));
}
@Test
public void test_multiplyingIntegers_returnsProduct() {
assertEquals(120, Math.multiplyExact(10, 12));
}
@Test
public void test_subtractingIntegers_returnsDifference() {
assertEquals(2, Math.subtractExact(12, 10));
}
@Test
public void test_minimumInteger() {
assertEquals(10, Math.min(10, 12));
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class ComparisonFunctionTest {
@Test
public void test_findMax() {
assertEquals(20, Math.max(10, 20));
}
@Test
public void test_findMin() {
assertEquals(10, Math.min(10, 20));
}
}

View File

@ -1,11 +1,11 @@
package com.baeldung;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({StringFunctionTest.class, MathFunctionTest.class})
public class FunctionTestSuite {
}
package com.baeldung;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ ComparisonFunctionTest.class, ArithmeticFunctionTest.class })
public class FunctionTestSuite {
}

View File

@ -1,50 +1,12 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>parallel-tests-junit</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>parallel-tests-junit</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<configuration>
<parallel>all</parallel>
<threadCount>10</threadCount>
<threadCountSuites>2</threadCountSuites>
<threadCountClasses>2</threadCountClasses>
<threadCountMethods>6</threadCountMethods>
<parallelTestTimeoutInSeconds>3.5</parallelTestTimeoutInSeconds>
<parallelTestTimeoutForcedInSeconds>5</parallelTestTimeoutForcedInSeconds>
<perCoreThreadCount>true</perCoreThreadCount>
<includes>
<include>FunctionTestSuite.class</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>parallel-tests-junit</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<modules>
<module>math-test-functions</module>
<module>string-test-functions</module>
</modules>
</project>

View File

@ -0,0 +1,41 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parallel-tests-junit</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>string-test-functions</artifactId>
<name>string-test-functions</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
<configuration>
<parallel>all</parallel>
<useUnlimitedThreads>true</useUnlimitedThreads>
<threadCountMethods>2</threadCountMethods>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,18 +1,18 @@
package com.baeldung;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class StringFunctionTest {
@Test
public void test_upperCase() {
assertEquals("TESTCASE", "testCase".toUpperCase());
}
@Test
public void test_indexOf() {
assertEquals(1, "testCase".indexOf("e"));
}
}
package com.baeldung;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class StringFunctionTest {
@Test
public void test_upperCase() {
assertEquals("TESTCASE", "testCase".toUpperCase());
}
@Test
public void test_indexOf() {
assertEquals(1, "testCase".indexOf("e"));
}
}