Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2017-08-10 19:16:26 +02:00
commit 5e4c913f72
33 changed files with 1002 additions and 81 deletions

View File

@ -0,0 +1,72 @@
package com.baeldung.java9.language;
import org.junit.Test;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
public class Java9ObjectsAPIUnitTest {
@Test
public void givenNullObject_whenRequireNonNullElse_thenElse(){
assertThat(Objects.<List>requireNonNullElse(null, Collections.EMPTY_LIST),
is(Collections.EMPTY_LIST));
}
@Test
public void givenObject_whenRequireNonNullElse_thenObject(){
assertThat(Objects.<List>requireNonNullElse(List.of("item1", "item2"),
Collections.EMPTY_LIST), is(List.of("item1", "item2")));
}
@Test
public void givenObject_whenRequireNonNullElseGet_thenObject(){
assertThat(Objects.<List>requireNonNullElseGet(null, List::of),
is(List.of()));
}
@Test
public void givenNumber_whenInvokeCheckIndex_thenNumber(){
int length = 5;
assertThat(Objects.checkIndex(4, length), is(4));
try{
Objects.checkIndex(5, length);
}catch(Exception ex){
assertThat(ex, instanceOf(IndexOutOfBoundsException.class));
}
}
@Test
public void givenSubRange_whenCheckFromToIndex_thenNumber(){
int length = 6;
assertThat(Objects.checkFromToIndex(2,length,length), is(2));
try{
Objects.checkFromToIndex(2,7,length);
}catch(Exception ex){
assertThat(ex, instanceOf(IndexOutOfBoundsException.class));
}
}
@Test
public void giveSubRange_whenCheckFromIndexSize_thenNumber(){
int length = 6;
assertThat(Objects.checkFromToIndex(2,5,length), is(2));
try{
Objects.checkFromToIndex(2,6,length);
}catch(Exception ex){
assertThat(ex, instanceOf(IndexOutOfBoundsException.class));
}
}
}

View File

@ -3,7 +3,7 @@
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>
<!-- NOT NEEDED - JSP <groupId>com.baeldung</groupId>-->
<artifactId>junit5</artifactId>
<version>1.0-SNAPSHOT</version>
@ -19,9 +19,9 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<junit.jupiter.version>5.0.0-M5</junit.jupiter.version>
<junit.platform.version>1.0.0-M5</junit.platform.version>
<junit.vintage.version>4.12.0-M5</junit.vintage.version>
<junit.jupiter.version>5.0.0-RC2</junit.jupiter.version>
<junit.platform.version>1.0.0-RC2</junit.platform.version>
<junit.vintage.version>4.12.0-RC2</junit.vintage.version>
<log4j2.version>2.8.2</log4j2.version>
<h2.version>1.4.196</h2.version>

View File

