Merge branch 'master' into stream-foreach-ifelse-logic

This commit is contained in:
RoscoeLotriet 2018-10-01 14:18:57 +02:00
commit 1a8b799e93
87 changed files with 2033 additions and 170 deletions

View File

@ -0,0 +1,50 @@
package com.baeldung.algorithms.mergesort;
public class MergeSort {
public static void main(String[] args) {
int[] a = { 5, 1, 6, 2, 3, 4 };
mergeSort(a, a.length);
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
public static void mergeSort(int[] a, int n) {
if (n < 2)
return;
int mid = n / 2;
int[] l = new int[mid];
int[] r = new int[n - mid];
for (int i = 0; i < mid; i++) {
l[i] = a[i];
}
for (int i = mid; i < n; i++) {
r[i - mid] = a[i];
}
mergeSort(l, mid);
mergeSort(r, n - mid);
merge(a, l, r, mid, n - mid);
}
public static void merge(int[] a, int[] l, int[] r, int left, int right) {
int i = 0, j = 0, k = 0;
while (i < left && j < right) {
if (l[i] < r[j])
a[k++] = l[i++];
else
a[k++] = r[j++];
}
while (i < left)
a[k++] = l[i++];
while (j < right)
a[k++] = r[j++];
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.mergesort;
import org.junit.Assert;
import org.junit.Test;
public class MergeSortUnitTest {
@Test
public void positiveTest() {
int[] actual = { 5, 1, 6, 2, 3, 4 };
int[] expected = { 1, 2, 3, 4, 5, 6 };
MergeSort.mergeSort(actual, actual.length);
Assert.assertArrayEquals(expected, actual);
}
}

View File

@ -7,7 +7,7 @@ import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
public class AppUnitTest
extends TestCase
{
/**
@ -15,7 +15,7 @@ public class AppTest
*
* @param testName name of the test case
*/
public AppTest( String testName )
public AppUnitTest( String testName )
{
super( testName );
}
@ -25,7 +25,7 @@ public class AppTest
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
return new TestSuite( AppUnitTest.class );
}
/**

View File

@ -6,7 +6,7 @@
<groupId>com.baeldung</groupId>
<artifactId>apache-avro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Apache Avro</version>
<name>Apache Avro</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

View File

@ -13,7 +13,7 @@ import java.util.Objects;
import static org.junit.Assert.*;
public class AvroSerealizerDeSerealizerTest {
public class AvroSerealizerDeSerealizerUnitTest {
AvroSerealizer serealizer;
AvroDeSerealizer deSerealizer;

46
apache-geode/pom.xml Normal file
View File

@ -0,0 +1,46 @@
<?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>apache-geode</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<geode.core>1.6.0</geode.core>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.geode</groupId>
<artifactId>geode-core</artifactId>
<version>${geode.core}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,78 @@
package com.baeldung.geode;
import java.io.Serializable;
import java.util.Objects;
public class Customer implements Serializable {
private static final long serialVersionUID = -7482516011038799900L;
private CustomerKey key;
private String firstName;
private String lastName;
private Integer age;
public Customer() {
}
public Customer(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public Customer(CustomerKey key, String firstName, String lastName, int age) {
this(firstName, lastName, age);
this.key = key;
}
// setters and getters
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Customer{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", age=" + age + '}';
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Customer customer = (Customer) o;
return Objects.equals(firstName, customer.firstName) && Objects.equals(lastName, customer.lastName) && Objects.equals(age, customer.age);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, age);
}
}

View File

@ -0,0 +1,57 @@
package com.baeldung.geode;
import java.io.Serializable;
public class CustomerKey implements Serializable {
private static final long serialVersionUID = -3529253035303792458L;
private long id;
private String country;
public CustomerKey(long id) {
this.id = id;
this.country = "USA";
}
public CustomerKey(long id, String country) {
this.id = id;
this.country = country;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
CustomerKey that = (CustomerKey) o;
if (id != that.id)
return false;
return country != null ? country.equals(that.country) : that.country == null;
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (country != null ? country.hashCode() : 0);
return result;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.geode.functions;
import com.baeldung.geode.Customer;
import com.baeldung.geode.CustomerKey;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionContext;
import org.apache.geode.cache.execute.RegionFunctionContext;
import java.util.Map;
public class UpperCaseNames implements Function<Boolean> {
private static final long serialVersionUID = -8946294032165677602L;
@Override
public void execute(FunctionContext<Boolean> context) {
RegionFunctionContext regionContext = (RegionFunctionContext) context;
Region<CustomerKey, Customer> region = regionContext.getDataSet();
for (Map.Entry<CustomerKey, Customer> entry : region.entrySet()) {
Customer customer = entry.getValue();
customer.setFirstName(customer.getFirstName()
.toUpperCase());
}
context.getResultSender()
.lastResult(true);
}
@Override
public String getId() {
return getClass().getName();
}
}

View File

@ -0,0 +1,110 @@
package com.baeldung.geode;
import com.baeldung.geode.functions.UpperCaseNames;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.cache.execute.Execution;
import org.apache.geode.cache.execute.FunctionService;
import org.apache.geode.cache.query.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class GeodeSamplesIntegrationTest {
ClientCache cache = null;
Region<String, String> region = null;
Region<Integer, Customer> queryRegion = null;
Region<CustomerKey, Customer> customerRegion = null;
@Before
public void connect() {
this.cache = new ClientCacheFactory().addPoolLocator("localhost", 10334)
.create();
this.region = this.cache.<String, String> createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
.create("baeldung");
this.customerRegion = this.cache.<CustomerKey, Customer> createClientRegionFactory(ClientRegionShortcut.CACHING_PROXY)
.create("baeldung-customers");
}
@After
public void cleanup() {
this.cache.close();
}
@Test
public void whenSendMessageToRegion_thenMessageSavedSuccessfully() {
this.region.put("1", "Hello");
this.region.put("2", "Baeldung");
assertEquals("Hello", region.get("1"));
assertEquals("Baeldung", region.get("2"));
}
@Test
public void whenPutMultipleValuesAtOnce_thenValuesSavedSuccessfully() {
Supplier<Stream<String>> keys = () -> Stream.of("A", "B", "C", "D", "E");
Map<String, String> values = keys.get()
.collect(Collectors.toMap(Function.identity(), String::toLowerCase));
this.region.putAll(values);
keys.get()
.forEach(k -> assertEquals(k.toLowerCase(), this.region.get(k)));
}
@Test
public void whenPutCustomKey_thenValuesSavedSuccessfully() {
CustomerKey key = new CustomerKey(123);
Customer customer = new Customer(key, "William", "Russell", 35);
Map<CustomerKey, Customer> customerInfo = new HashMap<>();
customerInfo.put(key, customer);
this.customerRegion.putAll(customerInfo);
Customer storedCustomer = this.customerRegion.get(key);
assertEquals("William", storedCustomer.getFirstName());
assertEquals("Russell", storedCustomer.getLastName());
}
@Test
public void whenFindACustomerUsingOQL_thenCorrectCustomerObject() throws NameResolutionException, TypeMismatchException, QueryInvocationTargetException, FunctionDomainException {
Map<CustomerKey, Customer> data = new HashMap<>();
data.put(new CustomerKey(1), new Customer("Gheorge", "Manuc", 36));
data.put(new CustomerKey(2), new Customer("Allan", "McDowell", 43));
this.customerRegion.putAll(data);
QueryService queryService = this.cache.getQueryService();
String query = "select * from /baeldung-customers c where c.firstName = 'Allan'";
SelectResults<Customer> queryResults = (SelectResults<Customer>) queryService.newQuery(query)
.execute();
assertEquals(1, queryResults.size());
}
@Test
public void whenExecuteUppercaseNames_thenCustomerNamesAreUppercased() {
Execution execution = FunctionService.onRegion(this.customerRegion);
execution.execute(UpperCaseNames.class.getName());
Customer customer = this.customerRegion.get(new CustomerKey(1));
assertEquals("GHEORGE", customer.getFirstName());
}
}

View File

@ -18,6 +18,7 @@ import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
@ -50,7 +51,7 @@ public class FileOperationsManualTest {
@Test
public void givenFileName_whenUsingJarFile_thenFileData() throws IOException {
String expectedData = "BSD License";
String expectedData = "MIT License";
Class clazz = Matchers.class;
InputStream inputStream = clazz.getResourceAsStream("/LICENSE.txt");
@ -79,7 +80,7 @@ public class FileOperationsManualTest {
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileTest.txt").getFile());
String data = FileUtils.readFileToString(file);
String data = FileUtils.readFileToString(file, "UTF-8");
assertEquals(expectedData, data.trim());
}
@ -102,12 +103,11 @@ public class FileOperationsManualTest {
Path path = Paths.get(getClass().getClassLoader().getResource("fileTest.txt").toURI());
StringBuilder data = new StringBuilder();
Stream<String> lines = Files.lines(path);
lines.forEach(line -> data.append(line).append("\n"));
String data = lines.collect(Collectors.joining("\n"));
lines.close();
assertEquals(expectedData, data.toString().trim());
assertEquals(expectedData, data.trim());
}
private String readFromInputStream(InputStream inputStream) throws IOException {

View File

@ -0,0 +1 @@
Hello World from fileTest.txt!!!

View File

@ -0,0 +1,9 @@
package com.baeldung.memoryleaks.equalshashcode;
public class Person {
public String name;
public Person(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.memoryleaks.equalshashcode;
public class PersonOptimized {
public String name;
public PersonOptimized(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof PersonOptimized)) {
return false;
}
PersonOptimized person = (PersonOptimized) o;
return person.name.equals(name);
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + name.hashCode();
return result;
}}

View File

@ -0,0 +1,32 @@
package com.baeldung.memoryleaks.finalize;
import java.nio.charset.Charset;
import java.util.Random;
public class BulkyObject {
private String data[];
public BulkyObject() {
data = new String[1000000];
for(int i=0; i<1000000; i++) {
data[i] = getRandomString();
}
}
private String getRandomString() {
byte[] array = new byte[1000];
new Random().nextBytes(array);
return new String(array, Charset.forName("UTF-8"));
}
@Override
public void finalize() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finalizer called");
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.memoryleaks.finalize;
import java.nio.charset.Charset;
import java.util.Random;
public class BulkyObjectOptimized {
private String data[];
public BulkyObjectOptimized() {
data = new String[1000000];
for(int i=0; i<1000000; i++) {
data[i] = getRandomString();
}
}
private String getRandomString() {
byte[] array = new byte[1000];
new Random().nextBytes(array);
return new String(array, Charset.forName("UTF-8"));
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.memoryleaks.innerclass;
import java.nio.charset.Charset;
import java.util.Random;
public class BulkyObject {
private String data[];
public BulkyObject() {
data = new String[1000000];
for(int i=0; i<1000000; i++) {
data[i] = getRandomString();
}
}
private String getRandomString() {
byte[] array = new byte[1000];
new Random().nextBytes(array);
return new String(array, Charset.forName("UTF-8"));
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.memoryleaks.innerclass;
public class InnerClassDriver {
public static InnerClassWrapper.SimpleInnerClass getSimpleInnerClassObj() {
return new InnerClassWrapper().new SimpleInnerClass();
}
public static void main2(String[] args) {
InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = getSimpleInnerClassObj();
System.out.println("Debug point");
}
public static void main(String[] args) {
StaticNestedClassWrapper.StaticNestedClass simpleInnerClassObj = new StaticNestedClassWrapper.StaticNestedClass();
System.out.println("Debug point");
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.memoryleaks.innerclass;
public class InnerClassWrapper {
private BulkyObject bulkyObject = new BulkyObject();
public class SimpleInnerClass {
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.memoryleaks.innerclass;
public class StaticNestedClassWrapper {
private BulkyObject bulkyObject = new BulkyObject();
public static class StaticNestedClass {
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.memoryleaks.internedstrings;
public class InternedString {
private static final String FILEPATH = "C:\\bigstring.txt";
public void readString() {
String s1 = ReadStringFromFileUtil.read(FILEPATH).intern();
String s2 = ReadStringFromFileUtil.read(FILEPATH).intern();
if (s1 == s2) {
System.out.println("Both the strings objects are same");
}
else {
System.out.println("Both the strings objects are different");
}
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.memoryleaks.internedstrings;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileUtil {
public static String read(String fileName) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.memoryleaks.internedstrings;
public class StringObject {
private static final String FILEPATH = "C:\\bigstring.txt";
public void readString() {
String s1 = ReadStringFromFileUtil.read(FILEPATH);
String s2 = ReadStringFromFileUtil.read(FILEPATH);
if (s1 == s2) {
System.out.println("Both the strings objects are same");
}
else {
System.out.println("Both the strings objects are different");
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.memoryleaks.staticfields;
import java.util.ArrayList;
import java.util.List;
public class NonStaticFieldsDemo {
public List<Double> list = new ArrayList<>();
public void populateList() {
for (int i = 0; i < 10000000; i++) {
list.add(Math.random());
}
System.out.println("Debug Point 2");
}
public static void main(String[] args) {
System.out.println("Debug Point 1");
new NonStaticFieldsDemo().populateList();
System.out.println("Debug Point 3");
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.memoryleaks.staticfields;
import java.util.ArrayList;
import java.util.List;
public class StaticFieldsDemo {
public static List<Double> list = new ArrayList<>();
public void populateList() {
for (int i = 0; i < 10000000; i++) {
list.add(Math.random());
}
System.out.println("Debug Point 2");
}
public static void main(String[] args) {
System.out.println("Debug Point 1");
new StaticFieldsDemo().populateList();
System.out.println("Debug Point 3");
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.memoryleaks.equalshashcode;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
public class PersonMemoryLeakUnitTest {
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenMap_whenEqualsAndHashCodeNotOverridden_thenMemoryLeak() {
Map<Person, Integer> map = new HashMap<Person, Integer>();
for(int i=0; i<10000000; i++) {
map.put(new Person("jon"), 1);
}
assertTrue(map.size() > 1);
System.out.print("Debug Point - VisuaLVM");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenMap_whenEqualsAndHashCodeOverridden_thenNoMemoryLeak() {
Map<PersonOptimized, Integer> map = new HashMap<PersonOptimized, Integer>();
for(int i=0; i<10000; i++) {
map.put(new PersonOptimized("jon"), 1);
}
assertTrue(map.size() == 1);
System.out.print("Debug Point - VisuaLVM");
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.memoryleaks.finalize;
import org.junit.Ignore;
import org.junit.Test;
public class FinalizeMemoryLeakUnitTest {
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenObjectWithFinalizer_whenCreatingAndDestroyingThisObject_thenMemoryLeak() {
BulkyObject[] stock = new BulkyObject[100000];
for(int i=0; i<100000; i++) {
stock[i] = new BulkyObject();
}
System.out.print("Debug Point - VisuaLVM");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenObjectWithoutFinalizer_whenCreatingAndDestroyingThisObject_thenNoMemoryLeak() {
BulkyObjectOptimized[] stock = new BulkyObjectOptimized[100000];
for(int i=0; i<100000; i++) {
stock[i] = new BulkyObjectOptimized();
}
System.out.print("Debug Point - VisuaLVM");
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.memoryleaks.innerclass;
import org.junit.Ignore;
import org.junit.Test;
public class StaticInnerClassMemoryLeakUnitTest {
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenUsingInnerClass_whenInitializingInnerClass_thenInnerClassHoldsReferenceOfOuterObject() {
InnerClassWrapper.SimpleInnerClass simpleInnerClassObj = new InnerClassWrapper().new SimpleInnerClass();
System.out.print("Debug Point - VisuaLVM");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenUsingStaticNestedClass_whenInitializingInnerClass_thenStaticNestedClassDoesntReferenceOuterObject() {
StaticNestedClassWrapper.StaticNestedClass staticNestedClassObj = new StaticNestedClassWrapper.StaticNestedClass();
System.out.print("Debug Point - VisuaLVM");
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.memoryleaks.internedstrings;
import org.junit.Ignore;
import org.junit.Test;
public class StringInternMemoryLeakUnitTest {
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenJava6OrBelow_whenInterningLargeStrings_thenPermgenIncreases() {
new InternedString().readString();
System.out.print("Debug Point - VisuaLVM");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenJava6OrBelow_whenNotInterningLargeStrings_thenPermgenDoesntIncrease() {
new StringObject().readString();
System.out.print("Debug Point - VisuaLVM");
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.memoryleaks.staticfields;
import java.util.ArrayList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
public class NonStaticFieldsMemoryLeakUnitTest {
public List<Double> list = new ArrayList<>();
public void populateList() {
for (int i = 0; i < 10000000; i++) {
list.add(Math.random());
}
System.out.println("Debug Point 2");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenNonStaticLargeList_whenPopulatingList_thenListGarbageCollected() {
System.out.println("Debug Point 1");
new NonStaticFieldsMemoryLeakUnitTest().populateList();
System.out.println("Debug Point 3");
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.memoryleaks.staticfields;
import java.util.ArrayList;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
public class StaticFieldsMemoryLeakUnitTest {
public static List<Double> list = new ArrayList<>();
public void populateList() {
for (int i = 0; i < 10000000; i++) {
list.add(Math.random());
}
System.out.println("Debug Point 2");
}
@Test
@Ignore // Test deliberately ignored as memory leak tests consume lots of resources
public void givenStaticLargeList_whenPopulatingList_thenListIsNotGarbageCollected() {
System.out.println("Debug Point 1");
new StaticFieldsDemo().populateList();
System.out.println("Debug Point 3");
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.ternaryoperator;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class TernaryOperatorUnitTest {
@Test
public void givenACondition_whenUsingTernaryOperator_thenItEvaluatesConditionAndReturnsAValue() {
int number = 10;
String msg = number > 10 ? "Number is greater than 10" : "Number is less than or equal to 10";
assertThat(msg).isEqualTo("Number is less than or equal to 10");
}
@Test
public void givenATrueCondition_whenUsingTernaryOperator_thenOnlyExpression1IsEvaluated() {
int exp1 = 0, exp2 = 0;
int result = 12 > 10 ? ++exp1 : ++exp2;
assertThat(exp1).isEqualTo(1);
assertThat(exp2).isEqualTo(0);
assertThat(result).isEqualTo(1);
}
@Test
public void givenAFalseCondition_whenUsingTernaryOperator_thenOnlyExpression2IsEvaluated() {
int exp1 = 0, exp2 = 0;
int result = 8 > 10 ? ++exp1 : ++exp2;
assertThat(exp1).isEqualTo(0);
assertThat(exp2).isEqualTo(1);
assertThat(result).isEqualTo(1);
}
@Test
public void givenANestedCondition_whenUsingTernaryOperator_thenCorrectValueIsReturned() {
int number = 6;
String msg = number > 10 ? "Number is greater than 10" : number > 5 ? "Number is greater than 5" : "Number is less than or equal to 5";
assertThat(msg).isEqualTo("Number is greater than 5");
}
}

View File

@ -65,6 +65,7 @@
<properties>
<flyway-core.version>5.0.2</flyway-core.version>
<flyway-maven-plugin.version>5.0.2</flyway-maven-plugin.version>
<h2.version>1.4.195</h2.version>
</properties>
</project>

View File

@ -16,7 +16,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@ContextConfiguration(classes = FlywayCallbackTestConfig.class)
public class FlywayApplicationTest {
public class FlywayApplicationUnitTest {
private Log log = LogFactory.getLog(getClass());

View File

@ -18,9 +18,9 @@ import org.junit.Test;
import com.stackify.models.User;
import com.stackify.services.MyService;
public class MyServiceTest {
public class MyServiceUnitTest {
private static final Logger logger = LogManager.getLogger(MyServiceTest.class);
private static final Logger logger = LogManager.getLogger(MyServiceUnitTest.class);
@Test
public void testService() {

View File

@ -9,7 +9,7 @@ import com.stackify.models.Employee;
import ch.qos.logback.classic.Level;
public class EmployeeServiceTest {
public class EmployeeServiceUnitTest {
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
private EmployeeService employeeService = new EmployeeService();

View File

@ -12,7 +12,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M5</version>
<version>2.0.0.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>

View File

@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M6</version>
<version>2.0.0.RELEASE</version>
<relativePath />
</parent>

View File

@ -6,7 +6,7 @@ import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.CoreMatchers.*;
public class UserServiceTest {
public class UserServiceLiveTest {
@Test
public void whenAddUser_thenGetUserOk() {
RestAssured.baseURI = "http://localhost:8080/rest-server";

View File

@ -0,0 +1,32 @@
package com.baeldung.date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.Date;
import org.joda.time.Years;
public class AgeCalculator {
public int calculateAge(LocalDate birthDate, LocalDate currentDate) {
// validate inputs ...
return Period.between(birthDate, currentDate)
.getYears();
}
public int calculateAgeWithJodaTime(org.joda.time.LocalDate birthDate, org.joda.time.LocalDate currentDate) {
// validate inputs ...
Years age = Years.yearsBetween(birthDate, currentDate);
return age.getYears();
}
public int calculateAgeWithJava7(Date birthDate, Date currentDate) {
// validate inputs ...
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
int d1 = Integer.parseInt(formatter.format(birthDate));
int d2 = Integer.parseInt(formatter.format(currentDate));
int age = (d2 - d1) / 10000;
return age;
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.date;
import static org.junit.Assert.assertEquals;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import org.junit.jupiter.api.Test;
public class AgeCalculatorUnitTest {
AgeCalculator ageCalculator = new AgeCalculator();
@Test
public void givenLocalDate_whenCalculateAge_thenOk() {
assertEquals(10, ageCalculator.calculateAge(LocalDate.of(2008, 5, 20), LocalDate.of(2018, 9, 20)));
}
@Test
public void givenJodaTime_whenCalculateAge_thenOk() {
assertEquals(10, ageCalculator.calculateAgeWithJodaTime(new org.joda.time.LocalDate(2008, 5, 20), new org.joda.time.LocalDate(2018, 9, 20)));
}
@Test
public void givenDate_whenCalculateAge_thenOk() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
Date birthDate = sdf.parse("2008-05-20");
Date currentDate = sdf.parse("2018-09-20");
assertEquals(10, ageCalculator.calculateAgeWithJava7(birthDate, currentDate));
}
}

View File

@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class DateDiffTest {
public class DateDiffUnitTest {
@Test
public void givenTwoDatesBeforeJava8_whenDifferentiating_thenWeGetSix() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH);

View File

@ -0,0 +1,21 @@
package com.baeldung.percentage;
import java.util.Scanner;
public class PercentageCalculator {
public double calculatePercentage(double obtained,double total){
return obtained*100/total;
}
public static void main(String[] args) {
PercentageCalculator pc = new PercentageCalculator();
Scanner in = new Scanner(System.in);
System.out.println("Enter obtained marks:");
double obtained = in.nextDouble();
System.out.println("Enter total marks:");
double total =in.nextDouble();
System.out.println("Percentage obtained :"+pc.calculatePercentage(obtained,total));
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.percentage;
import org.junit.Assert;
import org.junit.Test;
public class PercentageCalculatorUnitTest {
private PercentageCalculator pc = new PercentageCalculator();
@Test
public void whenPass2Integers_thenShouldCalculatePercentage(){
Assert.assertEquals("Result not as expected",
50.0,pc.calculatePercentage(50,100),0.1);
}
@Test
public void whenPassObtainedMarksAsDouble_thenShouldCalculatePercentage(){
Assert.assertEquals("Result not as expected",5.05,
pc.calculatePercentage(50.5,1000),0.1);
}
@Test
public void whenPassTotalMarksAsDouble_thenShouldCalculatePercentage(){
Assert.assertEquals("Result not as expected",19.6,
pc.calculatePercentage(5,25.5),0.1);
}
@Test
public void whenPass2DoubleNumbers_thenShouldCalculatePercentage(){
Assert.assertEquals("Result not as expected",20,
pc.calculatePercentage(5.5,27.5),0.1);
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung.collection;
package com.baeldung.stream;
import java.util.ArrayList;
import java.util.List;

View File

@ -1,55 +1,73 @@
<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>javaxval</artifactId>
<version>0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>${javax.el-api.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>${javax.el.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
</dependency>
</dependencies>
<properties>
<validation-api.version>2.0.1.Final</validation-api.version>
<hibernate-validator.version>6.0.7.Final</hibernate-validator.version>
<javax.el-api.version>3.0.0</javax.el-api.version>
<javax.el.version>2.2.6</javax.el.version>
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
</properties>
<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>javaxval</artifactId>
<version>0.1-SNAPSHOT</version>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>${validation-api.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<version>${hibernate-validator.version}</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>${javax.el-api.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>javax.el</artifactId>
<version>${javax.el.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<validation-api.version>2.0.1.Final</validation-api.version>
<hibernate-validator.version>6.0.7.Final</hibernate-validator.version>
<javax.el-api.version>3.0.0</javax.el-api.version>
<javax.el.version>2.2.6</javax.el.version>
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<junit.version>4.12</junit.version>
<assertj.version>3.11.1</assertj.version>
</properties>
</project>

View File

@ -0,0 +1,14 @@
package org.baeldung.javabeanconstraints.appplication;
import javax.validation.Validation;
import javax.validation.Validator;
import org.baeldung.javabeanconstraints.entities.UserNotBlank;
public class Application {
public static void main(String[] args) throws Exception {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
UserNotBlank user = new UserNotBlank(" ");
validator.validate(user).stream().forEach(violation -> System.out.println(violation.getMessage()));
}
}

View File

@ -0,0 +1,22 @@
package org.baeldung.javabeanconstraints.entities;
import javax.validation.constraints.NotBlank;
public class UserNotBlank {
@NotBlank(message = "Name is mandatory")
private final String name;
public UserNotBlank(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" + "name=" + name + "}";
}
}

View File

@ -0,0 +1,22 @@
package org.baeldung.javabeanconstraints.entities;
import javax.validation.constraints.NotEmpty;
public class UserNotEmpty {
@NotEmpty(message = "Name is mandatory")
private final String name;
public UserNotEmpty(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" + "name=" + name + "}";
}
}

View File

@ -0,0 +1,22 @@
package org.baeldung.javabeanconstraints.entities;
import javax.validation.constraints.NotNull;
public class UserNotNull {
@NotNull(message = "Name is mandatory")
private final String name;
public UserNotNull(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "User{" + "name=" + name + "}";
}
}

View File

@ -0,0 +1,63 @@
package org.baeldung.javabeanconstraints.test;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import static org.assertj.core.api.Assertions.assertThat;
import org.baeldung.javabeanconstraints.entities.UserNotBlank;
import org.junit.BeforeClass;
import org.junit.Test;
public class UserNotBlankUnitTest {
private static Validator validator;
@BeforeClass
public static void setupValidatorInstance() {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
@Test
public void whenNotBlankName_thenNoConstraintViolations() {
UserNotBlank user = new UserNotBlank("John");
Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);
assertThat(violations.size()).isEqualTo(0);
}
@Test
public void whenBlankName_thenOneConstraintViolation() {
UserNotBlank user = new UserNotBlank(" ");
Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);
assertThat(violations.size()).isEqualTo(1);
}
@Test
public void whenEmptyName_thenOneConstraintViolation() {
UserNotBlank user = new UserNotBlank("");
Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);
assertThat(violations.size()).isEqualTo(1);
}
@Test
public void whenNullName_thenOneConstraintViolation() {
UserNotBlank user = new UserNotBlank(null);
Set<ConstraintViolation<UserNotBlank>> violations = validator.validate(user);
assertThat(violations.size()).isEqualTo(1);
}
@Test
public void whenToString_thenCorrect() {
UserNotBlank user = new UserNotBlank("John");
assertThat(user.toString()).isEqualTo("User{name=John}");
}
}

View File

@ -0,0 +1,54 @@
package org.baeldung.javabeanconstraints.test;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import static org.assertj.core.api.Assertions.assertThat;
import org.baeldung.javabeanconstraints.entities.UserNotEmpty;
import org.junit.BeforeClass;
import org.junit.Test;
public class UserNotEmptyUnitTest {
private static Validator validator;
@BeforeClass
public static void setupValidatorInstance() {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
@Test
public void whenNotEmptyName_thenNoConstraintViolations() {
UserNotEmpty user = new UserNotEmpty("John");
Set<ConstraintViolation<UserNotEmpty>> violations = validator.validate(user);
assertThat(violations.size()).isEqualTo(0);
}
@Test
public void whenEmptyName_thenOneConstraintViolation() {
UserNotEmpty user = new UserNotEmpty("");
Set<ConstraintViolation<UserNotEmpty>> violations = validator.validate(user);
assertThat(violations.size()).isEqualTo(1);
}
@Test
public void whenNullName_thenOneConstraintViolation() {
UserNotEmpty user = new UserNotEmpty(null);
Set<ConstraintViolation<UserNotEmpty>> violations = validator.validate(user);
assertThat(violations.size()).isEqualTo(1);
}
@Test
public void whenToString_thenCorrect() {
UserNotEmpty user = new UserNotEmpty("John");
assertThat(user.toString()).isEqualTo("User{name=John}");
}
}

View File

@ -0,0 +1,54 @@
package org.baeldung.javabeanconstraints.test;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import static org.assertj.core.api.Assertions.assertThat;
import org.baeldung.javabeanconstraints.entities.UserNotNull;
import org.junit.BeforeClass;
import org.junit.Test;
public class UserNotNullUnitTest {
private static Validator validator;
@BeforeClass
public static void setupValidatorInstance() {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
@Test
public void whenNotNullName_thenNoConstraintViolations() {
UserNotNull user = new UserNotNull("John");
Set<ConstraintViolation<UserNotNull>> violations = validator.validate(user);
assertThat(violations.size()).isEqualTo(0);
}
@Test
public void whenNullName_thenOneConstraintViolation() {
UserNotNull user = new UserNotNull(null);
Set<ConstraintViolation<UserNotNull>> violations = validator.validate(user);
assertThat(violations.size()).isEqualTo(1);
}
@Test
public void whenEmptyName_thenNoConstraintViolations() {
UserNotNull user = new UserNotNull("");
Set<ConstraintViolation<UserNotNull>> violations = validator.validate(user);
assertThat(violations.size()).isEqualTo(0);
}
@Test
public void whenToString_thenCorrect() {
UserNotNull user = new UserNotNull("John");
assertThat(user.toString()).isEqualTo("User{name=John}");
}
}

View File

@ -38,6 +38,16 @@
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.passay</groupId>
<artifactId>passay</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.cryptacular</groupId>
<artifactId>cryptacular</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>

View File

@ -0,0 +1,149 @@
package com.baeldung.passay;
import org.cryptacular.bean.EncodingHashBean;
import org.cryptacular.spec.CodecSpec;
import org.cryptacular.spec.DigestSpec;
import org.junit.Assert;
import org.junit.Test;
import org.passay.DictionaryRule;
import org.passay.DictionarySubstringRule;
import org.passay.DigestHistoryRule;
import org.passay.EnglishSequenceData;
import org.passay.HistoryRule;
import org.passay.IllegalCharacterRule;
import org.passay.IllegalRegexRule;
import org.passay.IllegalSequenceRule;
import org.passay.NumberRangeRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RepeatCharacterRegexRule;
import org.passay.RuleResult;
import org.passay.SourceRule;
import org.passay.UsernameRule;
import org.passay.WhitespaceRule;
import org.passay.dictionary.ArrayWordList;
import org.passay.dictionary.WordListDictionary;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class NegativeMatchingRulesUnitTest {
@Test
public void givenDictionaryRules_whenValidatePassword_thenFoundIllegalWordsFromDictionary() {
ArrayWordList arrayWordList = new ArrayWordList(new String[] { "bar", "foobar" });
WordListDictionary wordListDictionary = new WordListDictionary(arrayWordList);
DictionaryRule dictionaryRule = new DictionaryRule(wordListDictionary);
DictionarySubstringRule dictionarySubstringRule = new DictionarySubstringRule(wordListDictionary);
PasswordValidator passwordValidator = new PasswordValidator(dictionaryRule, dictionarySubstringRule);
RuleResult validate = passwordValidator.validate(new PasswordData("foobar"));
assertFalse(validate.isValid());
assertEquals("ILLEGAL_WORD:{matchingWord=foobar}", getDetail(validate, 0));
assertEquals("ILLEGAL_WORD:{matchingWord=bar}", getDetail(validate, 1));
}
@Test
public void givenHistoryRule_whenValidatePassword_thenFoundIllegalWordsFromHistory() {
HistoryRule historyRule = new HistoryRule();
PasswordData passwordData = new PasswordData("123");
passwordData.setPasswordReferences(new PasswordData.HistoricalReference("12345"), new PasswordData.HistoricalReference("1234"), new PasswordData.HistoricalReference("123"));
PasswordValidator passwordValidator = new PasswordValidator(historyRule);
RuleResult validate = passwordValidator.validate(passwordData);
assertFalse(validate.isValid());
assertEquals("HISTORY_VIOLATION:{historySize=3}", getDetail(validate, 0));
}
@Test
public void givenSeveralIllegalRules_whenValidatePassword_thenFoundSeveralIllegalPatterns() {
IllegalCharacterRule illegalCharacterRule = new IllegalCharacterRule(new char[] { 'a' });
IllegalRegexRule illegalRegexRule = new IllegalRegexRule("\\w{2}\\d{2}");
IllegalSequenceRule illegalSequenceRule = new IllegalSequenceRule(EnglishSequenceData.Alphabetical, 3, true);
NumberRangeRule numberRangeRule = new NumberRangeRule(1, 10);
WhitespaceRule whitespaceRule = new WhitespaceRule();
PasswordValidator passwordValidator = new PasswordValidator(illegalCharacterRule, illegalRegexRule, illegalSequenceRule, numberRangeRule, whitespaceRule);
RuleResult validate = passwordValidator.validate(new PasswordData("abcd22 "));
assertFalse(validate.isValid());
assertEquals("ILLEGAL_CHAR:{illegalCharacter=a, matchBehavior=contains}", getDetail(validate, 0));
assertEquals("ILLEGAL_MATCH:{match=cd22, pattern=\\w{2}\\d{2}}", getDetail(validate, 1));
assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=abc}", getDetail(validate, 2));
assertEquals("ILLEGAL_ALPHABETICAL_SEQUENCE:{sequence=bcd}", getDetail(validate, 3));
assertEquals("ILLEGAL_NUMBER_RANGE:{number=2, matchBehavior=contains}", getDetail(validate, 4));
assertEquals("ILLEGAL_WHITESPACE:{whitespaceCharacter= , matchBehavior=contains}", getDetail(validate, 5));
}
@Test
public void givenSourceRule_whenValidatePassword_thenFoundIllegalWordsFromSource() {
SourceRule sourceRule = new SourceRule();
PasswordData passwordData = new PasswordData("password");
passwordData.setPasswordReferences(new PasswordData.SourceReference("source", "password"));
PasswordValidator passwordValidator = new PasswordValidator(sourceRule);
RuleResult validate = passwordValidator.validate(passwordData);
assertFalse(validate.isValid());
assertEquals("SOURCE_VIOLATION:{source=source}", getDetail(validate, 0));
}
@Test
public void givenRepeatCharacterRegexRuleRule_whenValidatePassword_thenFoundIllegalPatternMatches() {
RepeatCharacterRegexRule repeatCharacterRegexRule = new RepeatCharacterRegexRule(3);
PasswordValidator passwordValidator = new PasswordValidator(repeatCharacterRegexRule);
RuleResult validate = passwordValidator.validate(new PasswordData("aaabbb"));
assertFalse(validate.isValid());
assertEquals("ILLEGAL_MATCH:{match=aaa, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 0));
assertEquals("ILLEGAL_MATCH:{match=bbb, pattern=([^\\x00-\\x1F])\\1{2}}", getDetail(validate, 1));
}
@Test
public void givenUserNameRule_whenValidatePassword_thenFoundUserNameInPassword() {
PasswordValidator passwordValidator = new PasswordValidator(new UsernameRule());
PasswordData passwordData = new PasswordData("testuser1234");
passwordData.setUsername("testuser");
RuleResult validate = passwordValidator.validate(passwordData);
assertFalse(validate.isValid());
assertEquals("ILLEGAL_USERNAME:{username=testuser, matchBehavior=contains}", getDetail(validate, 0));
}
@Test
public void givenPasswordAndHashBeanAndEncryptedReferences_whenValidate_thenPasswordValidationShouldPass() {
List<PasswordData.Reference> historicalReferences = Arrays.asList(new PasswordData.HistoricalReference("SHA256", "2e4551de804e27aacf20f9df5be3e8cd384ed64488b21ab079fb58e8c90068ab"));
PasswordData passwordData = new PasswordData("example!");
passwordData.setPasswordReferences(historicalReferences);
EncodingHashBean encodingHashBean = new EncodingHashBean(new CodecSpec("Base64"), new DigestSpec("SHA256"), 1, false);
PasswordValidator passwordValidator = new PasswordValidator(new DigestHistoryRule(encodingHashBean));
RuleResult validate = passwordValidator.validate(passwordData);
Assert.assertTrue(validate.isValid());
}
private String getDetail(RuleResult validate, int i) {
return validate.getDetails()
.get(i)
.toString();
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.passay;
import org.junit.Assert;
import org.junit.Test;
import org.passay.CharacterData;
import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.PasswordGenerator;
import java.util.stream.Stream;
public class PasswordGeneratorUnitTest {
@Test
public void givenDigitsGenerator_whenGeneratingPassword_thenPasswordContainsDigitsHasLength10() {
CharacterRule digits = new CharacterRule(EnglishCharacterData.Digit);
PasswordGenerator passwordGenerator = new PasswordGenerator();
String password = passwordGenerator.generatePassword(10, digits);
Assert.assertTrue(password.length() == 10);
Assert.assertTrue(containsOnlyCharactersFromSet(password, "0123456789"));
}
@Test
public void givenCustomizedRule_whenGenerating_thenGeneratedPasswordContainsCustomizedCharacters() {
CharacterRule specialCharacterRule = new CharacterRule(new CharacterData() {
@Override
public String getErrorCode() {
return "SAMPLE_ERROR_CODE";
}
@Override
public String getCharacters() {
return "ABCxyz123!@#";
}
});
PasswordGenerator passwordGenerator = new PasswordGenerator();
String password = passwordGenerator.generatePassword(10, specialCharacterRule);
Assert.assertTrue(containsOnlyCharactersFromSet(password, "ABCxyz123!@#"));
}
private boolean containsOnlyCharactersFromSet(String password, String setOfCharacters) {
return Stream.of(password.split(""))
.allMatch(it -> setOfCharacters.contains(it));
}
}

View File

@ -0,0 +1,81 @@
package com.baeldung.passay;
import org.junit.Assert;
import org.junit.Test;
import org.passay.LengthRule;
import org.passay.MessageResolver;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.PropertiesMessageResolver;
import org.passay.RuleResult;
import org.passay.RuleResultDetail;
import org.passay.RuleResultMetadata;
import org.passay.WhitespaceRule;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class PasswordValidatorUnitTest {
@Test
public void givenPasswordValidatorWithLengthRule_whenValidation_thenTooShortPassword() {
PasswordData passwordData = new PasswordData("1234");
PasswordValidator passwordValidator = new PasswordValidator(new LengthRule(5));
RuleResult validate = passwordValidator.validate(passwordData);
assertEquals(false, validate.isValid());
RuleResultDetail ruleResultDetail = validate.getDetails()
.get(0);
assertEquals("TOO_SHORT", ruleResultDetail.getErrorCode());
assertEquals(5, ruleResultDetail.getParameters()
.get("minimumLength"));
assertEquals(5, ruleResultDetail.getParameters()
.get("maximumLength"));
Integer lengthCount = validate.getMetadata()
.getCounts()
.get(RuleResultMetadata.CountCategory.Length);
assertEquals(Integer.valueOf(4), lengthCount);
}
@Test
public void givenPasswordValidatorWithLengthRule_whenValidation_thenTooLongPassword() {
PasswordData passwordData = new PasswordData("123456");
PasswordValidator passwordValidator = new PasswordValidator(new LengthRule(5));
RuleResult validate = passwordValidator.validate(passwordData);
assertFalse(validate.isValid());
Assert.assertEquals("TOO_LONG", validate.getDetails()
.get(0)
.getErrorCode());
}
@Test
public void givenPasswordValidatorWithLengthRule_whenValidation_thenCustomizedMeesagesAvailable() throws IOException {
URL resource = this.getClass()
.getClassLoader()
.getResource("messages.properties");
Properties props = new Properties();
props.load(new FileInputStream(resource.getPath()));
MessageResolver resolver = new PropertiesMessageResolver(props);
PasswordValidator validator = new PasswordValidator(resolver, new LengthRule(8, 16), new WhitespaceRule());
RuleResult tooShort = validator.validate(new PasswordData("XXXX"));
RuleResult tooLong = validator.validate(new PasswordData("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"));
assertEquals("Password must not contain less characters than 16.", validator.getMessages(tooShort)
.get(0));
assertEquals("Password must not have more characters than 16.", validator.getMessages(tooLong)
.get(0));
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.passay;
import org.junit.Test;
import org.passay.AllowedCharacterRule;
import org.passay.AllowedRegexRule;
import org.passay.CharacterCharacteristicsRule;
import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.LengthComplexityRule;
import org.passay.LengthRule;
import org.passay.PasswordData;
import org.passay.PasswordValidator;
import org.passay.RuleResult;
import static org.junit.Assert.*;
public class PositiveMatchingRulesUnitTest {
@Test
public void givenPasswordValidationRules_whenValidatingPassword_thenPosswordIsNotValidWithSeveralErrors() {
PasswordValidator passwordValidator = new PasswordValidator(new AllowedCharacterRule(new char[] { 'a', 'b', 'c' }), new AllowedRegexRule("\\d{2}\\w{10}"), new CharacterRule(EnglishCharacterData.LowerCase, 5), new LengthRule(8, 10));
RuleResult validate = passwordValidator.validate(new PasswordData("12abc"));
assertFalse(validate.isValid());
assertEquals("ALLOWED_CHAR:{illegalCharacter=1, matchBehavior=contains}", getDetail(validate, 0));
assertEquals("ALLOWED_CHAR:{illegalCharacter=2, matchBehavior=contains}", getDetail(validate, 1));
assertEquals("ALLOWED_MATCH:{pattern=\\d{2}\\w{10}}", getDetail(validate, 2));
assertEquals("INSUFFICIENT_LOWERCASE:{" + "minimumRequired=5, matchingCharacterCount=3, " + "validCharacters=abcdefghijklmnopqrstuvwxyz, " + "matchingCharacters=abc}", getDetail(validate, 3));
assertEquals("TOO_SHORT:{minimumLength=8, maximumLength=10}", getDetail(validate, 4));
}
@Test
public void givenRulesForDifferentPasswordLength_whenValidatingTwoDifferentPassword_thenBothOfThemAreInvalid() {
PasswordData shortPassword = new PasswordData("12ab");
PasswordData longPassword = new PasswordData("1234abcde");
LengthComplexityRule lengthComplexityRule = new LengthComplexityRule();
lengthComplexityRule.addRules("[1,5]", new CharacterRule(EnglishCharacterData.LowerCase, 5));
lengthComplexityRule.addRules("[6,10]", new AllowedCharacterRule(new char[] { 'a', 'b', 'c', 'd' }));
PasswordValidator passwordValidator = new PasswordValidator(lengthComplexityRule);
RuleResult validateShort = passwordValidator.validate(shortPassword);
RuleResult validateLong = passwordValidator.validate(longPassword);
assertFalse(validateShort.isValid());
assertFalse(validateLong.isValid());
assertEquals("INSUFFICIENT_LOWERCASE:{" + "minimumRequired=5, " + "matchingCharacterCount=2, " + "validCharacters=abcdefghijklmnopqrstuvwxyz, " + "matchingCharacters=ab}", getDetail(validateShort, 0));
assertEquals("ALLOWED_CHAR:{illegalCharacter=1, matchBehavior=contains}", getDetail(validateLong, 0));
}
@Test
public void givenCharacterCharacteristicsRule_whenValidatingPassword_thenItIsInvalidAsItBreaksToManyRules() {
PasswordData shortPassword = new PasswordData();
shortPassword.setPassword("12345abcde!");
CharacterCharacteristicsRule characterCharacteristicsRule = new CharacterCharacteristicsRule(4, new CharacterRule(EnglishCharacterData.LowerCase, 5), new CharacterRule(EnglishCharacterData.UpperCase, 5), new CharacterRule(EnglishCharacterData.Digit),
new CharacterRule(EnglishCharacterData.Special));
PasswordValidator passwordValidator = new PasswordValidator(characterCharacteristicsRule);
RuleResult validate = passwordValidator.validate(shortPassword);
assertFalse(validate.isValid());
assertEquals("INSUFFICIENT_UPPERCASE:{" + "minimumRequired=5, " + "matchingCharacterCount=0, " + "validCharacters=ABCDEFGHIJKLMNOPQRSTUVWXYZ, " + "matchingCharacters=}", getDetail(validate, 0));
assertEquals("INSUFFICIENT_CHARACTERISTICS:{" + "successCount=3, " + "minimumRequired=4, " + "ruleCount=4}", getDetail(validate, 1));
}
private String getDetail(RuleResult validate, int i) {
return validate.getDetails()
.get(i)
.toString();
}
}

View File

@ -0,0 +1,2 @@
TOO_LONG=Password must not have more characters than %2$s.
TOO_SHORT=Password must not contain less characters than %2$s.

View File

@ -1,16 +1,67 @@
package org.baeldung;
import java.io.IOException;
import java.util.HashMap;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.thrift.transport.TTransportException;
import org.baeldung.spring.data.cassandra.config.CassandraConfig;
import org.baeldung.spring.data.cassandra.model.Book;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cassandra.core.cql.CqlIdentifier;
import org.springframework.data.cassandra.core.CassandraAdminOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CassandraConfig.class)
public class SpringContextIntegrationTest {
@Test
public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };";
public static final String KEYSPACE_ACTIVATE_QUERY = "USE testKeySpace;";
public static final String DATA_TABLE_NAME = "book";
@Autowired
private CassandraAdminOperations adminTemplate;
@BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra();
final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
final Session session = cluster.connect();
session.execute(KEYSPACE_CREATION_QUERY);
session.execute(KEYSPACE_ACTIVATE_QUERY);
Thread.sleep(5000);
}
@Before
public void createTable() throws InterruptedException, TTransportException, ConfigurationException, IOException {
adminTemplate.createTable(true, CqlIdentifier.cqlId(DATA_TABLE_NAME), Book.class, new HashMap<String, Object>());
}
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
@After
public void dropTable() {
adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME));
}
@AfterClass
public static void stopCassandraEmbedded() {
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
}
}

View File

@ -0,0 +1,18 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import com.baeldung.spring.data.gemfire.function.GemfireConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=GemfireConfiguration.class, loader=AnnotationConfigContextLoader.class)
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,19 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.data.neo4j.config.MovieDatabaseNeo4jTestConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MovieDatabaseNeo4jTestConfiguration.class)
@ActiveProfiles(profiles = "test")
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -0,0 +1,17 @@
package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.baeldung.spring.data.redis.config.RedisConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RedisConfig.class)
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

60
pom.xml
View File

@ -610,12 +610,12 @@
<!--<module>java-dates</module> --> <!-- Commented because we have still not upgraded to java 9 -->
<module>java-websocket</module>
<module>activejdbc</module>
<!-- <module>animal-sniffer-mvn-plugin</module> --><!-- PMD voilation -->
<!-- <module>apache-avro</module> --><!-- Malformed POM -->
<module>animal-sniffer-mvn-plugin</module>
<module>apache-avro</module>
<module>apache-bval</module>
<module>apache-shiro</module>
<module>apache-spark</module>
<!-- <module>asciidoctor</module> --><!-- Malformed POM -->
<module>asciidoctor</module>
<module>checker-plugin</module>
<!-- <module>core-java-10</module> --><!-- Not upgraded to java 10 -->
<!-- <module>core-java-11</module> --><!-- Not upgraded to java 11 -->
@ -624,9 +624,9 @@
<module>dagger</module>
<module>data-structures</module>
<module>dubbo</module>
<!-- <module>flyway</module> --><!-- Malformed POM -->
<module>flyway</module>
<!-- <module>grpc</module> --><!-- protobuf-maven-plugin filecopy failure -->
<!-- <module>java-difference-date</module> --><!-- PMD voilation -->
<module>java-difference-date</module>
<!-- <module>JGit</module> --><!-- Unit test failure -->
<module>jni</module>
<module>jooby</module>
@ -634,13 +634,13 @@
<!-- <module>microprofile</module> --><!-- Takes too much time : Downloads 93 MBs zip and .. -->
<!-- <module>muleesb</module> --><!-- load main class org.mule.munit.remote.RemoteRunner -->
<module>ratpack</module>
<!-- <module>rest-with-spark-java</module> --><!-- PMD voilation -->
<module>rest-with-spark-java</module>
<module>spring-boot-autoconfiguration</module>
<module>spring-boot-custom-starter</module>
<module>spring-boot-jasypt</module>
<!-- <module>spring-custom-aop</module> --><!-- Malformed POM -->
<module>spring-custom-aop</module>
<module>spring-data-rest-querydsl</module>
<!-- <module>spring-groovy</module> --><!-- PMD voilation -->
<module>spring-groovy</module>
<module>spring-mobile</module>
<module>spring-mustache</module>
<module>spring-mvc-simple</module>
@ -651,7 +651,7 @@
<module>spring-roo</module>
<module>spring-security-stormpath</module>
<module>sse-jaxrs</module>
<!-- <module>static-analysis</module> --><!-- PMD voilation -->
<module>static-analysis</module>
<module>stripe</module>
<!-- <module>structurizr</module> --><!-- Artiifact not found -->
<module>Twitter4J</module>
@ -662,13 +662,13 @@
<!-- <module>graphql/graphql-java</module> --><!-- Wrong parent -->
<!-- <module>guest/deep-jsf</module> --><!-- guest post on different site -->
<!-- <module>guest/junit5-example</module> --><!-- guest post on different site - Compilation failure -->
<!-- <module>guest/log4j2-example</module> --><!-- PMD voilation -->
<!-- <module>guest/logback-example</module> --><!-- PMD voilation -->
<!-- <module>guest/log4j2-example</module> --><!-- guest post on different site -->
<!-- <module>guest/logback-example</module> --><!-- guest post on different site -->
<!-- <module>guest/memory-leaks</module> --><!-- guest post on different site -->
<!-- <module>guest/remote-debugging</module> --><!-- guest post on different site -->
<!-- <module>guest/spring-boot-app</module> --><!-- guest post on different site -->
<!-- <module>guest/spring-mvc</module> --><!-- Malformed POM -->
<!-- <module>guest/spring-security</module> --><!-- Malformed POM -->
<!-- <module>guest/spring-mvc</module> --><!-- guest post on different site -->
<!-- <module>guest/spring-security</module> --><!-- guest post on different site -->
<!-- <module>guest/thread-pools</module> --><!-- guest post on different site -->
<!-- <module>guest/tomcat-app</module> --><!-- guest post on different site -->
<module>jenkins/hello-world</module>
@ -679,7 +679,7 @@
<module>spring-boot-h2/spring-boot-h2-database</module>
<!--module>spring-boot-h2/spring-boot-h2-remote-app</module-->
<!-- <module>guest\webservices\rest-client</module> --><!-- guest post on different site -->
<!-- <module>guest\webservices\rest-server</module> --><!-- PMD voilation -->
<!-- <module>guest\webservices\rest-server</module> --><!-- guest post on different site -->
<!-- <module>guest\webservices\spring-rest-service</module> --><!-- guest post on different site -->
</modules>
@ -1081,13 +1081,13 @@
<!-- <module>libraries</module> <module>jmeter</module> -->
<!--<module>java-dates</module> --> <!-- Commented because we have still not upgraded to java 9 -->
<module>java-websocket</module>
<!-- <module>activejdbc</module> --><!-- PMD voilation -->
<!-- <module>animal-sniffer-mvn-plugin</module> --><!-- PMD voilation -->
<!-- <module>apache-avro</module> --><!-- Malformed POM -->
<module>activejdbc</module>
<module>animal-sniffer-mvn-plugin</module>
<module>apache-avro</module>
<module>apache-bval</module>
<module>apache-shiro</module>
<module>apache-spark</module>
<!-- <module>asciidoctor</module> --><!-- Malformed POM -->
<module>asciidoctor</module>
<module>checker-plugin</module>
<!-- <module>core-java-10</module> --><!-- Not upgraded to java 10 -->
<!-- <module>core-java-11</module> --><!-- Not upgraded to java 11 -->
@ -1096,9 +1096,9 @@
<module>dagger</module>
<module>data-structures</module>
<module>dubbo</module>
<!-- <module>flyway</module> --><!-- Malformed POM -->
<module>flyway</module>
<!-- <module>grpc</module> --><!-- protobuf-maven-plugin filecopy failure -->
<!-- <module>java-difference-date</module> --><!-- PMD voilation -->
<module>java-difference-date</module>
<!-- <module>JGit</module> --><!-- Unit test failure -->
<module>jni</module>
<module>jooby</module>
@ -1106,13 +1106,13 @@
<!-- <module>microprofile</module> --><!-- Takes too much time : Downloads 93 MBs zip and .. -->
<!-- <module>muleesb</module> --><!-- load main class org.mule.munit.remote.RemoteRunner -->
<module>ratpack</module>
<!-- <module>rest-with-spark-java</module> --><!-- PMD voilation -->
<module>rest-with-spark-java</module>
<module>spring-boot-autoconfiguration</module>
<module>spring-boot-custom-starter</module>
<!-- <module>spring-boot-jasypt</module> --><!-- PMD voilation -->
<!-- <module>spring-custom-aop</module> --><!-- Malformed POM -->
<module>spring-boot-jasypt</module>
<module>spring-custom-aop</module>
<module>spring-data-rest-querydsl</module>
<!-- <module>spring-groovy</module> --><!-- PMD voilation -->
<module>spring-groovy</module>
<module>spring-mobile</module>
<module>spring-mustache</module>
<module>spring-mvc-simple</module>
@ -1123,7 +1123,7 @@
<module>spring-roo</module>
<module>spring-security-stormpath</module>
<module>sse-jaxrs</module>
<!-- <module>static-analysis</module> --><!-- PMD voilation -->
<module>static-analysis</module>
<module>stripe</module>
<!-- <module>structurizr</module> --><!-- Artiifact not found -->
<!-- <module>Twitter4J</module> --><!-- Test failure -->
@ -1134,13 +1134,13 @@
<!-- <module>graphql/graphql-java</module> --><!-- Wrong parent -->
<!-- <module>guest/deep-jsf</module> --><!-- guest post on different site -->
<!-- <module>guest/junit5-example</module> --><!-- guest post on different site - Compilation failure -->
<!-- <module>guest/log4j2-example</module> --><!-- PMD voilation -->
<!-- <module>guest/logback-example</module> --><!-- PMD voilation -->
<!-- <module>guest/log4j2-example</module> --><!-- guest post on different site -->
<!-- <module>guest/logback-example</module> --><!-- guest post on different site -->
<!-- <module>guest/memory-leaks</module> --><!-- guest post on different site -->
<!-- <module>guest/remote-debugging</module> --><!-- guest post on different site -->
<!-- <module>guest/spring-boot-app</module> --><!-- guest post on different site -->
<!-- <module>guest/spring-mvc</module> --><!-- Malformed POM -->
<!-- <module>guest/spring-security</module> --><!-- Malformed POM -->
<!-- <module>guest/spring-mvc</module> --><!-- guest post on different site -->
<!-- <module>guest/spring-security</module> --><!-- guest post on different site -->
<!-- <module>guest/thread-pools</module> --><!-- guest post on different site -->
<!-- <module>guest/tomcat-app</module> --><!-- guest post on different site -->
<module>jenkins/hello-world</module>
@ -1151,7 +1151,7 @@
<module>spring-boot-h2/spring-boot-h2-database</module>
<!--module>spring-boot-h2/spring-boot-h2-remote-app</module-->
<!-- <module>guest\webservices\rest-client</module> --><!-- guest post on different site -->
<!-- <module>guest\webservices\rest-server</module> --><!-- PMD voilation -->
<!-- <module>guest\webservices\rest-server</module> --><!-- guest post on different site -->
<!-- <module>guest\webservices\spring-rest-service</module> --><!-- guest post on different site -->
</modules>

View File

@ -16,16 +16,16 @@ import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class AppTest extends TestCase {
public class AppLiveTest extends TestCase {
ObjectMapper mapper = new ObjectMapper();
public AppTest( String testName ) {
public AppLiveTest( String testName ) {
super( testName );
}
public static Test suite() {
return new TestSuite( AppTest.class );
return new TestSuite( AppLiveTest.class );
}
public void testApp() throws IOException, ClassNotFoundException {

View File

@ -2,5 +2,6 @@
- [RxJava and Error Handling](http://www.baeldung.com/rxjava-error-handling)
- [RxJava 2 Flowable](http://www.baeldung.com/rxjava-2-flowable)
- [RxJava 2 - Completable](http://www.baeldung.com/rxjava-completable)
- [RxJava Maybe](http://www.baeldung.com/rxjava-maybe)
- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay)
- [Introduction to RxRelay for RxJava](http://www.baeldung.com/rx-relay)

View File

@ -38,9 +38,8 @@
<properties>
<assertj.version>3.8.0</assertj.version>
<rx.java2.version>2.1.3</rx.java2.version>
<rx.java2.version>2.2.2</rx.java2.version>
<awaitility.version>1.7.0</awaitility.version>
<rxrelay.version>2.0.0</rxrelay.version>
</properties>
</project>

View File

@ -0,0 +1,112 @@
package com.baeldung.rxjava;
import io.reactivex.Completable;
import io.reactivex.Flowable;
import io.reactivex.Single;
import io.reactivex.observers.DisposableCompletableObserver;
import org.junit.Before;
import org.junit.Test;
public class CompletableUnitTest {
Completable first;
Completable second;
Completable error;
Throwable throwable = new RuntimeException();
@Before
public void setUpCompletables() {
first = Completable.fromSingle(Single.just(1));
second = Completable.fromRunnable(() -> {});
error = Single.error(throwable)
.ignoreElement();
}
@Test
public void whenCompletableConstructed_thenCompletedSuccessfully() {
Completable completed = Completable.complete();
completed.subscribe(new DisposableCompletableObserver() {
@Override
public void onComplete() {
System.out.println("Completed!");
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
});
Flowable<String> flowable = Flowable.just("request received", "user logged in");
Completable flowableCompletable = Completable.fromPublisher(flowable);
Completable singleCompletable = Single.just(1)
.ignoreElement();
completed.andThen(flowableCompletable)
.andThen(singleCompletable)
.test()
.assertComplete();
}
@Test
public void whenCombiningCompletables_thenCompletedSuccessfully() {
first.andThen(second)
.test()
.assertComplete();
}
@Test
public void whenCombinedWithError_thenCompletedWithError() {
first.andThen(second)
.andThen(error)
.test()
.assertError(throwable);
}
@Test
public void whenCombinedWithNever_thenDoesNotComplete() {
first.andThen(second)
.andThen(Completable.never())
.test()
.assertNotComplete();
}
@Test
public void whenMergedCompletables_thenCompletedSuccessfully() {
Completable.mergeArray(first, second)
.test()
.assertComplete();
}
@Test
public void whenMergedWithError_thenCompletedWithError() {
Completable.mergeArray(first, second, error)
.test()
.assertError(throwable);
}
@Test
public void whenFlatMaped_thenCompletedSuccessfully() {
Completable allElementsCompletable = Flowable.just("request received", "user logged in")
.flatMapCompletable(message -> Completable
.fromRunnable(() -> System.out.println(message))
);
allElementsCompletable
.test()
.assertComplete();
}
@Test
public void whenAmbWithNever_thenCompletedSuccessfully() {
Completable.ambArray(first, Completable.never(), second)
.test()
.assertComplete();
}
@Test
public void whenAmbWithError_thenCompletedWithError() {
Completable.ambArray(error, first, second)
.test()
.assertError(throwable);
}
}

View File

@ -5,10 +5,10 @@ import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.ecommerce.EcommerceApplicationIntegrationTest;
import com.baeldung.ecommerce.EcommerceApplication;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = EcommerceApplicationIntegrationTest.class)
@SpringBootTest(classes = EcommerceApplication.class)
public class SpringContextIntegrationTest {
@Test

View File

@ -1,10 +1,27 @@
package com.baeldung.autoconfiguration;
import java.util.Arrays;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.*;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionMessage.Style;
import org.springframework.context.annotation.*;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
@ -14,11 +31,6 @@ import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.util.ClassUtils;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.Properties;
@Configuration
@ConditionalOnClass(DataSource.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)

View File

@ -19,32 +19,16 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--JSF-->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.18</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--JSF-->
<dependency>
<groupId>javax.faces</groupId>
<artifactId>javax.faces-api</artifactId>
<version>2.3</version>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.3.7</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.18</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>

View File

@ -145,6 +145,20 @@
<artifactId>chaos-monkey-spring-boot</artifactId>
<version>${chaos.monkey.version}</version>
</dependency>
<!-- for Graylog demo -->
<dependency>
<!-- forcing spring boot 1.x sing log4j was dropped in spring boot 1.4 and beyond -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.graylog2</groupId>
<artifactId>gelfj</artifactId>
<version>1.1.16</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
@ -224,4 +238,4 @@
<git-commit-id-plugin.version>2.2.4</git-commit-id-plugin.version>
</properties>
</project>
</project>

View File

@ -0,0 +1,17 @@
package com.baeldung.graylog;
import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GraylogDemoApplication {
private final static Logger LOG =
Logger.getLogger(GraylogDemoApplication.class);
public static void main(String[] args) {
SpringApplication.run(GraylogDemoApplication.class, args);
LOG.info("Hello from Spring Boot");
}
}

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/xml/doc-files/log4j.dtd">
<log4j:configuration>
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss.SSS} %5p ${PID:- } [%t] --- %-40.40logger{39} : %m%n"/>
</layout>
</appender>
<appender name="graylog" class="org.graylog2.log.GelfAppender">
<param name="graylogHost" value="18.217.253.212"/>
<param name="originHost" value="localhost"/>
<param name="graylogPort" value="12201"/>
<param name="extractStacktrace" value="true"/>
<param name="addExtendedInformation" value="true"/>
<param name="facility" value="log4j"/>
<param name="Threshold" value="DEBUG"/>
<param name="additionalFields" value="{'environment': 'DEV', 'application': 'GraylogDemoApplication'}"/>
</appender>
<root>
<priority value="DEBUG"/>
<appender-ref ref="stdout"/>
<appender-ref ref="graylog"/>
</root>
</log4j:configuration>

View File

@ -1,13 +1,15 @@
package org.baeldung;
import org.baeldung.spring.cloud.BatchJobApplication;
import org.baeldung.spring.cloud.JobConfiguration;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BatchJobApplication.class)
@SpringBootTest
@ContextConfiguration(classes = JobConfiguration.class)
public class SpringContextIntegrationTest {
@Test

View File

@ -149,6 +149,7 @@
<subethasmtp.version>3.1.7</subethasmtp.version>
<tomee-servlet-api.version>8.5.11</tomee-servlet-api.version>
<guava.version>18.0</guava.version>
<tomcat.version>8.0.43</tomcat.version>
</properties>
</project>

View File

@ -2,12 +2,17 @@ package org.baeldung;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import com.baeldung.Application;
import com.baeldung.config.PersistenceConfiguration;
import com.baeldung.config.PersistenceProductConfiguration;
import com.baeldung.config.PersistenceUserConfiguration;
@RunWith(SpringRunner.class)
@DataJpaTest(excludeAutoConfiguration = {PersistenceConfiguration.class, PersistenceUserConfiguration.class, PersistenceProductConfiguration.class})
@SpringBootTest(classes = Application.class)
public class SpringContextIntegrationTest {

View File

@ -7,7 +7,7 @@ import java.io.File;
import org.junit.Test;
import org.springframework.context.support.GenericGroovyApplicationContext;
public class GroovyConfigurationTest {
public class GroovyConfigurationUnitTest {
private static final String FILE_NAME = "GroovyBeanConfig.groovy";
private static final String FILE_PATH = "src/main/java/com/baeldug/groovyconfig/";

View File

@ -5,7 +5,7 @@ import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class JavaConfigurationTest {
public class JavaConfigurationUnitTest {
@Test
public void whenJavaConfig_thenCorrectPerson() {

View File

@ -6,7 +6,7 @@ import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class XmlConfigurationTest {
public class XmlConfigurationUnitTest {
@Test
public void whenXmlConfig_thenCorrectPerson() {

View File

@ -7,7 +7,7 @@ import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
public class AppUnitTest
extends TestCase
{
/**
@ -15,7 +15,7 @@ public class AppTest
*
* @param testName name of the test case
*/
public AppTest( String testName )
public AppUnitTest( String testName )
{
super( testName );
}
@ -25,7 +25,7 @@ public class AppTest
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
return new TestSuite( AppUnitTest.class );
}
/**

View File

@ -1,11 +1,13 @@
package com.baeldung.spring;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@ImportResource("classpath:webMvcConfig.xml")
@Configuration
@ComponentScan
public class ClientWebConfig implements WebMvcConfigurer {
public ClientWebConfig() {

View File

@ -1,9 +1,5 @@
package org.baeldung;
import org.baeldung.spring.ChannelSecSecurityConfig;
import org.baeldung.spring.MvcConfig;
import org.baeldung.spring.RedirectionSecurityConfig;
import org.baeldung.spring.SecSecurityConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
@ -11,12 +7,10 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { MvcConfig.class, ChannelSecSecurityConfig.class, RedirectionSecurityConfig.class,
SecSecurityConfig.class })
@ContextConfiguration({ "/RedirectionWebSecurityConfig.xml", "/mvc-servlet.xml" })
@WebAppConfiguration
public class SpringContextIntegrationTest {
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
@Test
public void whenSpringContextIsBootstrapped_thenNoExceptions() {
}
}

View File

@ -1,18 +1,12 @@
package org.baeldung;
import org.baeldung.client.spring.ClientConfig;
import org.baeldung.spring.SecSecurityConfig;
import org.baeldung.spring.WebConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.AnnotationConfigContextLoader;
import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { ClientConfig.class, SecSecurityConfig.class,
WebConfig.class }, loader = AnnotationConfigContextLoader.class)
@ContextConfiguration({ "/WebSecurityConfig.xml" })
public class SpringContextIntegrationTest {
@Test

View File

@ -4,7 +4,7 @@ import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CntTest {
public class CntUnitTest {
private Cnt service;

View File

@ -1,7 +1,6 @@
### Relevant Articles:
- [The Basics of JUnit 5 A Preview](http://www.baeldung.com/junit-5-preview)
- [A Guide to JUnit 5](http://www.baeldung.com/junit-5)
- [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests)
- [A Guide to @RepeatedTest in Junit 5](http://www.baeldung.com/junit-5-repeated-test)
- [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests)
- [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions)

View File

@ -1,3 +0,0 @@
### Relevant articles
- [Sample Application with Spring Boot and Vaadin](https://www.baeldung.com/spring-boot-vaadin)