Merge branch 'master' of github.com:eugenp/tutorials

This commit is contained in:
Karsten Silz
2020-05-17 14:29:07 +01:00
43 changed files with 1327 additions and 94 deletions
+1 -1
View File
@@ -3,7 +3,7 @@
This module contains articles about Apache CXF
## Relevant Articles:
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)
- [Apache CXF Support for RESTful Web Services](https://www.baeldung.com/apache-cxf-rest-api)
- [A Guide to Apache CXF with Spring](https://www.baeldung.com/apache-cxf-with-spring)
- [Introduction to Apache CXF](https://www.baeldung.com/introduction-to-apache-cxf)
+3
View File
@@ -0,0 +1,3 @@
### Relevant Articles:
- [Introduction to Apache CXF Aegis Data Binding](https://www.baeldung.com/aegis-data-binding-in-apache-cxf)
@@ -0,0 +1,83 @@
package com.baeldung.exchanger;
import java.util.Queue;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import static java.util.concurrent.CompletableFuture.runAsync;
public class ExchangerPipeLineManualTest {
private static final int BUFFER_SIZE = 100;
@Test
public void givenData_whenPassedThrough_thenCorrect() throws InterruptedException, ExecutionException {
Exchanger<Queue<String>> readerExchanger = new Exchanger<>();
Exchanger<Queue<String>> writerExchanger = new Exchanger<>();
int counter = 0;
Runnable reader = () -> {
Queue<String> readerBuffer = new ConcurrentLinkedQueue<>();
while (true) {
readerBuffer.add(UUID.randomUUID().toString());
if (readerBuffer.size() >= BUFFER_SIZE) {
try {
readerBuffer = readerExchanger.exchange(readerBuffer);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
};
Runnable processor = () -> {
Queue<String> processorBuffer = new ConcurrentLinkedQueue<>();
Queue<String> writterBuffer = new ConcurrentLinkedQueue<>();
try {
processorBuffer = readerExchanger.exchange(processorBuffer);
while (true) {
writterBuffer.add(processorBuffer.poll());
if (processorBuffer.isEmpty()) {
try {
processorBuffer = readerExchanger.exchange(processorBuffer);
writterBuffer = writerExchanger.exchange(writterBuffer);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
Runnable writer = () -> {
Queue<String> writterBuffer = new ConcurrentLinkedQueue<>();
try {
writterBuffer = writerExchanger.exchange(writterBuffer);
while (true) {
System.out.println(writterBuffer.poll());
if (writterBuffer.isEmpty()) {
writterBuffer = writerExchanger.exchange(writterBuffer);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
CompletableFuture.allOf(runAsync(reader), runAsync(processor), runAsync(writer)).get();
}
}
@@ -0,0 +1,63 @@
package com.baeldung.exchanger;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import static java.util.concurrent.CompletableFuture.runAsync;
public class ExchangerUnitTest {
@Test
public void givenThreads_whenMessageExchanged_thenCorrect() {
Exchanger<String> exchanger = new Exchanger<>();
Runnable taskA = () -> {
try {
String message = exchanger.exchange("from A");
assertEquals("from B", message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
Runnable taskB = () -> {
try {
String message = exchanger.exchange("from B");
assertEquals("from A", message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
CompletableFuture.allOf(runAsync(taskA), runAsync(taskB)).join();
}
@Test
public void givenThread_WhenExchangedMessage_thenCorrect() throws InterruptedException, ExecutionException {
Exchanger<String> exchanger = new Exchanger<>();
Runnable runner = () -> {
try {
String message = exchanger.exchange("from runner");
assertEquals("to runner", message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
};
CompletableFuture<Void> result = CompletableFuture.runAsync(runner);
String msg = exchanger.exchange("to runner");
assertEquals("from runner", msg);
result.join();
}
}
@@ -11,13 +11,26 @@ import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Scanner;
import java.util.UUID;
import java.util.stream.Collectors;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.equalTo;
@@ -46,6 +59,18 @@ public class JavaInputStreamToXUnitTest {
assertEquals(textBuilder.toString(), originalString);
}
@Test
public void givenUsingJava8_whenConvertingAnInputStreamToAString_thenCorrect() {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
final InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
final String text = new BufferedReader(new InputStreamReader(inputStream, Charset.forName(StandardCharsets.UTF_8.name())))
.lines()
.collect(Collectors.joining("\n"));
assertThat(text, equalTo(originalString));
}
@Test
public final void givenUsingJava7_whenConvertingAnInputStreamToAString_thenCorrect() throws IOException {
final String originalString = randomAlphabetic(DEFAULT_SIZE);
@@ -0,0 +1,86 @@
package com.baeldung.ifelseexpression
fun ifStatementUsage(): String {
val number = 15
if (number > 0) {
return "Positive number"
}
return "Positive number not found"
}
fun ifElseStatementUsage(): String {
val number = -50
if (number > 0) {
return "Positive number"
} else {
return "Negative number"
}
}
fun ifElseExpressionUsage(): String {
val number = -50
val result = if (number > 0) {
"Positive number"
} else {
"Negative number"
}
return result
}
fun ifElseExpressionSingleLineUsage(): String {
val number = -50
val result = if (number > 0) "Positive number" else "Negative number"
return result
}
fun ifElseMultipleExpressionUsage(): Int {
val x = 24
val y = 73
val result = if (x > y) {
println("$x is greater than $y")
x
} else {
println("$x is less than or equal to $y")
y
}
return result
}
fun ifElseLadderExpressionUsage(): String {
val number = 60
val result = if (number < 0) {
"Negative number"
} else if (number in 0..9) {
"Single digit number"
} else if (number in 10..99) {
"Double digit number"
} else {
"Number has more digits"
}
return result
}
fun ifElseNestedExpressionUsage(): Int {
val x = 37
val y = 89
val z = 6
val result = if (x > y) {
if (x > z)
x
else
z
} else {
if (y > z)
y
else
z
}
return result
}
@@ -0,0 +1,43 @@
package com.baeldung.ifelseexpression
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotEquals
class IfElseExpressionExampleTest {
@Test
fun givenNumber_whenIfStatementCalled_thenReturnsString() {
assertEquals("Positive number", ifStatementUsage())
}
@Test
fun givenNumber_whenIfElseStatementCalled_thenReturnsString() {
assertEquals("Negative number", ifElseStatementUsage())
}
@Test
fun givenNumber_whenIfElseExpressionCalled_thenReturnsString() {
assertEquals("Negative number", ifElseExpressionUsage())
}
@Test
fun givenNumber_whenIfElseExpressionSingleLineCalled_thenReturnsString() {
assertEquals("Negative number", ifElseExpressionSingleLineUsage())
}
@Test
fun givenNumber_whenIfElseMultipleExpressionCalled_thenReturnsNumber() {
assertEquals(73, ifElseMultipleExpressionUsage())
}
@Test
fun givenNumber_whenIfElseLadderExpressionCalled_thenReturnsString() {
assertEquals("Double digit number", ifElseLadderExpressionUsage())
}
@Test
fun givenNumber_whenIfElseNestedExpressionCalled_thenReturnsNumber() {
assertEquals(89, ifElseNestedExpressionUsage())
}
}
@@ -88,7 +88,7 @@ public class CollectionToArrayListUnitTest {
Iterator<Foo> iterA = a.iterator();
Iterator<Foo> iterB = b.iterator();
while (iterA.hasNext()) {
// use '==' to test instance identity
// test instance identity
assertSame("Foo instances differ!", iterA.next(), iterB.next());
}
}
@@ -0,0 +1,41 @@
package com.baeldung.o;
public class Addition implements CalculatorOperation {
private double number1;
private double number2;
private double result = 0.0;
public Addition(double number1, double number2) {
this.number1 = number1;
this.number2 = number2;
}
public double getNumber1() {
return number1;
}
public void setNumber1(double number1) {
this.number1 = number1;
}
public double getNumber2() {
return number2;
}
public void setNumber2(double number2) {
this.number2 = number2;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
@Override
public void perform() {
result = number1 + number2;
}
}
@@ -0,0 +1,14 @@
package com.baeldung.o;
import java.security.InvalidParameterException;
public class Calculator {
public void calculate(CalculatorOperation operation) {
if (operation == null) {
throw new InvalidParameterException("Can not perform operation");
}
operation.perform();
}
}
@@ -0,0 +1,7 @@
package com.baeldung.o;
public interface CalculatorOperation {
void perform();
}
@@ -0,0 +1,43 @@
package com.baeldung.o;
public class Division implements CalculatorOperation {
private double number1;
private double number2;
private double result = 0.0;
public Division(double number1, double number2) {
this.number1 = number1;
this.number2 = number2;
}
public double getNumber1() {
return number1;
}
public void setNumber1(double number1) {
this.number1 = number1;
}
public double getNumber2() {
return number2;
}
public void setNumber2(double number2) {
this.number2 = number2;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
@Override
public void perform() {
if (number2 != 0) {
result = number1 / number2;
}
}
}
@@ -0,0 +1,41 @@
package com.baeldung.o;
public class Subtraction implements CalculatorOperation {
private double number1;
private double number2;
private double result = 0.0;
public Subtraction(double number1, double number2) {
this.number1 = number1;
this.number2 = number2;
}
public double getNumber1() {
return number1;
}
public void setNumber1(double number1) {
this.number1 = number1;
}
public double getNumber2() {
return number2;
}
public void setNumber2(double number2) {
this.number2 = number2;
}
public double getResult() {
return result;
}
public void setResult(double result) {
this.result = result;
}
@Override
public void perform() {
result = number1 - number2;
}
}
@@ -0,0 +1,44 @@
package com.baeldung.o;
import static org.junit.Assert.assertEquals;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class CalculatorUnitTest {
private static final double NUMBER_1 = 10.0;
private static final double NUMBER_2 = 20.0;
private static final double SUM = 30.0;
private static final double SUBTRACTION_RESULT = 10.0;
private static final double DIVISION_RESULT = 2.0;
private Calculator calculator;
@BeforeEach
public void setUp() {
calculator = new Calculator();
}
@Test
public void whenAddTwoNumber_returnSum() {
Addition addition = new Addition(NUMBER_1, NUMBER_2);
calculator.calculate(addition);
assertEquals(SUM, addition.getResult(), 0.0);
}
@Test
public void whenSutractTwoNumber_returnCorrectResult() {
Subtraction subtraction = new Subtraction(NUMBER_2, NUMBER_1);
calculator.calculate(subtraction);
assertEquals(SUBTRACTION_RESULT, subtraction.getResult(), 0.0);
}
@Test
public void whenDivideTwoNumber_returnCorrectResult() {
Division division = new Division(NUMBER_2, NUMBER_1);
calculator.calculate(division);
assertEquals(DIVISION_RESULT, division.getResult(), 0.0);
}
}
+1 -29
View File
@@ -87,19 +87,6 @@
</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>
</repository>
<repository>
<id>jcenter-snapshots</id>
<name>jcenter</name>
@@ -107,27 +94,12 @@
</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>
</pluginRepository>
</pluginRepositories>
<properties>
<spring.fox.version>3.0.0-SNAPSHOT</spring.fox.version>
<start-class>com.baeldung.swagger2boot.SpringBootSwaggerApplication</start-class>
<!-- <start-class>com.baeldung.springbootmvc.SpringBootMvcFnApplication</start-class> -->
<spring-boot.version>2.2.0.BUILD-SNAPSHOT</spring-boot.version>
<spring-boot.version>2.2.6.RELEASE</spring-boot.version>
<xstream.version>1.4.11.1</xstream.version>
</properties>
@@ -0,0 +1,5 @@
## Spring Boot Properties
This module contains articles about Properties in Spring Boot.
### Relevant Articles:
@@ -0,0 +1,25 @@
<?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>spring-boot-properties-2</artifactId>
<name>spring-boot-properties-2</name>
<packaging>jar</packaging>
<description>Spring Boot Properties Module</description>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-boot-2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../../parent-boot-2</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,22 @@
package com.baeldung.properties.yaml;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class YamlApplication implements CommandLineRunner {
@Autowired
private YamlFooProperties yamlFooProperties;
public static void main(String[] args) {
SpringApplication.run(YamlApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println("YAML Properties " + yamlFooProperties);
}
}
@@ -0,0 +1,42 @@
package com.baeldung.properties.yaml;
import com.baeldung.properties.yaml.factory.YamlPropertySourceFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.List;
@Configuration
@ConfigurationProperties(prefix = "yaml")
@PropertySource(value = "classpath:foo.yml", factory = YamlPropertySourceFactory.class)
public class YamlFooProperties {
private String name;
private List<String> aliases;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getAliases() {
return aliases;
}
public void setAliases(List<String> aliases) {
this.aliases = aliases;
}
@Override
public String toString() {
return "YamlFooProperties{" +
"name='" + name + '\'' +
", aliases=" + aliases +
'}';
}
}
@@ -0,0 +1,24 @@
package com.baeldung.properties.yaml.factory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;
import java.io.IOException;
import java.util.Properties;
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
}
@@ -0,0 +1,5 @@
yaml:
name: foo
aliases:
- abc
- xyz
@@ -0,0 +1,23 @@
package com.baeldung.properties.yaml;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringRunner.class)
@SpringBootTest
public class YamlFooPropertiesIntegrationTest {
@Autowired
private YamlFooProperties yamlFooProperties;
@Test
public void whenFactoryProvidedThenYamlPropertiesInjected() {
assertThat(yamlFooProperties.getName()).isEqualTo("foo");
assertThat(yamlFooProperties.getAliases()).containsExactly("abc", "xyz");
}
}
@@ -7,7 +7,7 @@ import org.springframework.context.annotation.ComponentScan;
import com.baeldung.configurationproperties.ConfigProperties;
@SpringBootApplication
@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class, Database.class })
@ComponentScan(basePackageClasses = { ConfigProperties.class, JsonProperties.class, CustomJsonProperties.class})
public class ConfigPropertiesDemoApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(ConfigPropertiesDemoApplication.class).initializers(new JsonPropertyContextInitializer())
@@ -1,33 +0,0 @@
package com.baeldung.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "database")
public class Database {
private String url;
private String username;
private String password;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
@@ -14,8 +14,4 @@
<constructor-arg value="${key.something}"/>
</bean>
<bean id="dataSource" class="com.baeldung.configurationproperties.Database">
<property name="url" value="${jdbc.url}" />
</bean>
</beans>
@@ -1,4 +1,3 @@
jdbc.url=jdbc:postgresql:/localhost:5432
database.username=foo
database.password=bar
@@ -1,5 +1,6 @@
database:
url: jdbc:postresql:/localhost:5432/instance
jdbc:
url: jdbc:postresql:/localhost:5432
username: foo
password: bar
secret: foo
@@ -14,17 +14,13 @@ import com.baeldung.properties.AdditionalProperties;
import com.baeldung.properties.ConfigPropertiesDemoApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ConfigPropertiesDemoApplication.class, DatabaseConfigPropertiesApp.class})
@TestPropertySource(locations = {"classpath:configprops-test.properties", "classpath:database-test.properties"})
@SpringBootTest(classes = {ConfigPropertiesDemoApplication.class})
@TestPropertySource(locations = {"classpath:configprops-test.properties"})
public class ConfigPropertiesIntegrationTest {
@Autowired
private ConfigProperties properties;
@Autowired
@Qualifier("dataSource")
private Database databaseProperties;
@Autowired
private AdditionalProperties additionalProperties;
@@ -59,10 +55,4 @@ public class ConfigPropertiesIntegrationTest {
Assert.assertTrue(additionalProperties.getMax() == 100);
}
@Test
public void whenDatabasePropertyQueriedthenReturnsProperty() {
Assert.assertTrue(databaseProperties.getUrl().equals("jdbc:postgresql:/localhost:5432"));
Assert.assertTrue(databaseProperties.getUsername().equals("foo"));
Assert.assertTrue(databaseProperties.getPassword().equals("bar"));
}
}
@@ -4,26 +4,28 @@ import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.properties.ConfigPropertiesDemoApplication;
import com.baeldung.properties.Database;
import com.baeldung.configurationproperties.Database;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ConfigPropertiesDemoApplication.class)
@TestPropertySource("classpath:application.properties")
@SpringBootTest(classes = DatabaseConfigPropertiesApp.class)
@TestPropertySource("classpath:database-test.properties")
public class DatabasePropertiesIntegrationTest {
@Autowired
@Qualifier("dataSource")
private Database database;
@Test
public void testDatabaseProperties() {
Assert.assertNotNull(database);
Assert.assertEquals("jdbc:postgresql:/localhost:5432/instance", database.getUrl());
Assert.assertEquals("jdbc:postgresql:/localhost:5432", database.getUrl());
Assert.assertEquals("foo", database.getUsername());
Assert.assertEquals("bar", database.getPassword());
}

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