@ -0,0 +1,50 @@
package com.baeldung.param;
import java.util.Random;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
public class InvalidPersonParameterResolver implements ParameterResolver {
/**
* The "bad" (invalid) data for testing purposes has to go somewhere, right?
*/
public static Person[] INVALID_PERSONS = {
new Person().setId(1L).setLastName("Ad_ams").setFirstName("Jill,"),
new Person().setId(2L).setLastName(",Baker").setFirstName(""),
new Person().setId(3L).setLastName(null).setFirstName(null),
new Person().setId(4L).setLastName("Daniel&").setFirstName("{Joseph}"),
new Person().setId(5L).setLastName("").setFirstName("English, Jane"),
new Person()/* .setId(6L).setLastName("Fontana").setFirstName("Enrique") */,
// TODO: ADD MORE DATA HERE
};
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
Object ret = null;
//
// Return a random, valid Person object if Person.class is the type of Parameter
/// to be resolved. Otherwise return null.
if (parameterContext.getParameter().getType() == Person.class) {
ret = INVALID_PERSONS[new Random().nextInt(INVALID_PERSONS.length)];
}
return ret;
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
boolean ret = false;
//
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
if (parameterContext.getParameter().getType() == Person.class) {
ret = true;
}
return ret;
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.param;
/**
* Very simple Person entity.
* Use the Fluent-style interface to set properties.
*
* @author J Steven Perry
*
*/
public class Person {
private Long id;
private String lastName;
private String firstName;
public Long getId() {
return id;
}
public Person setId(Long id) {
this.id = id;
return this;
}
public String getLastName() {
return lastName;
}
public Person setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public String getFirstName() {
return firstName;
}
public Person setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
}

View File

@ -0,0 +1,142 @@
package com.baeldung.param;
import java.util.Arrays;
/**
* Somewhat contrived validation class to illustrate unit test
* concepts.
*
* @author J Steven Perry
*
*/
public class PersonValidator {
/**
* Contrived checked exception to illustrate one possible
* way to handle validation errors (via a checked exception).
*
* @author J Steven Perry
*
*/
public static class ValidationException extends Exception {
/**
*
*/
private static final long serialVersionUID = -134518049431883102L;
// Probably should implement some more constructors, but don't want
/// to tarnish the lesson...
/**
* The one and only way to create this checked exception.
*
* @param message
* The message accompanying the exception. Should be meaningful.
*/
public ValidationException(String message) {
super(message);
}
}
private static final String[] ILLEGAL_NAME_CHARACTERS = {
",",
"_",
"{",
"}",
"!"
};
/**
* Validate the first name of the specified Person object.
*
* @param person
* The Person object to validate.
*
* @return - returns true if the specified Person is valid
*
* @throws ValidationException
* - this Exception is thrown if any kind of validation error occurs.
*/
public static boolean validateFirstName(Person person) throws ValidationException {
boolean ret = true;
// The validation rules go here.
// Naive: use simple ifs
if (person == null) {
throw new ValidationException("Person is null (not allowed)!");
}
if (person.getFirstName() == null) {
throw new ValidationException("Person FirstName is null (not allowed)!");
}
if (person.getFirstName().isEmpty()) {
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
}
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
throw new ValidationException(
"Person FirstName (" + person.getFirstName() + ") may not contain any of the following characters: "
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
+ "!");
}
return ret;
}
/**
* Validate the last name of the specified Person object. Looks the same as first
* name? Look closer. Just kidding. It's the same. But real world code can (and will) diverge.
*
* @param person
* The Person object to validate.
*
* @return - returns true if the specified Person is valid
*
* @throws ValidationException
* - this Exception is thrown if any kind of validation error occurs.
*/
public static boolean validateLastName(Person person) throws ValidationException {
boolean ret = true;
// The validation rules go here.
// Naive: use simple ifs
if (person == null) {
throw new ValidationException("Person is null (not allowed)!");
}
if (person.getFirstName() == null) {
throw new ValidationException("Person FirstName is null (not allowed)!");
}
if (person.getFirstName().isEmpty()) {
throw new ValidationException("Person FirstName is an empty String (not allowed)!");
}
if (!isStringValid(person.getFirstName(), ILLEGAL_NAME_CHARACTERS)) {
throw new ValidationException(
"Person LastName (" + person.getLastName() + ") may not contain any of the following characters: "
+ Arrays.toString(ILLEGAL_NAME_CHARACTERS)
+ "!");
}
return ret;
}
/**
* Validates the specified name. If it contains any of the illegalCharacters,
* this method returns false (indicating the name is illegal). Otherwise it returns true.
*
* @param candidate
* The candidate String to validate
*
* @param illegalCharacters
* The characters the String is not allowed to have
*
* @return - boolean - true if the name is valid, false otherwise.
*/
private static boolean isStringValid(String candidate, String[] illegalCharacters) {
boolean ret = true;
for (String illegalChar : illegalCharacters) {
if (candidate.contains(illegalChar)) {
ret = false;
break;
}
}
return ret;
}
}

View File

