Merge branch 'master' into master

This commit is contained in:
iaforek 2017-06-02 00:36:15 +01:00 committed by GitHub
commit a955425592
202 changed files with 6085 additions and 1225 deletions

View File

@ -1,16 +1,12 @@
language: java
before_install:
- export MAVEN_OPTS="-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit"
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
install: travis_wait 60 mvn -q test -fae
sudo: required
before_script:
- echo "MAVEN_OPTS='-Xmx2048M -Xss128M -XX:+CMSClassUnloadingEnabled -XX:+UseG1GC -XX:-UseGCOverheadLimit'" > ~/.mavenrc
jdk:
- oraclejdk8

View File

@ -0,0 +1,85 @@
package com.baeldung.java9;
public class Java9OptionalTest {
@Test
public void givenOptionalOfSome_whenToStream_thenShouldTreatItAsOneElementStream() {
//given
Optional<String> value = Optional.of("a");
//when
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//then
assertThat(collect).hasSameElementsAs(List.of("A"));
}
@Test
public void givenOptionalOfNone_whenToStream_thenShouldTreatItAsZeroElementStream() {
//given
Optional<String> value = Optional.empty();
//when
List<String> collect = value.stream().map(String::toUpperCase).collect(Collectors.toList());
//then
assertThat(collect).isEmpty();
}
@Test
public void givenOptional_whenPresent_thenShouldExecuteProperCallback() {
//given
Optional<String> value = Optional.of("properValue");
AtomicInteger successCounter = new AtomicInteger(0);
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//when
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//then
assertThat(successCounter.get()).isEqualTo(1);
assertThat(onEmptyOptionalCounter.get()).isEqualTo(0);
}
@Test
public void givenOptional_whenNotPresent_thenShouldExecuteProperCallback() {
//given
Optional<String> value = Optional.empty();
AtomicInteger successCounter = new AtomicInteger(0);
AtomicInteger onEmptyOptionalCounter = new AtomicInteger(0);
//when
value.ifPresentOrElse((v) -> successCounter.incrementAndGet(), onEmptyOptionalCounter::incrementAndGet);
//then
assertThat(successCounter.get()).isEqualTo(0);
assertThat(onEmptyOptionalCounter.get()).isEqualTo(1);
}
@Test
public void givenOptional_whenPresent_thenShouldTakeAValueFromIt() {
//given
String expected = "properValue";
Optional<String> value = Optional.of(expected);
Optional<String> defaultValue = Optional.of("default");
//when
Optional<String> result = value.or(() -> defaultValue);
//then
assertThat(result.get()).isEqualTo(expected);
}
@Test
public void givenOptional_whenEmpty_thenShouldTakeAValueFromOr() {
//given
String defaultString = "default";
Optional<String> value = Optional.empty();
Optional<String> defaultValue = Optional.of(defaultString);
//when
Optional<String> result = value.or(() -> defaultValue);
//then
assertThat(result.get()).isEqualTo(defaultString);
}
}

View File

