Merge remote-tracking branch 'origin/master'

This commit is contained in:
slavisa-baeldung 2017-04-12 10:29:21 +01:00
commit 4777c93ddf
97 changed files with 2794 additions and 1033 deletions

1
algorithms/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target/

View File

@ -4,3 +4,4 @@
- [Introduction to Cobertura](http://www.baeldung.com/cobertura)
- [Ant Colony Optimization](http://www.baeldung.com/java-ant-colony-optimization)
- [Validating Input With Finite Automata in Java](http://www.baeldung.com/finite-automata-java)
- [Introduction to Jenetics Library](http://www.baeldung.com/jenetics)

View File

@ -31,6 +31,11 @@
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>io.jenetics</groupId>
<artifactId>jenetics</artifactId>
<version>3.7.0</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,47 @@
package com.baeldung.algorithms.ga.jenetics;
import static org.jenetics.engine.EvolutionResult.toBestPhenotype;
import static org.jenetics.engine.limit.bySteadyFitness;
import java.util.stream.Stream;
import org.jenetics.BitChromosome;
import org.jenetics.BitGene;
import org.jenetics.Mutator;
import org.jenetics.Phenotype;
import org.jenetics.RouletteWheelSelector;
import org.jenetics.SinglePointCrossover;
import org.jenetics.TournamentSelector;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionStatistics;
//The main class.
public class Knapsack {
public static void main(String[] args) {
int nItems = 15;
double ksSize = nItems * 100.0 / 3.0;
KnapsackFF ff = new KnapsackFF(Stream.generate(KnapsackItem::random)
.limit(nItems)
.toArray(KnapsackItem[]::new), ksSize);
Engine<BitGene, Double> engine = Engine.builder(ff, BitChromosome.of(nItems, 0.5))
.populationSize(500)
.survivorsSelector(new TournamentSelector<>(5))
.offspringSelector(new RouletteWheelSelector<>())
.alterers(new Mutator<>(0.115), new SinglePointCrossover<>(0.16))
.build();
EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber();
Phenotype<BitGene, Double> best = engine.stream()
.limit(bySteadyFitness(7))
.limit(100)
.peek(statistics)
.collect(toBestPhenotype());
System.out.println(statistics);
System.out.println(best);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.algorithms.ga.jenetics;
import java.util.function.Function;
import org.jenetics.BitChromosome;
import org.jenetics.BitGene;
import org.jenetics.Genotype;
public class KnapsackFF implements Function<Genotype<BitGene>, Double> {
private KnapsackItem[] items;
private double size;
public KnapsackFF(KnapsackItem[] items, double size) {
this.items = items;
this.size = size;
}
@Override
public Double apply(Genotype<BitGene> gt) {
KnapsackItem sum = ((BitChromosome) gt.getChromosome()).ones()
.mapToObj(i -> items[i])
.collect(KnapsackItem.toSum());
return sum.size <= this.size ? sum.value : 0;
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.algorithms.ga.jenetics;
import java.util.Random;
import java.util.stream.Collector;
import org.jenetics.util.RandomRegistry;
public class KnapsackItem {
public double size;
public double value;
public KnapsackItem(double size, double value) {
this.size = size;
this.value = value;
}
protected static KnapsackItem random() {
Random r = RandomRegistry.getRandom();
return new KnapsackItem(r.nextDouble() * 100, r.nextDouble() * 100);
}
protected static Collector<KnapsackItem, ?, KnapsackItem> toSum() {
return Collector.of(() -> new double[2], (a, b) -> {
a[0] += b.size;
a[1] += b.value;
} , (a, b) -> {
a[0] += b[0];
a[1] += b[1];
return a;
} , r -> new KnapsackItem(r[0], r[1]));
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.algorithms.ga.jenetics;
import org.jenetics.BitChromosome;
import org.jenetics.BitGene;
import org.jenetics.Genotype;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionResult;
import org.jenetics.util.Factory;
public class SimpleGeneticAlgorithm {
private static Integer eval(Genotype<BitGene> gt) {
return gt.getChromosome()
.as(BitChromosome.class)
.bitCount();
}
public static void main(String[] args) {
Factory<Genotype<BitGene>> gtf = Genotype.of(BitChromosome.of(10, 0.5));
System.out.println("Before the evolution:\n" + gtf);
Engine<BitGene, Integer> engine = Engine.builder(SimpleGeneticAlgorithm::eval, gtf)
.build();
Genotype<BitGene> result = engine.stream()
.limit(500)
.collect(EvolutionResult.toBestGenotype());
System.out.println("After the evolution:\n" + result);
}
}

View File

@ -0,0 +1,86 @@
package com.baeldung.algorithms.ga.jenetics;
import static java.util.Objects.requireNonNull;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.jenetics.BitGene;
import org.jenetics.engine.Codec;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionResult;
import org.jenetics.engine.Problem;
import org.jenetics.engine.codecs;
import org.jenetics.util.ISeq;
public class SpringsteenProblem implements Problem<ISeq<SpringsteenRecord>, BitGene, Double> {
private ISeq<SpringsteenRecord> records;
private double maxPricePerUniqueSong;
public SpringsteenProblem(ISeq<SpringsteenRecord> records, double maxPricePerUniqueSong) {
this.records = requireNonNull(records);
this.maxPricePerUniqueSong = maxPricePerUniqueSong;
}
@Override
public Function<ISeq<SpringsteenRecord>, Double> fitness() {
return SpringsteenRecords -> {
double cost = SpringsteenRecords.stream()
.mapToDouble(r -> r.price)
.sum();
int uniqueSongCount = SpringsteenRecords.stream()
.flatMap(r -> r.songs.stream())
.collect(Collectors.toSet())
.size();
double pricePerUniqueSong = cost / uniqueSongCount;
return pricePerUniqueSong <= maxPricePerUniqueSong ? uniqueSongCount : 0.0;
};
}
@Override
public Codec<ISeq<SpringsteenRecord>, BitGene> codec() {
return codecs.ofSubSet(records);
}
public static void main(String[] args) {
double maxPricePerUniqueSong = 2.5;
SpringsteenProblem springsteen = new SpringsteenProblem(
ISeq.of(new SpringsteenRecord("SpringsteenRecord1", 25, ISeq.of("Song1", "Song2", "Song3", "Song4", "Song5", "Song6")), new SpringsteenRecord("SpringsteenRecord2", 15, ISeq.of("Song2", "Song3", "Song4", "Song5", "Song6", "Song7")),
new SpringsteenRecord("SpringsteenRecord3", 35, ISeq.of("Song5", "Song6", "Song7", "Song8", "Song9", "Song10")), new SpringsteenRecord("SpringsteenRecord4", 17, ISeq.of("Song9", "Song10", "Song12", "Song4", "Song13", "Song14")),
new SpringsteenRecord("SpringsteenRecord5", 29, ISeq.of("Song1", "Song2", "Song13", "Song14", "Song15", "Song16")), new SpringsteenRecord("SpringsteenRecord6", 5, ISeq.of("Song18", "Song20", "Song30", "Song40"))),
maxPricePerUniqueSong);
Engine<BitGene, Double> engine = Engine.builder(springsteen)
.build();
ISeq<SpringsteenRecord> result = springsteen.codec()
.decoder()
.apply(engine.stream()
.limit(10)
.collect(EvolutionResult.toBestGenotype()));
double cost = result.stream()
.mapToDouble(r -> r.price)
.sum();
int uniqueSongCount = result.stream()
.flatMap(r -> r.songs.stream())
.collect(Collectors.toSet())
.size();
double pricePerUniqueSong = cost / uniqueSongCount;
System.out.println("Overall cost: " + cost);
System.out.println("Unique songs: " + uniqueSongCount);
System.out.println("Cost per song: " + pricePerUniqueSong);
System.out.println("Records: " + result.map(r -> r.name)
.toString(", "));
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.algorithms.ga.jenetics;
import static java.util.Objects.requireNonNull;
import org.jenetics.util.ISeq;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class SpringsteenRecord {
String name;
double price;
ISeq<String> songs;
public SpringsteenRecord(String name, double price, ISeq<String> songs) {
this.name = requireNonNull(name);
this.price = price;
this.songs = requireNonNull(songs);
}
}

View File

@ -0,0 +1,66 @@
package com.baeldung.algorithms.ga.jenetics;
import static java.util.Objects.requireNonNull;
import java.util.Random;
import java.util.function.Function;
import org.jenetics.EnumGene;
import org.jenetics.Mutator;
import org.jenetics.PartiallyMatchedCrossover;
import org.jenetics.Phenotype;
import org.jenetics.engine.Codec;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionResult;
import org.jenetics.engine.Problem;
import org.jenetics.engine.codecs;
import org.jenetics.engine.limit;
import org.jenetics.util.ISeq;
import org.jenetics.util.LCG64ShiftRandom;
public class SubsetSum implements Problem<ISeq<Integer>, EnumGene<Integer>, Integer> {
private ISeq<Integer> basicSet;
private int size;
public SubsetSum(ISeq<Integer> basicSet, int size) {
this.basicSet = requireNonNull(basicSet);
this.size = size;
}
@Override
public Function<ISeq<Integer>, Integer> fitness() {
return subset -> Math.abs(subset.stream()
.mapToInt(Integer::intValue)
.sum());
}
@Override
public Codec<ISeq<Integer>, EnumGene<Integer>> codec() {
return codecs.ofSubSet(basicSet, size);
}
public static SubsetSum of(int n, int k, Random random) {
return new SubsetSum(random.doubles()
.limit(n)
.mapToObj(d -> (int) ((d - 0.5) * n))
.collect(ISeq.toISeq()), k);
}
public static void main(String[] args) {
SubsetSum problem = of(500, 15, new LCG64ShiftRandom(101010));
Engine<EnumGene<Integer>, Integer> engine = Engine.builder(problem)
.minimizing()
.maximalPhenotypeAge(5)
.alterers(new PartiallyMatchedCrossover<>(0.4), new Mutator<>(0.3))
.build();
Phenotype<EnumGene<Integer>, Integer> result = engine.stream()
.limit(limit.bySteadyFitness(55))
.collect(EvolutionResult.toBestPhenotype());
System.out.print(result);
}
}

View File

@ -0,0 +1,67 @@
package com.baeldung.algorithms.ga.jenetics;
import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.sin;
import static org.jenetics.engine.EvolutionResult.toBestPhenotype;
import static org.jenetics.engine.limit.bySteadyFitness;
import java.util.stream.IntStream;
import org.jenetics.EnumGene;
import org.jenetics.Optimize;
import org.jenetics.PartiallyMatchedCrossover;
import org.jenetics.Phenotype;
import org.jenetics.SwapMutator;
import org.jenetics.engine.Engine;
import org.jenetics.engine.EvolutionStatistics;
import org.jenetics.engine.codecs;
public class TravelingSalesman {
private static final int STOPS = 50;
private static final double[][] ADJACENCE = matrix(STOPS);
private static double[][] matrix(int stops) {
final double radius = 100.0;
double[][] matrix = new double[stops][stops];
for (int i = 0; i < stops; ++i) {
for (int j = 0; j < stops; ++j) {
matrix[i][j] = chord(stops, abs(i - j), radius);
}
}
return matrix;
}
private static double chord(int stops, int i, double r) {
return 2.0 * r * abs(sin(PI * i / stops));
}
private static double dist(final int[] path) {
return IntStream.range(0, STOPS)
.mapToDouble(i -> ADJACENCE[path[i]][path[(i + 1) % STOPS]])
.sum();
}
public static void main(String[] args) {
final Engine<EnumGene<Integer>, Double> engine = Engine.builder(TravelingSalesman::dist, codecs.ofPermutation(STOPS))
.optimize(Optimize.MINIMUM)
.maximalPhenotypeAge(11)
.populationSize(500)
.alterers(new SwapMutator<>(0.2), new PartiallyMatchedCrossover<>(0.35))
.build();
final EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber();
final Phenotype<EnumGene<Integer>, Double> best = engine.stream()
.limit(bySteadyFitness(15))
.limit(250)
.peek(statistics)
.collect(toBestPhenotype());
System.out.println(statistics);
System.out.println(best);
}
}

View File

@ -11,7 +11,9 @@
- [Converting between a List and a Set in Java](http://www.baeldung.com/convert-list-to-set-and-set-to-list)
- [Convert a Map to an Array, List or Set in Java](http://www.baeldung.com/convert-map-values-to-array-list-set)
- [Java Write to File](http://www.baeldung.com/java-write-to-file)
- [Java - Convert File to InputStream] (http://www.baeldung.com/convert-file-to-input-stream)
- [Java - Convert File to InputStream](http://www.baeldung.com/convert-file-to-input-stream)
- [Java Random Long, Float, Integer and Double](http://www.baeldung.com/java-generate-random-long-float-integer-double)
- [Java Generate Random String](http://www.baeldung.com/java-random-string)
- [Java Scanner](http://www.baeldung.com/java-scanner)
- [Java Timer](http://www.baeldung.com/java-timer-and-timertask)
- [Java Byte Array to Writer](http://www.baeldung.com/java-convert-byte-array-to-writer)
@ -86,4 +88,7 @@
- [Java Primitive Conversions](http://www.baeldung.com/java-primitive-conversions)
- [Java Money and the Currency API](http://www.baeldung.com/java-money-and-currency)
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
- [Avoiding ConcurrentModificationException when iterating and removing](http://www.baeldung.com/avoiding-concurrentmodificationexception-when-iterating-and-removing)
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)

View File

@ -9,10 +9,10 @@ import java.util.List;
import java.util.StringTokenizer;
import java.util.stream.Collectors;
public class Application {
public class MyTokenizer {
public List<String> getTokens(String str) {
List<String> tokens = new ArrayList<String>();
List<String> tokens = new ArrayList<>();
// StringTokenizer tokenizer = new StringTokenizer( str );
StringTokenizer tokenizer = new StringTokenizer(str, ",");
// StringTokenizer tokenizer = new StringTokenizer( str , "," , true );
@ -25,18 +25,18 @@ public class Application {
}
public List<String> getTokensWithCollection(String str) {
StringTokenizer tokenizer = new StringTokenizer(str, ",");
return Collections.list(tokenizer).stream()
return Collections
.list(new StringTokenizer(str, ","))
.stream()
.map(token -> (String) token)
.collect(Collectors.toList());
}
public List<String> getTokensFromFile(String path, String delim) {
List<String> tokens = new ArrayList<>();
String currLine = "";
String currLine;
StringTokenizer tokenizer;
try (BufferedReader br = new BufferedReader(new InputStreamReader(Application.class.getResourceAsStream("/" + path)))) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(MyTokenizer.class.getResourceAsStream("/" + path)))) {
while ((currLine = br.readLine()) != null) {
tokenizer = new StringTokenizer(currLine, delim);
while (tokenizer.hasMoreElements()) {

View File

@ -0,0 +1,82 @@
package com.baeldung.java.collections;
import org.junit.Test;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import static java.util.Arrays.asList;
import static org.testng.Assert.assertEquals;
public class ConcurrentModificationExceptionTest {
@Test
public void changingContentWithSetDoesNotThrowConcurrentModificationException() throws Exception {
ArrayList<Object> array = new ArrayList<>(asList(0, "one", 2, "three"));
for (Object item : array) {
array.set(3, 3);
}
}
@Test
public void removingElementUsingIteratorAPI() throws Exception {
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
Iterator<String> iterator = originalList.iterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (Objects.equals(next, "one")) iterator.remove();
}
assertEquals(originalList, asList("zero", "two", "three"));
}
@Test
public void modifyingContentAndIteratingUsingListIteratorAPI() throws Exception {
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
ListIterator<String> iterator = originalList.listIterator();
while (iterator.hasNext()) {
String next = iterator.next();
if (Objects.equals(next, "one")) {
iterator.set("another");
}
if (Objects.equals(next, "two")) {
iterator.remove();
}
if (Objects.equals(next, "three")) {
iterator.add("four");
}
}
assertEquals(originalList, asList("zero", "another", "three", "four"));
}
@Test
public void removingElementUsingCopyAndListAPI() throws Exception {
List<String> originalList = new ArrayList<>(asList("zero", "one", "two", "three"));
List<String> listCopy = new ArrayList<>(originalList);
for (String next : listCopy) {
if (Objects.equals(next, "one")) originalList.remove(originalList.indexOf(next) - 1);
}
assertEquals(originalList, asList("one", "two", "three"));
}
@Test
public void copyOnWriteList() throws Exception {
List<String> originalList = new CopyOnWriteArrayList<>(asList("zero", "one", "two", "three"));
for (String next : originalList) {
if (Objects.equals(next, "one")) originalList.remove(originalList.indexOf(next) - 1);
}
assertEquals(originalList, asList("one", "two", "three"));
}
}

View File

@ -1,47 +0,0 @@
package com.baeldung.stringtokenizer;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ApplicationTest {
Application application = new Application();
List<String> expectedTokensForString = new ArrayList<String>();
List<String> expectedTokensForFile = new ArrayList<String>();
@Before
public void init() {
expectedTokensForString.add("Welcome");
expectedTokensForString.add("to");
expectedTokensForString.add("baeldung.com");
expectedTokensForFile.add("1");
expectedTokensForFile.add("IND");
expectedTokensForFile.add("India");
expectedTokensForFile.add("2");
expectedTokensForFile.add("MY");
expectedTokensForFile.add("Malaysia");
expectedTokensForFile.add("3");
expectedTokensForFile.add("AU");
expectedTokensForFile.add("Australia");
}
@Test
public void givenString_thenGetListOfString() {
String str = "Welcome,to,baeldung.com";
List<String> actualTokens = application.getTokens(str);
assertEquals(expectedTokensForString, actualTokens);
}
@Test
public void givenFile_thenGetListOfString() {
List<String> actualTokens = application.getTokensFromFile("data.csv", "|");
assertEquals(expectedTokensForFile, actualTokens);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.stringtokenizer;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertEquals;
public class TokenizerTest {
private final MyTokenizer myTokenizer = new MyTokenizer();
private final List<String> expectedTokensForString = Arrays.asList("Welcome", "to", "baeldung.com");
private final List<String> expectedTokensForFile = Arrays.asList("1", "IND", "India", "2", "MY", "Malaysia", "3", "AU", "Australia");
@Test
public void givenString_thenGetListOfString() {
String str = "Welcome,to,baeldung.com";
List<String> actualTokens = myTokenizer.getTokens(str);
assertEquals(expectedTokensForString, actualTokens);
}
@Test
public void givenFile_thenGetListOfString() {
List<String> actualTokens = myTokenizer.getTokensFromFile("data.csv", "|");
assertEquals(expectedTokensForFile, actualTokens);
}
}

View File

@ -1,167 +1,195 @@
package org.baeldung.guava;
import com.google.common.math.DoubleMath;
import com.google.common.math.IntMath;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.*;
import java.math.BigInteger;
import java.math.RoundingMode;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.google.common.math.DoubleMath;
import com.google.common.math.IntMath;
public class GuavaMathTest {
@Test
public void testIntMathAdd() {
try {
IntMath.checkedAdd(Integer.MAX_VALUE, 1);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
@Test(expected = ArithmeticException.class)
public void whenSumOverflow_thenThrowException() {
IntMath.checkedAdd(Integer.MAX_VALUE, 1);
}
try {
IntMath.checkedAdd(Integer.MIN_VALUE, -1);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
int result1 = IntMath.checkedAdd(2, 1);
assertThat(result1, equalTo(3));
int result2 = IntMath.saturatedAdd(Integer.MAX_VALUE, 100);
assertThat(result2, equalTo(Integer.MAX_VALUE));
int result3 = IntMath.saturatedAdd(Integer.MIN_VALUE, -100);
assertThat(result3, equalTo(Integer.MIN_VALUE));
@Test(expected = ArithmeticException.class)
public void whenSumUnderflow_thenThrowException() {
IntMath.checkedAdd(Integer.MIN_VALUE, -1);
}
@Test
public void testIntMathSubtract() {
try {
IntMath.checkedSubtract(Integer.MIN_VALUE, 1);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
try {
IntMath.checkedSubtract(Integer.MAX_VALUE, -1);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
};
int result1 = IntMath.checkedSubtract(200, 100);
assertThat(result1, equalTo(100));
int result2 = IntMath.saturatedSubtract(Integer.MIN_VALUE, 1);
assertThat(result2, equalTo(Integer.MIN_VALUE));
int result3 = IntMath.saturatedSubtract(Integer.MAX_VALUE, -1);
assertThat(result3, equalTo(Integer.MAX_VALUE));
public void should_calculate_sum() {
int result = IntMath.checkedAdd(2, 1);
assertThat(result, equalTo(3));
}
@Test
public void testIntMathMultiply() {
try {
IntMath.checkedMultiply(Integer.MAX_VALUE, 2);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
try {
IntMath.checkedMultiply(Integer.MIN_VALUE, 2);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
int result1 = IntMath.checkedMultiply(21, 3);
assertThat(result1, equalTo(63));
int result2 = IntMath.saturatedMultiply(Integer.MAX_VALUE, 2);
assertThat(result2, equalTo(Integer.MAX_VALUE));
int result3 = IntMath.saturatedMultiply(Integer.MIN_VALUE, 2);
assertThat(result3, equalTo(Integer.MIN_VALUE));
public void whenSumOverflow_thenReturnMaxInteger() {
int result = IntMath.saturatedAdd(Integer.MAX_VALUE, 100);
assertThat(result, equalTo(Integer.MAX_VALUE));
}
@Test
public void testIntMathPow() {
try {
IntMath.checkedPow(Integer.MAX_VALUE, 2);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
public void whenSumUnderflow_thenReturnMinInteger() {
int result = IntMath.saturatedAdd(Integer.MIN_VALUE, -100);
assertThat(result, equalTo(Integer.MIN_VALUE));
}
try {
IntMath.checkedPow(Integer.MIN_VALUE, 3);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
@Test(expected = ArithmeticException.class)
public void whenDifferenceOverflow_thenThrowException() {
IntMath.checkedSubtract(Integer.MAX_VALUE, -1);
}
int result1 = IntMath.saturatedPow(3, 3);
assertThat(result1, equalTo(27));
int result2 = IntMath.saturatedPow(Integer.MAX_VALUE, 2);
assertThat(result2, equalTo(Integer.MAX_VALUE));
int result3 = IntMath.saturatedPow(Integer.MIN_VALUE, 3);
assertThat(result3, equalTo(Integer.MIN_VALUE));
@Test(expected = ArithmeticException.class)
public void whenDifferenceUnderflow_thenThrowException() {
IntMath.checkedSubtract(Integer.MIN_VALUE, 1);
}
@Test
public void testIntMathRound() {
public void should_calculate_difference() {
int result = IntMath.checkedSubtract(200, 100);
assertThat(result, equalTo(100));
}
@Test
public void whenDifferenceOverflow_thenReturnMaxInteger() {
int result = IntMath.saturatedSubtract(Integer.MAX_VALUE, -1);
assertThat(result, equalTo(Integer.MAX_VALUE));
}
@Test
public void whenDifferenceUnderflow_thenReturnMinInteger() {
int result = IntMath.saturatedSubtract(Integer.MIN_VALUE, 1);
assertThat(result, equalTo(Integer.MIN_VALUE));
}
@Test(expected = ArithmeticException.class)
public void whenProductOverflow_thenThrowException() {
IntMath.checkedMultiply(Integer.MAX_VALUE, 2);
}
@Test(expected = ArithmeticException.class)
public void whenProductUnderflow_thenThrowException() {
IntMath.checkedMultiply(Integer.MIN_VALUE, 2);
}
@Test
public void should_calculate_product() {
int result = IntMath.checkedMultiply(21, 3);
assertThat(result, equalTo(63));
}
@Test
public void whenProductOverflow_thenReturnMaxInteger() {
int result = IntMath.saturatedMultiply(Integer.MAX_VALUE, 2);
assertThat(result, equalTo(Integer.MAX_VALUE));
}
@Test
public void whenProductUnderflow_thenReturnMinInteger() {
int result = IntMath.saturatedMultiply(Integer.MIN_VALUE, 2);
assertThat(result, equalTo(Integer.MIN_VALUE));
}
@Test(expected = ArithmeticException.class)
public void whenPowerOverflow_thenThrowException() {
IntMath.checkedPow(Integer.MAX_VALUE, 2);
}
@Test(expected = ArithmeticException.class)
public void whenPowerUnderflow_thenThrowException() {
IntMath.checkedPow(Integer.MIN_VALUE, 3);
}
@Test
public void should_calculate_power() {
int result = IntMath.saturatedPow(3, 3);
assertThat(result, equalTo(27));
}
@Test
public void whenPowerOverflow_thenReturnMaxInteger() {
int result = IntMath.saturatedPow(Integer.MAX_VALUE, 2);
assertThat(result, equalTo(Integer.MAX_VALUE));
}
@Test
public void whenPowerUnderflow_thenReturnMinInteger() {
int result = IntMath.saturatedPow(Integer.MIN_VALUE, 3);
assertThat(result, equalTo(Integer.MIN_VALUE));
}
@Test
public void should_round_divide_result() {
int result1 = IntMath.divide(3, 2, RoundingMode.DOWN);
assertThat(result1, equalTo(1));
int result2 = IntMath.divide(3, 2, RoundingMode.UP);
assertThat(result2, equalTo(2));
int result3 = IntMath.log2(5, RoundingMode.FLOOR);
assertThat(result3, equalTo(2));
int result4 = IntMath.log2(5, RoundingMode.CEILING);
assertThat(result4, equalTo(3));
int result5 = IntMath.log10(11, RoundingMode.HALF_UP);
assertThat(result5, equalTo(1));
int result6 = IntMath.sqrt(4, RoundingMode.UNNECESSARY);
assertThat(result6, equalTo(2));
try {
IntMath.sqrt(5, RoundingMode.UNNECESSARY);
assertTrue(false);
} catch (ArithmeticException e) {
assertTrue(true);
}
}
@Test
public void testIntMathAdditionalFunctions() {
int result1 = IntMath.gcd(15, 20);
assertThat(result1, equalTo(5));
public void should_round_log2_result() {
int result1 = IntMath.log2(5, RoundingMode.FLOOR);
assertThat(result1, equalTo(2));
int result2 = IntMath.mod(8, 3);
assertThat(result2, equalTo(2));
int result2 = IntMath.log2(5, RoundingMode.CEILING);
assertThat(result2, equalTo(3));
}
boolean result3 = IntMath.isPowerOfTwo(8);
assertTrue(result3);
boolean result4 = IntMath.isPowerOfTwo(9);
assertFalse(result4);
@Test
public void should_round_log10_result() {
int result = IntMath.log10(11, RoundingMode.HALF_UP);
assertThat(result, equalTo(1));
}
int result5 = IntMath.factorial(4);
assertThat(result5, equalTo(24));
@Test
public void should_round_sqrt_result() {
int result = IntMath.sqrt(4, RoundingMode.UNNECESSARY);
assertThat(result, equalTo(2));
}
int result6 = IntMath.binomial(7, 3);
assertThat(result6, equalTo(35));
@Test(expected = ArithmeticException.class)
public void whenNeedRounding_thenThrowException() {
IntMath.sqrt(5, RoundingMode.UNNECESSARY);
}
@Test
public void should_calculate_gcd() {
int result = IntMath.gcd(15, 20);
assertThat(result, equalTo(5));
}
@Test
public void should_calculate_mod() {
int result = IntMath.mod(8, 3);
assertThat(result, equalTo(2));
}
@Test
public void should_test_if_is_power_of_two() {
boolean result1 = IntMath.isPowerOfTwo(8);
assertTrue(result1);
boolean result2 = IntMath.isPowerOfTwo(9);
assertFalse(result2);
}
@Test
public void should_calculate_factorial() {
int result = IntMath.factorial(4);
assertThat(result, equalTo(24));
}
@Test
public void should_calculate_binomial() {
int result = IntMath.binomial(7, 3);
assertThat(result, equalTo(35));
}
@Test

View File

@ -7,7 +7,6 @@
<artifactId>jee7</artifactId>
<version>1.0-SNAPSHOT</version>
<description>JavaEE 7 Arquillian Archetype Sample</description>
<packaging>war</packaging>
<properties>
<java.min.version>1.8</java.min.version>
@ -28,6 +27,7 @@
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
<prerequisites>
@ -43,6 +43,13 @@
<scope>import</scope>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.extension</groupId>
<artifactId>arquillian-drone-bom</artifactId>
<version>2.0.1.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
@ -65,6 +72,13 @@
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.graphene</groupId>
<artifactId>graphene-webdriver</artifactId>
<version>2.1.0.Final</version>
<type>pom</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.awaitility</groupId>
<artifactId>awaitility</artifactId>
@ -85,6 +99,37 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.14</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.14</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
@ -167,6 +212,7 @@
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
@ -206,6 +252,7 @@
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</profile>
<profile>

View File

@ -0,0 +1,56 @@
package com.baeldung.convListVal;
import java.util.Date;
import javax.faces.bean.ManagedBean;
@ManagedBean
public class ConvListVal {
private Integer age;
private Double average;
private Date myDate;
private String name;
private String surname;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Double getAverage() {
return average;
}
public void setAverage(Double average) {
this.average = average;
}
public Date getMyDate() {
return myDate;
}
public void setMyDate(Date myDate) {
this.myDate = myDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.convListVal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;
public class MyListener implements ValueChangeListener {
private static final Logger LOG = Logger.getLogger(MyListener.class.getName());
@Override
public void processValueChange(ValueChangeEvent event) throws AbortProcessingException {
if (event.getNewValue() != null) {
LOG.log(Level.INFO, "\tNew Value:{0}", event.getNewValue());
}
}
}

View File

@ -12,8 +12,17 @@ NOTES: @WebServlet annotation designates the AccountServlet class as a Servlet c
An initialization parameter 'type' is being set to denote the type of the bank account.
@ServletSecurity annotation imposes security constraints on the AccountServlet based on
the tomcat-users.xml (this code assumes there is a role 'admin' in your tomcat-users.xml)
the tomcat-users.xml.
 
This code assumes that your tomcat-users.xml looks as follows:
<role rolename="Admin"/>
<role rolename="Member"/>
<role rolename="Guest"/>
<user username="Annie" password="admin" roles="Admin, Member, Guest" />
<user username="Diane" password="coder" roles="Member, Guest" />
<user username="Ted" password="newbie" roles="Guest" />
 
N.B : To see @ServletSecurity annotation in action, please uncomment the annotation code
for @ServletSecurity.

View File

@ -1,4 +1,4 @@
package com.baeldung.javaeeannotations;
package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations;
import java.io.IOException;
import java.io.PrintWriter;
@ -17,8 +17,8 @@ import javax.servlet.http.HttpServletResponse;
initParams = { @WebInitParam(name = "type", value = "savings") }
)
/*@ServletSecurity(
value = @HttpConstraint(rolesAllowed = {"admin"}),
httpMethodConstraints = {@HttpMethodConstraint(value = "POST", rolesAllowed = {"admin"})}
value = @HttpConstraint(rolesAllowed = {"Member"}),
httpMethodConstraints = {@HttpMethodConstraint(value = "POST", rolesAllowed = {"Admin"})}
)*/
public class AccountServlet extends javax.servlet.http.HttpServlet {

View File

@ -1,4 +1,4 @@
package com.baeldung.javaeeannotations;
package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

View File

@ -1,4 +1,4 @@
package com.baeldung.javaeeannotations;
package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations;
import java.io.IOException;

View File

@ -1,4 +1,4 @@
package com.baeldung.javaeeannotations;
package com.baeldung.javaeeannotations.JavaEEAnnotationsSample.src.main.java.com.baeldung.javaeeannotations;
import java.io.IOException;
import java.io.PrintWriter;

View File

@ -0,0 +1,50 @@
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Converters, Listeners and Validators</title>
</h:head>
<h:body>
<h1>Testing converters</h1>
<h:form id="myform">
<h:outputLabel value="Age:"/>
<h:inputText id="age" value="#{convListVal.age}">
<f:converter converterId="javax.faces.Integer" />
</h:inputText>
<h:message id="ageError" for="age" />
<br/>
<h:outputLabel value="Average:"/>
<h:inputText id="average" value="#{convListVal.average}">
<f:converter converterId="javax.faces.Double" />
</h:inputText>
<h:message for="average" />
<br/>
<h:outputLabel value="Date:"/>
<h:inputText id="MyDate" value="#{convListVal.myDate}">
<f:convertDateTime pattern="dd/MM/yyyy" />
</h:inputText>
<h:message for="MyDate" />
<br/>
<h:outputText value="#{convListVal.myDate}">
<f:convertDateTime dateStyle="full" locale="en"/>
</h:outputText>
<br/>
<h:outputLabel value="Name:"/>
<h:inputText id="name" size="30" value="#{convListVal.name}">
<f:valueChangeListener type="com.baeldung.convListVal.MyListener" />
</h:inputText>
<br/>
<h:outputLabel value="surname" for="surname"/>
<h:panelGroup>
<h:inputText id="surname" value="#{convListVal.surname}">
<f:validateLength minimum="5" maximum="10"/>
</h:inputText>
<h:message for="surname" errorStyle="color:red" />
</h:panelGroup>
<br/>
<h:commandButton id="send" value="submit" type="submit" />
</h:form>
</h:body>
</html>

View File

@ -1,4 +1,4 @@
package com.baeldung.jaxws;
/*package com.baeldung.jaxws;
import static org.junit.Assert.assertEquals;
@ -108,3 +108,4 @@ public class EmployeeServiceLiveTest {
}
}
*/

View File

@ -20,6 +20,31 @@
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<dependencies>
<dependency>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>3.3.0</version>
<type>maven-plugin</type>
</dependency>
</dependencies>
<extensions>true</extensions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
@ -92,6 +117,56 @@
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>${jetty.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-core</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-java</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-test-utils_2.10</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-core</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-java</artifactId>
<version>${flink.version}</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-test-utils_2.10</artifactId>
<version>${flink.version}</version>
</dependency>
</dependencies>
<properties>
@ -104,9 +179,14 @@
<assertj.version>3.6.2</assertj.version>
<jsonassert.version>1.5.0</jsonassert.version>
<javers.version>3.1.0</javers.version>
<jetty.version>9.4.3.v20170317</jetty.version>
<httpclient.version>4.5.3</httpclient.version>
<commons.io.version>2.5</commons.io.version>
<jetty.version>9.4.2.v20170220</jetty.version>
<httpclient.version>4.5.3</httpclient.version>
<commons.io.version>2.5</commons.io.version>
<flink.version>1.2.0</flink.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,20 @@
package com.baeldung.flink;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;
import java.util.stream.Stream;
@SuppressWarnings("serial")
public class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> {
@Override
public void flatMap(String value, Collector<Tuple2<String, Integer>> out) {
String[] tokens = value.toLowerCase().split("\\W+");
Stream.of(tokens)
.filter(t -> t.length() > 0)
.forEach(token -> out.collect(new Tuple2<>(token, 1)));
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.flink;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.aggregation.Aggregations;
import org.apache.flink.api.java.tuple.Tuple2;
import java.util.List;
public class WordCount {
public static DataSet<Tuple2<String, Integer>> startWordCount(ExecutionEnvironment env, List<String> lines) throws Exception {
DataSet<String> text = env.fromCollection(lines);
return text.flatMap(new LineSplitter())
.groupBy(0)
.aggregate(Aggregations.SUM, 1);
}
}

View File

@ -4,6 +4,7 @@ import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
public class JettyServer {
@ -11,7 +12,13 @@ public class JettyServer {
public void start() throws Exception {
server = new Server();
int maxThreads = 100;
int minThreads = 10;
int idleTimeout = 120;
QueuedThreadPool threadPool = new QueuedThreadPool(maxThreads, minThreads, idleTimeout);
server = new Server(threadPool);
ServerConnector connector = new ServerConnector(server);
connector.setPort(8090);
server.setConnectors(new Connector[]{connector});

View File

@ -0,0 +1,186 @@
package com.baeldung.flink;
import org.apache.flink.api.common.operators.Order;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.junit.Test;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class WordCountIntegrationTest {
final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
@Test
public void givenDataSet_whenExecuteWordCount_thenReturnWordCount() throws Exception {
//given
List<String> lines = Arrays.asList("This is a first sentence", "This is a second sentence with a one word");
//when
DataSet<Tuple2<String, Integer>> result = WordCount.startWordCount(env, lines);
//then
List<Tuple2<String, Integer>> collect = result.collect();
assertThat(collect).containsExactlyInAnyOrder(
new Tuple2<>("a", 3), new Tuple2<>("sentence", 2), new Tuple2<>("word", 1),
new Tuple2<>("is", 2), new Tuple2<>("this", 2), new Tuple2<>("second", 1),
new Tuple2<>("first", 1), new Tuple2<>("with", 1), new Tuple2<>("one", 1));
}
@Test
public void givenListOfAmounts_whenUseMapReduce_thenSumAmountsThatAreOnlyAboveThreshold() throws Exception {
//given
DataSet<Integer> amounts = env.fromElements(1, 29, 40, 50);
int threshold = 30;
//when
List<Integer> collect = amounts
.filter(a -> a > threshold)
.reduce((integer, t1) -> integer + t1)
.collect();
//then
assertThat(collect.get(0)).isEqualTo(90);
}
@Test
public void givenDataSetOfComplexObjects_whenMapToGetOneField_thenReturnedListHaveProperElements() throws Exception {
//given
DataSet<Person> personDataSource = env.fromCollection(Arrays.asList(new Person(23, "Tom"), new Person(75, "Michael")));
//when
List<Integer> ages = personDataSource.map(p -> p.age).collect();
//then
assertThat(ages.size()).isEqualTo(2);
assertThat(ages.containsAll(Arrays.asList(23, 75))).isTrue();
}
@Test
public void givenDataSet_whenSortItByOneField_thenShouldReturnSortedDataSet() throws Exception {
//given
Tuple2<Integer, String> secondPerson = new Tuple2<>(4, "Tom");
Tuple2<Integer, String> thirdPerson = new Tuple2<>(5, "Scott");
Tuple2<Integer, String> fourthPerson = new Tuple2<>(200, "Michael");
Tuple2<Integer, String> firstPerson = new Tuple2<>(1, "Jack");
DataSet<Tuple2<Integer, String>> transactions = env.fromElements(fourthPerson, secondPerson,
thirdPerson, firstPerson);
//when
List<Tuple2<Integer, String>> sorted = transactions
.sortPartition(new IdKeySelectorTransaction(), Order.ASCENDING)
.collect();
//then
assertThat(sorted).containsExactly(firstPerson, secondPerson, thirdPerson, fourthPerson);
}
@Test
public void giveTwoDataSets_whenJoinUsingId_thenProduceJoinedData() throws Exception {
//given
Tuple3<Integer, String, String> address = new Tuple3<>(1, "5th Avenue", "London");
DataSet<Tuple3<Integer, String, String>> addresses = env.fromElements(address);
Tuple2<Integer, String> firstTransaction = new Tuple2<>(1, "Transaction_1");
DataSet<Tuple2<Integer, String>> transactions =
env.fromElements(firstTransaction, new Tuple2<>(12, "Transaction_2"));
//when
List<Tuple2<Tuple2<Integer, String>, Tuple3<Integer, String, String>>> joined =
transactions.join(addresses)
.where(new IdKeySelectorTransaction())
.equalTo(new IdKeySelectorAddress())
.collect();
//then
assertThat(joined.size()).isEqualTo(1);
assertThat(joined.contains(new Tuple2<>(firstTransaction, address)));
}
@Test
public void givenStreamOfEvents_whenProcessEvents_thenShouldPrintResultsOnSinkOperation() throws Exception {
//given
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
DataStream<String> text
= env.fromElements("This is a first sentence", "This is a second sentence with a one word");
SingleOutputStreamOperator<String> upperCase = text.map(String::toUpperCase);
upperCase.print();
//when
env.execute();
}
@Test
public void givenStreamOfEvents_whenProcessEvents_thenShouldApplyWindowingOnTransformation() throws Exception {
//given
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
SingleOutputStreamOperator<Tuple2<Integer, Long>> windowed = env.fromElements(
new Tuple2<>(16, ZonedDateTime.now().plusMinutes(25).toInstant().getEpochSecond()),
new Tuple2<>(15, ZonedDateTime.now().plusMinutes(2).toInstant().getEpochSecond())
).assignTimestampsAndWatermarks(new BoundedOutOfOrdernessTimestampExtractor<Tuple2<Integer, Long>>(Time.seconds(20)) {
@Override
public long extractTimestamp(Tuple2<Integer, Long> element) {
return element.f1 * 1000;
}
});
SingleOutputStreamOperator<Tuple2<Integer, Long>> reduced = windowed
.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
.maxBy(0, true);
reduced.print();
//when
env.execute();
}
private static class IdKeySelectorTransaction implements KeySelector<Tuple2<Integer, String>, Integer> {
@Override
public Integer getKey(Tuple2<Integer, String> value) {
return value.f0;
}
}
private static class IdKeySelectorAddress implements KeySelector<Tuple3<Integer, String, String>, Integer> {
@Override
public Integer getKey(Tuple3<Integer, String, String> value) {
return value.f0;
}
}
private static class Person {
private final int age;
private final String name;
private Person(int age, String name) {
this.age = age;
this.name = name;
}
}
}

View File

@ -2,8 +2,6 @@ package org.baeldung.mockito;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.hamcrest.Matchers.equalTo;
@ -69,7 +67,7 @@ public class MockitoConfigExamplesTest {
}
@Test
public final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMetehodIsCalled() {
public final void whenMockMethodCallIsConfiguredToCallTheRealMethod_thenRealMethodIsCalled() {
final MyList listMock = Mockito.mock(MyList.class);
when(listMock.size()).thenCallRealMethod();
@ -77,14 +75,9 @@ public class MockitoConfigExamplesTest {
}
@Test
public final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMetehodIsCalled() {
public final void whenMockMethodCallIsConfiguredWithCustomAnswer_thenRealMethodIsCalled() {
final MyList listMock = Mockito.mock(MyList.class);
doAnswer(new Answer<String>() {
@Override
public final String answer(final InvocationOnMock invocation) {
return "Always the same";
}
}).when(listMock).get(anyInt());
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
final String element = listMock.get(1);
assertThat(element, is(equalTo("Always the same")));

View File

@ -153,7 +153,6 @@
<module>spring-mvc-email</module>
<module>spring-mvc-forms</module>
<module>spring-mvc-java</module>
<module>spring-mvc-no-xml</module>
<module>spring-mvc-tiles</module>
<module>spring-mvc-velocity</module>
<module>spring-mvc-web-vs-initializer</module>

View File

@ -1,164 +1,171 @@
<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>rest-testing</artifactId>
<version>0.1-SNAPSHOT</version>
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>rest-testing</artifactId>
<version>0.1-SNAPSHOT</version>
<name>rest-testing</name>
<name>rest-testing</name>
<dependencies>
<dependencies>
<!-- utils -->
<!-- utils -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- http client -->
<!-- http client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcore.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcore.version}</version>
</dependency>
<!-- marshalling -->
<!-- marshalling -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<!-- logging -->
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<scope>runtime</scope>
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<!-- test scoped -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<version>${wiremock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
</dependency>
</dependencies>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>${cucumber.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-junit</artifactId>
<version>${cucumber.version}</version>
</dependency>
<build>
<finalName>rest-testing</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<dependency>
<groupId>org.jbehave</groupId>
<artifactId>jbehave-core</artifactId>
<version>${jbehave.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<plugins>
<build>
<finalName>rest-testing</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugin>
</plugins>
</plugins>
</build>
</build>
<profiles>
<profile>
@ -177,10 +184,10 @@
<configuration>
<excludes>
<exclude>**/*UnitTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
<exclude>**/*LiveTest.java</exclude>
</includes>
</configuration>
</execution>
@ -195,37 +202,38 @@
</build>
</profile>
</profiles>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<properties>
<!-- marshalling -->
<jackson.version>2.8.5</jackson.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-io.version>2.5</commons-io.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<!-- util -->
<guava.version>19.0</guava.version>
<commons-lang3.version>3.5</commons-lang3.version>
<commons-io.version>2.5</commons-io.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<rest-assured.version>2.9.0</rest-assured.version>
<cucumber.version>1.2.5</cucumber.version>
<wiremock.version>2.4.1</wiremock.version>
<httpcore.version>4.4.5</httpcore.version>
<httpclient.version>4.5.2</httpclient.version>
<httpcore.version>4.4.5</httpcore.version>
<httpclient.version>4.5.2</httpclient.version>
<jbehave.version>4.1</jbehave.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<!-- maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</properties>
</project>

View File

@ -0,0 +1,45 @@
package com.baeldung.rest.jbehave;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import java.util.Arrays;
import java.util.List;
import static org.jbehave.core.io.CodeLocations.codeLocationFromClass;
import static org.jbehave.core.reporters.Format.CONSOLE;
/**
* @author aiet
*/
public abstract class AbstractStory extends JUnitStories {
abstract String storyName();
@Override
public Configuration configuration() {
return new MostUsefulConfiguration()
.useStoryLoader(new LoadFromClasspath(this.getClass()))
.useStoryReporterBuilder(new StoryReporterBuilder()
.withCodeLocation(codeLocationFromClass(this.getClass()))
.withFormats(CONSOLE));
}
abstract Object stepInstance();
@Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), stepInstance());
}
@Override
protected List<String> storyPaths() {
return Arrays.asList(storyName());
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.rest.jbehave;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import java.io.IOException;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.apache.http.HttpStatus.SC_NOT_FOUND;
import static org.junit.Assert.assertTrue;
public class GithubUserNotFoundSteps {
private String api;
private String nonExistentUser;
private int githubResponseCode;
@Given("github user profile api")
public void givenGithubUserProfileApi() {
api = "https://api.github.com/users/%s";
}
@Given("a random non-existent username")
public void givenANonexistentUsername() {
nonExistentUser = randomAlphabetic(8);
}
@When("I look for the random user via the api")
public void whenILookForTheUserViaTheApi() throws IOException {
githubResponseCode = getGithubUserProfile(api, nonExistentUser)
.getStatusLine()
.getStatusCode();
}
@When("I look for $user via the api")
public void whenILookForSomeNonExistentUserViaTheApi(String user) throws IOException {
githubResponseCode = getGithubUserProfile(api, user)
.getStatusLine()
.getStatusCode();
}
static HttpResponse getGithubUserProfile(String api, String username) throws IOException {
HttpUriRequest request = new HttpGet(String.format(api, username));
return HttpClientBuilder
.create()
.build()
.execute(request);
}
@Then("github respond: 404 not found")
public void thenGithubRespond404NotFound() {
assertTrue(SC_NOT_FOUND == githubResponseCode);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.rest.jbehave;
/**
* @author aiet
*/
public class GithubUserNotFoundStoryLiveTest extends AbstractStory {
@Override
String storyName() {
return "github_user_not_found.story";
}
@Override
Object stepInstance() {
return new GithubUserNotFoundSteps();
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.rest.jbehave;
import org.apache.http.entity.ContentType;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import java.io.IOException;
import static com.baeldung.rest.jbehave.GithubUserNotFoundSteps.getGithubUserProfile;
import static org.junit.Assert.assertEquals;
public class GithubUserResponseMediaTypeSteps {
private String api;
private String validUser;
private String mediaType;
@Given("github user profile api")
public void givenGithubUserProfileApi() {
api = "https://api.github.com/users/%s";
}
@Given("a valid username")
public void givenAValidUsername() {
validUser = "eugenp";
}
@When("I look for the user via the api")
public void whenILookForTheUserViaTheApi() throws IOException {
mediaType = ContentType
.getOrDefault(getGithubUserProfile(api, validUser).getEntity())
.getMimeType();
}
@Then("github respond data of type json")
public void thenGithubRespondDataOfTypeJson() {
assertEquals("application/json", mediaType);
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.rest.jbehave;
/**
* @author aiet
*/
public class GithubUserResponseMediaTypeStoryLiveTest extends AbstractStory {
@Override
String storyName() {
return "github_user_response_mediatype.story";
}
@Override
Object stepInstance() {
return new GithubUserResponseMediaTypeSteps();
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.rest.jbehave;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.baeldung.rest.GitHubUser;
import org.baeldung.rest.RetrieveUtil;
import org.hamcrest.Matchers;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import java.io.IOException;
import static com.baeldung.rest.jbehave.GithubUserNotFoundSteps.getGithubUserProfile;
import static org.hamcrest.MatcherAssert.assertThat;
public class GithubUserResponsePayloadSteps {
private String api;
private GitHubUser resource;
@Given("github user profile api")
public void givenGithubUserProfileApi() {
api = "https://api.github.com/users/%s";
}
@When("I look for $user via the api")
public void whenILookForEugenpViaTheApi(String user) throws IOException {
HttpResponse httpResponse = getGithubUserProfile(api, user);
resource = RetrieveUtil.retrieveResourceFromResponse(httpResponse, GitHubUser.class);
}
@Then("github's response contains a 'login' payload same as $username")
public void thenGithubsResponseContainsAloginPayloadSameAsEugenp(String username) {
assertThat(username, Matchers.is(resource.getLogin()));
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.rest.jbehave;
/**
* @author aiet
*/
public class GithubUserResponsePayloadStoryLiveTest extends AbstractStory {
@Override
String storyName() {
return "github_user_response_payload.story";
}
@Override
Object stepInstance() {
return new GithubUserResponsePayloadSteps();
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.rest.jbehave;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import java.util.Random;
import static org.junit.Assert.assertTrue;
public class IncreaseSteps {
private int counter;
private int previousValue;
@Given("a counter")
public void aCounter() {
}
@Given("the counter has any integral value")
public void counterHasAnyIntegralValue() {
counter = new Random().nextInt();
previousValue = counter;
}
@When("the user increases the counter")
public void increasesTheCounter() {
counter++;
}
@Then("the value of the counter must be 1 greater than previous value")
public void theValueOfTheCounterMustBe1Greater() {
assertTrue(1 == counter - previousValue);
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.rest.jbehave;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.configuration.MostUsefulConfiguration;
import org.jbehave.core.io.LoadFromClasspath;
import org.jbehave.core.junit.JUnitStories;
import org.jbehave.core.reporters.StoryReporterBuilder;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import java.util.Arrays;
import java.util.List;
import static org.jbehave.core.io.CodeLocations.codeLocationFromClass;
import static org.jbehave.core.reporters.Format.CONSOLE;
public class IncreaseStoryLiveTest extends JUnitStories {
@Override
public Configuration configuration() {
return new MostUsefulConfiguration()
.useStoryLoader(new LoadFromClasspath(this.getClass()))
.useStoryReporterBuilder(new StoryReporterBuilder()
.withCodeLocation(codeLocationFromClass(this.getClass()))
.withFormats(CONSOLE));
}
@Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), new IncreaseSteps());
}
@Override
protected List<String> storyPaths() {
return Arrays.asList("increase.story");
}
}

View File

@ -0,0 +1,19 @@
Meta:
Narrative:
As a user
I want to look up a non-existent user's profile on github
So that I can be sure that the username can not be found on github
Scenario: when a user checks a non-existent user on github, github would respond 'not found'
Given github user profile api
And a random non-existent username
When I look for the random user via the api
Then github respond: 404 not found
When I look for eugenp1 via the api
Then github respond: 404 not found
When I look for eugenp2 via the api
Then github respond: 404 not found

View File

@ -0,0 +1,13 @@
Meta:
Narrative:
As a user
I want to look up a valid user's profile on github
So that I can know that github responds data of type json
Scenario: when a user checks a valid user's profile on github, github would respond json data
Given github user profile api
And a valid username
When I look for the user via the api
Then github respond data of type json

View File

@ -0,0 +1,12 @@
Meta:
Narrative:
As a user
I want to look up a valid user's profile on github
So that I can know the login payload should be the same as username
Scenario: when a user checks a valid user's profile on github, github's response json should include a login payload with the same username
Given github user profile api
When I look for eugenp via the api
Then github's response contains a 'login' payload same as eugenp

View File

@ -0,0 +1,15 @@
JBehave Story - An increase test
Meta:
Narrative:
As a user
I want to increase a counter
So that I can have the counter's value increase by 1
Scenario: when a user increases a counter, its value is increased by 1
Given a counter
And the counter has any integral value
When the user increases the counter
Then the value of the counter must be 1 greater than previous value

View File

@ -1,6 +1,6 @@
<?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">
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>
@ -15,7 +15,7 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.BUILD-SNAPSHOT</version>
<relativePath /> <!-- lookup parent from repository -->
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
@ -58,11 +58,39 @@
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.jupiter.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.test.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.jupiter.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>${junit.platform.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
@ -92,7 +120,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<parallel>methods</parallel>
<useUnlimitedThreads>true</useUnlimitedThreads>
@ -143,6 +171,10 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<junit.platform.version>1.0.0-M3</junit.platform.version>
<junit.jupiter.version>5.0.0-M3</junit.jupiter.version>
<spring.test.version>4.3.7.RELEASE</spring.test.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,46 @@
package com.baeldung.jupiter;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.util.Assert;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
abstract class MethodParameterFactory {
private MethodParameterFactory() {
}
public static MethodParameter createMethodParameter(Parameter parameter) {
Assert.notNull(parameter, "Parameter must not be null");
Executable executable = parameter.getDeclaringExecutable();
if (executable instanceof Method) {
return new MethodParameter((Method) executable, getIndex(parameter));
}
return new MethodParameter((Constructor<?>) executable, getIndex(parameter));
}
public static SynthesizingMethodParameter createSynthesizingMethodParameter(Parameter parameter) {
Assert.notNull(parameter, "Parameter must not be null");
Executable executable = parameter.getDeclaringExecutable();
if (executable instanceof Method) {
return new SynthesizingMethodParameter((Method) executable, getIndex(parameter));
}
throw new UnsupportedOperationException("Cannot create a SynthesizingMethodParameter for a constructor parameter: " + parameter);
}
private static int getIndex(Parameter parameter) {
Assert.notNull(parameter, "Parameter must not be null");
Executable executable = parameter.getDeclaringExecutable();
Parameter[] parameters = executable.getParameters();
for (int i = 0; i < parameters.length; i++) {
if (parameters[i] == parameter) {
return i;
}
}
throw new IllegalStateException(String.format("Failed to resolve index of parameter [%s] in executable [%s]", parameter, executable.toGenericString()));
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.jupiter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.context.ApplicationContext;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Optional;
import static org.springframework.core.annotation.AnnotatedElementUtils.hasAnnotation;
abstract class ParameterAutowireUtils {
private ParameterAutowireUtils() {
}
public static boolean isAutowirable(Parameter parameter) {
return ApplicationContext.class.isAssignableFrom(parameter.getType()) || hasAnnotation(parameter, Autowired.class) || hasAnnotation(parameter, Qualifier.class) || hasAnnotation(parameter, Value.class);
}
public static Object resolveDependency(Parameter parameter, Class<?> containingClass, ApplicationContext applicationContext) {
boolean required = findMergedAnnotation(parameter, Autowired.class)
.map(Autowired::required)
.orElse(true);
MethodParameter methodParameter = (parameter.getDeclaringExecutable() instanceof Method ? MethodParameterFactory.createSynthesizingMethodParameter(parameter) : MethodParameterFactory.createMethodParameter(parameter));
DependencyDescriptor descriptor = new DependencyDescriptor(methodParameter, required);
descriptor.setContainingClass(containingClass);
return applicationContext
.getAutowireCapableBeanFactory()
.resolveDependency(descriptor, null);
}
private static <A extends Annotation> Optional<A> findMergedAnnotation(AnnotatedElement element, Class<A> annotationType) {
return Optional.ofNullable(AnnotatedElementUtils.findMergedAnnotation(element, annotationType));
}
}

View File

@ -0,0 +1,94 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.extension.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.test.context.TestContextManager;
import org.springframework.util.Assert;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
public class SpringExtension implements BeforeAllCallback, AfterAllCallback, TestInstancePostProcessor, BeforeEachCallback, AfterEachCallback, ParameterResolver {
private static final ExtensionContext.Namespace namespace = ExtensionContext.Namespace.create(SpringExtension.class);
@Override
public void beforeAll(ContainerExtensionContext context) throws Exception {
getTestContextManager(context).beforeTestClass();
}
@Override
public void afterAll(ContainerExtensionContext context) throws Exception {
try {
getTestContextManager(context).afterTestClass();
} finally {
context
.getStore(namespace)
.remove(context
.getTestClass()
.get());
}
}
@Override
public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception {
getTestContextManager(context).prepareTestInstance(testInstance);
}
@Override
public void beforeEach(TestExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance();
Method testMethod = context
.getTestMethod()
.get();
getTestContextManager(context).beforeTestMethod(testInstance, testMethod);
}
@Override
public void afterEach(TestExtensionContext context) throws Exception {
Object testInstance = context.getTestInstance();
Method testMethod = context
.getTestMethod()
.get();
Throwable testException = context
.getTestException()
.orElse(null);
getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException);
}
@Override
public boolean supports(ParameterContext parameterContext, ExtensionContext extensionContext) {
Parameter parameter = parameterContext.getParameter();
Executable executable = parameter.getDeclaringExecutable();
return (executable instanceof Constructor && AnnotatedElementUtils.hasAnnotation(executable, Autowired.class)) || ParameterAutowireUtils.isAutowirable(parameter);
}
@Override
public Object resolve(ParameterContext parameterContext, ExtensionContext extensionContext) {
Parameter parameter = parameterContext.getParameter();
Class<?> testClass = extensionContext
.getTestClass()
.get();
ApplicationContext applicationContext = getApplicationContext(extensionContext);
return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext);
}
private ApplicationContext getApplicationContext(ExtensionContext context) {
return getTestContextManager(context)
.getTestContext()
.getApplicationContext();
}
private TestContextManager getTestContextManager(ExtensionContext context) {
Assert.notNull(context, "ExtensionContext must not be null");
Class<?> testClass = context
.getTestClass()
.get();
ExtensionContext.Store store = context.getStore(namespace);
return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.AliasFor;
import org.springframework.test.context.ContextConfiguration;
import java.lang.annotation.*;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface SpringJUnit5Config {
@AliasFor(annotation = ContextConfiguration.class, attribute = "classes")
Class<?>[] value() default {};
@AliasFor(annotation = ContextConfiguration.class)
Class<?>[] classes() default {};
@AliasFor(annotation = ContextConfiguration.class)
String[] locations() default {};
@AliasFor(annotation = ContextConfiguration.class)
Class<? extends ApplicationContextInitializer<?
extends ConfigurableApplicationContext>>[] initializers() default {};
@AliasFor(annotation = ContextConfiguration.class)
boolean inheritLocations() default true;
@AliasFor(annotation = ContextConfiguration.class)
boolean inheritInitializers() default true;
@AliasFor(annotation = ContextConfiguration.class)
String name() default "";
}

View File

@ -0,0 +1,20 @@
package com.baeldung.jupiter;
import com.baeldung.web.reactive.Task;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
@Configuration
public class TestConfig {
@Bean
static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
Task taskName() {
return new Task("taskName", 1);
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.web.reactive;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Task {
private final String name;
private final int id;
public Task(@JsonProperty("name") String name, @JsonProperty("id") int id) {
this.name = name;
this.id = id;
}
public String getName() {
return this.name;
}
public int getId() {
return this.id;
}
@Override
public String toString() {
return "Task{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}

View File

@ -7,7 +7,7 @@ import org.springframework.boot.web.server.WebServer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;
//import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserters;
@ -15,140 +15,141 @@ import org.springframework.web.reactive.function.BodyInserters;
import static org.springframework.web.reactive.function.BodyInserters.fromObject;
import static org.springframework.web.reactive.function.BodyInserters.fromResource;
// TODO The class does not compile, WebTestClient cannot be resolved. Missing dependency?
public class FunctionalWebApplicationIntegrationTest {
private static WebTestClient client;
private static WebServer server;
@BeforeClass
public static void setup() throws Exception {
server = new FunctionalWebApplication().start();
client = WebTestClient
.bindToServer()
.baseUrl("http://localhost:" + server.getPort())
.build();
}
@AfterClass
public static void destroy() {
server.stop();
}
@Test
public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
client
.get()
.uri("/test")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.value()
.isEqualTo("helloworld");
}
@Test
public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
client
.get()
.uri("/")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.value()
.isEqualTo("helloworld");
}
@Test
public void givenLoginForm_whenPostValidToken_thenSuccess() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(1);
formData.add("user", "baeldung");
formData.add("token", "you_know_what_to_do");
client
.post()
.uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.exchange(BodyInserters.fromFormData(formData))
.expectStatus()
.isOk()
.expectBody(String.class)
.value()
.isEqualTo("welcome back!");
}
@Test
public void givenLoginForm_whenRequestWithInvalidToken_thenFail() throws Exception {
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(2);
formData.add("user", "baeldung");
formData.add("token", "try_again");
client
.post()
.uri("/login")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.exchange(BodyInserters.fromFormData(formData))
.expectStatus()
.isBadRequest();
}
@Test
public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception {
Resource resource = new ClassPathResource("/baeldung-weekly.png");
client
.post()
.uri("/upload")
.contentType(MediaType.MULTIPART_FORM_DATA)
.exchange(fromResource(resource))
.expectStatus()
.isOk()
.expectBody(String.class)
.value()
.isEqualTo(String.valueOf(resource.contentLength()));
}
@Test
public void givenActors_whenAddActor_thenAdded() throws Exception {
client
.get()
.uri("/actor")
.exchange()
.expectStatus()
.isOk()
.expectBody(Actor.class)
.list()
.hasSize(2);
client
.post()
.uri("/actor")
.exchange(fromObject(new Actor("Clint", "Eastwood")))
.expectStatus()
.isOk();
client
.get()
.uri("/actor")
.exchange()
.expectStatus()
.isOk()
.expectBody(Actor.class)
.list()
.hasSize(3);
}
@Test
public void givenResources_whenAccess_thenGot() throws Exception {
client
.get()
.uri("/files/hello.txt")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.value()
.isEqualTo("hello");
}
// private static WebTestClient client;
// private static WebServer server;
//
// @BeforeClass
// public static void setup() throws Exception {
// server = new FunctionalWebApplication().start();
// client = WebTestClient
// .bindToServer()
// .baseUrl("http://localhost:" + server.getPort())
// .build();
// }
//
// @AfterClass
// public static void destroy() {
// server.stop();
// }
//
// @Test
// public void givenRouter_whenGetTest_thenGotHelloWorld() throws Exception {
// client
// .get()
// .uri("/test")
// .exchange()
// .expectStatus()
// .isOk()
// .expectBody(String.class)
// .value()
// .isEqualTo("helloworld");
// }
//
// @Test
// public void givenIndexFilter_whenRequestRoot_thenRewrittenToTest() throws Exception {
// client
// .get()
// .uri("/")
// .exchange()
// .expectStatus()
// .isOk()
// .expectBody(String.class)
// .value()
// .isEqualTo("helloworld");
// }
//
// @Test
// public void givenLoginForm_whenPostValidToken_thenSuccess() throws Exception {
// MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(1);
// formData.add("user", "baeldung");
// formData.add("token", "you_know_what_to_do");
//
// client
// .post()
// .uri("/login")
// .contentType(MediaType.APPLICATION_FORM_URLENCODED)
// .exchange(BodyInserters.fromFormData(formData))
// .expectStatus()
// .isOk()
// .expectBody(String.class)
// .value()
// .isEqualTo("welcome back!");
// }
//
// @Test
// public void givenLoginForm_whenRequestWithInvalidToken_thenFail() throws Exception {
// MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(2);
// formData.add("user", "baeldung");
// formData.add("token", "try_again");
//
// client
// .post()
// .uri("/login")
// .contentType(MediaType.APPLICATION_FORM_URLENCODED)
// .exchange(BodyInserters.fromFormData(formData))
// .expectStatus()
// .isBadRequest();
// }
//
// @Test
// public void givenUploadForm_whenRequestWithMultipartData_thenSuccess() throws Exception {
// Resource resource = new ClassPathResource("/baeldung-weekly.png");
// client
// .post()
// .uri("/upload")
// .contentType(MediaType.MULTIPART_FORM_DATA)
// .exchange(fromResource(resource))
// .expectStatus()
// .isOk()
// .expectBody(String.class)
// .value()
// .isEqualTo(String.valueOf(resource.contentLength()));
// }
//
// @Test
// public void givenActors_whenAddActor_thenAdded() throws Exception {
// client
// .get()
// .uri("/actor")
// .exchange()
// .expectStatus()
// .isOk()
// .expectBody(Actor.class)
// .list()
// .hasSize(2);
//
// client
// .post()
// .uri("/actor")
// .exchange(fromObject(new Actor("Clint", "Eastwood")))
// .expectStatus()
// .isOk();
//
// client
// .get()
// .uri("/actor")
// .exchange()
// .expectStatus()
// .isOk()
// .expectBody(Actor.class)
// .list()
// .hasSize(3);
// }
//
// @Test
// public void givenResources_whenAccess_thenGot() throws Exception {
// client
// .get()
// .uri("/files/hello.txt")
// .exchange()
// .expectStatus()
// .isOk()
// .expectBody(String.class)
// .value()
// .isEqualTo("hello");
// }
}

View File

@ -0,0 +1,38 @@
package com.baeldung.jupiter;
import com.baeldung.web.reactive.Task;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringJUnit5Config(TestConfig.class)
@DisplayName("@SpringJUnit5Config Tests")
class Spring5JUnit5ComposedAnnotationTests {
@Autowired
Task task;
@Autowired
List<Task> tasks;
@Test
@DisplayName("ApplicationContext injected into method")
void givenAMethodName_whenInjecting_thenApplicationContextInjectedIntoMethod(ApplicationContext applicationContext) {
assertNotNull(applicationContext, "ApplicationContext should have been injected into method by Spring");
assertEquals(this.task, applicationContext.getBean("taskName", Task.class));
}
@Test
@DisplayName("Spring @Beans injected into fields")
void givenAnObject_whenInjecting_thenSpringBeansInjected() {
assertNotNull(task, "Task should have been @Autowired by Spring");
assertEquals("taskName", task.getName(), "Task's name");
assertEquals(1, tasks.size(), "Number of Tasks in context");
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.jupiter;
import com.baeldung.IntegrationTestExample1;
import com.baeldung.IntegrationTestExample2;
import org.junit.experimental.ParallelComputer;
import org.junit.jupiter.api.Test;
import org.junit.runner.Computer;
import org.junit.runner.JUnitCore;
public class Spring5JUnit5ParallelTest {
@Test
public void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingParallel() {
final Class<?>[] classes = {
IntegrationTestExample1.class, IntegrationTestExample2.class
};
JUnitCore.runClasses(new ParallelComputer(true, true), classes);
}
@Test
public void givenTwoTestClasses_whenJUnitRunParallel_thenTheTestsExecutingLinear() {
final Class<?>[] classes = {
IntegrationTestExample1.class, IntegrationTestExample2.class
};
JUnitCore.runClasses(new Computer(), classes);
}
}

View File

@ -0,0 +1,27 @@
package com.baeldung.jupiter;
import com.baeldung.web.reactive.Task;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = TestConfig.class)
class Spring5JUnit5Tests {
@Autowired
Task task;
@Test
void givenAMethodName_whenInjecting_thenApplicationContextInjectedIntoMetho(ApplicationContext applicationContext) {
assertNotNull(applicationContext, "ApplicationContext should have been injected by Spring");
assertEquals(this.task, applicationContext.getBean("taskName", Task.class));
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.jupiter;
import org.junit.jupiter.api.Test;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class Spring5Java8NewFeaturesTest {
@FunctionalInterface
public interface FunctionalInterfaceExample<Input, Result> {
Result reverseString(Input input);
}
public class StringUtils{
public FunctionalInterfaceExample<String, String>
functionLambdaString = s -> {
return Pattern.compile(" +").splitAsStream(s)
.map(word->new StringBuilder(word).reverse())
.collect(Collectors.joining(" "));
};
}
@Test
void givenStringUtil_whenSupplierCall_thenFunctionalInterfaceReverseString()
throws Exception {
Supplier<StringUtils> stringUtilsSupplier = StringUtils::new;
assertEquals(stringUtilsSupplier.get().functionLambdaString
.reverseString("hello"), "olleh");
}
}

View File

@ -0,0 +1,110 @@
package com.baeldung.jupiter;
import com.baeldung.web.reactive.Task;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ClientRequest;
import org.springframework.web.reactive.function.client.ExchangeFunction;
import org.springframework.web.reactive.function.client.ExchangeFunctions;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.ipc.netty.NettyContext;
import reactor.ipc.netty.http.server.HttpServer;
import java.net.URI;
import java.time.Duration;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.web.reactive.function.server.RequestPredicates.GET;
import static org.springframework.web.reactive.function.server.RequestPredicates.POST;
public class Spring5ReactiveServerClientTest {
private static NettyContext nettyContext;
@BeforeAll
public static void setUp() throws Exception {
HttpServer server = HttpServer.create("localhost", 8080);
RouterFunction<?> route = RouterFunctions
.route(POST("/task/process"), request -> ServerResponse
.ok()
.body(request
.bodyToFlux(Task.class)
.map(ll -> new Task("TaskName", 1)), Task.class))
.and(RouterFunctions.route(GET("/task"), request -> ServerResponse
.ok()
.body(Mono.just("server is alive"), String.class)));
HttpHandler httpHandler = RouterFunctions.toHttpHandler(route);
ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
nettyContext = server
.newHandler(adapter)
.block();
}
@AfterAll
public static void shutDown() {
nettyContext.dispose();
}
@Test
public void givenCheckTask_whenServerHandle_thenServerResponseALiveString() throws Exception {
WebClient client = WebClient.create("http://localhost:8080");
Mono<String> result = client
.get()
.uri("/task")
.exchange()
.then(response -> response.bodyToMono(String.class));
assertThat(result.block()).isInstanceOf(String.class);
}
@Test
public void givenThreeTasks_whenServerHandleTheTasks_thenServerResponseATask() throws Exception {
URI uri = URI.create("http://localhost:8080/task/process");
ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
ClientRequest request = ClientRequest
.method(HttpMethod.POST, uri)
.body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
.build();
Flux<Task> taskResponse = exchange
.exchange(request)
.flatMap(response -> response.bodyToFlux(Task.class));
assertThat(taskResponse.blockFirst()).isInstanceOf(Task.class);
}
@Test
public void givenCheckTask_whenServerHandle_thenOragicServerResponseALiveString() throws Exception {
URI uri = URI.create("http://localhost:8080/task");
ExchangeFunction exchange = ExchangeFunctions.create(new ReactorClientHttpConnector());
ClientRequest request = ClientRequest
.method(HttpMethod.GET, uri)
.body(BodyInserters.fromPublisher(getLatLngs(), Task.class))
.build();
Flux<String> taskResponse = exchange
.exchange(request)
.flatMap(response -> response.bodyToFlux(String.class));
assertThat(taskResponse.blockFirst()).isInstanceOf(String.class);
}
private static Flux<Task> getLatLngs() {
return Flux
.range(0, 3)
.zipWith(Flux.interval(Duration.ofSeconds(1)))
.map(x -> new Task("taskname", 1))
.doOnNext(ll -> System.out.println("Produced: {}" + ll));
}
}

View File

@ -106,6 +106,12 @@
<artifactId>guava</artifactId>
<version>${guava.version}</version>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>${jasperreports.version}</version>
</dependency>
<!-- logging -->
@ -296,6 +302,7 @@
<ehcache.version>3.1.3</ehcache.version>
<easymock.version>3.4</easymock.version>
<assertj.version>3.6.1</assertj.version>
<jasperreports.version>6.4.0</jasperreports.version>
</properties>

View File

@ -0,0 +1,39 @@
package org.baeldung.jasperreports;
import java.util.HashMap;
import java.util.Map;
import org.baeldung.jasperreports.config.JasperRerportsSimpleConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
ctx.register(JasperRerportsSimpleConfig.class);
ctx.refresh();
SimpleReportFiller simpleReportFiller = ctx.getBean(SimpleReportFiller.class);
simpleReportFiller.setReportFileName("employeeEmailReport.jrxml");
simpleReportFiller.compileReport();
simpleReportFiller.setReportFileName("employeeReport.jrxml");
simpleReportFiller.compileReport();
Map<String, Object> parameters = new HashMap<>();
parameters.put("title", "Employee Report Example");
parameters.put("minSalary", 15000.0);
parameters.put("condition", " LAST_NAME ='Smith' ORDER BY FIRST_NAME");
simpleReportFiller.setParameters(parameters);
simpleReportFiller.fillReport();
SimpleReportExporter simpleExporter = ctx.getBean(SimpleReportExporter.class);
simpleExporter.setJasperPrint(simpleReportFiller.getJasperPrint());
simpleExporter.exportToPdf("employeeReport.pdf", "baeldung");
simpleExporter.exportToXlsx("employeeReport.xlsx", "Employee Data");
simpleExporter.exportToCsv("employeeReport.csv");
simpleExporter.exportToHtml("employeeReport.html");
}
}

View File

@ -0,0 +1,115 @@
package org.baeldung.jasperreports;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.HtmlExporter;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleHtmlExporterOutput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimplePdfExporterConfiguration;
import net.sf.jasperreports.export.SimplePdfReportConfiguration;
import net.sf.jasperreports.export.SimpleWriterExporterOutput;
import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;
import org.springframework.stereotype.Component;
@Component
public class SimpleReportExporter {
private JasperPrint jasperPrint;
public SimpleReportExporter() {
}
public SimpleReportExporter (JasperPrint jasperPrint){
this.jasperPrint = jasperPrint;
}
public JasperPrint getJasperPrint() {
return jasperPrint;
}
public void setJasperPrint(JasperPrint jasperPrint) {
this.jasperPrint = jasperPrint;
}
public void exportToPdf(String fileName, String author) {
// print report to file
JRPdfExporter exporter = new JRPdfExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(fileName));
SimplePdfReportConfiguration reportConfig = new SimplePdfReportConfiguration();
reportConfig.setSizePageToContent(true);
reportConfig.setForceLineBreakPolicy(false);
SimplePdfExporterConfiguration exportConfig = new SimplePdfExporterConfiguration();
exportConfig.setMetadataAuthor(author);
exportConfig.setEncrypted(true);
exportConfig.setAllowedPermissionsHint("PRINTING");
exporter.setConfiguration(reportConfig);
exporter.setConfiguration(exportConfig);
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public void exportToXlsx(String fileName,String sheetName) {
JRXlsxExporter exporter = new JRXlsxExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(fileName));
SimpleXlsxReportConfiguration reportConfig = new SimpleXlsxReportConfiguration();
reportConfig.setSheetNames(new String[]{sheetName});
exporter.setConfiguration(reportConfig);
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public void exportToCsv(String fileName) {
JRCsvExporter exporter = new JRCsvExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleWriterExporterOutput(fileName));
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public void exportToHtml(String fileName) {
HtmlExporter exporter = new HtmlExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleHtmlExporterOutput(fileName));
try {
exporter.exportReport();
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}

View File

@ -0,0 +1,90 @@
package org.baeldung.jasperreports;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRSaver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SimpleReportFiller {
private String reportFileName;
private JasperReport jasperReport;
private JasperPrint jasperPrint;
@Autowired
private DataSource dataSource;
private Map<String, Object> parameters;
public SimpleReportFiller() {
parameters = new HashMap<>();
}
public void prepareReport() {
compileReport();
fillReport();
}
public void compileReport() {
try {
InputStream reportStream = getClass().getResourceAsStream("/".concat(reportFileName));
jasperReport = JasperCompileManager.compileReport(reportStream);
JRSaver.saveObject(jasperReport, reportFileName.replace(".jrxml", ".jasper"));
} catch (JRException ex) {
Logger.getLogger(SimpleReportFiller.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public void fillReport() {
try {
jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource.getConnection());
} catch (JRException | SQLException ex) {
Logger.getLogger(SimpleReportFiller.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Map<String, Object> getParameters() {
return parameters;
}
public void setParameters(Map<String, Object> parameters) {
this.parameters = parameters;
}
public String getReportFileName() {
return reportFileName;
}
public void setReportFileName(String reportFileName) {
this.reportFileName = reportFileName;
}
public JasperPrint getJasperPrint() {
return jasperPrint;
}
}

View File

@ -0,0 +1,32 @@
package org.baeldung.jasperreports.config;
import javax.sql.DataSource;
import org.baeldung.jasperreports.SimpleReportExporter;
import org.baeldung.jasperreports.SimpleReportFiller;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
@Configuration
public class JasperRerportsSimpleConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:employee-schema.sql")
.build();
}
@Bean
public SimpleReportFiller reportFiller() {
return new SimpleReportFiller();
}
@Bean
public SimpleReportExporter reportExporter() {
return new SimpleReportExporter();
}
}

View File

@ -0,0 +1,27 @@
CREATE TABLE EMPLOYEE(
ID INT NOT NULL PRIMARY KEY,
FIRST_NAME VARCHAR(255),
LAST_NAME VARCHAR(255),
SALARY DOUBLE,
);
CREATE TABLE EMAIL(
ID INT NOT NULL PRIMARY KEY,
ID_EMPLOYEE VARCHAR(255),
ADDRESS VARCHAR(255)
);
INSERT INTO EMPLOYEE VALUES (1, 'John', 'Doe', 10000.10);
INSERT INTO EMPLOYEE VALUES (2, 'Kevin', 'Smith', 20000.20);
INSERT INTO EMPLOYEE VALUES (3, 'Kim', 'Smith', 30000.30);
INSERT INTO EMPLOYEE VALUES (4, 'Stephen', 'Torvalds', 40000.40);
INSERT INTO EMPLOYEE VALUES (5, 'Christian', 'Reynolds', 50000.50);
INSERT INTO EMAIL VALUES (1, 1, 'john@baeldung.com');
INSERT INTO EMAIL VALUES (2, 1, 'john@gmail.com');
INSERT INTO EMAIL VALUES (3, 2, 'kevin@baeldung.com');
INSERT INTO EMAIL VALUES (4, 3, 'kim@baeldung.com');
INSERT INTO EMAIL VALUES (5, 3, 'kim@gmail.com');
INSERT INTO EMAIL VALUES (6, 3, 'kim@outlook.com');
INSERT INTO EMAIL VALUES (7, 4, 'stephen@baeldung.com');
INSERT INTO EMAIL VALUES (8, 5, 'christian@gmail.com');

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="employeeReport" pageWidth="612" pageHeight="792" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<parameter name="idEmployee" class="java.lang.Integer" isForPrompting="false"/>
<queryString>
<![CDATA[SELECT * FROM EMAIL WHERE ID_EMPLOYEE = $P{idEmployee}]]>
</queryString>
<field name="ADDRESS" class="java.lang.String"/>
<detail>
<band height="20" splitType="Stretch">
<textField>
<reportElement x="0" y="0" width="156" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{ADDRESS}]]></textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>

View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="employeeReport" pageWidth="612" pageHeight="792" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<parameter name="title" class="java.lang.String" isForPrompting="false"/>
<parameter name="condition" class="java.lang.String" isForPrompting="false">
<defaultValueExpression><![CDATA[" 1 = 1"]]></defaultValueExpression>
</parameter>
<parameter name="minSalary" class="java.lang.Double" isForPrompting="false"/>
<queryString>
<![CDATA[SELECT * FROM EMPLOYEE WHERE SALARY >= $P{minSalary} AND $P!{condition}]]>
</queryString>
<field name="FIRST_NAME" class="java.lang.String"/>
<field name="LAST_NAME" class="java.lang.String"/>
<field name="SALARY" class="java.lang.Double"/>
<field name="ID" class="java.lang.Integer"/>
<title>
<band height="20" splitType="Stretch">
<textField>
<reportElement x="238" y="0" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$P{title}]]></textFieldExpression>
</textField>
</band>
</title>
<detail>
<band height="47" splitType="Stretch">
<textField>
<reportElement x="0" y="0" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{FIRST_NAME}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="100" y="0" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{LAST_NAME}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="200" y="0" width="100" height="20"/>
<textElement/>
<textFieldExpression class="java.lang.String"><![CDATA[$F{SALARY}]]></textFieldExpression>
</textField>
<subreport>
<reportElement x="0" y="20" width="300" height="27"/>
<subreportParameter name="idEmployee">
<subreportParameterExpression><![CDATA[$F{ID}]]></subreportParameterExpression>
</subreportParameter>
<connectionExpression><![CDATA[$P{REPORT_CONNECTION}]]></connectionExpression>
<subreportExpression class="java.lang.String"><![CDATA["employeeEmailReport.jasper"]]></subreportExpression>
</subreport>
</band>
</detail>
</jasperReport>

View File

@ -16,4 +16,5 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Using Custom Banners in Spring Boot](http://www.baeldung.com/spring-boot-custom-banners)
- [Guide to Internationalization in Spring Boot](http://www.baeldung.com/spring-boot-internationalization)
- [Create a Custom FailureAnalyzer with Spring Boot](http://www.baeldung.com/spring-boot-failure-analyzer)
- [Configuring Separate Spring DataSource for Tests](http://www.baeldung.com/spring-testing-separate-data-source)

View File

@ -1,3 +1,5 @@
drop table if exists USERS;
create table USERS(
ID int not null AUTO_INCREMENT,
NAME varchar(100) not null,

View File

@ -63,4 +63,4 @@ public class SpringBootApplicationIntegrationTest {
mockMvc.perform(MockMvcRequestBuilders.get("/entity/findbyversion").header("Version", "1.0.0")).andExpect(MockMvcResultMatchers.status().isOk()).andExpect(MockMvcResultMatchers.content().contentType(contentType))
.andExpect(jsonPath("$.id", equalTo(1)));
}
}
}

View File

@ -1 +1 @@
Insert into Foo values(1,'Foo_Name');
--insert into Foo values(1,'Foo_Name');

View File

@ -1,8 +1,8 @@
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:db;DB_CLOSE_DELAY=-1
jdbc.username=sa
jdbc.password=sa
jdbc.user=sa
jdbc.pass=sa
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=create-drop
hibernate.hbm2ddl.auto=create-drop

View File

@ -77,39 +77,4 @@
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -35,11 +35,6 @@
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>1.5.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>

View File

@ -5,16 +5,9 @@
*/
package com.baeldung.spring.cloud.greeting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@EnableDiscoveryClient

View File

@ -6,16 +6,11 @@
package com.baeldung.spring.cloud.greeting;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@Controller
@RestController
public class GreetingController {
@Autowired
@ -23,10 +18,9 @@ public class GreetingController {
@RequestMapping(value = "/get-greeting", method = RequestMethod.GET)
public String greeting(Model model) {
public String greeting() {
model.addAttribute("greeting", helloWorldClient.HelloWorld());
return "greeting-view";
return helloWorldClient.HelloWorld();
}

View File

@ -5,8 +5,6 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@ -36,12 +34,6 @@ public class HelloWorldClient {
String HelloWorld();
}
/**
* Initiate call to Validation.
*
* @param name
* @return the response
*/
public String HelloWorld() {
return theClient.HelloWorld();
}

View File

@ -5,7 +5,6 @@
*/
package com.baeldung.spring.cloud.helloworld;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

View File

@ -72,38 +72,4 @@
</plugins>
</build>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -21,10 +21,11 @@ import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import com.baeldung.spring.web.config.ApplicationConfig;
import com.baeldung.spring.web.config.WebConfig;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = { ApplicationConfig.class })
@ContextConfiguration(classes = { ApplicationConfig.class, WebConfig.class })
public class GreetControllerIntegrationTest {
@Autowired

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -1,9 +0,0 @@
=========
## Spring MVC with NO XML Configuration Example Project
###The Course
The "REST With Spring" Classes: http://bit.ly/restwithspring
### Relevant Articles:
-

View File

@ -1,175 +0,0 @@
<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>
<version>0.1-SNAPSHOT</version>
<artifactId>spring-mvc-no-xml</artifactId>
<name>spring-mvc-no-xml</name>
<packaging>war</packaging>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
<scope>runtime</scope>
</dependency>
<!-- logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<!-- <scope>runtime</scope> -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
<!-- <scope>runtime</scope> --> <!-- some spring dependencies need to compile against jcl -->
</dependency>
<dependency> <!-- needed to bridge to slf4j for projects that use the log4j APIs directly -->
<groupId>org.slf4j</groupId>
<artifactId>log4j-over-slf4j</artifactId>
<version>${org.slf4j.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>${org.hamcrest.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>spring-mvc-no-xml</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<excludes>
<!-- <exclude>**/*ProductionTest.java</exclude> -->
</excludes>
<systemPropertyVariables>
<!-- <provPersistenceTarget>h2</provPersistenceTarget> -->
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<!-- Spring -->
<org.springframework.version>4.3.4.RELEASE</org.springframework.version>
<!-- logging -->
<org.slf4j.version>1.7.21</org.slf4j.version>
<logback.version>1.1.7</logback.version>
<!-- testing -->
<org.hamcrest.version>1.3</org.hamcrest.version>
<junit.version>4.12</junit.version>
<mockito.version>1.10.19</mockito.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<jstl.version>1.2</jstl.version>
<httpcore.version>4.4.5</httpcore.version>
<httpclient.version>4.5.2</httpclient.version>
<rest-assured.version>2.9.0</rest-assured.version>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.19.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.6.1</cargo-maven2-plugin.version>
</properties>
</project>

View File

@ -1,42 +0,0 @@
package org.baeldung.servlet;
import javax.servlet.ServletRegistration.Dynamic;
import org.baeldung.spring.ClientWebConfig;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/**
* <b>Further reading</b>: <br/>
* - http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-container-config <br/>
* - http://geowarin.wordpress.com/2013/01/23/complete-example-of-a-spring-mvc-3-2-project/ <br/>
* - http://www.objectpartners.com/2012/01/16/introduction-to-servlet-3-0/ <br/>
*/
public class WebAppNew extends AbstractAnnotationConfigDispatcherServletInitializer {
public WebAppNew() {
super();
}
// API
@Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { ClientWebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
@Override
protected void customizeRegistration(final Dynamic registration) {
super.customizeRegistration(registration);
}
}

View File

@ -1,23 +0,0 @@
package org.baeldung.servlet;
// public class WebApp implements WebApplicationInitializer {
//
// public WebApp() {
// super();
// }
//
// // API
//
// @Override
// public void onStartup(final ServletContext servletContext) throws ServletException {
// final AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
// root.setServletContext(servletContext);
// root.scan("org.baeldung.spring");
// root.refresh();
//
// final Dynamic servlet = servletContext.addServlet("mvc", new DispatcherServlet(root));
// servlet.setLoadOnStartup(1);
// servlet.addMapping("/");
// }
//
// }

View File

@ -1,39 +0,0 @@
package org.baeldung.spring;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@EnableWebMvc
@Configuration
public class ClientWebConfig extends WebMvcConfigurerAdapter {
public ClientWebConfig() {
super();
}
// API
@Override
public void addViewControllers(final ViewControllerRegistry registry) {
super.addViewControllers(registry);
registry.addViewController("/sample.html");
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}

View File

@ -1,20 +0,0 @@
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>web - %date [%thread] %-5level %logger{36} - %message%n
</pattern>
</encoder>
</appender>
<logger name="org.springframework" level="WARN" />
<logger name="org.springframework.transaction" level="WARN" />
<!-- in order to debug some marshalling issues, this needs to be TRACE -->
<logger name="org.springframework.web.servlet.mvc" level="WARN" />
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>
</configuration>

View File

@ -1,37 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd"
>
<http use-expressions="true">
<access-denied-handler error-page="/access-denied.html" />
<intercept-url pattern="/access-denied*" access="hasAnyRole('ROLE_LOCATION_WRITE','ROLE_POLYGON_WRITE')"/>
<intercept-url pattern="/admin/**" access="hasAnyRole('ROLE_ADMIN')"/>
<intercept-url pattern="/organization/**" access="hasAnyRole('ROLE_ORGANIZATION')"/>
<intercept-url pattern="/location/edit*" access="hasAnyRole('ROLE_LOCATION_WRITE')"/>
<intercept-url pattern="/location/view*" access="permitAll"/>
<intercept-url pattern="/login*" access="isAnonymous()"/>
<intercept-url pattern="/register*" access="isAnonymous()"/>
<intercept-url pattern="/login-denied/**" access="isAnonymous()"/>
<intercept-url pattern="/**" access="permitAll"/>
<form-login login-page='/login.html' default-target-url="/" always-use-default-target="false" authentication-failure-url="/login.html?error=true"/>
<logout/>
<anonymous/>
<session-management invalid-session-url="/">
<concurrency-control max-sessions="1"/>
</session-management>
</http>
<authentication-manager alias="authenticationManager" erase-credentials="false">
<authentication-provider ref="restAuthenticationProvider"/>
</authentication-manager>
</beans:beans>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd" >
</beans>

View File

@ -1,7 +0,0 @@
<html>
<head></head>
<body>
<h1>This is the body of the sample view</h1>
</body>
</html>

View File

@ -1,43 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="
http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"
>
<display-name>Spring MVC No XML Application</display-name>
<!-- Spring root -->
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>org.baeldung.spring</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Spring child -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- additional config -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>

View File

@ -1,13 +0,0 @@
*.class
#folders#
/target
/neoDb*
/data
/src/main/webapp/WEB-INF/classes
*/META-INF/*
# Packaged files #
*.jar
*.war
*.ear

View File

@ -81,6 +81,9 @@
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<rest-assured.version>2.9.0</rest-assured.version>
</properties>

View File

@ -29,6 +29,7 @@ The "Learn Spring Security" Classes: http://github.learnspringsecurity.com
- [Changing Spring Model Parameters with Handler Interceptor](http://www.baeldung.com/spring-model-parameters-with-handler-interceptor)
- [Introduction to Spring MVC HandlerInterceptor](http://www.baeldung.com/spring-mvc-handlerinterceptor)
- [Using a Custom Spring MVCs Handler Interceptor to Manage Sessions](http://www.baeldung.com/spring-mvc-custom-handler-interceptor)
- [Bootstrap a Web Application with Spring 4](http://www.baeldung.com/bootstraping-a-web-application-with-spring-and-java-based-configuration)
### Build the Project
```