@ -0,0 +1,102 @@
package com.baeldung.param;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
@RunWith(JUnitPlatform.class)
@DisplayName("Testing PersonValidator")
public class PersonValidatorTest {
/**
* Nested class, uses ExtendWith
* {@link com.baeldung.param.ValidPersonParameterResolver ValidPersonParameterResolver}
* to feed Test methods with "good" data.
*/
@Nested
@DisplayName("When using Valid data")
@ExtendWith(ValidPersonParameterResolver.class)
public class ValidData {
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* A valid Person object to validate.
*/
@RepeatedTest(value = 10)
@DisplayName("All first names are valid")
public void validateFirstName(Person person) {
try {
assertTrue(PersonValidator.validateFirstName(person));
} catch (PersonValidator.ValidationException e) {
fail("Exception not expected: " + e.getLocalizedMessage());
}
}
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* A valid Person object to validate.
*/
@RepeatedTest(value = 10)
@DisplayName("All last names are valid")
public void validateLastName(Person person) {
try {
assertTrue(PersonValidator.validateLastName(person));
} catch (PersonValidator.ValidationException e) {
fail("Exception not expected: " + e.getLocalizedMessage());
}
}
}
/**
* Nested class, uses ExtendWith
* {@link com.baeldung.param.InvalidPersonParameterResolver InvalidPersonParameterResolver}
* to feed Test methods with "bad" data.
*/
@Nested
@DisplayName("When using Invalid data")
@ExtendWith(InvalidPersonParameterResolver.class)
public class InvalidData {
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* An invalid Person object to validate.
*/
@RepeatedTest(value = 10)
@DisplayName("All first names are invalid")
public void validateFirstName(Person person) {
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateFirstName(person));
}
/**
* Repeat the test ten times, that way we have a good shot at
* running all of the data through at least once.
*
* @param person
* An invalid Person object to validate.
*/
@RepeatedTest(value = 10)
@DisplayName("All first names are invalid")
public void validateLastName(Person person) {
assertThrows(PersonValidator.ValidationException.class, () -> PersonValidator.validateLastName(person));
}
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.param;
import java.util.Random;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
public class ValidPersonParameterResolver implements ParameterResolver {
/**
* The "good" (valid) data for testing purposes has to go somewhere, right?
*/
public static Person[] VALID_PERSONS = {
new Person().setId(1L).setLastName("Adams").setFirstName("Jill"),
new Person().setId(2L).setLastName("Baker").setFirstName("James"),
new Person().setId(3L).setLastName("Carter").setFirstName("Samanta"),
new Person().setId(4L).setLastName("Daniels").setFirstName("Joseph"),
new Person().setId(5L).setLastName("English").setFirstName("Jane"),
new Person().setId(6L).setLastName("Fontana").setFirstName("Enrique"),
// TODO: ADD MORE DATA HERE
};
@Override
public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
Object ret = null;
//
// Return a random, valid Person object if Person.class is the type of Parameter
/// to be resolved. Otherwise return null.
if (parameterContext.getParameter().getType() == Person.class) {
ret = VALID_PERSONS[new Random().nextInt(VALID_PERSONS.length)];
}
return ret;
}
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException {
boolean ret = false;
//
// If the Parameter.type == Person.class, then we support it, otherwise, get outta here!
if (parameterContext.getParameter().getType() == Person.class) {
ret = true;
}
return ret;
}
}

View File