@ -102,3 +102,15 @@
- [How to Perform a Simple HTTP Request in Java](http://www.baeldung.com/java-http-request)
- [Call Methods at Runtime Using Java Reflection](http://www.baeldung.com/java-method-reflection)
- [Guide to DelayQueue](http://www.baeldung.com/java-delay-queue)
- [Guide to UUID in JAVA] (http://www.baeldung.com/guide-to-uuid-in-java)
- [Comparing getPath(), getAbsolutePath(), and getCanonicalPath() in Java](http://www.baeldung.com/java-path)
- [How to Add a Single Element to a Stream](http://www.baeldung.com/java-stream-append-prepend)
- [Iterating Over Enum Values in Java](http://www.baeldung.com/java-enum-iteration)
- [A Guide to Java SynchronousQueue](http://www.baeldung.com/java-synchronous-queue)
- [Guide to the Java TransferQueue](http://www.baeldung.com/java-transfer-queue)
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
- [Guide to the ConcurrentSkipListMap](http://www.baeldung.com/java-concurrent-skip-list-map)
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
- [Using Java MappedByteBuffer](http://www.baeldung.com/java-mapped-byte-buffer)

View File

@ -0,0 +1,29 @@
package com.baeldung.concurrent.diningphilosophers;
public class DiningPhilosophers {
public static void main(String[] args) throws Exception {
Philosopher[] philosophers = new Philosopher[5];
Object[] forks = new Object[philosophers.length];
for (int i = 0; i < forks.length; i++) {
forks[i] = new Object();
}
for (int i = 0; i < philosophers.length; i++) {
Object leftFork = forks[i];
Object rightFork = forks[(i + 1) % forks.length];
if (i == philosophers.length - 1) {
philosophers[i] = new Philosopher(rightFork, leftFork); // The last philosopher picks up the right fork first
} else {
philosophers[i] = new Philosopher(leftFork, rightFork);
}
Thread t = new Thread(philosophers[i], "Philosopher " + (i + 1));
t.start();
}
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.concurrent.diningphilosophers;
public class Philosopher implements Runnable {
private final Object leftFork;
private final Object rightFork;
public Philosopher(Object left, Object right) {
this.leftFork = left;
this.rightFork = right;
}
private void doAction(String action) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " " + action);
Thread.sleep(((int) (Math.random() * 100)));
}
@Override public void run() {
try {
while (true) {
doAction(System.nanoTime() + ": Thinking"); // thinking
synchronized (leftFork) {
doAction(System.nanoTime() + ": Picked up left fork");
synchronized (rightFork) {
doAction(System.nanoTime() + ": Picked up right fork - eating"); // eating
doAction(System.nanoTime() + ": Put down right fork");
}
doAction(System.nanoTime() + ": Put down left fork. Returning to thinking");
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.java.enumiteration;
import java.util.stream.Stream;
public enum DaysOfWeekEnum {
SUNDAY("off"),
MONDAY("working"),
TUESDAY("working"),
WEDNESDAY("working"),
THURSDAY("working"),
FRIDAY("working"),
SATURDAY("off");
private String typeOfDay;
DaysOfWeekEnum(String typeOfDay) {
this.typeOfDay = typeOfDay;
}
public String getTypeOfDay() {
return typeOfDay;
}
public void setTypeOfDay(String typeOfDay) {
this.typeOfDay = typeOfDay;
}
public static Stream<DaysOfWeekEnum> stream() {
return Stream.of(DaysOfWeekEnum.values());
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.java.enumiteration;
import java.util.EnumSet;
public class EnumIterationExamples {
public static void main(String[] args) {
System.out.println("Enum iteration using forEach:");
EnumSet.allOf(DaysOfWeekEnum.class).forEach(day -> System.out.println(day));
System.out.println("Enum iteration using Stream:");
DaysOfWeekEnum.stream().filter(d -> d.getTypeOfDay().equals("off")).forEach(System.out::println);
System.out.println("Enum iteration using for loop:");
for (DaysOfWeekEnum day : DaysOfWeekEnum.values()) {
System.out.println(day);
}
}
}

View File

@ -33,7 +33,7 @@ public class Round {
public static double roundNotPrecise(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();

View File

@ -0,0 +1,5 @@
package com.baeldung.noclassdeffounderror;
public class ClassWithInitErrors {
static int data = 1 / 0;
}

View File

@ -0,0 +1,14 @@
package com.baeldung.noclassdeffounderror;
public class NoClassDefFoundErrorExample {
public ClassWithInitErrors getClassWithInitErrors() {
ClassWithInitErrors test;
try {
test = new ClassWithInitErrors();
} catch (Throwable t) {
System.out.println(t);
}
test = new ClassWithInitErrors();
return test;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.stream;
import java.util.List;
import java.util.stream.Stream;
public class StreamApi {
public String getLastElementUsingReduce(List<String> valueList) {
Stream<String> stream = valueList.stream();
return stream.reduce((first, second) -> second).orElse(null);
}
public Integer getInfiniteStreamLastElementUsingReduce() {
Stream<Integer> stream = Stream.iterate(0, i -> i + 1);
return stream.limit(20).reduce((first, second) -> second).orElse(null);
}
public String getLastElementUsingSkip(List<String> valueList) {
long count = valueList.stream().count();
Stream<String> stream = valueList.stream();
return stream.skip(count - 1).findFirst().orElse(null);
}
}

View File

@ -2,23 +2,23 @@ package com.baeldung.string;
import java.util.Optional;
public class StringHelper {
public static String removeLastChar(String s) {
class StringHelper {
static String removeLastChar(String s) {
return (s == null || s.length() == 0) ? s : (s.substring(0, s.length() - 1));
}
public static String removeLastCharRegex(String s) {
static String removeLastCharRegex(String s) {
return (s == null) ? s : s.replaceAll(".$", "");
}
public static String removeLastCharOptional(String s) {
static String removeLastCharOptional(String s) {
return Optional.ofNullable(s)
.filter(str -> str.length() != 0)
.map(str -> str.substring(0, str.length() - 1))
.orElse(s);
}
public static String removeLastCharRegexOptional(String s) {
static String removeLastCharRegexOptional(String s) {
return Optional.ofNullable(s)
.map(str -> str.replaceAll(".$", ""))
.orElse(s);

View File

@ -0,0 +1,118 @@
package com.baeldung.uuid;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
public class UUIDGenerator {
/**
* These are predefined UUID for name spaces
*/
private static final String NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_OID = "6ba7b812-9dad-11d1-80b4-00c04fd430c8";
private static final String NAMESPACE_X500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8";
private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
public static void main(String[] args) {
try {
System.out.println("Type 3 : " + generateType3UUID(NAMESPACE_DNS, "google.com"));
System.out.println("Type 4 : " + generateType4UUID());
System.out.println("Type 5 : " + generateType5UUID(NAMESPACE_URL, "google.com"));
System.out.println("Unique key : " + generateUniqueKeysWithUUIDAndMessageDigest());
} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
e.printStackTrace();
}
}
/**
* Type 4 UUID Generation
*/
public static UUID generateType4UUID() {
UUID uuid = UUID.randomUUID();
return uuid;
}
/**
* Type 3 UUID Generation
*
* @throws UnsupportedEncodingException
*/
public static UUID generateType3UUID(String namespace, String name) throws UnsupportedEncodingException {
String source = namespace + name;
byte[] bytes = source.getBytes("UTF-8");
UUID uuid = UUID.nameUUIDFromBytes(bytes);
return uuid;
}
/**
* Type 5 UUID Generation
*
* @throws UnsupportedEncodingException
*/
public static UUID generateType5UUID(String namespace, String name) throws UnsupportedEncodingException {
String source = namespace + name;
byte[] bytes = source.getBytes("UTF-8");
UUID uuid = type5UUIDFromBytes(bytes);
return uuid;
}
public static UUID type5UUIDFromBytes(byte[] name) {
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA-1");
} catch (NoSuchAlgorithmException nsae) {
throw new InternalError("MD5 not supported", nsae);
}
byte[] bytes = md.digest(name);
bytes[6] &= 0x0f; /* clear version */
bytes[6] |= 0x50; /* set to version 5 */
bytes[8] &= 0x3f; /* clear variant */
bytes[8] |= 0x80; /* set to IETF variant */
return constructType5UUID(bytes);
}
private static UUID constructType5UUID(byte[] data) {
long msb = 0;
long lsb = 0;
assert data.length == 16 : "data must be 16 bytes in length";
for (int i=0; i<8; i++)
msb = (msb << 8) | (data[i] & 0xff);
for (int i=8; i<16; i++)
lsb = (lsb << 8) | (data[i] & 0xff);
return new UUID(msb, lsb);
}
/**
* Unique Keys Generation Using Message Digest and Type 4 UUID
*
* @throws NoSuchAlgorithmException
* @throws UnsupportedEncodingException
*/
public static String generateUniqueKeysWithUUIDAndMessageDigest() throws NoSuchAlgorithmException, UnsupportedEncodingException {
MessageDigest salt = MessageDigest.getInstance("SHA-256");
salt.update(UUID.randomUUID()
.toString()
.getBytes("UTF-8"));
String digest = bytesToHex(salt.digest());
return digest;
}
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.classnotfoundexception;
import org.junit.Test;
public class ClassNotFoundExceptionTest {
@Test(expected = ClassNotFoundException.class)
public void givenNoDriversInClassPath_whenLoadDrivers_thenClassNotFoundException() throws ClassNotFoundException {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.noclassdeffounderror;
import org.junit.Test;
public class NoClassDefFoundErrorTest {
@Test(expected = NoClassDefFoundError.class)
public void givenInitErrorInClass_whenloadClass_thenNoClassDefFoundError() {
NoClassDefFoundErrorExample sample = new NoClassDefFoundErrorExample();
sample.getClassWithInitErrors();
}
}

View File

@ -0,0 +1,71 @@
package com.baeldung.regexp;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.Test;
public class EscapingCharsTest {
@Test
public void givenRegexWithDot_whenMatchingStr_thenMatches() {
String strInput = "foof";
String strRegex = "foo.";
assertEquals(true, strInput.matches(strRegex));
}
@Test
public void givenRegexWithDotEsc_whenMatchingStr_thenNotMatching() {
String strInput = "foof";
String strRegex = "foo\\.";
assertEquals(false, strInput.matches(strRegex));
}
@Test
public void givenRegexWithPipeEscaped_whenSplitStr_thenSplits() {
String strInput = "foo|bar|hello|world";
String strRegex = "\\Q|\\E";
assertEquals(4, strInput.split(strRegex).length);
}
@Test
public void givenRegexWithPipeEscQuoteMeth_whenSplitStr_thenSplits() {
String strInput = "foo|bar|hello|world";
String strRegex = "|";
assertEquals(4,strInput.split(Pattern.quote(strRegex)).length);
}
@Test
public void givenRegexWithDollar_whenReplacing_thenNotReplace() {
String strInput = "I gave $50 to my brother."
+ "He bought candy for $35. Now he has $15 left.";
String strRegex = "$";
String strReplacement = "£";
String output = "I gave £50 to my brother."
+ "He bought candy for £35. Now he has £15 left.";
Pattern p = Pattern.compile(strRegex);
Matcher m = p.matcher(strInput);
assertThat(output, not(equalTo(m.replaceAll(strReplacement))));
}
@Test
public void givenRegexWithDollarEsc_whenReplacing_thenReplace() {
String strInput = "I gave $50 to my brother."
+ "He bought candy for $35. Now he has $15 left.";
String strRegex = "\\$";
String strReplacement = "£";
String output = "I gave £50 to my brother."
+ "He bought candy for £35. Now he has £15 left.";
Pattern p = Pattern.compile(strRegex);
Matcher m = p.matcher(strInput);
assertEquals(output,m.replaceAll(strReplacement));
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.stream;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class StreamAddUnitTest {
@Test
public void givenStream_whenAppendingObject_thenAppended() {
Stream<String> anStream = Stream.of("a", "b", "c", "d", "e");
Stream<String> newStream = Stream.concat(anStream, Stream.of("A"));
List<String> resultList = newStream.collect(Collectors.toList());
assertEquals(resultList.get(resultList.size() - 1), "A");
}
@Test
public void givenStream_whenPrependingObject_thenPrepended() {
Stream<Integer> anStream = Stream.of(1, 2, 3, 4, 5);
Stream<Integer> newStream = Stream.concat(Stream.of(99), anStream);
assertEquals(newStream.findFirst()
.get(), (Integer) 99);
}
@Test
public void givenStream_whenInsertingObject_thenInserted() {
Stream<Double> anStream = Stream.of(1.1, 2.2, 3.3);
Stream<Double> newStream = insertInStream(anStream, 9.9, 3);
List<Double> resultList = newStream.collect(Collectors.toList());
assertEquals(resultList.get(3), (Double) 9.9);
}
public <T> Stream<T> insertInStream(Stream<T> stream, T elem, int index) {
List<T> result = stream.collect(Collectors.toList());
result.add(index, elem);
return result.stream();
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.stream;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class StreamApiTest {
private StreamApi streamApi = new StreamApi();
@Test
public void givenList_whenGetLastElementUsingReduce_thenReturnLastElement() {
List<String> valueList = new ArrayList<String>();
valueList.add("Joe");
valueList.add("John");
valueList.add("Sean");
String last = streamApi.getLastElementUsingReduce(valueList);
assertEquals("Sean", last);
}
@Test
public void givenInfiniteStream_whenGetInfiniteStreamLastElementUsingReduce_thenReturnLastElement() {
Integer last = streamApi.getInfiniteStreamLastElementUsingReduce();
assertEquals(new Integer(19), last);
}
@Test
public void givenListAndCount_whenGetLastElementUsingSkip_thenReturnLastElement() {
List<String> valueList = new ArrayList<String>();
valueList.add("Joe");
valueList.add("John");
valueList.add("Sean");
String last = streamApi.getLastElementUsingSkip(valueList);
assertEquals("Sean", last);
}
}

View File

@ -167,9 +167,11 @@ public class JavaRandomUnitTest {
final int leftLimit = 97; // letter 'a'
final int rightLimit = 122; // letter 'z'
final int targetStringLength = 10;
final Random random = new Random();
final StringBuilder buffer = new StringBuilder(targetStringLength);
for (int i = 0; i < targetStringLength; i++) {
final int randomLimitedInt = leftLimit + (int) (new Random().nextFloat() * (rightLimit - leftLimit + 1));
final int randomLimitedInt = leftLimit + (int) (random.nextFloat() * (rightLimit - leftLimit + 1));
buffer.append((char) randomLimitedInt);
}
final String generatedString = buffer.toString();

View File

@ -0,0 +1,106 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>ejb-session-beans</artifactId>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<arquillian-bom.version>1.1.12.Final</arquillian-bom.version>
<shrinkwrap-resolver-impl-maven.version>2.2.6</shrinkwrap-resolver-impl-maven.version>
<arquillian-junit-container.version>1.1.12.Final</arquillian-junit-container.version>
<arquillian-glassfish-embedded-3.1.version>1.0.0.Final</arquillian-glassfish-embedded-3.1.version>
<junit.version>4.12</junit.version>
<javaee-api.version>7.0</javaee-api.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>1.1.13.Final</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>arquillian-glassfish-embedded</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-embedded-3.1</artifactId>
<version>1.0.0.CR4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>3.1.2</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
</profiles>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,11 @@
package com.baeldung.ejb.stateful;
import javax.ejb.EJB;
public class EJBClient1 {
@EJB
public StatefulEJB statefulEJB;
}

View File

@ -0,0 +1,11 @@
package com.baeldung.ejb.stateful;
import javax.ejb.EJB;
public class EJBClient2 {
@EJB
public StatefulEJB statefulEJB;
}

View File

@ -0,0 +1,10 @@
package com.baeldung.ejb.stateful;
import javax.ejb.Stateful;
@Stateful
public class StatefulEJB {
public String name;
}

View File

@ -0,0 +1,10 @@
package com.baeldung.ejb.stateless;
import javax.ejb.EJB;
public class EJBClient1 {
@EJB
public StatelessEJB statelessEJB;
}

View File

@ -0,0 +1,11 @@
package com.baeldung.ejb.stateless;
import javax.ejb.EJB;
public class EJBClient2 {
@EJB
public StatelessEJB statelessEJB;
}

View File

@ -0,0 +1,11 @@
package com.baeldung.ejb.stateless;
import javax.ejb.Stateless;
@Stateless
public class StatelessEJB {
public String name;
}

View File

@ -0,0 +1,51 @@
package com.baeldung.ejb.test.stateful;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.baeldung.ejb.stateful.EJBClient1;
import com.baeldung.ejb.stateful.EJBClient2;
import com.baeldung.ejb.stateful.StatefulEJB;
import javax.inject.Inject;
@RunWith(Arquillian.class)
public class StatefulEJBTest {
@Inject
private EJBClient1 ejbClient1;
@Inject
private EJBClient2 ejbClient2;
@Test
public void givenOneStatefulBean_whenTwoClientsSetValueOnBean_thenClientStateIsMaintained() {
// act
ejbClient1.statefulEJB.name = "Client 1";
ejbClient2.statefulEJB.name = "Client 2";
// assert
Assert.assertNotEquals(ejbClient1.statefulEJB.name, ejbClient2.statefulEJB.name);
Assert.assertEquals("Client 1", ejbClient1.statefulEJB.name);
Assert.assertEquals("Client 2", ejbClient2.statefulEJB.name);
}
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addClass(StatefulEJB.class)
.addClass(EJBClient1.class)
.addClass(EJBClient2.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.ejb.test.stateless;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.baeldung.ejb.stateless.EJBClient1;
import com.baeldung.ejb.stateless.EJBClient2;
import com.baeldung.ejb.stateless.StatelessEJB;
import javax.inject.Inject;
@RunWith(Arquillian.class)
public class StatelessEJBTest {
@Inject
private EJBClient1 ejbClient1;
@Inject
private EJBClient2 ejbClient2;
@Test
public void givenOneStatelessBean_whenStateIsSetInOneBean_secondBeanShouldHaveSameState() {
// act
ejbClient1.statelessEJB.name = "Client 1";
// assert
Assert.assertEquals("Client 1", ejbClient1.statelessEJB.name);
Assert.assertEquals("Client 1", ejbClient2.statelessEJB.name);
}
@Test
public void givenOneStatelessBean_whenStateIsSetInBothBeans_secondBeanShouldHaveSecondBeanState() {
// act
ejbClient1.statelessEJB.name = "Client 1";
ejbClient2.statelessEJB.name = "Client 2";
// assert
Assert.assertEquals("Client 2", ejbClient2.statelessEJB.name);
}
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addClass(StatelessEJB.class)
.addClass(EJBClient1.class)
.addClass(EJBClient2.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
}

View File

@ -40,7 +40,12 @@
<version>1.0-SNAPSHOT</version>
<type>ejb</type>
</dependency>
<dependency>
<groupId>com.baeldung.ejb</groupId>
<artifactId>ejb-session-beans</artifactId>
<version>1.0-SNAPSHOT</version>
<type>ejb</type>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
@ -75,5 +80,7 @@
<modules>
<module>ejb-remote</module>
<module>ejb-client</module>
<module>ejb-session-beans</module>
<module>ejb-session-beans-client</module>
</modules>
</project>

View File

@ -1,2 +1,3 @@
### Relevant articles:
- [New Stream, Comparator and Collector Functionality in Guava 21](http://www.baeldung.com/guava-21-new)
- [New in Guava 21 common.util.concurrent](http://www.baeldung.com/guava-21-util-concurrent)

4
guest/log4j2-example/.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
/target/
.settings/
.classpath
.project

View File

@ -0,0 +1,3 @@
14:00:35.258 INFO Programmatic Logger Message
14:03:51.178 INFO Programmatic Logger Message
14:04:11.753 INFO Programmatic Logger Message

View File

@ -0,0 +1,25 @@
[
{
"timeMillis" : 1496315051753,
"thread" : "main",
"level" : "INFO",
"loggerName" : "RollingFileLogger",
"message" : "Json Message 1",
"endOfBatch" : false,
"loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
"threadId" : 1,
"threadPriority" : 5
}
, {
"timeMillis" : 1496315051862,
"thread" : "main",
"level" : "INFO",
"loggerName" : "RollingFileLogger",
"message" : "Json Messag 2",
"endOfBatch" : false,
"loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
"threadId" : 1,
"threadPriority" : 5
}
]

View File

@ -0,0 +1,56 @@
<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>log4j2-example</groupId>
<artifactId>log4j2-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- This is the needed core component. -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>${log4j-core.version}</version>
</dependency>
<!-- This is used by JSONLayout. -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources/</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<jackson.version>2.8.8.1</jackson.version>
<log4j-core.version>2.8.2</log4j-core.version>
</properties>
</project>

View File

@ -0,0 +1,43 @@
package com.stackify.models;
import java.time.LocalDate;
public class User {
private String name;
private String email;
private LocalDate dateOfBirth;
public User() {
}
public User(String name, String email) {
super();
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}

View File

@ -0,0 +1,14 @@
package com.stackify.services;
import java.time.LocalDate;
import java.time.Period;
import com.stackify.models.User;
public class MyService {
public int calculateUserAge(User user) {
return Period.between(user.getDateOfBirth(), LocalDate.now()).getYears();
}
}

View File

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<CustomLevels>
<CustomLevel name="NEW_XML_LEVEL" intLevel="350" />
</CustomLevels>
<Filters>
<BurstFilter level="INFO" rate="10" maxBurst="100" />
</Filters>
<Appenders>
<Console name="ColoredConsole" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{HH:mm:ss.SSS} [%t] %highlight{%level}{FATAL=bg_red, ERROR=red, WARN=yellow, INFO=green, DEBUG=blue, NEW_LEVEL=black, NEW_XML_LEVEL=black} - %msg%n" />
</Console>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %level - %msg%n" />
</Console>
<RollingFile name="RollingFileAppender" fileName="logs/app.log"
filePattern="logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<JSONLayout complete="true" compact="false" />
<Policies>
<OnStartupTriggeringPolicy />
<TimeBasedTriggeringPolicy />
<SizeBasedTriggeringPolicy size="50 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingFile>
<!--
<JDBC name="JDBCAppender" tableName="logs">
<DataSource jndiName="java:/comp/env/jdbc/LoggingDataSource" />
<Column name="date" isEventTimestamp="true" />
<Column name="logger" pattern="%logger" />
<Column name="level" pattern="%level" />
<Column name="message" pattern="%message" />
<Column name="exception" pattern="%ex{full}" />
</JDBC>
<Failover name="FailoverAppender" primary="JDBCAppender">
<Failovers>
<AppenderRef ref="RollingFileAppender" />
<AppenderRef ref="Console" />
</Failovers>
</Failover>
-->
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="ColoredConsole" />
</Root>
<Logger name="ConsoleLogger">
<AppenderRef ref="Console" />
</Logger>
<Logger name="RollingFileLogger">
<AppenderRef ref="RollingFileAppender" />
</Logger>
<!--
<Logger name="JDBCLogger">
<AppenderRef ref="JDBCAppender" />
<RegexFilter regex="*jdbc*" onMatch="ACCEPT" onMismatch="DENY" />
</Logger>
-->
</Loggers>
</Configuration>

View File

@ -0,0 +1,81 @@
package com.stackify.services;
import java.time.LocalDate;
import java.time.Month;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Appender;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.FileAppender;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.junit.Test;
import com.stackify.models.User;
import com.stackify.services.MyService;
public class MyServiceTest {
private static final Logger logger = LogManager.getLogger(MyServiceTest.class);
@Test
public void testService() {
MyService myService = new MyService();
User user = new User("John", "john@yahoo.com");
user.setDateOfBirth(LocalDate.of(1980, Month.APRIL, 20));
logger.info("Age of user {} is {}", () -> user.getName(), () -> myService.calculateUserAge(user));
}
@Test
public void testColoredLogger() {
logger.fatal("Fatal level message");
logger.error("Error level message");
logger.warn("Warn level message");
logger.info("Info level message");
logger.debug("Debug level message");
}
@Test
public void testRollingFileAppender() {
Logger rfLogger = LogManager.getLogger("RollingFileLogger");
rfLogger.info("Json Message 1");
rfLogger.info("Json Message 2");
}
@Test
public void testProgrammaticConfig() {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
PatternLayout layout = PatternLayout.newBuilder().withConfiguration(config).withPattern("%d{HH:mm:ss.SSS} %level %msg%n").build();
Appender appender = FileAppender.newBuilder().setConfiguration(config).withName("programmaticFileAppender").withLayout(layout).withFileName("java.log").build();
appender.start();
config.addAppender(appender);
AppenderRef ref = AppenderRef.createAppenderRef("programmaticFileAppender", null, null);
AppenderRef[] refs = new AppenderRef[] { ref };
LoggerConfig loggerConfig = LoggerConfig.createLogger(false, Level.INFO, "programmaticLogger", "true", refs, null, config, null);
loggerConfig.addAppender(appender, null, null);
config.addLogger("programmaticLogger", loggerConfig);
ctx.updateLoggers();
Logger pLogger = LogManager.getLogger("programmaticLogger");
pLogger.info("Programmatic Logger Message");
}
@Test
public void testCustomLevel() {
Level myLevel = Level.forName("NEW_LEVEL", 350);
logger.log(myLevel, "Custom Level Message");
logger.log(Level.getLevel("NEW_XML_LEVEL"), "Custom XML Level Message");
}
}

View File

@ -15,6 +15,8 @@
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- Maven plugins -->
<maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version>
</properties>
<dependencies>
<dependency>
@ -22,6 +24,11 @@
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
@ -37,6 +44,32 @@
</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-surefire-plugin</artifactId>
<configuration>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
<excludes>
<exclude>**/*IntegrationTest.java</exclude>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,5 +1,9 @@
package com.baeldung.hibernate;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@ -20,44 +24,56 @@ import com.baeldung.hibernate.pojo.Supplier;
public class HibernateMultiTenantUtil {
private static SessionFactory sessionFactory;
private static Map<String, ConnectionProvider> connectionProviderMap = new HashMap<>();
private static final String[] tenantDBNames = { "mydb1","mydb2"};
private static final String[] tenantDBNames = { "mydb1", "mydb2" };
public static SessionFactory getSessionFactory() throws UnsupportedTenancyException {
public static SessionFactory getSessionFactory() throws UnsupportedTenancyException, IOException {
if (sessionFactory == null) {
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = configureServiceRegistry(configuration);
sessionFactory = makeSessionFactory (serviceRegistry);
// sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = makeSessionFactory(serviceRegistry);
}
return sessionFactory;
}
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources( serviceRegistry );
for(Class annotatedClasses : getAnnotatedClasses()) {
metadataSources.addAnnotatedClass( annotatedClasses );
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
for (Class annotatedClasses : getAnnotatedClasses()) {
metadataSources.addAnnotatedClass(annotatedClasses);
}
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder().build();
return metadata.getSessionFactoryBuilder()
.build();
}
private static Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Supplier.class
};
return new Class<?>[] { Supplier.class };
}
private static ServiceRegistry configureServiceRegistry(Configuration configuration) throws UnsupportedTenancyException {
Properties properties = configuration.getProperties();
private static ServiceRegistry configureServiceRegistry() throws UnsupportedTenancyException, IOException {
// Properties properties = configuration.getProperties();
Properties properties = getProperties();
connectionProviderMap = setUpConnectionProviders(properties, tenantDBNames);
properties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, new ConfigurableMultiTenantConnectionProvider(connectionProviderMap));
return new StandardServiceRegistryBuilder().applySettings(properties).build();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate.properties");
FileInputStream inputStream = new FileInputStream(propertiesURL.getFile());
properties.load(inputStream);
System.out.println("LOADED PROPERTIES FROM hibernate.properties");
return properties;
}
private static Map<String, ConnectionProvider> setUpConnectionProviders(Properties properties, String[] tenantNames) throws UnsupportedTenancyException {
@ -66,23 +82,27 @@ public class HibernateMultiTenantUtil {
DriverManagerConnectionProviderImpl connectionProvider = new DriverManagerConnectionProviderImpl();
String tenantStrategy = properties.getProperty("hibernate.multiTenancy");
System.out.println("Strategy:"+tenantStrategy);
System.out.println("Strategy:" + tenantStrategy);
properties.put(Environment.URL, tenantUrl(properties.getProperty(Environment.URL), tenant, tenantStrategy));
System.out.println("URL:"+properties.getProperty(Environment.URL));
System.out.println("URL:" + properties.getProperty(Environment.URL));
connectionProvider.configure(properties);
System.out.println("Tenant:"+tenant);
System.out.println("Tenant:" + tenant);
providerMap.put(tenant, connectionProvider);
}
System.out.println("Added connections for:");
providerMap.keySet().stream().forEach(System.out::println);
providerMap.keySet()
.stream()
.forEach(System.out::println);
return providerMap;
}
private static Object tenantUrl(String originalUrl, String tenant, String tenantStrategy) throws UnsupportedTenancyException {
if (tenantStrategy.toUpperCase().equals("DATABASE")) {
if (tenantStrategy.toUpperCase()
.equals("DATABASE")) {
return originalUrl.replace(DEFAULT_DB_NAME, tenant);
} else if (tenantStrategy.toUpperCase().equals("SCHEMA")) {
} else if (tenantStrategy.toUpperCase()
.equals("SCHEMA")) {
return originalUrl + String.format(SCHEMA_TOKEN, tenant);
} else {
throw new UnsupportedTenancyException("Not yet supported");

View File

@ -1,14 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.url">jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1</property>
<property name="hibernate.connection.username">sa</property>
<property name="connection.password"/>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.multiTenancy">DATABASE</property>
</session-factory>
</hibernate-configuration>

View File

@ -0,0 +1,8 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.multiTenancy=DATABASE

View File

@ -1,65 +1,71 @@
package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.Supplier;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Test;
import static org.junit.Assert.assertNotEquals;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.junit.Before;
import org.junit.Test;
import com.baeldung.hibernate.pojo.Supplier;
public class MultiTenantHibernateIntegrationTest {
@Test
public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs () {
SessionFactory sessionFactory;
try {
sessionFactory = HibernateMultiTenantUtil.getSessionFactory();
Session db1Session = sessionFactory
.withOptions().tenantIdentifier("mydb1").openSession();
initDb1(db1Session);
Transaction transaction = db1Session.getTransaction();
transaction.begin();
Supplier supplierFromDB1 = (Supplier)db1Session.createCriteria(Supplier.class).list().get(0);
transaction.commit();
Session db2Session = sessionFactory
.withOptions().tenantIdentifier("mydb2").openSession();
initDb2(db2Session);
db2Session.getTransaction().begin();
Supplier supplierFromDB2 = (Supplier) db2Session.createCriteria(Supplier.class).list().get(0);
db2Session.getTransaction().commit();
System.out.println(supplierFromDB1);
System.out.println(supplierFromDB2);
assertNotEquals(supplierFromDB1, supplierFromDB2);
} catch (UnsupportedTenancyException e) {
e.printStackTrace();
}
public void givenDBMode_whenFetchingSuppliers_thenComparingFromDbs() throws UnsupportedTenancyException, IOException {
SessionFactory sessionFactory = HibernateMultiTenantUtil.getSessionFactory();
Session db1Session = sessionFactory.withOptions().tenantIdentifier("mydb1").openSession();
initDb1(db1Session);
Transaction transaction = db1Session.getTransaction();
transaction.begin();
Supplier supplierFromDB1 = (Supplier) db1Session.createCriteria(Supplier.class).list().get(0);
transaction.commit();
Session db2Session = sessionFactory.withOptions().tenantIdentifier("mydb2").openSession();
initDb2(db2Session);
db2Session.getTransaction().begin();
Supplier supplierFromDB2 = (Supplier) db2Session.createCriteria(Supplier.class).list().get(0);
db2Session.getTransaction().commit();
System.out.println(supplierFromDB1);
System.out.println(supplierFromDB2);
assertNotEquals(supplierFromDB1, supplierFromDB2);
}
private void initDb1(Session db1Session) {
System.out.println("Init DB1");
Transaction transaction = db1Session.getTransaction();
transaction.begin();
db1Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate();
db1Session.createSQLQuery("create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))").executeUpdate();
db1Session
.createSQLQuery(
"create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))")
.executeUpdate();
db1Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'John', 'USA')").executeUpdate();
transaction.commit();
}
private void initDb2(Session db2Session) {
System.out.println("Init DB2");
Transaction transaction = db2Session.getTransaction();
transaction.begin();
db2Session.createSQLQuery("DROP ALL OBJECTS").executeUpdate();
db2Session.createSQLQuery("create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))").executeUpdate();
db2Session
.createSQLQuery(
"create table Supplier (id integer generated by default as identity, country varchar(255), name varchar(255), primary key (id))")
.executeUpdate();
db2Session.createSQLQuery("insert into Supplier (id, country, name) values (null, 'Miller', 'UK')").executeUpdate();
transaction.commit();
}

View File

@ -0,0 +1,8 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.multiTenancy=DATABASE

View File

@ -40,6 +40,16 @@
<groupId>commons-logging</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-core</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>com.twelvemonkeys.imageio</groupId>
<artifactId>imageio-bmp</artifactId>
<version>3.3.2</version>
</dependency>
</dependencies>

View File

@ -0,0 +1,47 @@
package com.baeldung.imageprocessing.twelvemonkeys;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class TwelveMonkeysExample {
public static void main(String[] args) throws IOException {
BufferedImage image = loadImage();
drawRectangle(image);
displayImage(image);
}
private static BufferedImage loadImage() throws IOException {
String imagePath = TwelveMonkeysExample.class.getClassLoader().getResource("Penguin.ico").getPath();
return ImageIO.read(new File(imagePath));
}
private static void drawRectangle(BufferedImage image) {
Graphics2D g = (Graphics2D) image.getGraphics();
g.setStroke(new BasicStroke(3));
g.setColor(Color.BLUE);
g.drawRect(10, 10, image.getWidth() - 20, image.getHeight() - 20);
}
private static void displayImage(BufferedImage image) {
JLabel picLabel = new JLabel(new ImageIcon(image));
JPanel jPanel = new JPanel();
jPanel.add(picLabel);
JFrame f = new JFrame();
f.setSize(new Dimension(200, 200));
f.add(jPanel);
f.setVisible(true);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 164 KiB

View File

@ -3,3 +3,4 @@
- [JSON Processing in Java EE 7](http://www.baeldung.com/jee7-json)
- [Converters, Listeners and Validators in Java EE 7](http://www.baeldung.com/java-ee7-converter-listener-validator)
- [Introduction to JAX-WS](http://www.baeldung.com/jax-ws)
- [A Guide to Java EE Web-Related Annotations](http://www.baeldung.com/javaee-web-annotations)

View File

@ -1,381 +1,381 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
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>jee7</artifactId>
<version>1.0-SNAPSHOT</version>
<description>JavaEE 7 Arquillian Archetype Sample</description>
<groupId>com.baeldung</groupId>
<artifactId>jee7</artifactId>
<version>1.0-SNAPSHOT</version>
<description>JavaEE 7 Arquillian Archetype Sample</description>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<java.min.version>1.8</java.min.version>
<maven.min.version>3.0.0</maven.min.version>
<properties>
<java.min.version>1.8</java.min.version>
<maven.min.version>3.0.0</maven.min.version>
<javaee_api.version>7.0</javaee_api.version>
<arquillian_core.version>1.1.11.Final</arquillian_core.version>
<wildfly.version>8.2.1.Final</wildfly.version>
<awaitility.version>1.7.0</awaitility.version>
<undertow-websockets-jsr.version>1.4.6.Final</undertow-websockets-jsr.version>
<resteasy.version>3.0.19.Final</resteasy.version>
<glassfish-embedded-all.version>4.1.1</glassfish-embedded-all.version>
<javax.json.version>1.0.4</javax.json.version>
<tyrus.version>1.13</tyrus.version>
<jersey.version>2.25</jersey.version>
<arquillian-glassfish.version>1.0.0.Final</arquillian-glassfish.version>
<javaee_api.version>7.0</javaee_api.version>
<arquillian_core.version>1.1.11.Final</arquillian_core.version>
<wildfly.version>8.2.1.Final</wildfly.version>
<awaitility.version>1.7.0</awaitility.version>
<undertow-websockets-jsr.version>1.4.6.Final</undertow-websockets-jsr.version>
<resteasy.version>3.0.19.Final</resteasy.version>
<glassfish-embedded-all.version>4.1.1</glassfish-embedded-all.version>
<javax.json.version>1.0.4</javax.json.version>
<tyrus.version>1.13</tyrus.version>
<jersey.version>2.25</jersey.version>
<arquillian-glassfish.version>1.0.0.Final</arquillian-glassfish.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
</properties>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
</properties>
<prerequisites>
<maven>${maven.min.version}</maven>
</prerequisites>
<prerequisites>
<maven>${maven.min.version}</maven>
</prerequisites>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>${arquillian_core.version}</version>
<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>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.jboss.arquillian</groupId>
<artifactId>arquillian-bom</artifactId>
<version>${arquillian_core.version}</version>
<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>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee_api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependencies>
<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>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee_api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-impl-maven</artifactId>
<scope>test</scope>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-impl-maven-archive</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</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>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<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>
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-impl-maven</artifactId>
<scope>test</scope>
<type>jar</type>
</dependency>
<profiles>
<dependency>
<groupId>org.jboss.shrinkwrap.resolver</groupId>
<artifactId>shrinkwrap-resolver-impl-maven-archive</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</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>
<profile>
<id>wildfly-managed-arquillian</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<serverProfile>standalone-full.xml</serverProfile>
<serverRoot>${project.build.directory}/wildfly-${version.wildfly}</serverRoot>
</properties>
<dependencies>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-websockets-jsr</artifactId>
<version>${undertow-websockets-jsr.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-json-p-provider</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-managed</artifactId>
<version>${wildfly.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<configuration>
<skip>${maven.test.skip}</skip>
</configuration>
<executions>
<execution>
<id>unpack</id>
<phase>process-test-classes</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-dist</artifactId>
<version>${wildfly.version}</version>
<type>zip</type>
<overWrite>false</overWrite>
<outputDirectory>${project.build.directory}</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
<configuration>
<environmentVariables>
<JBOSS_HOME>${project.build.directory}/wildfly-${wildfly.version}</JBOSS_HOME>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</profile>
<profile>
<id>wildfly-remote-arquillian</id>
<dependencies>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-websockets-jsr</artifactId>
<version>${undertow-websockets-jsr.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-json-p-provider</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-remote</artifactId>
<version>${wildfly.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>glassfish-embedded-arquillian</id>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>${glassfish-embedded-all.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>${javax.json.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-client</artifactId>
<version>${tyrus.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly-client</artifactId>
<version>${tyrus.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-embedded-3.1</artifactId>
<version>${arquillian-glassfish.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>glassfish-remote-arquillian</id>
<dependencies>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>${javax.json.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-client</artifactId>
<version>${tyrus.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly-client</artifactId>
<version>${tyrus.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-remote-3.1</artifactId>
<version>${arquillian-glassfish.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>webdriver-chrome</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<browser>chrome</browser>
</properties>
</profile>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<profile>
<id>webdriver-firefox</id>
<properties>
<browser>firefox</browser>
</properties>
<profiles>
<profile>
<id>wildfly-managed-arquillian</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<serverProfile>standalone-full.xml</serverProfile>
<serverRoot>${project.build.directory}/wildfly-${version.wildfly}</serverRoot>
</properties>
<dependencies>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-websockets-jsr</artifactId>
<version>${undertow-websockets-jsr.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-json-p-provider</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-managed</artifactId>
<version>${wildfly.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<configuration>
<skip>${maven.test.skip}</skip>
</configuration>
<executions>
<execution>
<id>unpack</id>
<phase>process-test-classes</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-dist</artifactId>
<version>${wildfly.version}</version>
<type>zip</type>
<overWrite>false</overWrite>
<outputDirectory>${project.build.directory}</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
<configuration>
<environmentVariables>
<JBOSS_HOME>${project.build.directory}/wildfly-${wildfly.version}</JBOSS_HOME>
</environmentVariables>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</profile>
</profiles>
<profile>
<id>wildfly-remote-arquillian</id>
<dependencies>
<dependency>
<groupId>io.undertow</groupId>
<artifactId>undertow-websockets-jsr</artifactId>
<version>${undertow-websockets-jsr.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-json-p-provider</artifactId>
<version>${resteasy.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-remote</artifactId>
<version>${wildfly.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>glassfish-embedded-arquillian</id>
<dependencies>
<dependency>
<groupId>org.glassfish.main.extras</groupId>
<artifactId>glassfish-embedded-all</artifactId>
<version>${glassfish-embedded-all.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>${javax.json.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-client</artifactId>
<version>${tyrus.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly-client</artifactId>
<version>${tyrus.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-embedded-3.1</artifactId>
<version>${arquillian-glassfish.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>glassfish-remote-arquillian</id>
<dependencies>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>${javax.json.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-client</artifactId>
<version>${tyrus.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.tyrus</groupId>
<artifactId>tyrus-container-grizzly-client</artifactId>
<version>${tyrus.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-processing</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.container</groupId>
<artifactId>arquillian-glassfish-remote-3.1</artifactId>
<version>${arquillian-glassfish.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<id>webdriver-chrome</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<browser>chrome</browser>
</properties>
</profile>
<profile>
<id>webdriver-firefox</id>
<properties>
<browser>firefox</browser>
</properties>
</profile>
</profiles>
</project>

View File

@ -3,7 +3,6 @@ package com.baeldung;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
@ -18,6 +17,9 @@ import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.function.ThrowingConsumer;
import com.baeldung.helpers.Employee;
import com.baeldung.helpers.EmployeeDao;
public class DynamicTestsExample {
@TestFactory
@ -53,32 +55,12 @@ public class DynamicTestsExample {
// sample input and output
List<String> inputList =
new ArrayList<>(Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com"));
Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
List<String> outputList =
new ArrayList<>(Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156"));
Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");
// input generator that generates inputs using inputList
Iterator<String> inputGenerator = new Iterator<String>() {
String current;
int size = inputList.size();
int index = 0;
@Override
public boolean hasNext() {
if(index == size) {
return false;
}
current = inputList.get(index);
index++;
return true;
}
@Override
public String next() {
return current;
}
};
Iterator<String> inputGenerator = inputList.iterator();
// a display name generator that creates a different name based on the input
Function<String, String> displayNameGenerator = (input) -> "Resolving: " + input;
@ -111,6 +93,29 @@ public class DynamicTestsExample {
}
@TestFactory
Stream<DynamicTest> dynamicTestsForEmployeeWorkflows() {
List<Employee> inputList =
Arrays.asList(new Employee(1, "Fred"), new Employee(2), new Employee(3, "John"));
EmployeeDao dao = new EmployeeDao();
Stream<DynamicTest> saveEmployeeStream = inputList.stream().map(emp ->
DynamicTest.dynamicTest("saveEmployee: " + emp.toString(), () -> {
Employee returned = dao.save(emp.getId());
assertEquals(returned.getId(), emp.getId());
}));
Stream<DynamicTest> saveEmployeeWithFirstNameStream
= inputList.stream().filter(emp -> !emp.getFirstName().isEmpty())
.map(emp -> DynamicTest.dynamicTest("saveEmployeeWithName" + emp.toString(), () -> {
Employee returned = dao.save(emp.getId(), emp.getFirstName());
assertEquals(returned.getId(), emp.getId());
assertEquals(returned.getFirstName(), emp.getFirstName());
}));
return Stream.concat(saveEmployeeStream, saveEmployeeWithFirstNameStream);
}
class DomainNameResolver {
private Map<String, String> ipByDomainName = new HashMap<>();

View File

@ -0,0 +1,38 @@
package com.baeldung.helpers;
public class Employee {
private long id;
private String firstName;
public Employee(long id) {
this.id = id;
this.firstName = "";
}
public Employee(long id, String firstName) {
this.id = id;
this.firstName = firstName;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + "]";
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.helpers;
public class EmployeeDao {
public Employee save(long id) {
return new Employee(id);
}
public Employee save(long id, String firstName) {
return new Employee(id, firstName);
}
public Employee update(Employee employee) {
return employee;
}
}

View File

@ -5,3 +5,4 @@
- [Comprehensive Guide to Null Safety in Kotlin](http://www.baeldung.com/kotlin-null-safety)
- [Kotlin Java Interoperability](http://www.baeldung.com/kotlin-java-interoperability)
- [Difference Between “==” and “===” in Kotlin]()
- [Generics in Kotlin](http://www.baeldung.com/kotlin-generics)

View File

@ -9,7 +9,8 @@
- [Introduction to Apache Flink with Java](http://www.baeldung.com/apache-flink)
- [Introduction to JSONassert](http://www.baeldung.com/jsonassert)
- [Intro to JaVer](http://www.baeldung.com/javers)
- [Introduction to Apache Commons Math](http://www.baeldung.com/apache-commons-math)
- [Intro to JaVer](http://www.baeldung.com/serenity-bdd)
The libraries module contains examples related to small libraries that are relatively easy to use and does not require any separate module of its own.

View File

@ -225,12 +225,7 @@
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-maven-plugin</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.194</version>
</dependency>
</dependency>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-xml</artifactId>
@ -269,6 +264,28 @@
<artifactId>h2</artifactId>
<version>1.4.195</version>
</dependency>
<dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>
<version>${jUnitParams.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>one.util</groupId>
<artifactId>streamex</artifactId>
<version>0.6.5</version>
</dependency>
<dependency>
<groupId>org.jooq</groupId>
<artifactId>jool</artifactId>
<version>0.9.12</version>
</dependency>
</dependencies>
<properties>
<multiverse.version>0.7.0</multiverse.version>
@ -292,6 +309,7 @@
<serenity.jbehave.version>1.24.0</serenity.jbehave.version>
<serenity.jira.version>1.1.3-rc.5</serenity.jira.version>
<serenity.plugin.version>1.4.0</serenity.plugin.version>
<jUnitParams.version>1.1.0</jUnitParams.version>
</properties>
</project>

View File

@ -0,0 +1,15 @@
package com.baeldung.junitparams;
public class SafeAdditionUtil {
public int safeAdd(int a, int b) {
long result = ((long) a) + b;
if (result > Integer.MAX_VALUE) {
return Integer.MAX_VALUE;
} else if (result < Integer.MIN_VALUE) {
return Integer.MIN_VALUE;
}
return (int) result;
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.quartz;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
public class QuartzExample {
public static void main(String args[]) {
SchedulerFactory schedFact = new StdSchedulerFactory();
try {
Scheduler sched = schedFact.getScheduler();
JobDetail job = JobBuilder.newJob(SimpleJob.class)
.withIdentity("myJob", "group1")
.build();
Trigger trigger = TriggerBuilder.newTrigger()
.withIdentity("myTrigger", "group1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(40)
.repeatForever())
.build();
sched.scheduleJob(job, trigger);
sched.start();
} catch (SchedulerException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.quartz;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class SimpleJob implements Job {
public void execute(JobExecutionContext arg0) throws JobExecutionException {
System.out.println("This is a quartz job!");
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.serenity.spring;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
* @author aiet
*/
@RequestMapping(value = "/adder", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class AdderController {
private AdderService adderService;
public AdderController(AdderService adderService) {
this.adderService = adderService;
}
@GetMapping("/current")
public int currentNum() {
return adderService.currentBase();
}
@PostMapping
public int add(@RequestParam int num) {
return adderService.add(num);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.serenity.spring;
import org.springframework.stereotype.Service;
@Service
public class AdderService {
private int num;
public void baseNum(int base) {
this.num = base;
}
public int currentBase() {
return num;
}
public int add(int adder) {
return this.num + adder;
}
public int accumulate(int adder) {
return this.num += adder;
}
}

View File

@ -1,28 +0,0 @@
package com.baeldung.serenity.spring;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author aiet
*/
@RequestMapping(value = "/konamicode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class KonamiCodeController {
private final String classicCode = "↑↑↓↓←→←→BA";
@GetMapping("/classic")
public String classicCode() {
return classicCode;
}
@GetMapping("/cheatable")
public boolean cheatCheck(@RequestParam String cheatcode){
return classicCode.equals(cheatcode);
}
}

View File

@ -1,39 +0,0 @@
package com.baeldung.serenity.spring;
import org.springframework.stereotype.Service;
/**
* refer to <a href="https://en.wikipedia.org/wiki/Konami_Code">Konami Code</a>
*/
@Service
public class KonamiCodeService {
private String classicCode = "↑↑↓↓←→←→BA";
public String getClassicCode() {
return classicCode;
}
public void alterClassicCode(String newCode) {
classicCode = newCode;
}
public boolean cheatWith(String cheatcode) {
if ("↑↑↓↓←→←→BA".equals(cheatcode)) {
stageLeft++;
return true;
}
return false;
}
private int stageLeft = 1;
public void clearStage() {
stageLeft = 0;
}
public int stageLeft() {
return stageLeft;
}
}

View File

@ -1,41 +0,0 @@
package com.baeldung.serenity.spring;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
* @author aiet
*/
@RequestMapping(value = "/konamicode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class KonamiCodeServiceInjectionController {
private KonamiCodeService konamiCodeService;
public KonamiCodeServiceInjectionController(KonamiCodeService konamiCodeService) {
this.konamiCodeService = konamiCodeService;
}
@PutMapping("/stages")
public void clearStage(@RequestParam String action) {
if ("clear".equals(action)) {
konamiCodeService.clearStage();
}
}
@GetMapping("/classic")
public String classicCode() {
return konamiCodeService.getClassicCode();
}
@GetMapping("/cheatable")
public boolean cheatCheck(@RequestParam String cheatcode) {
return konamiCodeService.cheatWith(cheatcode);
}
@GetMapping("/stages")
public int stageLeft() {
return konamiCodeService.stageLeft();
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.serenity.spring;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
* @author aiet
*/
@RequestMapping(value = "/adder", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
public class PlainAdderController {
private final int currentNumber = RandomUtils.nextInt();
@GetMapping("/current")
public int currentNum() {
return currentNumber;
}
@PostMapping
public int add(@RequestParam int num) {
return currentNumber + num;
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.junitparams;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import junitparams.FileParameters;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
@RunWith(JUnitParamsRunner.class)
public class SafeAdditionUtilTest {
private SafeAdditionUtil serviceUnderTest = new SafeAdditionUtil();
@Test
@Parameters({ "1, 2, 3", "-10, 30, 20", "15, -5, 10", "-5, -10, -15" })
public void whenCalledWithAnnotationProvidedParams_thenSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
@Test
@Parameters(method = "parametersToTestAdd")
public void whenCalledWithNamedMethod_thendSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
private Object[] parametersToTestAdd() {
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } };
}
@Test
@Parameters
public void whenCalledWithnoParam_thenLoadByNameSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
private Object[] parametersForWhenCalledWithnoParam_thenLoadByNameSafeAddAndReturn() {
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -8, Integer.MIN_VALUE } };
}
@Test
@Parameters(source = TestDataProvider.class)
public void whenCalledWithNamedClass_thenSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
@Test
@FileParameters("src/test/resources/JunitParamsTestParameters.csv")
public void whenCalledWithCsvFile_thenSafeAddAndReturn(int a, int b, int expectedValue) {
assertEquals(expectedValue, serviceUnderTest.safeAdd(a, b));
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.junitparams;
public class TestDataProvider {
public static Object[] provideBasicData() {
return new Object[] { new Object[] { 1, 2, 3 }, new Object[] { -10, 30, 20 }, new Object[] { 15, -5, 10 }, new Object[] { -5, -10, -15 } };
}
public static Object[] provideEdgeCaseData() {
return new Object[] { new Object[] { Integer.MAX_VALUE, 2, Integer.MAX_VALUE }, new Object[] { Integer.MIN_VALUE, -2, Integer.MIN_VALUE }, };
}
}

View File

@ -0,0 +1,76 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderServiceSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationClassRule;
import net.thucydides.core.annotations.Steps;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS;
/**
* @author aiet
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({
AdderClassDirtiesContextIntegrationTest.DirtiesContextTest.class, AdderClassDirtiesContextIntegrationTest.AnotherDirtiesContextTest.class
})
public class AdderClassDirtiesContextIntegrationTest {
@RunWith(SerenityRunner.class)
@ContextConfiguration(classes = AdderService.class)
public static abstract class Base {
@Steps AdderServiceSteps adderServiceSteps;
@ClassRule public static SpringIntegrationClassRule springIntegrationClassRule = new SpringIntegrationClassRule();
void whenAccumulate_thenSummedUp() {
adderServiceSteps.whenAccumulate();
adderServiceSteps.summedUp();
}
void whenAdd_thenSumWrong() {
adderServiceSteps.whenAdd();
adderServiceSteps.sumWrong();
}
void whenAdd_thenSummedUp() {
adderServiceSteps.whenAdd();
adderServiceSteps.summedUp();
}
}
@DirtiesContext(classMode = AFTER_CLASS)
public static class AnotherDirtiesContextTest extends Base {
@Test
public void givenNumber_whenAdd_thenSumWrong() {
super.whenAdd_thenSummedUp(); //expecting zero
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
super.whenAccumulate_thenSummedUp();
super.whenAdd_thenSumWrong();
}
}
@DirtiesContext(classMode = AFTER_CLASS)
public static class DirtiesContextTest extends Base {
@Test
public void givenNumber_whenAdd_thenSumWrong() {
super.whenAdd_thenSummedUp(); //expecting zero
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
super.whenAccumulate_thenSummedUp();
super.whenAdd_thenSumWrong();
}
}
}

View File

@ -0,0 +1,54 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderConstructorDependencySteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ContextConfiguration(classes = AdderService.class)
public class AdderMethodDirtiesContextDependencyWorkaroundIntegrationTest {
private AdderConstructorDependencySteps adderSteps;
@Autowired private AdderService adderService;
@Before
public void init() {
adderSteps = new AdderConstructorDependencySteps(adderService);
}
@Test
public void _1_givenNumber_whenAdd_thenSumWrong() {
adderSteps.whenAdd();
adderSteps.summedUp();
}
@Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@DirtiesContext
@Test
public void _0_givenNumber_whenAddAndAccumulate_thenSummedUp() {
adderSteps.givenBaseAndAdder(randomInt(), randomInt());
adderSteps.whenAccumulate();
adderSteps.summedUp();
adderSteps.whenAdd();
adderSteps.sumWrong();
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderServiceSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule;
import net.thucydides.core.annotations.Steps;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ContextConfiguration(classes = AdderService.class)
public class AdderMethodDirtiesContextInitWorkaroundIntegrationTest {
@Steps private AdderServiceSteps adderServiceSteps;
@Before
public void init() {
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
}
@Test
public void _1_givenNumber_whenAdd_thenSumWrong() {
adderServiceSteps.whenAdd();
adderServiceSteps.summedUp();
}
@Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@DirtiesContext
@Test
public void _0_givenNumber_whenAddAndAccumulate_thenSummedUp() {
adderServiceSteps.whenAccumulate();
adderServiceSteps.summedUp();
adderServiceSteps.whenAdd();
adderServiceSteps.sumWrong();
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderServiceSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule;
import net.thucydides.core.annotations.Steps;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ContextConfiguration(classes = AdderService.class)
public class AdderMethodDirtiesContextIntegrationTest {
@Steps private AdderServiceSteps adderServiceSteps;
@Test
public void _1_givenNumber_whenAdd_thenSumWrong() {
adderServiceSteps.whenAdd();
adderServiceSteps.sumWrong();
}
@Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@DirtiesContext
@Test
public void _0_givenNumber_whenAddAndAccumulate_thenSummedUp() {
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
adderServiceSteps.whenAccumulate();
adderServiceSteps.summedUp();
adderServiceSteps.whenAdd();
adderServiceSteps.sumWrong();
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule;
import net.thucydides.core.annotations.Steps;
import org.junit.*;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
/**
* Unit test for simple App.
*/
@RunWith(SerenityRunner.class)
@ContextConfiguration(locations = "classpath:adder-beans.xml")
public class AdderMethodRuleIntegrationTest {
private static Logger LOG = LoggerFactory.getLogger(AdderMethodRuleIntegrationTest.class);
@BeforeClass
public static void initClass() {
LOG.info("static adder before test class: {}", staticAdder);
}
@AfterClass
public static void destroyClass() {
LOG.info("static adder after test class: {}", staticAdder);
}
@Before
public void init() {
LOG.info("adder before test: {}", adder);
staticAdder = adder;
}
@After
public void destroy() {
LOG.info("adder after test: {}", adder);
}
@Rule public SpringIntegrationMethodRule springMethodIntegration = new SpringIntegrationMethodRule();
@Steps private AdderSteps adderSteps;
@Value("#{props['adder']}") private int adder;
private static int staticAdder;
@Test
public void givenNumber_whenAdd_thenSummedUp() {
adderSteps.givenNumber();
adderSteps.whenAdd(adder);
adderSteps.thenSummedUp();
}
}

View File

@ -0,0 +1,33 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderRestSteps;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Steps;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
public class AdderMockMvcIntegrationTest {
@Before
public void init() {
RestAssuredMockMvc.standaloneSetup(new PlainAdderController());
}
@Steps AdderRestSteps steps;
@Test
public void givenNumber_whenAdd_thenSummedUp() throws Exception {
steps.givenCurrentNumber();
steps.whenAddNumber(randomInt());
steps.thenSummedUp();
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderServiceSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Steps;
import org.junit.Test;
import org.junit.runner.RunWith;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
public class AdderServiceIntegrationTest {
@Steps private AdderServiceSteps adderServiceSteps;
@Test
public void givenNumber_whenAdd_thenSummedUp() {
adderServiceSteps.givenBaseAndAdder(randomInt(), randomInt());
adderServiceSteps.whenAdd();
adderServiceSteps.summedUp();
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.AdderSteps;
import net.serenitybdd.junit.spring.integration.SpringIntegrationSerenityRunner;
import net.thucydides.core.annotations.Steps;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
/**
* Unit test for simple App.
*/
@RunWith(SpringIntegrationSerenityRunner.class)
@ContextConfiguration(locations = "classpath:adder-beans.xml")
public class AdderSpringSerenityRunnerIntegrationTest {
@Steps private AdderSteps adderSteps;
@Value("#{props['adder']}") private int adder;
@Test
public void givenNumber_whenAdd_thenSummedUp() {
adderSteps.givenNumber();
adderSteps.whenAdd(adder);
adderSteps.thenSummedUp();
}
}

View File

@ -9,14 +9,14 @@ import org.springframework.test.context.ContextConfiguration;
/**
* @author aiet
*/
@ContextConfiguration(classes = { KonamiCodeServiceInjectionController.class, KonamiCodeService.class })
public class KonamiCodeTest extends SerenityStory {
@ContextConfiguration(classes = { AdderController.class, AdderService.class })
public class AdderTest extends SerenityStory {
@Autowired private KonamiCodeService konamiCodeService;
@Autowired private AdderService adderService;
@BeforeStory
public void init() {
RestAssuredMockMvc.standaloneSetup(new KonamiCodeServiceInjectionController(konamiCodeService));
RestAssuredMockMvc.standaloneSetup(new AdderController(adderService));
}
}

View File

@ -1,74 +0,0 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.KonamiCodeServiceInjectionSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationClassRule;
import net.thucydides.core.annotations.Steps;
import net.thucydides.core.annotations.Title;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
import static org.springframework.test.annotation.DirtiesContext.ClassMode.AFTER_CLASS;
/**
* @author aiet
*/
@RunWith(Suite.class)
@Suite.SuiteClasses({
KonamCheatClassDirtiesContextIntegrationTest.DirtiesContextTest.class, KonamCheatClassDirtiesContextIntegrationTest.AnotherDirtiesContextTest.class
})
public class KonamCheatClassDirtiesContextIntegrationTest {
@RunWith(SerenityRunner.class)
@ContextConfiguration(classes = KonamiCodeService.class)
public static abstract class Base {
@Steps KonamiCodeServiceInjectionSteps cheatSteps;
@ClassRule public static SpringIntegrationClassRule springIntegrationClassRule = new SpringIntegrationClassRule();
void hiddenStageShouldBeUnlockedAfterCheating() {
fetchAndCheat();
cheatSteps.aStageRemains();
cheatSteps.letsHack();
fetchAndCheat();
cheatSteps.noStageRemains();
}
private void fetchAndCheat() {
cheatSteps.gameStageCleared();
cheatSteps.fetchLatestCheatcode();
cheatSteps.cheatWithLatestcode();
}
}
@DirtiesContext(classMode = AFTER_CLASS)
public static class AnotherDirtiesContextTest extends Base {
@Test
@Title("altering the cheatcode after unlocking would stop others from cheating, not affected by other tests (another)")
public void givenGameStageCleared_whenCheat_thenHiddenStageUnlocked() {
super.hiddenStageShouldBeUnlockedAfterCheating();
}
}
@DirtiesContext(classMode = AFTER_CLASS)
public static class DirtiesContextTest extends Base {
@Test
@Title("altering the cheatcode after unlocking would stop others from cheating, not affected by other tests")
public void givenGameStageCleared_whenCheat_thenHiddenStageUnlocked() {
super.hiddenStageShouldBeUnlockedAfterCheating();
}
}
}

View File

@ -1,62 +0,0 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.KonamiCodeConstructorDependencySteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule;
import net.thucydides.core.annotations.Title;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ContextConfiguration(classes = KonamiCodeService.class)
public class KonamCheatWithDirtyActionIntegrationTest {
private KonamiCodeConstructorDependencySteps cheatSteps;
@Autowired private KonamiCodeService codeService;
@Before
public void init() {
cheatSteps = new KonamiCodeConstructorDependencySteps(codeService);
}
@Test
@Title("hidden stage should be unlocked after cheating (run in service with dirty action)")
public void givenGameStageCleared_whenCheat_thenHiddenStageUnlocked() {
fetchCodeAndCheat();
cheatSteps.aStageRemains();
}
@Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@DirtiesContext
@Test
@Title("altering the cheatcode after unlocking would stop others from cheating")
public void givenGameStageCleared_whenCheatAndHack_thenAnotherCheatFail() {
fetchCodeAndCheat();
cheatSteps.aStageRemains();
cheatSteps.letsHack();
fetchCodeAndCheat();
cheatSteps.noStageRemains();
}
private void fetchCodeAndCheat() {
cheatSteps.gameStageCleared();
cheatSteps.fetchLatestCheatcode();
cheatSteps.cheatWithLatestcode();
}
}

View File

@ -1,54 +0,0 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.KonamiCodeServiceInjectionSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule;
import net.thucydides.core.annotations.Steps;
import net.thucydides.core.annotations.Title;
import org.junit.FixMethodOrder;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ContextConfiguration(classes = KonamiCodeService.class)
public class KonamCheatWithDirtyActionWithImplicitInjectionIntegrationTest {
@Steps private KonamiCodeServiceInjectionSteps cheatSteps;
@Test
@Title("hidden stage is not unlocked after cheating (cheatcode hacked)")
public void givenGameStageCleared_whenCheat_thenCheatFail() {
fetchCodeAndCheat();
cheatSteps.noStageRemains();
}
private void fetchCodeAndCheat() {
cheatSteps.gameStageCleared();
cheatSteps.fetchLatestCheatcode();
cheatSteps.cheatWithLatestcode();
}
@Rule public SpringIntegrationMethodRule springIntegration = new SpringIntegrationMethodRule();
@DirtiesContext
@Test
@Title("altering the cheatcode after unlocking would stop others from cheating")
public void givenGameStageCleared_whenCheatAndHack_thenAnotherCheatFail() {
fetchCodeAndCheat();
cheatSteps.aStageRemains();
cheatSteps.letsHack();
fetchCodeAndCheat();
cheatSteps.noStageRemains();
}
}

View File

@ -1,27 +0,0 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.KonamiCodeServiceInjectionSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Steps;
import net.thucydides.core.annotations.Title;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
public class KonamCheatWithServiceIntegrationTest {
@Steps private KonamiCodeServiceInjectionSteps cheatSteps;
@Test
@Title("hidden stage should be unlocked after cheating (mockmvc)")
public void givenGameStageCleared_whenCheat_thenHiddenStageUnlocked() {
cheatSteps.gameStageCleared();
cheatSteps.fetchLatestCheatcode();
cheatSteps.cheatWithLatestcode();
cheatSteps.aStageRemains();
}
}

View File

@ -1,61 +0,0 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.KonamiCheatSteps;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.serenitybdd.junit.spring.integration.SpringIntegrationMethodRule;
import net.thucydides.core.annotations.Steps;
import net.thucydides.core.annotations.Title;
import org.junit.*;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
/**
* Unit test for simple App.
*/
@RunWith(SerenityRunner.class)
@ContextConfiguration(locations = "classpath:konami-cheat-beans.xml")
public class KonamiCheatWithIntegrationMethodRulesIntegrationTest {
private static Logger LOG = LoggerFactory.getLogger(KonamiCheatWithIntegrationMethodRulesIntegrationTest.class);
@BeforeClass
public static void initClass() {
LOG.info("static chaincode before test class: {}", staticCheatCode);
}
@AfterClass
public static void destroyClass() {
LOG.info("static chaincode after test class: {}", staticCheatCode);
}
@Before
public void init() {
staticCheatCode = cheatCode;
LOG.info("cheatcode before test: {}", cheatCode);
}
@After
public void destroy() {
LOG.info("cheatcode after test: {}", cheatCode);
}
@Rule public SpringIntegrationMethodRule springMethodIntegration = new SpringIntegrationMethodRule();
@Steps private KonamiCheatSteps konamiCheatSteps;
@Value("#{konami_props['code']}") private String cheatCode;
private static String staticCheatCode;
@Test
@Title("hidden stage should be unlocked after cheating (rule integration)")
public void givenGameStageCleared_whenCheat_thenHiddenStageUnlocked() {
konamiCheatSteps.gameStageCleared();
konamiCheatSteps.cheatWith(cheatCode);
konamiCheatSteps.aStageRemains();
}
}

View File

@ -1,58 +0,0 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.KonamiCheatSteps;
import net.serenitybdd.junit.spring.integration.SpringIntegrationSerenityRunner;
import net.thucydides.core.annotations.Steps;
import net.thucydides.core.annotations.Title;
import org.junit.*;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
/**
* Unit test for simple App.
*/
@RunWith(SpringIntegrationSerenityRunner.class)
@ContextConfiguration(locations = "classpath:konami-cheat-beans.xml")
public class KonamiCheatWithIntegrationRunnerIntegrationTest {
private static Logger LOG = LoggerFactory.getLogger(KonamiCheatWithIntegrationRunnerIntegrationTest.class);
@BeforeClass
public static void initClass() {
LOG.info("static chaincode before test class: {}", staticCheatCode);
}
@AfterClass
public static void destroyClass() {
LOG.info("static chaincode after test class: {}", staticCheatCode);
}
@Before
public void init() {
staticCheatCode = cheatCode;
LOG.info("cheatcode before test: {}", cheatCode);
}
@After
public void destroy() {
LOG.info("cheatcode after test: {}", cheatCode);
}
@Steps private KonamiCheatSteps konamiCheatSteps;
@Value("#{konami_props['code']}") private String cheatCode;
private static String staticCheatCode;
@Test
@Title("hidden stage should be unlocked after cheating (with integration runner)")
public void givenGameStageCleared_whenCheat_thenHiddenStageUnlocked() {
konamiCheatSteps.gameStageCleared();
konamiCheatSteps.cheatWith(cheatCode);
konamiCheatSteps.aStageRemains();
}
}

View File

@ -1,31 +0,0 @@
package com.baeldung.serenity.spring;
import com.baeldung.serenity.spring.steps.KonamiCodeRestSteps;
import io.restassured.module.mockmvc.RestAssuredMockMvc;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Steps;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* @author aiet
*/
@RunWith(SerenityRunner.class)
public class KonamiCodeMockMvcIntegrationTest {
@Before
public void init() {
RestAssuredMockMvc.standaloneSetup(new KonamiCodeController());
}
@Steps KonamiCodeRestSteps steps;
@Test
public void givenOfficialClassicCheatcode_whenCheat_ThenTheCodeShouldDoTheTrick() throws Exception {
steps.givenClassicCheatCode();
steps.whenCheat();
steps.thenClassicCodeCanDoTheTrick();
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.serenity.spring;
import org.apache.commons.lang3.RandomUtils;
/**
* @author aiet
*/
public class RandomNumberUtil {
public static int randomInt() {
return RandomUtils.nextInt(1, 10);
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.serenity.spring.steps;
import com.baeldung.serenity.spring.AdderService;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
/**
* @author aiet
*/
public class AdderConstructorDependencySteps {
private AdderService adderService;
public AdderConstructorDependencySteps(AdderService adderService) {
this.adderService = adderService;
}
private int givenNumber;
private int base;
private int sum;
public void givenBaseAndAdder(int base, int adder) {
this.base = base;
adderService.baseNum(base);
this.givenNumber = adder;
}
public void whenAdd() {
sum = adderService.add(givenNumber);
}
public void summedUp() {
assertEquals(base + givenNumber, sum);
}
public void sumWrong() {
assertNotEquals(base + givenNumber, sum);
}
public void whenAccumulate() {
sum = adderService.accumulate(givenNumber);
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.serenity.spring.steps;
import io.restassured.module.mockmvc.response.MockMvcResponse;
import net.thucydides.core.annotations.Step;
import java.io.UnsupportedEncodingException;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.hamcrest.core.IsEqual.equalTo;
/**
* @author aiet
*/
public class AdderRestSteps {
private MockMvcResponse mockMvcResponse;
private int currentNum;
@Step("get the current number")
public void givenCurrentNumber() throws UnsupportedEncodingException {
currentNum = Integer.valueOf(given()
.when()
.get("/adder/current")
.mvcResult()
.getResponse()
.getContentAsString());
}
@Step("adding {0}")
public void whenAddNumber(int num) {
mockMvcResponse = given()
.queryParam("num", num)
.when()
.post("/adder");
currentNum += num;
}
@Step("got the sum")
public void thenSummedUp() {
mockMvcResponse
.then()
.statusCode(200)
.body(equalTo(currentNum + ""));
}
}

View File

@ -0,0 +1,44 @@
package com.baeldung.serenity.spring.steps;
import com.baeldung.serenity.spring.AdderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
/**
* @author aiet
*/
@ContextConfiguration(classes = AdderService.class)
public class AdderServiceSteps {
@Autowired private AdderService adderService;
private int givenNumber;
private int base;
private int sum;
public void givenBaseAndAdder(int base, int adder) {
this.base = base;
adderService.baseNum(base);
this.givenNumber = adder;
}
public void whenAdd() {
sum = adderService.add(givenNumber);
}
public void summedUp() {
assertEquals(base + givenNumber, sum);
}
public void sumWrong() {
assertNotEquals(base + givenNumber, sum);
}
public void whenAccumulate() {
sum = adderService.accumulate(givenNumber);
}
}

View File

@ -0,0 +1,29 @@
package com.baeldung.serenity.spring.steps;
import net.thucydides.core.annotations.Step;
import static com.baeldung.serenity.spring.RandomNumberUtil.randomInt;
/**
* @author aiet
*/
public class AdderSteps {
int currentNumber;
int sum;
@Step("given current number")
public void givenNumber() {
currentNumber = randomInt();
}
@Step("add up {0}")
public void whenAdd(int adder) {
sum = currentNumber + adder;
}
@Step("summed up")
public void thenSummedUp() {
}
}

View File

@ -1,25 +0,0 @@
package com.baeldung.serenity.spring.steps;
import net.thucydides.core.annotations.Step;
import static org.junit.Assert.assertEquals;
/**
* @author aiet
*/
public class KonamiCheatSteps {
@Step("all stages of the game are cleared")
public void gameStageCleared() {
}
@Step("input the classic 'Konami Code': {0} ")
public void cheatWith(String cheatcode) {
assertEquals("cheatcode wrong", "↑↑↓↓←→←→BA", cheatcode);
}
@Step("there is still a stage left")
public void aStageRemains() {
}
}

View File

@ -1,58 +0,0 @@
package com.baeldung.serenity.spring.steps;
import com.baeldung.serenity.spring.KonamiCodeService;
import net.thucydides.core.annotations.Step;
import org.apache.commons.lang3.RandomStringUtils;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.*;
/**
* @author aiet
*/
public class KonamiCodeConstructorDependencySteps {
private String latestCheatcode;
private boolean cheatSuccess;
private KonamiCodeService konamiCodeService;
public KonamiCodeConstructorDependencySteps(KonamiCodeService konamiCodeService) {
this.konamiCodeService = konamiCodeService;
}
@Step("fetch latest cheat code")
public void fetchLatestCheatcode() {
latestCheatcode = konamiCodeService.getClassicCode();
}
@Step("cheat with latest code")
public void cheatWithLatestcode() {
cheatSuccess = konamiCodeService.cheatWith(latestCheatcode);
}
@Step("all stages of the game are cleared")
public void gameStageCleared() {
konamiCodeService.clearStage();
}
@Step("there is still a stage left")
public void aStageRemains() {
assertTrue("cheatcode wrong", cheatSuccess);
assertThat(konamiCodeService.stageLeft(), equalTo(1));
}
// @Rule public SpringIntegrationMethodRule methodRule = new SpringIntegrationMethodRule();
// @DirtiesContext
@Step
public void letsHack() {
konamiCodeService.alterClassicCode(RandomStringUtils.random(4));
}
@Step("there is no stage left")
public void noStageRemains() {
assertFalse(cheatSuccess);
assertThat(konamiCodeService.stageLeft(), equalTo(0));
}
}

View File

@ -1,68 +0,0 @@
package com.baeldung.serenity.spring.steps;
import io.restassured.module.mockmvc.response.MockMvcResponse;
import net.thucydides.core.annotations.Step;
import java.io.UnsupportedEncodingException;
import static io.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.hamcrest.core.IsEqual.equalTo;
/**
* @author aiet
*/
public class KonamiCodeRestSteps {
MockMvcResponse mockMvcResponse;
String cheatcode;
@Step("get the classic cheat code")
public void givenClassicCheatCode() throws UnsupportedEncodingException {
cheatcode = given()
.when()
.get("/konamicode/classic")
.mvcResult()
.getResponse()
.getContentAsString();
}
@Step("check if the cheat code works")
public void whenCheat() {
mockMvcResponse = given()
.queryParam("cheatcode", cheatcode)
.when()
.get("/konamicode/cheatable");
}
@Step("classic cheat code matches")
public void thenClassicCodeCanDoTheTrick() {
mockMvcResponse
.then()
.statusCode(200)
.body(equalTo("true"));
}
@Step("all stage cleared")
public void stageCleared() {
given()
.queryParam("action", "clear")
.when()
.put("/konamicode/stages");
given()
.when()
.get("/konamicode/stages")
.then()
.body(equalTo("0"));
}
@Step("one more stage to play")
public void thenMoreStages() {
given()
.when()
.get("/konamicode/stages")
.then()
.body(equalTo("1"));
}
}

View File

@ -1,55 +0,0 @@
package com.baeldung.serenity.spring.steps;
import com.baeldung.serenity.spring.KonamiCodeService;
import net.thucydides.core.annotations.Step;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.*;
/**
* @author aiet
*/
@ContextConfiguration(classes = KonamiCodeService.class)
public class KonamiCodeServiceInjectionSteps {
private String latestCheatcode;
private boolean cheatSuccess;
@Autowired private KonamiCodeService konamiCodeService;
@Step("fetch latest cheat code")
public void fetchLatestCheatcode() {
latestCheatcode = konamiCodeService.getClassicCode();
}
@Step("cheat with latest code")
public void cheatWithLatestcode() {
cheatSuccess = konamiCodeService.cheatWith(latestCheatcode);
}
@Step("all stages of the game are cleared")
public void gameStageCleared() {
konamiCodeService.clearStage();
}
@Step("there is still a stage left")
public void aStageRemains() {
assertTrue("cheatcode wrong", cheatSuccess);
assertThat(konamiCodeService.stageLeft(), equalTo(1));
}
@Step("altering default cheat code")
public void letsHack() {
konamiCodeService.alterClassicCode(RandomStringUtils.random(4));
}
@Step("there is no stage left")
public void noStageRemains() {
assertFalse(cheatSuccess);
assertThat(konamiCodeService.stageLeft(), equalTo(0));
}
}

View File

@ -0,0 +1,31 @@
package com.baeldung.serenity.spring.stories;
import com.baeldung.serenity.spring.steps.AdderRestSteps;
import net.thucydides.core.annotations.Steps;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
/**
* @author aiet
*/
public class AdderStory {
@Steps AdderRestSteps restSteps;
@Given("a number")
public void givenANumber() throws Exception {
restSteps.givenCurrentNumber();
}
@When("I submit another number $num to adder")
public void whenISubmitToAdderWithNumber(int num) {
restSteps.whenAddNumber(num);
}
@Then("I get a sum of the numbers")
public void thenIGetTheSum() {
restSteps.thenSummedUp();
}
}

View File

@ -1,37 +0,0 @@
package com.baeldung.serenity.spring.stories;
import com.baeldung.serenity.spring.steps.KonamiCodeRestSteps;
import net.thucydides.core.annotations.Steps;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
/**
* @author aiet
*/
public class KonamiCodeStory {
@Steps KonamiCodeRestSteps restSteps;
@Given("game stage cleared")
public void givenStageCleared(){
restSteps.stageCleared();
}
@Given("KONAMI cheat code")
public void givenKONAMICheatCode() throws Exception{
restSteps.givenClassicCheatCode();
}
@When("I input the cheat code")
public void whenIInputTheCheatCode() {
restSteps.whenCheat();
}
@Then("a hidden stage will be unlocked")
public void thenAHiddenStageWillBeUnlocked() {
restSteps.thenClassicCodeCanDoTheTrick();
restSteps.thenMoreStages();
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.stream;
import org.jooq.lambda.Seq;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import static junit.framework.TestCase.assertEquals;
public class JoolMergeStreamsTest {
@Test
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
Seq<Integer> seq1 = Seq.of(1, 3, 5);
Seq<Integer> seq2 = Seq.of(2, 4, 6);
Seq<Integer> resultingSeq = seq1.append(seq2);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6),
resultingSeq.toList());
}
@Test
public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() {
Seq<String> seq = Seq.of("foo", "bar");
Seq<String> openingBracketSeq = Seq.of("[");
Seq<String> closingBracketSeq = Seq.of("]");
Seq<String> resultingStream = seq.append(closingBracketSeq)
.prepend(openingBracketSeq);
Assert.assertEquals(Arrays.asList("[", "foo", "bar", "]"),
resultingStream.toList());
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.stream;
import org.junit.Test;
import java.util.Arrays;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.Assert.assertEquals;
public class MergeStreamsTest {
@Test
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
Stream<Integer> stream1 = Stream.of(1, 3, 5);
Stream<Integer> stream2 = Stream.of(2, 4, 6);
Stream<Integer> resultingStream = Stream.concat(stream1,
stream2);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6),
resultingStream.collect(Collectors.toList()));
}
@Test
public void givenThreeStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() {
Stream<Integer> stream1 = Stream.of(1, 3, 5);
Stream<Integer> stream2 = Stream.of(2, 4, 6);
Stream<Integer> stream3 = Stream.of(18, 15, 36);
Stream<Integer> resultingStream = Stream.concat(Stream.concat(stream1,
stream2),
stream3);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36),
resultingStream.collect(Collectors.toList()));
}
@Test
public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() {
Stream<Integer> stream1 = Stream.of(1, 3, 5);
Stream<Integer> stream2 = Stream.of(2, 4, 6);
Stream<Integer> stream3 = Stream.of(18, 15, 36);
Stream<Integer> stream4 = Stream.of(99);
Stream<Integer> resultingStream = Stream.of(stream1, stream2, stream3, stream4).flatMap(Function.identity());
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99),
resultingStream.collect(Collectors.toList()));
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.stream;
import one.util.streamex.StreamEx;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
public class StreamExMergeStreamsTest {
@Test
public void givenTwoStreams_whenMergingStreams_thenResultingStreamContainsElementsFromBothStreams() {
StreamEx<Integer> stream1 = StreamEx.of(1, 3, 5);
StreamEx<Integer> stream2 = StreamEx.of(2, 4, 6);
StreamEx<Integer> resultingStream = stream1.append(stream2);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6),
resultingStream.toList());
}
@Test
public void givenFourStreams_whenMergingStreams_thenResultingStreamContainsElementsFromAllStreams() {
StreamEx<Integer> stream1 = StreamEx.of(1, 3, 5);
StreamEx<Integer> stream2 = StreamEx.of(2, 4, 6);
StreamEx<Integer> stream3 = StreamEx.of(18, 15, 36);
StreamEx<Integer> stream4 = StreamEx.of(99);
StreamEx<Integer> resultingStream = stream1.append(stream2)
.append(stream3)
.append(stream4);
assertEquals(Arrays.asList(1, 3, 5, 2, 4, 6, 18, 15, 36, 99),
resultingStream.toList());
}
@Test
public void givenThreeStreams_whenAppendingAndPrependingStreams_thenResultingStreamContainsElementsFromAllStreams() {
StreamEx<String> stream1 = StreamEx.of("foo", "bar");
StreamEx<String> openingBracketStream = StreamEx.of("[");
StreamEx<String> closingBracketStream = StreamEx.of("]");
StreamEx<String> resultingStream = stream1.append(closingBracketStream)
.prepend(openingBracketStream);
assertEquals(Arrays.asList("[", "foo", "bar", "]"),
resultingStream.toList());
}
}

View File

@ -0,0 +1,4 @@
1,2,3
-10, 30, 20
15, -5, 10
-5, -10, -15
1 1 2 3
2 -10 30 20
3 15 -5 10
4 -5 -10 -15

View File

@ -3,11 +3,11 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<util:properties id="konami_props">
<prop key="code">
↑↑↓↓←→←→BA
<util:properties id="props">
<prop key="adder">
4
</prop>
</util:properties>
</beans>

View File

@ -0,0 +1,11 @@
Meta:
Narrative:
As user
I want to add a number
So that I can have the sum
Scenario: A user can submit a number to adder and get current sum
Given a number
When I submit another number 5 to adder
Then I get a sum of the numbers

View File

@ -1,12 +0,0 @@
Meta:
Narrative:
As a KONAMI player
I want to cheat
So that I can unlock hidden stages of the game
Scenario: A KONAMI player can use the cheatcode to unlock hidden stages
Given game stage cleared
And KONAMI cheat code
When I input the cheat code
Then a hidden stage will be unlocked

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