@ -462,6 +462,11 @@
<artifactId>pcollections</artifactId>
<version>${pcollections.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.collections</groupId>
<artifactId>eclipse-collections</artifactId>
<version>${eclipse-collections.version}</version>
</dependency>
</dependencies>
<properties>
<multiverse.version>0.7.0</multiverse.version>
@ -503,5 +508,6 @@
<bytebuddy.version>1.7.1</bytebuddy.version>
<pcollections.version>2.1.2</pcollections.version>
<rome.version>1.0</rome.version>
<eclipse-collections.version>8.2.0</eclipse-collections.version>
</properties>
</project>

View File

@ -0,0 +1,20 @@
package com.baeldung.eclipsecollections;
import java.util.List;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.set.mutable.UnifiedSet;
public class ConvertContainerToAnother {
@SuppressWarnings("rawtypes")
public static List convertToList() {
UnifiedSet<String> cars = new UnifiedSet<>();
cars.add("Toyota");
cars.add("Mercedes");
cars.add("Volkswagen");
return cars.toList();
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.eclipsecollections;
public class Student {
private String firstName;
private String lastName;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.eclipsecollections;
import static org.junit.Assert.assertTrue;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Before;
import org.junit.Test;
public class AllSatisfyPatternTest {
MutableList<Integer> list;
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
}
@Test
public void whenAnySatisfiesCondition_thenCorrect() {
boolean result = list.allSatisfy(Predicates.greaterThan(0));
assertTrue(result);
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.eclipsecollections;
import static org.junit.Assert.assertTrue;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Before;
import org.junit.Test;
public class AnySatisfyPatternTest {
MutableList<Integer> list;
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
}
@Test
public void whenAnySatisfiesCondition_thenCorrect() {
boolean result = list.anySatisfy(Predicates.greaterThan(30));
assertTrue(result);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.eclipsecollections;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.list.mutable.FastList;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CollectPatternTest {
@Test
public void whenCollect_thenCorrect() {
Student student1 = new Student("John", "Hopkins");
Student student2 = new Student("George", "Adams");
MutableList<Student> students = FastList.newListWith(student1, student2);
MutableList<String> lastNames = students.collect(Student::getLastName);
assertEquals(lastNames.get(0), "Hopkins");
assertEquals(lastNames.get(1), "Adams");
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.eclipsecollections;
import static org.junit.Assert.assertTrue;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.junit.Test;
public class ConvertContainerToAnotherTest {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void whenConvertContainerToAnother_thenCorrect() {
MutableList<String> cars = (MutableList) ConvertContainerToAnother.convertToList();
assertTrue(cars.anySatisfy(Predicates.equal("Toyota")));
assertTrue(cars.anySatisfy(Predicates.equal("Mercedes")));
assertTrue(cars.anySatisfy(Predicates.equal("Volkswagen")));
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.eclipsecollections;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class DetectPatternTest {
MutableList<Integer> list;
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
}
@Test
public void whenDetect_thenCorrect() {
Integer result = list.detect(Predicates.greaterThan(30));
assertEquals((int) result, 41);
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.eclipsecollections;
import org.eclipse.collections.api.block.procedure.Procedure;
import org.eclipse.collections.api.tuple.Pair;
import org.eclipse.collections.impl.map.mutable.UnifiedMap;
import org.eclipse.collections.impl.tuple.Tuples;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Test;
public class ForEachPatternTest {
@SuppressWarnings("unchecked")
@Test
public void whenInstantiateAndChangeValues_thenCorrect() {
Pair<Integer, String> pair1 = Tuples.pair(1, "One");
Pair<Integer, String> pair2 = Tuples.pair(2, "Two");
Pair<Integer, String> pair3 = Tuples.pair(3, "Three");
UnifiedMap<Integer, String> map = UnifiedMap.newMapWith(pair1, pair2, pair3);
for (int i = 0; i < map.size(); i++) {
map.put(i + 1, "New Value");
}
for (int i = 0; i < map.size(); i++) {
assertEquals("New Value", map.get(i + 1));
}
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.eclipsecollections;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.eclipse.collections.impl.factory.Lists;
import org.junit.Test;
public class InjectIntoPatternTest {
@Test
public void whenInjectInto_thenCorrect() {
List<Integer> list = Lists.mutable.of(1, 2, 3, 4);
int result = 5;
for (int i = 0; i < list.size(); i++) {
Integer v = list.get(i);
result = result + v.intValue();
}
assertEquals(15, result);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.eclipsecollections;
import org.eclipse.collections.api.LazyIterable;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.factory.Lists;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class LazyIterationTest {
@Test
public void whenLazyIteration_thenCorrect() {
Student student1 = new Student("John", "Hopkins");
Student student2 = new Student("George", "Adams");
Student student3 = new Student("Jennifer", "Rodriguez");
MutableList<Student> students = Lists.mutable.with(student1, student2, student3);
LazyIterable<Student> lazyStudents = students.asLazy();
LazyIterable<String> lastNames = lazyStudents.collect(Student::getLastName);
assertTrue(lastNames.anySatisfy(Predicates.equal("Hopkins")));
assertTrue(lastNames.anySatisfy(Predicates.equal("Adams")));
assertTrue(lastNames.anySatisfy(Predicates.equal("Rodriguez")));
}
}

View File

@ -0,0 +1,61 @@
package com.baeldung.eclipsecollections;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.eclipse.collections.api.block.predicate.Predicate;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.api.partition.list.PartitionMutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import org.junit.Before;
import org.junit.Test;
public class PartitionPatternTest {
MutableList<Integer> list;
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
}
@SuppressWarnings({ "unused" })
@Test
public void whenAnySatisfiesCondition_thenCorrect() {
MutableList<Integer> numbers = list;
PartitionMutableList<Integer> partitionedFolks = numbers.partition(new Predicate<Integer>() {
/**
*
*/
private static final long serialVersionUID = -1551138743683678406L;
public boolean accept(Integer each) {
return each > 30;
}
});
MutableList<Integer> greaterThanThirty = partitionedFolks.getSelected()
.sortThis();
MutableList<Integer> smallerThanThirty = partitionedFolks.getRejected()
.sortThis();
assertEquals(1, (int) smallerThanThirty.getFirst());
assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(5)));
assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(8)));
assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(17)));
assertTrue(smallerThanThirty.anySatisfy(Predicates.equal(23)));
assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(31)));
assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(38)));
assertTrue(greaterThanThirty.anySatisfy(Predicates.equal(41)));
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.eclipsecollections;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class RejectPatternTest {
MutableList<Integer> list;
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
}
@Test
public void whenReject_thenCorrect() {
MutableList<Integer> notGreaterThanThirty = list.reject(Predicates.greaterThan(30))
.sortThis();
assertEquals(1, (int) notGreaterThanThirty.getFirst());
assertEquals(5, (int) notGreaterThanThirty.get(1));
assertEquals(8, (int) notGreaterThanThirty.get(2));
assertEquals(17, (int) notGreaterThanThirty.get(3));
assertEquals(23, (int) notGreaterThanThirty.getLast());
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.eclipsecollections;
import org.eclipse.collections.api.list.MutableList;
import org.eclipse.collections.impl.block.factory.Predicates;
import org.eclipse.collections.impl.list.mutable.FastList;
import static org.junit.Assert.assertEquals;
import org.junit.Before;
import org.junit.Test;
public class SelectPatternTest {
MutableList<Integer> list;
@Before
public void getList() {
this.list = new FastList<>();
list.add(1);
list.add(8);
list.add(5);
list.add(41);
list.add(31);
list.add(17);
list.add(23);
list.add(38);
}
@Test
public void givenListwhenSelect_thenCorrect() {
MutableList<Integer> greaterThanThirty = list.select(Predicates.greaterThan(30))
.sortThis();
assertEquals(31, (int) greaterThanThirty.getFirst());
assertEquals(38, (int) greaterThanThirty.get(1));
assertEquals(41, (int) greaterThanThirty.getLast());
}
@SuppressWarnings("rawtypes")
public MutableList selectUsingLambda() {
return list.select(each -> each > 30)
.sortThis();
}
@SuppressWarnings("unchecked")
@Test
public void givenListwhenSelectUsingLambda_thenCorrect() {
MutableList<Integer> greaterThanThirty = selectUsingLambda();
assertEquals(31, (int) greaterThanThirty.getFirst());
assertEquals(38, (int) greaterThanThirty.get(1));
assertEquals(41, (int) greaterThanThirty.getLast());
}
}

View File

@ -31,7 +31,7 @@ import org.springframework.web.client.RestTemplate;
import io.specto.hoverfly.junit.core.SimulationSource;
import io.specto.hoverfly.junit.rule.HoverflyRule;
public class HoverflyApiTest {
public class HoverflyApiIntegrationTest {
private static final SimulationSource source = dsl(
service("http://www.baeldung.com")

View File

@ -1,7 +1,12 @@
package com.baeldung.pcollections;
import org.junit.Test;
import org.pcollections.*;
import org.pcollections.HashPMap;
import org.pcollections.HashTreePMap;
import org.pcollections.HashTreePSet;
import org.pcollections.MapPSet;
import org.pcollections.PVector;
import org.pcollections.TreePVector;
import java.util.Arrays;
import java.util.HashMap;
@ -27,7 +32,7 @@ public class PCollectionsUnitTest {
@Test
public void givenExistingHashMap_whenFrom_thenCreateHashPMap() {
Map map = new HashMap();
Map<String, String> map = new HashMap<>();
map.put("mkey1", "mval1");
map.put("mkey2", "mval2");
@ -41,7 +46,7 @@ public class PCollectionsUnitTest {
HashPMap<String, String> pmap = HashTreePMap.empty();
HashPMap<String, String> pmap0 = pmap.plus("key1", "value1");
Map map = new HashMap();
Map<String, String> map = new HashMap<>();
map.put("key2", "val2");
map.put("key3", "val3");
@ -57,22 +62,24 @@ public class PCollectionsUnitTest {
@Test
public void whenTreePVectorMethods_thenPerformOperations() {
TreePVector pVector = TreePVector.empty();
TreePVector<String> pVector = TreePVector.empty();
TreePVector<String> pV1 = pVector.plus("e1");
TreePVector<String> pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4"));
TreePVector pV1 = pVector.plus("e1");
TreePVector pV2 = pV1.plusAll(Arrays.asList("e2", "e3", "e4"));
assertEquals(1, pV1.size());
assertEquals(4, pV2.size());
TreePVector pV3 = pV2.minus("e1");
TreePVector pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4"));
TreePVector<String> pV3 = pV2.minus("e1");
TreePVector<String> pV4 = pV3.minusAll(Arrays.asList("e2", "e3", "e4"));
assertEquals(pV3.size(), 3);
assertEquals(pV4.size(), 0);
TreePVector pSub = pV2.subList(0, 2);
TreePVector<String> pSub = pV2.subList(0, 2);
assertTrue(pSub.contains("e1") && pSub.contains("e2"));
TreePVector pVW = (TreePVector) pV2.with(0, "e10");
PVector<String> pVW = pV2.with(0, "e10");
assertEquals(pVW.get(0), "e10");
}
@ -80,7 +87,7 @@ public class PCollectionsUnitTest {
public void whenMapPSetMethods_thenPerformOperations() {
MapPSet pSet = HashTreePSet.empty()
.plusAll(Arrays.asList("e1","e2","e3","e4"));
.plusAll(Arrays.asList("e1", "e2", "e3", "e4"));
assertEquals(pSet.size(), 4);
MapPSet pSet1 = pSet.minus("e4");

View File

@ -27,9 +27,6 @@ import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
/**
* @author aiet
*/
public class AtlasObserverLiveTest {
private final String atlasUri = "http://localhost:7101/api/v1";

View File

@ -22,10 +22,7 @@ import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
/**
* @author aiet
*/
public class MetricAnnotationTest extends MetricTestBase {
public class MetricAnnotationManualTest extends MetricTestBase {
@Monitor(name = "integerCounter", type = DataSourceType.COUNTER, description = "Total number of update operations.")
private final AtomicInteger updateCount = new AtomicInteger(0);

View File

@ -13,14 +13,16 @@ import java.util.List;
import static com.netflix.servo.annotations.DataSourceType.GAUGE;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/**
* @author aiet
*/
public class MetricObserverTest extends MetricTestBase {
public class MetricObserverManualTest extends MetricTestBase {
@Test
public void givenMetrics_whenRegister_thenMonitored() throws InterruptedException {

View File

@ -1,20 +1,23 @@
package com.baeldung.metrics.servo;
import com.netflix.servo.Metric;
import com.netflix.servo.publish.*;
import com.netflix.servo.publish.BasicMetricFilter;
import com.netflix.servo.publish.JvmMetricPoller;
import com.netflix.servo.publish.MemoryMetricObserver;
import com.netflix.servo.publish.PollRunnable;
import com.netflix.servo.publish.PollScheduler;
import org.junit.Test;
import java.util.List;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.Assert.assertThat;
/**
* @author aiet
*/
public class MetricPollerTest {
public class MetricPollerManualTest {
@Test
public void givenJvmPoller_whenMonitor_thenDataCollected() throws Exception {

View File

@ -1,14 +1,16 @@
package com.baeldung.metrics.servo;
import com.netflix.servo.publish.*;
import com.netflix.servo.publish.BasicMetricFilter;
import com.netflix.servo.publish.MemoryMetricObserver;
import com.netflix.servo.publish.MetricFilter;
import com.netflix.servo.publish.MonitorRegistryMetricPoller;
import com.netflix.servo.publish.PollRunnable;
import com.netflix.servo.publish.PollScheduler;
import org.junit.After;
import org.junit.Before;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* @author aiet
*/
abstract class MetricTestBase {
MemoryMetricObserver observer;

View File

@ -1,6 +1,21 @@
package com.baeldung.metrics.servo;
import com.netflix.servo.monitor.*;
import com.netflix.servo.monitor.BasicCounter;
import com.netflix.servo.monitor.BasicGauge;
import com.netflix.servo.monitor.BasicInformational;
import com.netflix.servo.monitor.BasicTimer;
import com.netflix.servo.monitor.BucketConfig;
import com.netflix.servo.monitor.BucketTimer;
import com.netflix.servo.monitor.Counter;
import com.netflix.servo.monitor.Gauge;
import com.netflix.servo.monitor.MaxGauge;
import com.netflix.servo.monitor.Monitor;
import com.netflix.servo.monitor.MonitorConfig;
import com.netflix.servo.monitor.Monitors;
import com.netflix.servo.monitor.PeakRateCounter;
import com.netflix.servo.monitor.StatsTimer;
import com.netflix.servo.monitor.StepCounter;
import com.netflix.servo.monitor.Stopwatch;
import com.netflix.servo.stats.StatsConfig;
import org.junit.Ignore;
import org.junit.Test;
@ -9,13 +24,12 @@ import java.util.Map;
import static java.util.concurrent.TimeUnit.SECONDS;
import static java.util.stream.Collectors.toMap;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasEntry;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
/**
* Unit test for simple App.
*/
public class MetricTypeTest {
@Test
@ -113,7 +127,7 @@ public class MetricTypeTest {
BucketTimer timer = new BucketTimer(MonitorConfig
.builder("test")
.build(), new BucketConfig.Builder()
.withBuckets(new long[] { 2L, 5L })
.withBuckets(new long[]{2L, 5L})
.withTimeUnit(SECONDS)
.build(), SECONDS);
timer.record(3);
@ -150,7 +164,7 @@ public class MetricTypeTest {
.builder("test")
.build(), new StatsConfig.Builder()
.withComputeFrequencyMillis(2000)
.withPercentiles(new double[] { 99.0, 95.0, 90.0 })
.withPercentiles(new double[]{99.0, 95.0, 90.0})
.withPublishMax(true)
.withPublishMin(true)
.withPublishCount(true)

View File

@ -3,11 +3,12 @@ package com.example.activitiwithspring;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.ProcessEngines;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
public class ProcessEngineCreationTests {
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class ProcessEngineCreationIntegrationTest {
@Test
public void givenXMLConfig_whenGetDefault_thenGotProcessEngine() {

View File

@ -1,10 +1,6 @@
package com.example.activitiwithspring;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
@ -13,11 +9,16 @@ import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ProcessExecutionTests {
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class ProcessExecutionIntegrationTest {
@Test
public void givenBPMN_whenDeployProcess_thenDeployed() {

View File

@ -1,11 +1,15 @@
package org.baeldung.web.controller.redirect;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
@ -49,4 +53,16 @@ public class RedirectController {
model.addAttribute("redirectionAttribute", flashAttribute);
return new ModelAndView("redirection", model);
}
@RequestMapping(value = "/redirectPostToPost", method = RequestMethod.POST)
public ModelAndView redirectPostToPost(HttpServletRequest request) {
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
return new ModelAndView("redirect:/redirectedPostToPost");
}
@RequestMapping(value = "/redirectedPostToPost", method = RequestMethod.POST)
public ModelAndView redirectedPostToPost() {
return new ModelAndView("redirection");
}
}