[JAVA-9421] Cleanup code present in stackify repo (#11709)
This commit is contained in:
parent
4380185074
commit
d8cb70194d
@ -1,35 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>com.stackify</groupId>
|
|
||||||
<artifactId>core-java-9</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>core-java-9</name>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
<relativePath>../../</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>${maven-compiler-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<source>${maven.compiler.source}</source>
|
|
||||||
<target>${maven.compiler.target}</target>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<maven.compiler.source>1.9</maven.compiler.source>
|
|
||||||
<maven.compiler.target>1.9</maven.compiler.target>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,28 +0,0 @@
|
|||||||
package com.stackify.optional;
|
|
||||||
|
|
||||||
public class User {
|
|
||||||
private String email;
|
|
||||||
private String password;
|
|
||||||
|
|
||||||
public User(String email, String password) {
|
|
||||||
super();
|
|
||||||
this.email = email;
|
|
||||||
this.password = password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getEmail() {
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setEmail(String email) {
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getPassword() {
|
|
||||||
return password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPassword(String password) {
|
|
||||||
this.password = password;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,13 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<configuration>
|
|
||||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
|
||||||
<encoder>
|
|
||||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
|
||||||
</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<root level="INFO">
|
|
||||||
<appender-ref ref="STDOUT" />
|
|
||||||
</root>
|
|
||||||
</configuration>
|
|
@ -1,41 +0,0 @@
|
|||||||
package com.stackify.optional;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
|
|
||||||
public class OptionalTest {
|
|
||||||
|
|
||||||
private User user;
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenEmptyOptional_thenGetValueFromOr() {
|
|
||||||
User result = Optional.ofNullable(user)
|
|
||||||
.or( () -> Optional.of(new User("default","1234"))).get();
|
|
||||||
|
|
||||||
assertEquals(result.getEmail(), "default");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenIfPresentOrElse_thenOk() {
|
|
||||||
Optional.ofNullable(user)
|
|
||||||
.ifPresentOrElse( u -> System.out.println("User is:" + u.getEmail()), () -> System.out.println("User not found"));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenGetStream_thenOk() {
|
|
||||||
User user = new User("john@gmail.com", "1234");
|
|
||||||
List<String> emails = Optional.ofNullable(user)
|
|
||||||
.stream()
|
|
||||||
.filter(u -> u.getEmail() != null && u.getEmail().contains("@"))
|
|
||||||
.map( u -> u.getEmail())
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertTrue(emails.size() == 1);
|
|
||||||
assertEquals(emails.get(0), user.getEmail());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,29 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>com.stackify</groupId>
|
|
||||||
<artifactId>core-java</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>core-java</name>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
<relativePath>../../</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
|
||||||
<artifactId>log4j-core</artifactId>
|
|
||||||
<version>${log4j2.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<log4j2.version>2.8.2</log4j2.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,40 +0,0 @@
|
|||||||
package com.stackify.optional;
|
|
||||||
|
|
||||||
public class Address {
|
|
||||||
private String addressLine;
|
|
||||||
private String city;
|
|
||||||
private Country country;
|
|
||||||
|
|
||||||
public Address(String addressLine, String city, Country country) {
|
|
||||||
super();
|
|
||||||
this.addressLine = addressLine;
|
|
||||||
this.city = city;
|
|
||||||
this.country = country;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAddressLine() {
|
|
||||||
return addressLine;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAddressLine(String addressLine) {
|
|
||||||
this.addressLine = addressLine;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCity() {
|
|
||||||
return city;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCity(String city) {
|
|
||||||
this.city = city;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Country getCountry() {
|
|
||||||
return country;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCountry(Country country) {
|
|
||||||
this.country = country;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
@ -1,29 +0,0 @@
|
|||||||
package com.stackify.optional;
|
|
||||||
|
|
||||||
public class Country {
|
|
||||||
private String name;
|
|
||||||
private String isocode;
|
|
||||||
|
|
||||||
public Country(String name, String isocode) {
|
|
||||||
super();
|
|
||||||
this.name = name;
|
|
||||||
this.isocode = isocode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getIsocode() {
|
|
||||||
return isocode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsocode(String isocode) {
|
|
||||||
this.isocode = isocode;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,51 +0,0 @@
|
|||||||
package com.stackify.optional;
|
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public class User {
|
|
||||||
private String email;
|
|
||||||
private String password;
|
|
||||||
|
|
||||||
private Address address;
|
|
||||||
|
|
||||||
private String position;
|
|
||||||
|
|
||||||
public User(String email, String password) {
|
|
||||||
super();
|
|
||||||
this.email = email;
|
|
||||||
this.password = password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getEmail() {
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setEmail(String email) {
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getPassword() {
|
|
||||||
return password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPassword(String password) {
|
|
||||||
this.password = password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Address getAddress() {
|
|
||||||
return address;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAddress(Address address) {
|
|
||||||
this.address = address;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Optional<String> getPosition() {
|
|
||||||
return Optional.ofNullable(position);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPosition(String position) {
|
|
||||||
this.position = position;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,38 +0,0 @@
|
|||||||
package com.stackify.optional.chaining;
|
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public class Address {
|
|
||||||
private String addressLine;
|
|
||||||
private String city;
|
|
||||||
private Country country;
|
|
||||||
|
|
||||||
public Address(String addressLine, String city) {
|
|
||||||
this.addressLine = addressLine;
|
|
||||||
this.city = city;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getAddressLine() {
|
|
||||||
return addressLine;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAddressLine(String addressLine) {
|
|
||||||
this.addressLine = addressLine;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getCity() {
|
|
||||||
return city;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCity(String city) {
|
|
||||||
this.city = city;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Optional<Country> getCountry() {
|
|
||||||
return Optional.ofNullable(country);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCountry(Country country) {
|
|
||||||
this.country = country;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,28 +0,0 @@
|
|||||||
package com.stackify.optional.chaining;
|
|
||||||
|
|
||||||
public class Country {
|
|
||||||
private String name;
|
|
||||||
private String isocode;
|
|
||||||
|
|
||||||
public Country(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getIsocode() {
|
|
||||||
return isocode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIsocode(String isocode) {
|
|
||||||
this.isocode = isocode;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
}
|
|
@ -1,50 +0,0 @@
|
|||||||
package com.stackify.optional.chaining;
|
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
public class User {
|
|
||||||
private String email;
|
|
||||||
private String password;
|
|
||||||
|
|
||||||
private Address address;
|
|
||||||
|
|
||||||
private String position;
|
|
||||||
|
|
||||||
public User(String email, String password) {
|
|
||||||
this.email = email;
|
|
||||||
this.password = password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getEmail() {
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setEmail(String email) {
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getPassword() {
|
|
||||||
return password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPassword(String password) {
|
|
||||||
this.password = password;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Optional<Address> getAddress() {
|
|
||||||
return Optional.ofNullable(address);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setAddress(Address address) {
|
|
||||||
this.address = address;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Optional<String> getPosition() {
|
|
||||||
return Optional.ofNullable(position);
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setPosition(String position) {
|
|
||||||
this.position = position;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,50 +0,0 @@
|
|||||||
package com.stackify.optionalparams;
|
|
||||||
|
|
||||||
public class MultiVitamin {
|
|
||||||
|
|
||||||
private String name; // required
|
|
||||||
private int vitaminA; // in mcg
|
|
||||||
private int vitaminC; // in mg
|
|
||||||
private int calcium; // in mg
|
|
||||||
private int iron; // in mg
|
|
||||||
|
|
||||||
public MultiVitamin(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getVitaminA() {
|
|
||||||
return vitaminA;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVitaminA(int vitaminA) {
|
|
||||||
this.vitaminA = vitaminA;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getVitaminC() {
|
|
||||||
return vitaminC;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setVitaminC(int vitaminC) {
|
|
||||||
this.vitaminC = vitaminC;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getCalcium() {
|
|
||||||
return calcium;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCalcium(int calcium) {
|
|
||||||
this.calcium = calcium;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getIron() {
|
|
||||||
return iron;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setIron(int iron) {
|
|
||||||
this.iron = iron;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,38 +0,0 @@
|
|||||||
package com.stackify.optionalparams;
|
|
||||||
|
|
||||||
public class MultiVitaminAllowingNulls {
|
|
||||||
|
|
||||||
private String name; // required
|
|
||||||
private Integer vitaminA; // in mcg
|
|
||||||
private Integer vitaminC; // in mg
|
|
||||||
private Integer calcium; // in mg
|
|
||||||
private Integer iron; // in mg
|
|
||||||
|
|
||||||
public MultiVitaminAllowingNulls(String name, Integer vitaminA, Integer vitaminC, Integer calcium, Integer iron) {
|
|
||||||
this.name = name;
|
|
||||||
this.vitaminA = vitaminA;
|
|
||||||
this.vitaminC = vitaminC;
|
|
||||||
this.calcium = calcium;
|
|
||||||
this.iron = iron;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getVitaminA() {
|
|
||||||
return vitaminA;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getVitaminC() {
|
|
||||||
return vitaminC;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getCalcium() {
|
|
||||||
return calcium;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getIron() {
|
|
||||||
return iron;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,56 +0,0 @@
|
|||||||
package com.stackify.optionalparams;
|
|
||||||
|
|
||||||
public class MultiVitaminOverloading {
|
|
||||||
|
|
||||||
static final int DEFAULT_IRON_AMOUNT = 20;
|
|
||||||
|
|
||||||
private final String name; // required
|
|
||||||
private final int vitaminA; // in mcg
|
|
||||||
private final int vitaminC; // in mg
|
|
||||||
private final int calcium; // in mg
|
|
||||||
private final int iron; // in mg
|
|
||||||
|
|
||||||
public MultiVitaminOverloading(String name) {
|
|
||||||
this(name, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public MultiVitaminOverloading(String name, int vitaminA) {
|
|
||||||
this(name, vitaminA, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public MultiVitaminOverloading(String name, int vitaminA, int vitaminC) {
|
|
||||||
this(name, vitaminA, vitaminC, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium) {
|
|
||||||
this(name, vitaminA, vitaminC, calcium, DEFAULT_IRON_AMOUNT);
|
|
||||||
}
|
|
||||||
|
|
||||||
public MultiVitaminOverloading(String name, int vitaminA, int vitaminC, int calcium, int iron) {
|
|
||||||
this.name = name;
|
|
||||||
this.vitaminA = vitaminA;
|
|
||||||
this.vitaminC = vitaminC;
|
|
||||||
this.calcium = calcium;
|
|
||||||
this.iron = iron;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getVitaminA() {
|
|
||||||
return vitaminA;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getVitaminC() {
|
|
||||||
return vitaminC;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getCalcium() {
|
|
||||||
return calcium;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getIron() {
|
|
||||||
return iron;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,52 +0,0 @@
|
|||||||
package com.stackify.optionalparams;
|
|
||||||
|
|
||||||
public class MultiVitaminStaticFactoryMethods {
|
|
||||||
|
|
||||||
static final int IRON_AMT_DEF = 20;
|
|
||||||
static final int IRON_AMT_MEN = 30;
|
|
||||||
|
|
||||||
static final int CALCIUM_AMT_DEF = 100;
|
|
||||||
static final int CALCIUM_AMT_WOMEN = 120;
|
|
||||||
|
|
||||||
private final String name; // required
|
|
||||||
private final int vitaminA; // in mcg
|
|
||||||
private final int vitaminC; // in mg
|
|
||||||
private final int calcium; // in mg
|
|
||||||
private final int iron; // in mg
|
|
||||||
|
|
||||||
public static MultiVitaminStaticFactoryMethods forMen(String name) {
|
|
||||||
return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_DEF, IRON_AMT_MEN);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static MultiVitaminStaticFactoryMethods forWomen(String name) {
|
|
||||||
return new MultiVitaminStaticFactoryMethods(name, 5000, 60, CALCIUM_AMT_WOMEN, IRON_AMT_DEF);
|
|
||||||
}
|
|
||||||
|
|
||||||
private MultiVitaminStaticFactoryMethods(String name, int vitaminA, int vitaminC, int calcium, int iron) {
|
|
||||||
this.name = name;
|
|
||||||
this.vitaminA = vitaminA;
|
|
||||||
this.vitaminC = vitaminC;
|
|
||||||
this.calcium = calcium;
|
|
||||||
this.iron = iron;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getVitaminA() {
|
|
||||||
return vitaminA;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getVitaminC() {
|
|
||||||
return vitaminC;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getCalcium() {
|
|
||||||
return calcium;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getIron() {
|
|
||||||
return iron;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,77 +0,0 @@
|
|||||||
package com.stackify.optionalparams;
|
|
||||||
|
|
||||||
public class MultiVitaminWithBuilder {
|
|
||||||
|
|
||||||
private final String name; // required
|
|
||||||
private final int vitaminA; // in mcg
|
|
||||||
private final int vitaminC; // in mg
|
|
||||||
private final int calcium; // in mg
|
|
||||||
private final int iron; // in mg
|
|
||||||
|
|
||||||
private MultiVitaminWithBuilder(MultiVitaminBuilder builder) {
|
|
||||||
this.name = builder.name;
|
|
||||||
this.vitaminA = builder.vitaminA;
|
|
||||||
this.vitaminC = builder.vitaminC;
|
|
||||||
this.calcium = builder.calcium;
|
|
||||||
this.iron = builder.iron;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getVitaminA() {
|
|
||||||
return vitaminA;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getVitaminC() {
|
|
||||||
return vitaminC;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getCalcium() {
|
|
||||||
return calcium;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getIron() {
|
|
||||||
return iron;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static class MultiVitaminBuilder {
|
|
||||||
|
|
||||||
private static final int ZERO = 0;
|
|
||||||
|
|
||||||
private final String name; // required
|
|
||||||
private int vitaminA = ZERO;
|
|
||||||
private int vitaminC = ZERO;
|
|
||||||
private int calcium = ZERO;
|
|
||||||
private int iron = ZERO;
|
|
||||||
|
|
||||||
public MultiVitaminBuilder(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MultiVitaminBuilder withVitaminA(int vitaminA) {
|
|
||||||
this.vitaminA = vitaminA;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MultiVitaminBuilder withVitaminC(int vitaminC) {
|
|
||||||
this.vitaminC = vitaminC;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MultiVitaminBuilder withCalcium(int calcium) {
|
|
||||||
this.calcium = calcium;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MultiVitaminBuilder withIron(int iron) {
|
|
||||||
this.iron = iron;
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
public MultiVitaminWithBuilder build() {
|
|
||||||
return new MultiVitaminWithBuilder(this);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,46 +0,0 @@
|
|||||||
package com.stackify.stream;
|
|
||||||
|
|
||||||
public class Employee {
|
|
||||||
private Integer id;
|
|
||||||
private String name;
|
|
||||||
private Double salary;
|
|
||||||
|
|
||||||
public Employee(Integer id, String name, Double salary) {
|
|
||||||
this.id = id;
|
|
||||||
this.name = name;
|
|
||||||
this.salary = salary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Integer getId() {
|
|
||||||
return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setId(Integer id) {
|
|
||||||
this.id = id;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Double getSalary() {
|
|
||||||
return salary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSalary(Double salary) {
|
|
||||||
this.salary = salary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void salaryIncrement(Double percentage) {
|
|
||||||
Double newSalary = salary + percentage * salary / 100;
|
|
||||||
setSalary(newSalary);
|
|
||||||
}
|
|
||||||
|
|
||||||
public String toString() {
|
|
||||||
return "Id: " + id + " Name:" + name + " Price:" + salary;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,21 +0,0 @@
|
|||||||
package com.stackify.stream;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public class EmployeeRepository {
|
|
||||||
private List<Employee> empList;
|
|
||||||
|
|
||||||
public EmployeeRepository(List<Employee> empList) {
|
|
||||||
this.empList = empList;
|
|
||||||
|
|
||||||
}
|
|
||||||
public Employee findById(Integer id) {
|
|
||||||
for (Employee emp : empList) {
|
|
||||||
if (emp.getId() == id) {
|
|
||||||
return emp;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,13 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<Configuration status="WARN">
|
|
||||||
<Appenders>
|
|
||||||
<Console name="Console" target="SYSTEM_OUT">
|
|
||||||
<PatternLayout pattern="%msg%n" />
|
|
||||||
</Console>
|
|
||||||
</Appenders>
|
|
||||||
<Loggers>
|
|
||||||
<Root level="info">
|
|
||||||
<AppenderRef ref="Console" />
|
|
||||||
</Root>
|
|
||||||
</Loggers>
|
|
||||||
</Configuration>
|
|
@ -1,166 +0,0 @@
|
|||||||
package com.stackify.optional;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.NoSuchElementException;
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
|
||||||
import org.apache.logging.log4j.Logger;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class OptionalTest {
|
|
||||||
|
|
||||||
private User user;
|
|
||||||
|
|
||||||
private Logger logger = LogManager.getLogger(OptionalTest.class);
|
|
||||||
|
|
||||||
@Test(expected = NullPointerException.class)
|
|
||||||
public void testNull() {
|
|
||||||
String isocode = user.getAddress().getCountry().getIsocode().toUpperCase();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void test() {
|
|
||||||
|
|
||||||
if (user != null) {
|
|
||||||
Address address = user.getAddress();
|
|
||||||
if (address != null) {
|
|
||||||
Country country = address.getCountry();
|
|
||||||
if (country != null) {
|
|
||||||
String isocode = country.getIsocode();
|
|
||||||
if (isocode != null) {
|
|
||||||
isocode = isocode.toUpperCase();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test(expected = NoSuchElementException.class)
|
|
||||||
public void whenCreateEmptyOptional_thenNull() {
|
|
||||||
Optional<User> emptyOpt = Optional.empty();
|
|
||||||
emptyOpt.get();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test(expected = NullPointerException.class)
|
|
||||||
public void whenCreateOfEmptyOptional_thenNullPointerException() {
|
|
||||||
Optional<User> opt = Optional.of(user);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenCreateOfNullableOptional_thenOk() {
|
|
||||||
String name = "John";
|
|
||||||
Optional<String> opt = Optional.ofNullable(name);
|
|
||||||
assertEquals("John", opt.get());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenCheckIsPresent_thenOk() {
|
|
||||||
user = new User("john@gmail.com", "1234");
|
|
||||||
Optional<User> opt = Optional.ofNullable(user);
|
|
||||||
assertTrue(opt.isPresent());
|
|
||||||
|
|
||||||
assertEquals(user.getEmail(), opt.get().getEmail());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenCheckIfPresent_thenOk() {
|
|
||||||
user = new User("john@gmail.com", "1234");
|
|
||||||
Optional<User> opt = Optional.ofNullable(user);
|
|
||||||
assertTrue(opt.isPresent());
|
|
||||||
|
|
||||||
opt.ifPresent(u -> assertEquals(user.getEmail(), u.getEmail()));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenEmptyValue_thenReturnDefault() {
|
|
||||||
User user = null;
|
|
||||||
User user2 = new User("anna@gmail.com", "1234");
|
|
||||||
User result = Optional.ofNullable(user).orElse(user2);
|
|
||||||
|
|
||||||
assertEquals("anna@gmail.com", result.getEmail());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenValueNotNull_thenIgnoreDefault() {
|
|
||||||
User user = new User("john@gmail.com", "1234");
|
|
||||||
User user2 = new User("anna@gmail.com", "1234");
|
|
||||||
User result = Optional.ofNullable(user).orElse(user2);
|
|
||||||
|
|
||||||
assertEquals("john@gmail.com", result.getEmail());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenSetDefaultOrElseGet_thenOk() {
|
|
||||||
User user = null;
|
|
||||||
User user2 = new User("anna@gmail.com", "1234");
|
|
||||||
User result = Optional.ofNullable(user).orElseGet(() -> user2);
|
|
||||||
|
|
||||||
assertEquals("anna@gmail.com", result.getEmail());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenPresentValue_whenCompare_thenOk() {
|
|
||||||
User user = new User("john@gmail.com", "1234");
|
|
||||||
logger.info("Using orElse");
|
|
||||||
User result = Optional.ofNullable(user).orElse(createNewUser());
|
|
||||||
logger.info("Using orElseGet");
|
|
||||||
User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
|
|
||||||
}
|
|
||||||
|
|
||||||
private User createNewUser() {
|
|
||||||
logger.info("Creating New User");
|
|
||||||
return new User("extra@gmail.com", "1234");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenEmptyValue_whenCompare_thenOk() {
|
|
||||||
User user = null;
|
|
||||||
logger.info("Using orElse");
|
|
||||||
User result = Optional.ofNullable(user).orElse(createNewUser());
|
|
||||||
logger.info("Using orElseGet");
|
|
||||||
User result2 = Optional.ofNullable(user).orElseGet(() -> createNewUser());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test(expected = IllegalArgumentException.class)
|
|
||||||
public void whenThrowException_thenOk() {
|
|
||||||
User result = Optional.ofNullable(user).orElseThrow(() -> new IllegalArgumentException());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenMap_thenOk() {
|
|
||||||
user = new User("anna@gmail.com", "1234");
|
|
||||||
String email = Optional.ofNullable(user).map(u -> u.getEmail()).orElse("default@gmail.com");
|
|
||||||
assertEquals(email, user.getEmail());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenFlatMap_thenOk() {
|
|
||||||
user = new User("anna@gmail.com", "1234");
|
|
||||||
user.setPosition("Developer");
|
|
||||||
String position = Optional.ofNullable(user).flatMap(u -> u.getPosition()).orElse("default");
|
|
||||||
assertEquals(position, user.getPosition().get());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenFilter_thenOk() {
|
|
||||||
user = new User("anna@gmail.com", "1234");
|
|
||||||
Optional<User> result = Optional.ofNullable(user).filter(u -> u.getEmail() != null && u.getEmail().contains("@"));
|
|
||||||
|
|
||||||
assertTrue(result.isPresent());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenStream_thenOk() {
|
|
||||||
List<User> users = new ArrayList<>();
|
|
||||||
User user = users.stream().findFirst().orElse(new User("default", "1234"));
|
|
||||||
assertEquals(user.getEmail(), "default");
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,36 +0,0 @@
|
|||||||
package com.stackify.optional.chaining;
|
|
||||||
|
|
||||||
import static org.junit.Assert.*;
|
|
||||||
|
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class OptionalChainingTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenChaining_thenOk() {
|
|
||||||
User user = new User("anna@gmail.com", "1234");
|
|
||||||
|
|
||||||
String result = Optional.ofNullable(user)
|
|
||||||
.flatMap(u -> u.getAddress())
|
|
||||||
.flatMap(a -> a.getCountry())
|
|
||||||
.map(c -> c.getIsocode())
|
|
||||||
.orElse("default");
|
|
||||||
|
|
||||||
assertEquals(result, "default");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenChainingWithMethodReferences_thenOk() {
|
|
||||||
User user = new User("anna@gmail.com", "1234");
|
|
||||||
|
|
||||||
String result = Optional.ofNullable(user)
|
|
||||||
.flatMap(User::getAddress)
|
|
||||||
.flatMap(Address::getCountry)
|
|
||||||
.map(Country::getIsocode)
|
|
||||||
.orElse("default");
|
|
||||||
|
|
||||||
assertEquals(result, "default");
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,96 +0,0 @@
|
|||||||
package com.stackify.optionalparams;
|
|
||||||
|
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
|
||||||
|
|
||||||
import java.math.BigDecimal;
|
|
||||||
|
|
||||||
import org.assertj.core.util.Arrays;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class OptionalParamsUnitTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenCreateMultiVitaminWithOverloading_thenOk() {
|
|
||||||
MultiVitaminOverloading multiVitamin = new MultiVitaminOverloading("Default Multivitamin");
|
|
||||||
|
|
||||||
assertThat(multiVitamin.getName()).isEqualTo("Default Multivitamin");
|
|
||||||
assertThat(multiVitamin.getVitaminA()).isEqualTo(0);
|
|
||||||
assertThat(multiVitamin.getVitaminC()).isEqualTo(0);
|
|
||||||
assertThat(multiVitamin.getCalcium()).isEqualTo(0);
|
|
||||||
assertThat(multiVitamin.getIron()).isEqualTo(MultiVitaminOverloading.DEFAULT_IRON_AMOUNT);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenCreateMultiVitaminWithStaticFactoryMethods_thenOk() {
|
|
||||||
MultiVitaminStaticFactoryMethods mensMultiVitamin = MultiVitaminStaticFactoryMethods.forMen("Complete for Men");
|
|
||||||
|
|
||||||
assertThat(mensMultiVitamin.getName()).isEqualTo("Complete for Men");
|
|
||||||
assertThat(mensMultiVitamin.getCalcium()).isEqualTo(MultiVitaminStaticFactoryMethods.CALCIUM_AMT_DEF);
|
|
||||||
assertThat(mensMultiVitamin.getIron()).isEqualTo(MultiVitaminStaticFactoryMethods.IRON_AMT_MEN);
|
|
||||||
|
|
||||||
MultiVitaminStaticFactoryMethods womensMultiVitamin = MultiVitaminStaticFactoryMethods.forWomen("Complete for Women");
|
|
||||||
|
|
||||||
assertThat(womensMultiVitamin.getName()).isEqualTo("Complete for Women");
|
|
||||||
assertThat(womensMultiVitamin.getCalcium()).isEqualTo(MultiVitaminStaticFactoryMethods.CALCIUM_AMT_WOMEN);
|
|
||||||
assertThat(womensMultiVitamin.getIron()).isEqualTo(MultiVitaminStaticFactoryMethods.IRON_AMT_DEF);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenCreateMultiVitaminWithBuilder_thenOk() {
|
|
||||||
MultiVitaminWithBuilder vitamin = new MultiVitaminWithBuilder.MultiVitaminBuilder("Maximum Strength")
|
|
||||||
.withCalcium(100)
|
|
||||||
.withIron(200)
|
|
||||||
.withVitaminA(50)
|
|
||||||
.withVitaminC(1000)
|
|
||||||
.build();
|
|
||||||
|
|
||||||
assertThat(vitamin.getName()).isEqualTo("Maximum Strength");
|
|
||||||
assertThat(vitamin.getCalcium()).isEqualTo(100);
|
|
||||||
assertThat(vitamin.getIron()).isEqualTo(200);
|
|
||||||
assertThat(vitamin.getVitaminA()).isEqualTo(50);
|
|
||||||
assertThat(vitamin.getVitaminC()).isEqualTo(1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenCreateMutliVitaminWithAccessors_thenOk() {
|
|
||||||
MultiVitamin vitamin = new MultiVitamin("Generic");
|
|
||||||
vitamin.setVitaminA(50);
|
|
||||||
vitamin.setVitaminC(1000);
|
|
||||||
vitamin.setCalcium(100);
|
|
||||||
vitamin.setIron(200);
|
|
||||||
|
|
||||||
assertThat(vitamin.getName()).isEqualTo("Generic");
|
|
||||||
assertThat(vitamin.getCalcium()).isEqualTo(100);
|
|
||||||
assertThat(vitamin.getIron()).isEqualTo(200);
|
|
||||||
assertThat(vitamin.getVitaminA()).isEqualTo(50);
|
|
||||||
assertThat(vitamin.getVitaminC()).isEqualTo(1000);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenCreateMultiVitaminWithNulls_thenOk() {
|
|
||||||
MultiVitamin vitamin = new MultiVitamin(null);
|
|
||||||
|
|
||||||
assertThat(vitamin.getName()).isNull();
|
|
||||||
}
|
|
||||||
|
|
||||||
public void varArgsDemo() {
|
|
||||||
Object[] args = Arrays.array(Long.valueOf(1), Integer.valueOf(2), BigDecimal.valueOf(3));
|
|
||||||
|
|
||||||
processVarArgsWithCastingAntiPattern(args);
|
|
||||||
}
|
|
||||||
|
|
||||||
private void processVarArgsWithCastingAntiPattern(Object... args) {
|
|
||||||
String message = "processing %s as %s";
|
|
||||||
|
|
||||||
// never do this sort of thing
|
|
||||||
for (Object arg : args) {
|
|
||||||
if (arg instanceof Long) {
|
|
||||||
System.out.println(String.format(message, arg, "Long"));
|
|
||||||
} else if (arg instanceof Integer) {
|
|
||||||
System.out.println(String.format(message, arg, "Integer"));
|
|
||||||
} else if (arg instanceof BigDecimal) {
|
|
||||||
System.out.println(String.format(message, arg, "BigDecimal"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,455 +0,0 @@
|
|||||||
package com.stackify.stream;
|
|
||||||
|
|
||||||
import static org.hamcrest.CoreMatchers.equalTo;
|
|
||||||
import static org.hamcrest.MatcherAssert.assertThat;
|
|
||||||
import static org.hamcrest.Matchers.contains;
|
|
||||||
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
|
|
||||||
import static org.junit.Assert.assertEquals;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.io.PrintWriter;
|
|
||||||
import java.nio.file.Files;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.Comparator;
|
|
||||||
import java.util.DoubleSummaryStatistics;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.Map;
|
|
||||||
import java.util.NoSuchElementException;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.Set;
|
|
||||||
import java.util.Vector;
|
|
||||||
import java.util.function.BinaryOperator;
|
|
||||||
import java.util.stream.Collectors;
|
|
||||||
import java.util.stream.Stream;
|
|
||||||
|
|
||||||
import org.junit.After;
|
|
||||||
import org.junit.Test;
|
|
||||||
|
|
||||||
public class EmployeeTest {
|
|
||||||
private String fileName = "src/test/resources/test.txt";
|
|
||||||
|
|
||||||
private static Employee[] arrayOfEmps = {
|
|
||||||
new Employee(1, "Jeff Bezos", 100000.0),
|
|
||||||
new Employee(2, "Bill Gates", 200000.0),
|
|
||||||
new Employee(3, "Mark Zuckerberg", 300000.0)
|
|
||||||
};
|
|
||||||
|
|
||||||
private static List<Employee> empList = Arrays.asList(arrayOfEmps);
|
|
||||||
private static EmployeeRepository employeeRepository = new EmployeeRepository(empList);
|
|
||||||
|
|
||||||
@After
|
|
||||||
public void cleanup() throws IOException {
|
|
||||||
Files.deleteIfExists(Paths.get(fileName));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenGetStreamFromList_ObtainStream() {
|
|
||||||
assert(empList.stream() instanceof Stream<?>);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenGetStreamFromArray_ObtainStream() {
|
|
||||||
assert(Stream.of(arrayOfEmps) instanceof Stream<?>);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenGetStreamFromElements_ObtainStream() {
|
|
||||||
assert(Stream.of(arrayOfEmps[0], arrayOfEmps[1], arrayOfEmps[2]) instanceof Stream<?>);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenBuildStreamFromElements_ObtainStream() {
|
|
||||||
Stream.Builder<Employee> empStreamBuilder = Stream.builder();
|
|
||||||
|
|
||||||
empStreamBuilder.accept(arrayOfEmps[0]);
|
|
||||||
empStreamBuilder.accept(arrayOfEmps[1]);
|
|
||||||
empStreamBuilder.accept(arrayOfEmps[2]);
|
|
||||||
|
|
||||||
Stream<Employee> empStream = empStreamBuilder.build();
|
|
||||||
|
|
||||||
assert(empStream instanceof Stream<?>);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenIncrementSalaryForEachEmployee_thenApplyNewSalary() {
|
|
||||||
Employee[] arrayOfEmps = {
|
|
||||||
new Employee(1, "Jeff Bezos", 100000.0),
|
|
||||||
new Employee(2, "Bill Gates", 200000.0),
|
|
||||||
new Employee(3, "Mark Zuckerberg", 300000.0)
|
|
||||||
};
|
|
||||||
|
|
||||||
List<Employee> empList = Arrays.asList(arrayOfEmps);
|
|
||||||
|
|
||||||
empList.stream().forEach(e -> e.salaryIncrement(10.0));
|
|
||||||
|
|
||||||
assertThat(empList, contains(
|
|
||||||
hasProperty("salary", equalTo(110000.0)),
|
|
||||||
hasProperty("salary", equalTo(220000.0)),
|
|
||||||
hasProperty("salary", equalTo(330000.0))
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenIncrementSalaryUsingPeek_thenApplyNewSalary() {
|
|
||||||
Employee[] arrayOfEmps = {
|
|
||||||
new Employee(1, "Jeff Bezos", 100000.0),
|
|
||||||
new Employee(2, "Bill Gates", 200000.0),
|
|
||||||
new Employee(3, "Mark Zuckerberg", 300000.0)
|
|
||||||
};
|
|
||||||
|
|
||||||
List<Employee> empList = Arrays.asList(arrayOfEmps);
|
|
||||||
|
|
||||||
empList.stream()
|
|
||||||
.peek(e -> e.salaryIncrement(10.0))
|
|
||||||
.peek(System.out::println)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertThat(empList, contains(
|
|
||||||
hasProperty("salary", equalTo(110000.0)),
|
|
||||||
hasProperty("salary", equalTo(220000.0)),
|
|
||||||
hasProperty("salary", equalTo(330000.0))
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenMapIdToEmployees_thenGetEmployeeStream() {
|
|
||||||
Integer[] empIds = { 1, 2, 3 };
|
|
||||||
|
|
||||||
List<Employee> employees = Stream.of(empIds)
|
|
||||||
.map(employeeRepository::findById)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(employees.size(), empIds.length);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenFlatMapEmployeeNames_thenGetNameStream() {
|
|
||||||
List<List<String>> namesNested = Arrays.asList(
|
|
||||||
Arrays.asList("Jeff", "Bezos"),
|
|
||||||
Arrays.asList("Bill", "Gates"),
|
|
||||||
Arrays.asList("Mark", "Zuckerberg"));
|
|
||||||
|
|
||||||
List<String> namesFlatStream = namesNested.stream()
|
|
||||||
.flatMap(Collection::stream)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(namesFlatStream.size(), namesNested.size() * 2);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenFilterEmployees_thenGetFilteredStream() {
|
|
||||||
Integer[] empIds = { 1, 2, 3, 4 };
|
|
||||||
|
|
||||||
List<Employee> employees = Stream.of(empIds)
|
|
||||||
.map(employeeRepository::findById)
|
|
||||||
.filter(e -> e != null)
|
|
||||||
.filter(e -> e.getSalary() > 200000)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(Arrays.asList(arrayOfEmps[2]), employees);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenFindFirst_thenGetFirstEmployeeInStream() {
|
|
||||||
Integer[] empIds = { 1, 2, 3, 4 };
|
|
||||||
|
|
||||||
Employee employee = Stream.of(empIds)
|
|
||||||
.map(employeeRepository::findById)
|
|
||||||
.filter(e -> e != null)
|
|
||||||
.filter(e -> e.getSalary() > 100000)
|
|
||||||
.findFirst()
|
|
||||||
.orElse(null);
|
|
||||||
|
|
||||||
assertEquals(employee.getSalary(), new Double(200000));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenCollectStreamToList_thenGetList() {
|
|
||||||
List<Employee> employees = empList.stream().collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(empList, employees);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenStreamToArray_thenGetArray() {
|
|
||||||
Employee[] employees = empList.stream().toArray(Employee[]::new);
|
|
||||||
|
|
||||||
assertThat(empList.toArray(), equalTo(employees));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenStreamCount_thenGetElementCount() {
|
|
||||||
Long empCount = empList.stream()
|
|
||||||
.filter(e -> e.getSalary() > 200000)
|
|
||||||
.count();
|
|
||||||
|
|
||||||
assertEquals(empCount, new Long(1));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenLimitInfiniteStream_thenGetFiniteElements() {
|
|
||||||
Stream<Integer> infiniteStream = Stream.iterate(2, i -> i * 2);
|
|
||||||
|
|
||||||
List<Integer> collect = infiniteStream
|
|
||||||
.skip(3)
|
|
||||||
.limit(5)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(collect, Arrays.asList(16, 32, 64, 128, 256));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenSortStream_thenGetSortedStream() {
|
|
||||||
List<Employee> employees = empList.stream()
|
|
||||||
.sorted((e1, e2) -> e1.getName().compareTo(e2.getName()))
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(employees.get(0).getName(), "Bill Gates");
|
|
||||||
assertEquals(employees.get(1).getName(), "Jeff Bezos");
|
|
||||||
assertEquals(employees.get(2).getName(), "Mark Zuckerberg");
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenFindMin_thenGetMinElementFromStream() {
|
|
||||||
Employee firstEmp = empList.stream()
|
|
||||||
.min((e1, e2) -> e1.getId() - e2.getId())
|
|
||||||
.orElseThrow(NoSuchElementException::new);
|
|
||||||
|
|
||||||
assertEquals(firstEmp.getId(), new Integer(1));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenFindMax_thenGetMaxElementFromStream() {
|
|
||||||
Employee maxSalEmp = empList.stream()
|
|
||||||
.max(Comparator.comparing(Employee::getSalary))
|
|
||||||
.orElseThrow(NoSuchElementException::new);
|
|
||||||
|
|
||||||
assertEquals(maxSalEmp.getSalary(), new Double(300000.0));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenApplyDistinct_thenRemoveDuplicatesFromStream() {
|
|
||||||
List<Integer> intList = Arrays.asList(2, 5, 3, 2, 4, 3);
|
|
||||||
List<Integer> distinctIntList = intList.stream().distinct().collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(distinctIntList, Arrays.asList(2, 5, 3, 4));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenApplyMatch_thenReturnBoolean() {
|
|
||||||
List<Integer> intList = Arrays.asList(2, 4, 5, 6, 8);
|
|
||||||
|
|
||||||
boolean allEven = intList.stream().allMatch(i -> i % 2 == 0);
|
|
||||||
boolean oneEven = intList.stream().anyMatch(i -> i % 2 == 0);
|
|
||||||
boolean noneMultipleOfThree = intList.stream().noneMatch(i -> i % 3 == 0);
|
|
||||||
|
|
||||||
assertEquals(allEven, false);
|
|
||||||
assertEquals(oneEven, true);
|
|
||||||
assertEquals(noneMultipleOfThree, false);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenFindMaxOnIntStream_thenGetMaxInteger() {
|
|
||||||
Integer latestEmpId = empList.stream()
|
|
||||||
.mapToInt(Employee::getId)
|
|
||||||
.max()
|
|
||||||
.orElseThrow(NoSuchElementException::new);
|
|
||||||
|
|
||||||
assertEquals(latestEmpId, new Integer(3));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenApplySumOnIntStream_thenGetSum() {
|
|
||||||
Double avgSal = empList.stream()
|
|
||||||
.mapToDouble(Employee::getSalary)
|
|
||||||
.average()
|
|
||||||
.orElseThrow(NoSuchElementException::new);
|
|
||||||
|
|
||||||
assertEquals(avgSal, new Double(200000));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenApplyReduceOnStream_thenGetValue() {
|
|
||||||
Double sumSal = empList.stream()
|
|
||||||
.map(Employee::getSalary)
|
|
||||||
.reduce(0.0, Double::sum);
|
|
||||||
|
|
||||||
assertEquals(sumSal, new Double(600000));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenCollectByJoining_thenGetJoinedString() {
|
|
||||||
String empNames = empList.stream()
|
|
||||||
.map(Employee::getName)
|
|
||||||
.collect(Collectors.joining(", "))
|
|
||||||
.toString();
|
|
||||||
|
|
||||||
assertEquals(empNames, "Jeff Bezos, Bill Gates, Mark Zuckerberg");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenCollectBySet_thenGetSet() {
|
|
||||||
Set<String> empNames = empList.stream()
|
|
||||||
.map(Employee::getName)
|
|
||||||
.collect(Collectors.toSet());
|
|
||||||
|
|
||||||
assertEquals(empNames.size(), 3);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenToVectorCollection_thenGetVector() {
|
|
||||||
Vector<String> empNames = empList.stream()
|
|
||||||
.map(Employee::getName)
|
|
||||||
.collect(Collectors.toCollection(Vector::new));
|
|
||||||
|
|
||||||
assertEquals(empNames.size(), 3);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenApplySummarizing_thenGetBasicStats() {
|
|
||||||
DoubleSummaryStatistics stats = empList.stream()
|
|
||||||
.collect(Collectors.summarizingDouble(Employee::getSalary));
|
|
||||||
|
|
||||||
assertEquals(stats.getCount(), 3);
|
|
||||||
assertEquals(stats.getSum(), 600000.0, 0);
|
|
||||||
assertEquals(stats.getMin(), 100000.0, 0);
|
|
||||||
assertEquals(stats.getMax(), 300000.0, 0);
|
|
||||||
assertEquals(stats.getAverage(), 200000.0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenApplySummaryStatistics_thenGetBasicStats() {
|
|
||||||
DoubleSummaryStatistics stats = empList.stream()
|
|
||||||
.mapToDouble(Employee::getSalary)
|
|
||||||
.summaryStatistics();
|
|
||||||
|
|
||||||
assertEquals(stats.getCount(), 3);
|
|
||||||
assertEquals(stats.getSum(), 600000.0, 0);
|
|
||||||
assertEquals(stats.getMin(), 100000.0, 0);
|
|
||||||
assertEquals(stats.getMax(), 300000.0, 0);
|
|
||||||
assertEquals(stats.getAverage(), 200000.0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenStreamPartition_thenGetMap() {
|
|
||||||
List<Integer> intList = Arrays.asList(2, 4, 5, 6, 8);
|
|
||||||
Map<Boolean, List<Integer>> isEven = intList.stream().collect(
|
|
||||||
Collectors.partitioningBy(i -> i % 2 == 0));
|
|
||||||
|
|
||||||
assertEquals(isEven.get(true).size(), 4);
|
|
||||||
assertEquals(isEven.get(false).size(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenStreamGroupingBy_thenGetMap() {
|
|
||||||
Map<Character, List<Employee>> groupByAlphabet = empList.stream().collect(
|
|
||||||
Collectors.groupingBy(e -> new Character(e.getName().charAt(0))));
|
|
||||||
|
|
||||||
assertEquals(groupByAlphabet.get('B').get(0).getName(), "Bill Gates");
|
|
||||||
assertEquals(groupByAlphabet.get('J').get(0).getName(), "Jeff Bezos");
|
|
||||||
assertEquals(groupByAlphabet.get('M').get(0).getName(), "Mark Zuckerberg");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenStreamMapping_thenGetMap() {
|
|
||||||
Map<Character, List<Integer>> idGroupedByAlphabet = empList.stream().collect(
|
|
||||||
Collectors.groupingBy(e -> new Character(e.getName().charAt(0)),
|
|
||||||
Collectors.mapping(Employee::getId, Collectors.toList())));
|
|
||||||
|
|
||||||
assertEquals(idGroupedByAlphabet.get('B').get(0), new Integer(2));
|
|
||||||
assertEquals(idGroupedByAlphabet.get('J').get(0), new Integer(1));
|
|
||||||
assertEquals(idGroupedByAlphabet.get('M').get(0), new Integer(3));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenStreamReducing_thenGetValue() {
|
|
||||||
Double percentage = 10.0;
|
|
||||||
Double salIncrOverhead = empList.stream().collect(Collectors.reducing(
|
|
||||||
0.0, e -> e.getSalary() * percentage / 100, (s1, s2) -> s1 + s2));
|
|
||||||
|
|
||||||
assertEquals(salIncrOverhead, 60000.0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenStreamGroupingAndReducing_thenGetMap() {
|
|
||||||
Comparator<Employee> byNameLength = Comparator.comparing(Employee::getName);
|
|
||||||
|
|
||||||
Map<Character, Optional<Employee>> longestNameByAlphabet = empList.stream().collect(
|
|
||||||
Collectors.groupingBy(e -> new Character(e.getName().charAt(0)),
|
|
||||||
Collectors.reducing(BinaryOperator.maxBy(byNameLength))));
|
|
||||||
|
|
||||||
assertEquals(longestNameByAlphabet.get('B').get().getName(), "Bill Gates");
|
|
||||||
assertEquals(longestNameByAlphabet.get('J').get().getName(), "Jeff Bezos");
|
|
||||||
assertEquals(longestNameByAlphabet.get('M').get().getName(), "Mark Zuckerberg");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenParallelStream_thenPerformOperationsInParallel() {
|
|
||||||
Employee[] arrayOfEmps = {
|
|
||||||
new Employee(1, "Jeff Bezos", 100000.0),
|
|
||||||
new Employee(2, "Bill Gates", 200000.0),
|
|
||||||
new Employee(3, "Mark Zuckerberg", 300000.0)
|
|
||||||
};
|
|
||||||
|
|
||||||
List<Employee> empList = Arrays.asList(arrayOfEmps);
|
|
||||||
|
|
||||||
empList.stream().parallel().forEach(e -> e.salaryIncrement(10.0));
|
|
||||||
|
|
||||||
assertThat(empList, contains(
|
|
||||||
hasProperty("salary", equalTo(110000.0)),
|
|
||||||
hasProperty("salary", equalTo(220000.0)),
|
|
||||||
hasProperty("salary", equalTo(330000.0))
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenGenerateStream_thenGetInfiniteStream() {
|
|
||||||
Stream.generate(Math::random)
|
|
||||||
.limit(5)
|
|
||||||
.forEach(System.out::println);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenIterateStream_thenGetInfiniteStream() {
|
|
||||||
Stream<Integer> evenNumStream = Stream.iterate(2, i -> i * 2);
|
|
||||||
|
|
||||||
List<Integer> collect = evenNumStream
|
|
||||||
.limit(5)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
|
|
||||||
assertEquals(collect, Arrays.asList(2, 4, 8, 16, 32));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenStreamToFile_thenGetFile() throws IOException {
|
|
||||||
String[] words = {
|
|
||||||
"hello",
|
|
||||||
"refer",
|
|
||||||
"world",
|
|
||||||
"level"
|
|
||||||
};
|
|
||||||
|
|
||||||
try (PrintWriter pw = new PrintWriter(
|
|
||||||
Files.newBufferedWriter(Paths.get(fileName)))) {
|
|
||||||
Stream.of(words).forEach(pw::println);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private List<String> getPalindrome(Stream<String> stream, int length) {
|
|
||||||
return stream.filter(s -> s.length() == length)
|
|
||||||
.filter(s -> s.compareToIgnoreCase(
|
|
||||||
new StringBuilder(s).reverse().toString()) == 0)
|
|
||||||
.collect(Collectors.toList());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenFileToStream_thenGetStream() throws IOException {
|
|
||||||
whenStreamToFile_thenGetFile();
|
|
||||||
|
|
||||||
List<String> str = getPalindrome(Files.lines(Paths.get(fileName)), 5);
|
|
||||||
assertThat(str, contains("refer", "level"));
|
|
||||||
}
|
|
||||||
}
|
|
14
guest/core-kotlin/.gitignore
vendored
14
guest/core-kotlin/.gitignore
vendored
@ -1,14 +0,0 @@
|
|||||||
/bin/
|
|
||||||
|
|
||||||
#ignore gradle
|
|
||||||
.gradle/
|
|
||||||
|
|
||||||
|
|
||||||
#ignore build and generated files
|
|
||||||
build/
|
|
||||||
node/
|
|
||||||
out/
|
|
||||||
|
|
||||||
#ignore installed node modules and package lock file
|
|
||||||
node_modules/
|
|
||||||
package-lock.json
|
|
@ -1,201 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>com.stackify</groupId>
|
|
||||||
<artifactId>core-kotlin</artifactId>
|
|
||||||
<version>1.0-SNAPSHOT</version>
|
|
||||||
<name>core-kotlin</name>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<repositories>
|
|
||||||
<repository>
|
|
||||||
<id>jcenter</id>
|
|
||||||
<url>http://jcenter.bintray.com</url>
|
|
||||||
</repository>
|
|
||||||
</repositories>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.junit.platform</groupId>
|
|
||||||
<artifactId>junit-platform-runner</artifactId>
|
|
||||||
<version>${junit-platform.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-stdlib</artifactId>
|
|
||||||
<version>${kotlin-stdlib.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
|
||||||
<version>${kotlin-stdlib.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-test-junit</artifactId>
|
|
||||||
<version>${kotlin-test-junit.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-reflect</artifactId>
|
|
||||||
<version>${kotlin-reflect.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.spek</groupId>
|
|
||||||
<artifactId>spek-api</artifactId>
|
|
||||||
<version>${spek.api.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.spek</groupId>
|
|
||||||
<artifactId>spek-subject-extension</artifactId>
|
|
||||||
<version>${spek.subject.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.spek</groupId>
|
|
||||||
<artifactId>spek-junit-platform-engine</artifactId>
|
|
||||||
<version>${spek.junit.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.nhaarman</groupId>
|
|
||||||
<artifactId>mockito-kotlin</artifactId>
|
|
||||||
<version>${mockito-kotlin.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.assertj</groupId>
|
|
||||||
<artifactId>assertj-core</artifactId>
|
|
||||||
<version>${assertj.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>${maven-compiler-plugin.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-failsafe-plugin</artifactId>
|
|
||||||
<version>${maven-failsafe-plugin.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-maven-plugin</artifactId>
|
|
||||||
<version>${kotlin-maven-plugin.version}</version>
|
|
||||||
<scope>provided</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.jetbrains.kotlin</groupId>
|
|
||||||
<artifactId>kotlin-maven-plugin</artifactId>
|
|
||||||
<version>${kotlin-maven-plugin.version}</version>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>compile</id>
|
|
||||||
<goals>
|
|
||||||
<goal>compile</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<sourceDirs>
|
|
||||||
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
|
|
||||||
</sourceDirs>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
<execution>
|
|
||||||
<id>test-compile</id>
|
|
||||||
<goals>
|
|
||||||
<goal>test-compile</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<sourceDirs>
|
|
||||||
<sourceDir>${project.basedir}/src/test/kotlin</sourceDir>
|
|
||||||
</sourceDirs>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-compiler-plugin</artifactId>
|
|
||||||
<version>${maven-compiler-plugin.version}</version>
|
|
||||||
<configuration>
|
|
||||||
<source>${java.version}</source>
|
|
||||||
<target>${java.version}</target>
|
|
||||||
</configuration>
|
|
||||||
<executions>
|
|
||||||
<!-- Replacing default-compile as it is treated specially
|
|
||||||
by maven -->
|
|
||||||
<execution>
|
|
||||||
<id>default-compile</id>
|
|
||||||
<phase>none</phase>
|
|
||||||
</execution>
|
|
||||||
<!-- Replacing default-testCompile as it is treated specially
|
|
||||||
by maven -->
|
|
||||||
<execution>
|
|
||||||
<id>default-testCompile</id>
|
|
||||||
<phase>none</phase>
|
|
||||||
</execution>
|
|
||||||
<execution>
|
|
||||||
<id>java-compile</id>
|
|
||||||
<phase>compile</phase>
|
|
||||||
<goals>
|
|
||||||
<goal>compile</goal>
|
|
||||||
</goals>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
<plugin>
|
|
||||||
<artifactId>maven-failsafe-plugin</artifactId>
|
|
||||||
<version>${maven-failsafe-plugin.version}</version>
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.junit.platform</groupId>
|
|
||||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
|
||||||
<version>${junit-platform-surefire-provider.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
<executions>
|
|
||||||
<execution>
|
|
||||||
<id>junit5</id>
|
|
||||||
<goals>
|
|
||||||
<goal>integration-test</goal>
|
|
||||||
<goal>verify</goal>
|
|
||||||
</goals>
|
|
||||||
<configuration>
|
|
||||||
<includes>
|
|
||||||
<include>**/*Test5.java</include>
|
|
||||||
</includes>
|
|
||||||
</configuration>
|
|
||||||
</execution>
|
|
||||||
</executions>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<maven-failsafe-plugin.version>2.22.0</maven-failsafe-plugin.version>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<kotlin-maven-plugin.version>1.2.60</kotlin-maven-plugin.version>
|
|
||||||
<kotlin-test-junit.version>1.2.51</kotlin-test-junit.version>
|
|
||||||
<kotlin-stdlib.version>1.2.51</kotlin-stdlib.version>
|
|
||||||
<kotlin-reflect.version>1.2.51</kotlin-reflect.version>
|
|
||||||
<kotlinx.version>0.22.5</kotlinx.version>
|
|
||||||
<mockito-kotlin.version>1.5.0</mockito-kotlin.version>
|
|
||||||
<commons-math3.version>3.6.1</commons-math3.version>
|
|
||||||
<assertj.version>3.10.0</assertj.version>
|
|
||||||
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
|
|
||||||
<spek.api.version>1.1.5</spek.api.version>
|
|
||||||
<spek.subject.version>1.1.5</spek.subject.version>
|
|
||||||
<spek.junit.version>1.1.5</spek.junit.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,21 +0,0 @@
|
|||||||
package com.baeldung.kotlinvsjava
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
class CompanionObjectTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenAClassWithCompanionObject_whenCallingMethodTheSameAsStaticOne_thenWeGetAResult() {
|
|
||||||
assertEquals("A", A.returnClassName())
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
class A {
|
|
||||||
companion object {
|
|
||||||
fun returnClassName(): String {
|
|
||||||
return "A"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,18 +0,0 @@
|
|||||||
package com.baeldung.kotlinvsjava
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
class ConstructorTests {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenAClassWithPrimaryConstructor_whenCreatingAnInstance_thenWeGetObject() {
|
|
||||||
var example = Example(1, "Example")
|
|
||||||
|
|
||||||
assertEquals(1, example.id)
|
|
||||||
assertEquals("Example", example.name)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
class Example constructor(val id: Int, var name: String)
|
|
@ -1,33 +0,0 @@
|
|||||||
package com.baeldung.kotlinvsjava
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
import kotlin.test.assertFalse
|
|
||||||
|
|
||||||
class DataClassTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenASampleDataClass_whenCallingToStringMethod_thenItReturnsAllProperties() {
|
|
||||||
val student = Student(1, "John", "Smith")
|
|
||||||
|
|
||||||
assertEquals(1, student.id)
|
|
||||||
assertEquals("John", student.name)
|
|
||||||
assertEquals("Smith", student.lastName)
|
|
||||||
assertEquals("Student(id=1, name=John, lastName=Smith)", student.toString())
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenASampleDataClass_whenCreatingACopyWithGeneratedFunction_thenItReturnsACopyWithRequestedChanges() {
|
|
||||||
val student = Student(1, "John", "Smith")
|
|
||||||
val student2 = student.copy(id = 2, name = "Anne")
|
|
||||||
|
|
||||||
assertEquals(2, student2.id)
|
|
||||||
assertEquals("Anne", student2.name)
|
|
||||||
assertEquals("Smith", student2.lastName)
|
|
||||||
assertEquals("Student(id=2, name=Anne, lastName=Smith)", student2.toString())
|
|
||||||
assertFalse(student.equals(student2))
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
data class Student(val id: Int, val name: String, val lastName: String)
|
|
@ -1,27 +0,0 @@
|
|||||||
package com.baeldung.kotlinvsjava
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
class DelegationTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenAClassWithDelegation_whenCallDelegatedMethod_thenWeGetAResultDefinedInPassedObject() {
|
|
||||||
val car = Car(V6Engine())
|
|
||||||
|
|
||||||
assertEquals("Vroom", car.makeSound())
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Engine {
|
|
||||||
fun makeSound(): String
|
|
||||||
}
|
|
||||||
|
|
||||||
class V6Engine: Engine {
|
|
||||||
override fun makeSound(): String {
|
|
||||||
return "Vroom"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class Car(e: Engine) : Engine by e
|
|
@ -1,34 +0,0 @@
|
|||||||
package com.baeldung.kotlinvsjava
|
|
||||||
|
|
||||||
import java.io.IOException
|
|
||||||
import kotlin.test.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
class ExceptionsTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenATryExpression_whenReturning5InLastExpressionOfTryBlock_thenWeGet5() {
|
|
||||||
val value: Int = try { 5 } catch (e: IOException) { 6 }
|
|
||||||
|
|
||||||
assertEquals(5, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenATryExpression_whenReturning6InLastExpressionOfCatchBlock_thenWeGet6() {
|
|
||||||
val value: Int = try { funThrowingException() } catch (e: IOException) { 6 }
|
|
||||||
|
|
||||||
assertEquals(6, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
@org.junit.Test(expected = IllegalArgumentException::class)
|
|
||||||
fun givenANullString_whenUsingElvisOperator_thenExceptionIsThrown() {
|
|
||||||
val sampleString: String? = null
|
|
||||||
|
|
||||||
sampleString?.length ?: throw IllegalArgumentException("String must not be null")
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun funThrowingException(): Nothing {
|
|
||||||
throw IOException()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,30 +0,0 @@
|
|||||||
package com.baeldung.kotlinvsjava
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
class ExtensionFunctionsTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenAStringWithAnExtensionFunction_whenCallingThatFunction_thenItConcatenatesStrings() {
|
|
||||||
val sampleString = "ABC"
|
|
||||||
val concatenatedString = sampleString.appendString("DEF")
|
|
||||||
|
|
||||||
assertEquals("ABCDEF", concatenatedString)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenAStringWithAnExtensionProperty_whenReadingProperty_thenItReturnsLengthOfString() {
|
|
||||||
val sampleString = "ABC"
|
|
||||||
|
|
||||||
assertEquals(3, sampleString.size)
|
|
||||||
}
|
|
||||||
|
|
||||||
fun String.appendString(str : String): String {
|
|
||||||
return plus(str)
|
|
||||||
}
|
|
||||||
|
|
||||||
val String.size: Int
|
|
||||||
get() = length
|
|
||||||
|
|
||||||
}
|
|
@ -1,70 +0,0 @@
|
|||||||
package com.baeldung.kotlinvsjava
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
class FunctionsTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenALambdaExpressionConcatenatingString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() {
|
|
||||||
val concat: (String, String) -> String = { a, b -> a + b }
|
|
||||||
|
|
||||||
assertEquals("AB", concat("A","B"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenAnAnonymousFunctionConcatenatingString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() {
|
|
||||||
val concat: (String, String) -> String = fun(a: String, b: String): String { return a + b }
|
|
||||||
|
|
||||||
assertEquals("AB", concat("A","B"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenAnPlusMethodOfString_whenUsingTheFunctionWithAAndBString_thenWeGetAB() {
|
|
||||||
val concat = String::plus
|
|
||||||
|
|
||||||
assertEquals("AB", concat("A","B"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenAStringConstractorAssignedToFunction_whenUsingFunctionReference_thenWeGetNewString() {
|
|
||||||
val concat = ::String
|
|
||||||
|
|
||||||
assertEquals("A", concat().plus("A"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenAClassImplementingAFunctionType_whenUsingTheFunctionWithAAndBString_thenWeGetAB() {
|
|
||||||
val concat = StringConcatenation()
|
|
||||||
|
|
||||||
assertEquals("AB", concat("A", "B"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenALambdaExpressionWithReceiver_whenUsingTheFunctionWithReceiver_thenWeGetABC() {
|
|
||||||
val concat: String.(String, String) -> String = { a, b -> plus(a).plus(b) }
|
|
||||||
|
|
||||||
assertEquals("ABC", "A".concat("B", "C"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenALambdaExpressionWithinLambdaExpression_whenUsingTheFunction_thenWeGetAB() {
|
|
||||||
val concat: (String) -> ((String) -> String) = { a -> {b -> a + b} }
|
|
||||||
|
|
||||||
assertEquals("AB", (concat("A")("B")))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun given3NestedLambdaExpression_whenUsingTheFunction_thenWeGetABC() {
|
|
||||||
val concat: (String) -> (String) -> (String) -> String = { a -> {b -> { c -> a + b + c} } }
|
|
||||||
|
|
||||||
assertEquals("ABC", concat("A")("B")("C"))
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
class StringConcatenation: (String, String) -> String {
|
|
||||||
override fun invoke(p1: String, p2: String): String {
|
|
||||||
return p1 + p2
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,36 +0,0 @@
|
|||||||
package com.baeldung.kotlinvsjava
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.math.absoluteValue
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
import kotlin.test.assertTrue
|
|
||||||
|
|
||||||
class IsOperatorTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenSampleValue_whenUsingIsOperatorInIfStatement_thenItCastsAutomaticallyToString() {
|
|
||||||
val value: Any = "string"
|
|
||||||
|
|
||||||
if(value is String) {
|
|
||||||
assertEquals(6, value.length)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenSampleValue_whenUsingIsOperatorWithAndOperator_thenItCastsAutomaticallyToString() {
|
|
||||||
val value: Any = "string"
|
|
||||||
|
|
||||||
assertTrue(value is String && value.length == 6)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenSampleValue_whenUsingWithWhenOperator_thenItCastsAutomaticallyToString() {
|
|
||||||
val value: Any = "string"
|
|
||||||
|
|
||||||
when(value) {
|
|
||||||
is String -> assertEquals(6, value.length)
|
|
||||||
is Int -> assertEquals(6, value.absoluteValue)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,67 +0,0 @@
|
|||||||
package com.baeldung.kotlinvsjava
|
|
||||||
|
|
||||||
import kotlin.test.Test
|
|
||||||
import java.lang.NullPointerException
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
import kotlin.test.assertNotNull
|
|
||||||
import kotlin.test.assertNull
|
|
||||||
|
|
||||||
class NullSafetyTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenStringAndNull_whenUsingSafeCallOperatorWithLengthMethod_thenReturnsLengthForStringAndNullForNull() {
|
|
||||||
val stringValue: String? = "string"
|
|
||||||
val nullValue: String? = null
|
|
||||||
|
|
||||||
assertNotNull(stringValue?.length)
|
|
||||||
assertNull(nullValue?.length)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test(expected = NullPointerException::class)
|
|
||||||
fun givenNullReference_whenUsingTheNotNullAssertionOperator_thenItThrowsNullPointerException() {
|
|
||||||
val stringValue: String? = "string"
|
|
||||||
val nullValue: String? = null
|
|
||||||
|
|
||||||
assertNotNull(stringValue!!.length)
|
|
||||||
nullValue!!.length
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenStringAndNull_whenUsingElvisOperator_thenItTestsAgainstNullAndReturnsTheProperValue() {
|
|
||||||
val stringValue: String? = "string"
|
|
||||||
val nullValue: String? = null
|
|
||||||
|
|
||||||
val shouldBeLength: Int = stringValue?.length ?: -1
|
|
||||||
val souldBeMinusOne: Int = nullValue?.length ?: -1
|
|
||||||
|
|
||||||
assertEquals(6, shouldBeLength)
|
|
||||||
assertEquals(-1, souldBeMinusOne)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenString_whenCastingToInt_thenItReturnsNull() {
|
|
||||||
val stringValue: String? = "string"
|
|
||||||
|
|
||||||
val intValue: Int? = stringValue as? Int
|
|
||||||
|
|
||||||
assertNull(intValue)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenCollectionWithNulls_whenFilterNonNull_thenItReturnsCollectionWithoutNulls() {
|
|
||||||
val list: List<String?> = listOf("a", "b", null)
|
|
||||||
val nonNullList = list.filterNotNull()
|
|
||||||
|
|
||||||
assertEquals(2, nonNullList.size)
|
|
||||||
assertEquals(nonNullList, listOf("a", "b"))
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenCollectionWithNulls_whenLetWithSafeCallOperator_thenItOmitsNulls() {
|
|
||||||
val list: List<String?> = listOf("a", "b", null)
|
|
||||||
for(elem in list) {
|
|
||||||
elem?.let { assertNotNull(it) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,61 +0,0 @@
|
|||||||
package com.baeldung.kotlinvsjava
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
import kotlin.test.assertTrue
|
|
||||||
|
|
||||||
class OperatorsOverloadingTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenThePlaneClassWithOverloadedIncrementationOperator_whenCallingTheOperator_thenItIncreasesSpeed(){
|
|
||||||
var plane = Plane(0.0)
|
|
||||||
|
|
||||||
plane++
|
|
||||||
assertEquals(50.0, plane.currentSpeed)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenThePlaneClassWithOverloadedMinusOperator_whenCallingTheOperator_thenItDecreaseSpeed(){
|
|
||||||
var plane = Plane(1000.0)
|
|
||||||
|
|
||||||
plane - 500.0
|
|
||||||
assertEquals(500.0, plane.currentSpeed)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenThePlaneClassWithOverloadedInvokeOperator_whenCallingTheOperator_thenItSetSpeed(){
|
|
||||||
var plane = Plane(0.0)
|
|
||||||
|
|
||||||
plane(150.0)
|
|
||||||
assertEquals(150.0, plane.currentSpeed)
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun given2PlaneObjectWithOverloadedComparisonOperator_whenCallingTheOperator_thenItComparesSpeedValues(){
|
|
||||||
var plane = Plane(0.0)
|
|
||||||
var plane2 = Plane(150.0)
|
|
||||||
|
|
||||||
assertTrue(plane < (plane2))
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
class Plane(var currentSpeed: Double) {
|
|
||||||
|
|
||||||
operator fun inc(): Plane {
|
|
||||||
currentSpeed += 50.0
|
|
||||||
return this
|
|
||||||
}
|
|
||||||
|
|
||||||
operator fun minus(number: Double) {
|
|
||||||
currentSpeed = if(currentSpeed < number) 0.0 else currentSpeed - number
|
|
||||||
}
|
|
||||||
|
|
||||||
operator fun invoke(speed: Double) {
|
|
||||||
currentSpeed = speed
|
|
||||||
}
|
|
||||||
|
|
||||||
operator fun compareTo(plane: Plane): Int {
|
|
||||||
return currentSpeed.compareTo(plane.currentSpeed)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,32 +0,0 @@
|
|||||||
package com.baeldung.kotlinvsjava
|
|
||||||
|
|
||||||
import org.junit.Test
|
|
||||||
import java.math.BigDecimal
|
|
||||||
import kotlin.test.assertEquals
|
|
||||||
|
|
||||||
class PropertiesTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
fun givenASampleClassWithValAndVarProperties_whenSettingPrice_thenWeGetZeroOrOne() {
|
|
||||||
val product = Product()
|
|
||||||
product.price = BigDecimal(10)
|
|
||||||
|
|
||||||
val product2 = Product()
|
|
||||||
product2.price = null
|
|
||||||
|
|
||||||
assertEquals("empty", product.id)
|
|
||||||
assertEquals("empty", product2.id)
|
|
||||||
assertEquals(BigDecimal(10), product.price)
|
|
||||||
assertEquals(BigDecimal(1), product2.price)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
class Product {
|
|
||||||
|
|
||||||
val id: String? = "empty"
|
|
||||||
|
|
||||||
var price: BigDecimal? = BigDecimal.ZERO
|
|
||||||
set(value) = if(value == null) { field = BigDecimal.ONE} else { field = value }
|
|
||||||
|
|
||||||
}
|
|
@ -1,15 +0,0 @@
|
|||||||
## Building
|
|
||||||
|
|
||||||
To build the module, use Maven's `package` goal:
|
|
||||||
|
|
||||||
```
|
|
||||||
mvn clean package
|
|
||||||
```
|
|
||||||
|
|
||||||
The `war` file will be available at `target/deep-jsf.war`
|
|
||||||
|
|
||||||
## Running
|
|
||||||
|
|
||||||
The `war` application is deployed to a Java EE 7 compliant application server, for example, to GlassFish 4 or later.
|
|
||||||
|
|
||||||
The example then will be accessible at http://localhost:8080/deep-jsf/index.xhtml
|
|
@ -1,36 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>com.stackify</groupId>
|
|
||||||
<artifactId>deep-jsf</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>deep-jsf</name>
|
|
||||||
<packaging>war</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
<relativePath>../../</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>javax</groupId>
|
|
||||||
<artifactId>javaee-api</artifactId>
|
|
||||||
<version>${javaee-api.version}</version>
|
|
||||||
<scope>provided</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<finalName>deep-jsf</finalName>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<failOnMissingWebXml>false</failOnMissingWebXml>
|
|
||||||
<javaee-api.version>7.0</javaee-api.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,14 +0,0 @@
|
|||||||
package com.stackify.deepjsf;
|
|
||||||
|
|
||||||
import javax.faces.bean.ManagedBean;
|
|
||||||
import javax.faces.bean.RequestScoped;
|
|
||||||
|
|
||||||
@ManagedBean
|
|
||||||
@RequestScoped
|
|
||||||
public class GreetControllerBean {
|
|
||||||
|
|
||||||
public String greet() {
|
|
||||||
return "greet";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,47 +0,0 @@
|
|||||||
package com.stackify.deepjsf;
|
|
||||||
|
|
||||||
import javax.faces.bean.ManagedBean;
|
|
||||||
import javax.faces.bean.RequestScoped;
|
|
||||||
import javax.faces.component.UIComponent;
|
|
||||||
import javax.faces.component.UIViewRoot;
|
|
||||||
import javax.faces.component.visit.VisitContext;
|
|
||||||
import javax.faces.component.visit.VisitResult;
|
|
||||||
import javax.faces.event.PhaseEvent;
|
|
||||||
import javax.faces.event.PhaseId;
|
|
||||||
import javax.servlet.http.HttpServletRequest;
|
|
||||||
|
|
||||||
@ManagedBean
|
|
||||||
@RequestScoped
|
|
||||||
public class PhaseListenerBean {
|
|
||||||
|
|
||||||
public void beforeListener(PhaseEvent event) {
|
|
||||||
if (!event.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
UIViewRoot root = event.getFacesContext().getViewRoot();
|
|
||||||
|
|
||||||
boolean showNewFeature = showNewFeatureForIp(event);
|
|
||||||
|
|
||||||
processComponentTree(root, event, showNewFeature);
|
|
||||||
}
|
|
||||||
|
|
||||||
private boolean showNewFeatureForIp(PhaseEvent event) {
|
|
||||||
HttpServletRequest request = (HttpServletRequest) event.getFacesContext()
|
|
||||||
.getExternalContext().getRequest();
|
|
||||||
String ip = request.getRemoteAddr();
|
|
||||||
return !ip.startsWith("127.0");
|
|
||||||
}
|
|
||||||
|
|
||||||
private void processComponentTree(UIComponent component, PhaseEvent event, boolean show) {
|
|
||||||
component.visitTree(VisitContext.createVisitContext(event.getFacesContext()),
|
|
||||||
(context, target) -> {
|
|
||||||
if (target.getId() != null
|
|
||||||
&& target.getId().startsWith("new-feature-")
|
|
||||||
&& !show) {
|
|
||||||
target.setRendered(false);
|
|
||||||
}
|
|
||||||
return VisitResult.ACCEPT;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,48 +0,0 @@
|
|||||||
package com.stackify.deepjsf;
|
|
||||||
|
|
||||||
import javax.faces.bean.ManagedBean;
|
|
||||||
import javax.faces.bean.SessionScoped;
|
|
||||||
import javax.faces.event.ValueChangeEvent;
|
|
||||||
|
|
||||||
@ManagedBean
|
|
||||||
@SessionScoped
|
|
||||||
public class UserBean {
|
|
||||||
|
|
||||||
private String name = "";
|
|
||||||
|
|
||||||
private String lastName = "";
|
|
||||||
|
|
||||||
private String proposedLogin = "";
|
|
||||||
|
|
||||||
public void nameChanged(ValueChangeEvent event) {
|
|
||||||
this.proposedLogin = event.getNewValue() + "-" + lastName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void lastNameChanged(ValueChangeEvent event) {
|
|
||||||
this.proposedLogin = name + "-" + event.getNewValue();
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getLastName() {
|
|
||||||
return lastName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLastName(String lastName) {
|
|
||||||
this.lastName = lastName;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getProposedLogin() {
|
|
||||||
return proposedLogin;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setProposedLogin(String proposedLogin) {
|
|
||||||
this.proposedLogin = proposedLogin;
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,14 +0,0 @@
|
|||||||
package com.stackify.deepjsf;
|
|
||||||
|
|
||||||
import javax.faces.bean.ManagedBean;
|
|
||||||
import javax.faces.bean.RequestScoped;
|
|
||||||
|
|
||||||
@ManagedBean
|
|
||||||
@RequestScoped
|
|
||||||
public class UserControllerBean {
|
|
||||||
|
|
||||||
public String register() {
|
|
||||||
return "register-success";
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,13 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<configuration>
|
|
||||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
|
||||||
<encoder>
|
|
||||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
|
||||||
</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<root level="INFO">
|
|
||||||
<appender-ref ref="STDOUT" />
|
|
||||||
</root>
|
|
||||||
</configuration>
|
|
@ -1,15 +0,0 @@
|
|||||||
<?xml version='1.0' encoding='UTF-8'?>
|
|
||||||
<faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
|
|
||||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
|
|
||||||
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
|
|
||||||
|
|
||||||
<navigation-rule>
|
|
||||||
<from-view-id>/register.xhtml</from-view-id>
|
|
||||||
<navigation-case>
|
|
||||||
<from-outcome>register-success</from-outcome>
|
|
||||||
<to-view-id>/hello.xhtml</to-view-id>
|
|
||||||
</navigation-case>
|
|
||||||
</navigation-rule>
|
|
||||||
|
|
||||||
</faces-config>
|
|
@ -1,11 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
|
||||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
|
||||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
|
||||||
xmlns:h="http://xmlns.jcp.org/jsf/html"
|
|
||||||
xmlns:f="http://xmlns.jcp.org/jsf/core">
|
|
||||||
<f:view beforePhase="#{phaseListenerBean.beforeListener}">
|
|
||||||
<h:outputLabel value="Hello, #{userBean.name}"/>
|
|
||||||
<h:outputLabel id="new-feature-last-name" value=" #{userBean.lastName}"/>
|
|
||||||
</f:view>
|
|
||||||
</html>
|
|
@ -1,10 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
|
||||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
|
||||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
|
||||||
xmlns:h="http://xmlns.jcp.org/jsf/html"
|
|
||||||
xmlns:f="http://xmlns.jcp.org/jsf/core">
|
|
||||||
<f:view>
|
|
||||||
<h:outputLabel value="Hello, #{userBean.name} #{userBean.lastName}! Your login is: #{userBean.proposedLogin}"/>
|
|
||||||
</f:view>
|
|
||||||
</html>
|
|
@ -1,18 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
|
||||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
|
||||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
|
||||||
xmlns:h="http://xmlns.jcp.org/jsf/html"
|
|
||||||
xmlns:f="http://xmlns.jcp.org/jsf/core">
|
|
||||||
<f:view beforePhase="#{phaseListenerBean.beforeListener}">
|
|
||||||
<h:form>
|
|
||||||
<h:panelGrid columns="2">
|
|
||||||
<h:outputLabel value="First Name:"/>
|
|
||||||
<h:inputText id="name" value="#{userBean.name}"/>
|
|
||||||
<h:outputLabel id="new-feature-last-name-label" value="Last Name:"/>
|
|
||||||
<h:inputText id="new-feature-last-name" value="#{userBean.lastName}"/>
|
|
||||||
<h:commandButton value="Submit" action="#{greetControllerBean.greet}"/>
|
|
||||||
</h:panelGrid>
|
|
||||||
</h:form>
|
|
||||||
</f:view>
|
|
||||||
</html>
|
|
@ -1,31 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
|
||||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
|
||||||
<html xmlns="http://www.w3.org/1999/xhtml"
|
|
||||||
xmlns:h="http://xmlns.jcp.org/jsf/html"
|
|
||||||
xmlns:f="http://xmlns.jcp.org/jsf/core">
|
|
||||||
|
|
||||||
<h:head>
|
|
||||||
<h:outputScript library="javax.faces" name="jsf.js"/>
|
|
||||||
</h:head>
|
|
||||||
|
|
||||||
<f:view>
|
|
||||||
<h:form>
|
|
||||||
<h:panelGrid columns="2">
|
|
||||||
<h:outputLabel value="First Name:"/>
|
|
||||||
<h:inputText id="name" value="#{userBean.name}"
|
|
||||||
valueChangeListener="#{userBean.nameChanged}">
|
|
||||||
<f:ajax event="change" execute="@this" render="proposed-login"/>
|
|
||||||
</h:inputText>
|
|
||||||
<h:outputLabel id="lastname-label" value="Last Name:"/>
|
|
||||||
<h:inputText id="lastname" value="#{userBean.lastName}"
|
|
||||||
valueChangeListener="#{userBean.lastNameChanged}">
|
|
||||||
<f:ajax event="change" execute="@this" render="proposed-login"/>
|
|
||||||
</h:inputText>
|
|
||||||
<h:outputLabel id="login-label" value="Proposed Login:"/>
|
|
||||||
<h:inputText id="proposed-login" disabled="true" value="#{userBean.proposedLogin}"/>
|
|
||||||
<h:commandButton value="Submit" action="#{userControllerBean.register}"/>
|
|
||||||
</h:panelGrid>
|
|
||||||
</h:form>
|
|
||||||
</f:view>
|
|
||||||
</html>
|
|
4
guest/junit5-example/.gitignore
vendored
4
guest/junit5-example/.gitignore
vendored
@ -1,4 +0,0 @@
|
|||||||
/target/
|
|
||||||
.settings/
|
|
||||||
.classpath
|
|
||||||
.project
|
|
@ -1,57 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>junit5-example</groupId>
|
|
||||||
<artifactId>junit5-example</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>junit5-example</name>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
<relativePath>../../</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.junit.jupiter</groupId>
|
|
||||||
<artifactId>junit-jupiter-params</artifactId>
|
|
||||||
<version>${junit-jupiter.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.junit.vintage</groupId>
|
|
||||||
<artifactId>junit-vintage-engine</artifactId>
|
|
||||||
<version>${junit-jupiter.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.h2database</groupId>
|
|
||||||
<artifactId>h2</artifactId>
|
|
||||||
<version>${h2.version}</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
|
||||||
<artifactId>log4j-core</artifactId>
|
|
||||||
<version>${log4j-core.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.apache.maven.plugins</groupId>
|
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
|
||||||
<configuration>
|
|
||||||
<properties>
|
|
||||||
<excludeTags>math</excludeTags>
|
|
||||||
</properties>
|
|
||||||
</configuration>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<log4j-core.version>2.8.2</log4j-core.version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
|
@ -1,141 +0,0 @@
|
|||||||
package com.stackify.daos;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
|
||||||
import org.apache.logging.log4j.Logger;
|
|
||||||
|
|
||||||
import com.stackify.models.User;
|
|
||||||
import com.stackify.utils.ConnectionUtil;
|
|
||||||
|
|
||||||
public class UserDAO {
|
|
||||||
|
|
||||||
private Logger logger = LogManager.getLogger(UserDAO.class);
|
|
||||||
|
|
||||||
public void createTable() {
|
|
||||||
try (Connection con = ConnectionUtil.getConnection()) {
|
|
||||||
String createQuery = "CREATE TABLE users(email varchar(50) primary key, name varchar(50))";
|
|
||||||
PreparedStatement pstmt = con.prepareStatement(createQuery);
|
|
||||||
|
|
||||||
pstmt.execute();
|
|
||||||
} catch (SQLException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
public void add(User user) {
|
|
||||||
try (Connection con = ConnectionUtil.getConnection()) {
|
|
||||||
|
|
||||||
String insertQuery = "INSERT INTO users(email,name) VALUES(?,?)";
|
|
||||||
PreparedStatement pstmt = con.prepareStatement(insertQuery);
|
|
||||||
pstmt.setString(1, user.getEmail());
|
|
||||||
pstmt.setString(2, user.getName());
|
|
||||||
|
|
||||||
pstmt.executeUpdate();
|
|
||||||
} catch (SQLException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void update(User user) {
|
|
||||||
try (Connection con = ConnectionUtil.getConnection()) {
|
|
||||||
|
|
||||||
String updateQuery = "UPDATE users SET name=? WHERE email=?";
|
|
||||||
PreparedStatement pstmt = con.prepareStatement(updateQuery);
|
|
||||||
pstmt.setString(1, user.getName());
|
|
||||||
pstmt.setString(2, user.getEmail());
|
|
||||||
|
|
||||||
pstmt.executeUpdate();
|
|
||||||
} catch (SQLException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void delete(User user) {
|
|
||||||
try (Connection con = ConnectionUtil.getConnection()) {
|
|
||||||
|
|
||||||
String deleteQuery = "DELETE FROM users WHERE email=?";
|
|
||||||
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
|
|
||||||
pstmt.setString(1, user.getEmail());
|
|
||||||
|
|
||||||
pstmt.executeUpdate();
|
|
||||||
} catch (SQLException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void delete(String email) {
|
|
||||||
try (Connection con = ConnectionUtil.getConnection()) {
|
|
||||||
|
|
||||||
String deleteQuery = "DELETE FROM users WHERE email=?";
|
|
||||||
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
|
|
||||||
pstmt.setString(1, email);
|
|
||||||
|
|
||||||
pstmt.executeUpdate();
|
|
||||||
} catch (SQLException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public User findOne(String email) {
|
|
||||||
User user = null;
|
|
||||||
|
|
||||||
try (Connection con = ConnectionUtil.getConnection()) {
|
|
||||||
String query = "SELECT * FROM users WHERE email=?";
|
|
||||||
PreparedStatement pstmt = con.prepareStatement(query);
|
|
||||||
pstmt.setString(1, email);
|
|
||||||
|
|
||||||
ResultSet rs = pstmt.executeQuery();
|
|
||||||
while (rs.next()) {
|
|
||||||
user = new User();
|
|
||||||
user.setEmail(rs.getString("email"));
|
|
||||||
user.setName(rs.getString("name"));
|
|
||||||
}
|
|
||||||
|
|
||||||
} catch (SQLException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
public List<User> findAll() {
|
|
||||||
List<User> users = new ArrayList<>();
|
|
||||||
|
|
||||||
try (Connection con = ConnectionUtil.getConnection()) {
|
|
||||||
String query = "SELECT * FROM users";
|
|
||||||
PreparedStatement pstmt = con.prepareStatement(query);
|
|
||||||
|
|
||||||
ResultSet rs = pstmt.executeQuery();
|
|
||||||
while (rs.next()) {
|
|
||||||
User user = new User();
|
|
||||||
user.setEmail(rs.getString("email"));
|
|
||||||
user.setName(rs.getString("name"));
|
|
||||||
users.add(user);
|
|
||||||
}
|
|
||||||
} catch (SQLException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
return users;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void deleteAll() {
|
|
||||||
try (Connection con = ConnectionUtil.getConnection()) {
|
|
||||||
|
|
||||||
String deleteQuery = "DELETE FROM users";
|
|
||||||
PreparedStatement pstmt = con.prepareStatement(deleteQuery);
|
|
||||||
|
|
||||||
pstmt.executeUpdate();
|
|
||||||
} catch (SQLException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,63 +0,0 @@
|
|||||||
package com.stackify.models;
|
|
||||||
|
|
||||||
public class User {
|
|
||||||
private String email;
|
|
||||||
private String name;
|
|
||||||
|
|
||||||
public User() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public User(String email, String name) {
|
|
||||||
super();
|
|
||||||
this.email = email;
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getEmail() {
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setEmail(String email) {
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public int hashCode() {
|
|
||||||
final int prime = 31;
|
|
||||||
int result = 1;
|
|
||||||
result = prime * result + ((email == null) ? 0 : email.hashCode());
|
|
||||||
result = prime * result + ((name == null) ? 0 : name.hashCode());
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean equals(Object obj) {
|
|
||||||
if (this == obj)
|
|
||||||
return true;
|
|
||||||
if (obj == null)
|
|
||||||
return false;
|
|
||||||
if (getClass() != obj.getClass())
|
|
||||||
return false;
|
|
||||||
User other = (User) obj;
|
|
||||||
if (email == null) {
|
|
||||||
if (other.email != null)
|
|
||||||
return false;
|
|
||||||
} else if (!email.equals(other.email))
|
|
||||||
return false;
|
|
||||||
if (name == null) {
|
|
||||||
if (other.name != null)
|
|
||||||
return false;
|
|
||||||
} else if (!name.equals(other.name))
|
|
||||||
return false;
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,15 +0,0 @@
|
|||||||
package com.stackify.test.conditions;
|
|
||||||
|
|
||||||
import java.lang.annotation.ElementType;
|
|
||||||
import java.lang.annotation.Retention;
|
|
||||||
import java.lang.annotation.RetentionPolicy;
|
|
||||||
import java.lang.annotation.Target;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
|
||||||
|
|
||||||
@Target({ ElementType.METHOD })
|
|
||||||
@Retention(RetentionPolicy.RUNTIME)
|
|
||||||
@ExtendWith(DisabledOnEnvironmentCondition.class)
|
|
||||||
public @interface DisabledOnEnvironment {
|
|
||||||
String[] value();
|
|
||||||
}
|
|
@ -1,38 +0,0 @@
|
|||||||
package com.stackify.test.conditions;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Optional;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.extension.ConditionEvaluationResult;
|
|
||||||
import org.junit.jupiter.api.extension.TestExecutionCondition;
|
|
||||||
import org.junit.jupiter.api.extension.TestExtensionContext;
|
|
||||||
import org.junit.platform.commons.support.AnnotationSupport;
|
|
||||||
|
|
||||||
import com.stackify.utils.ConnectionUtil;
|
|
||||||
|
|
||||||
public class DisabledOnEnvironmentCondition implements TestExecutionCondition {
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public ConditionEvaluationResult evaluate(TestExtensionContext context) {
|
|
||||||
Properties props = new Properties();
|
|
||||||
String env = "";
|
|
||||||
try {
|
|
||||||
props.load(ConnectionUtil.class.getResourceAsStream("/application.properties"));
|
|
||||||
env = props.getProperty("env");
|
|
||||||
} catch (IOException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
Optional<DisabledOnEnvironment> disabled = AnnotationSupport.findAnnotation(context.getElement().get(), DisabledOnEnvironment.class);
|
|
||||||
if (disabled.isPresent()) {
|
|
||||||
String[] envs = disabled.get().value();
|
|
||||||
if (Arrays.asList(envs).contains(env)) {
|
|
||||||
return ConditionEvaluationResult.disabled("Disabled on environment " + env);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ConditionEvaluationResult.enabled("Enabled on environment "+env);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,38 +0,0 @@
|
|||||||
package com.stackify.utils;
|
|
||||||
|
|
||||||
import java.io.FileNotFoundException;
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.DriverManager;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
import java.util.Properties;
|
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
|
||||||
import org.apache.logging.log4j.Logger;
|
|
||||||
|
|
||||||
public class ConnectionUtil {
|
|
||||||
|
|
||||||
private static Logger logger = LogManager.getLogger(ConnectionUtil.class);
|
|
||||||
|
|
||||||
public static Connection getConnection() {
|
|
||||||
try {
|
|
||||||
Properties props = new Properties();
|
|
||||||
props.load(ConnectionUtil.class.getResourceAsStream("jdbc.properties"));
|
|
||||||
Class.forName(props.getProperty("jdbc.driver"));
|
|
||||||
Connection con = DriverManager.getConnection(props.getProperty("jdbc.url"), props.getProperty("jdbc.user"), props.getProperty("jdbc.password"));
|
|
||||||
return con;
|
|
||||||
}
|
|
||||||
|
|
||||||
catch (FileNotFoundException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
} catch (IOException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
} catch (ClassNotFoundException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
} catch (SQLException exc) {
|
|
||||||
logger.error(exc.getMessage());
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
env=dev
|
|
@ -1,4 +0,0 @@
|
|||||||
jdbc.driver=org.h2.Driver
|
|
||||||
jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
|
|
||||||
jdbc.user=
|
|
||||||
jdbc.password=
|
|
@ -1,13 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<Configuration status="WARN">
|
|
||||||
<Appenders>
|
|
||||||
<Console name="Console" target="SYSTEM_OUT">
|
|
||||||
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
|
|
||||||
</Console>
|
|
||||||
</Appenders>
|
|
||||||
<Loggers>
|
|
||||||
<Root level="info">
|
|
||||||
<AppenderRef ref="Console"/>
|
|
||||||
</Root>
|
|
||||||
</Loggers>
|
|
||||||
</Configuration>
|
|
@ -1,19 +0,0 @@
|
|||||||
package com.stackify.test;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import com.stackify.utils.ConnectionUtil;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
|
|
||||||
public interface DatabaseConnectionTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
default void testDatabaseConnection() {
|
|
||||||
Connection con = ConnectionUtil.getConnection();
|
|
||||||
assertNotNull(con);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,38 +0,0 @@
|
|||||||
package com.stackify.test;
|
|
||||||
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collection;
|
|
||||||
import java.util.List;
|
|
||||||
import java.util.function.Function;
|
|
||||||
import java.util.stream.Stream;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
import org.junit.jupiter.api.DynamicTest;
|
|
||||||
import org.junit.jupiter.api.TestFactory;
|
|
||||||
import org.junit.jupiter.api.function.ThrowingConsumer;
|
|
||||||
|
|
||||||
import com.stackify.daos.UserDAO;
|
|
||||||
import com.stackify.models.User;
|
|
||||||
|
|
||||||
public class DynamicTests {
|
|
||||||
|
|
||||||
@TestFactory
|
|
||||||
public Collection<DynamicTest> dynamicTestCollection() {
|
|
||||||
return Arrays.asList(DynamicTest.dynamicTest("Dynamic Test", () -> assertTrue(1 == 1)));
|
|
||||||
}
|
|
||||||
|
|
||||||
@TestFactory
|
|
||||||
public Stream<DynamicTest> dynamicUserTestCollection() {
|
|
||||||
List<User> inputList = Arrays.asList(new User("john@yahoo.com", "John"), new User("ana@yahoo.com", "Ana"));
|
|
||||||
|
|
||||||
Function<User, String> displayNameGenerator = (input) -> "Saving user: " + input;
|
|
||||||
|
|
||||||
UserDAO userDAO = new UserDAO();
|
|
||||||
ThrowingConsumer<User> testExecutor = (input) -> {
|
|
||||||
userDAO.add(input);
|
|
||||||
assertNotNull(userDAO.findOne(input.getEmail()));
|
|
||||||
};
|
|
||||||
|
|
||||||
return DynamicTest.stream(inputList.iterator(), displayNameGenerator, testExecutor);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,25 +0,0 @@
|
|||||||
package com.stackify.test;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
|
||||||
import org.apache.logging.log4j.Logger;
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.RepeatedTest;
|
|
||||||
import org.junit.jupiter.api.RepetitionInfo;
|
|
||||||
|
|
||||||
public class IncrementTest {
|
|
||||||
|
|
||||||
private static Logger logger = LogManager.getLogger(IncrementTest.class);
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
public void increment() {
|
|
||||||
logger.info("Before Each Test");
|
|
||||||
}
|
|
||||||
|
|
||||||
@RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME)
|
|
||||||
public void test(RepetitionInfo info) {
|
|
||||||
assertTrue(1 == 1);
|
|
||||||
logger.info("Repetition #" + info.getCurrentRepetition());
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,16 +0,0 @@
|
|||||||
package com.stackify.test;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
import org.junit.jupiter.api.Tag;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
@Tag("math")
|
|
||||||
public class TaggedTest {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Tag("arithmetic")
|
|
||||||
public void testEquals() {
|
|
||||||
assertTrue(1 == 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,155 +0,0 @@
|
|||||||
package com.stackify.test;
|
|
||||||
|
|
||||||
import org.apache.logging.log4j.LogManager;
|
|
||||||
import org.apache.logging.log4j.Logger;
|
|
||||||
import org.junit.jupiter.api.AfterAll;
|
|
||||||
import org.junit.jupiter.api.BeforeAll;
|
|
||||||
import org.junit.jupiter.api.Disabled;
|
|
||||||
import org.junit.jupiter.api.DisplayName;
|
|
||||||
import org.junit.jupiter.api.Nested;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.junit.jupiter.api.TestInfo;
|
|
||||||
import org.junit.jupiter.params.ParameterizedTest;
|
|
||||||
import org.junit.jupiter.params.provider.ValueSource;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
import static org.junit.jupiter.api.Assumptions.*;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.Arrays;
|
|
||||||
import java.util.Collections;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import com.stackify.daos.UserDAO;
|
|
||||||
import com.stackify.models.User;
|
|
||||||
|
|
||||||
import com.stackify.test.conditions.DisabledOnEnvironment;
|
|
||||||
|
|
||||||
public class UsersTest implements DatabaseConnectionTest {
|
|
||||||
|
|
||||||
private static UserDAO userDAO;
|
|
||||||
|
|
||||||
private static Logger logger = LogManager.getLogger(UsersTest.class);
|
|
||||||
|
|
||||||
@BeforeAll
|
|
||||||
public static void addData() {
|
|
||||||
userDAO = new UserDAO();
|
|
||||||
userDAO.createTable();
|
|
||||||
|
|
||||||
User user1 = new User("john@gmail.com", "John");
|
|
||||||
User user2 = new User("ana@gmail.com", "Ana");
|
|
||||||
userDAO.add(user1);
|
|
||||||
userDAO.add(user2);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@DisplayName("Test Get Users")
|
|
||||||
public void testGetUsersNumber() {
|
|
||||||
assertEquals(2, userDAO.findAll().size());
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@DisplayName("Test Get Users")
|
|
||||||
public void testGetUsersNumberWithInfo(TestInfo testInfo) {
|
|
||||||
assertEquals(2, userDAO.findAll().size());
|
|
||||||
assertEquals("Test Get Users", testInfo.getDisplayName());
|
|
||||||
assertEquals(UsersTest.class, testInfo.getTestClass().get());
|
|
||||||
logger.info("Running test method:" + testInfo.getTestMethod().get().getName());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testGetUser() {
|
|
||||||
User user = userDAO.findOne("john@gmail.com");
|
|
||||||
assertEquals("John", user.getName(), "User name:" + user.getName() + " incorrect");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testClassicAssertions() {
|
|
||||||
User user1 = userDAO.findOne("john@gmail.com");
|
|
||||||
User user2 = userDAO.findOne("john@yahoo.com");
|
|
||||||
|
|
||||||
assertNotNull(user1);
|
|
||||||
assertNull(user2);
|
|
||||||
|
|
||||||
user2 = new User("john@yahoo.com", "John");
|
|
||||||
assertEquals(user1.getName(), user2.getName(), "Names are not equal");
|
|
||||||
assertFalse(user1.getEmail().equals(user2.getEmail()), "Emails are equal");
|
|
||||||
assertNotSame(user1, user2);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@Disabled
|
|
||||||
public void testGroupedAssertions() {
|
|
||||||
User user = userDAO.findOne("john@gmail.com");
|
|
||||||
assertAll("user", () -> assertEquals("Johnson", user.getName()), () -> assertEquals("johnson@gmail.com", user.getEmail()));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testIterableEquals() {
|
|
||||||
User user1 = new User("john@gmail.com", "John");
|
|
||||||
User user2 = new User("ana@gmail.com", "Ana");
|
|
||||||
|
|
||||||
List<User> users = new ArrayList<>();
|
|
||||||
users.add(user1);
|
|
||||||
users.add(user2);
|
|
||||||
|
|
||||||
assertIterableEquals(users, userDAO.findAll());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testLinesMatch() {
|
|
||||||
List<String> expectedLines = Collections.singletonList("(.*)@(.*)");
|
|
||||||
List<String> emails = Arrays.asList("john@gmail.com");
|
|
||||||
assertLinesMatch(expectedLines, emails);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testThrows() {
|
|
||||||
User user = null;
|
|
||||||
Exception exception = assertThrows(NullPointerException.class, () -> user.getName());
|
|
||||||
logger.info(exception.getMessage());
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
@DisabledOnEnvironment({ "dev", "prod")
|
|
||||||
void testFail() {
|
|
||||||
fail("this test fails");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testAssumptions() {
|
|
||||||
List<User> users = userDAO.findAll();
|
|
||||||
assumeFalse(users == null);
|
|
||||||
assumeTrue(users.size() > 0);
|
|
||||||
|
|
||||||
User user1 = new User("john@gmail.com", "John");
|
|
||||||
|
|
||||||
assumingThat(users.contains(user1), () -> assertTrue(users.size() > 1));
|
|
||||||
}
|
|
||||||
|
|
||||||
@ParameterizedTest
|
|
||||||
@ValueSource(strings = { "john@gmail.com", "ana@gmail.com" })
|
|
||||||
public void testParameterized(String email) {
|
|
||||||
assertNotNull(userDAO.findOne(email));
|
|
||||||
}
|
|
||||||
|
|
||||||
@AfterAll
|
|
||||||
public static void removeData() {
|
|
||||||
userDAO.deleteAll();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Nested
|
|
||||||
class DeleteUsersTest {
|
|
||||||
@Test
|
|
||||||
public void addUser() {
|
|
||||||
User user = new User("bob@gmail.com", "Bob");
|
|
||||||
userDAO.add(user);
|
|
||||||
assertNotNull(userDAO.findOne("bob@gmail.com"));
|
|
||||||
|
|
||||||
userDAO.delete("bob@gmail.com");
|
|
||||||
assertNull(userDAO.findOne("bob@gmail.com"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
4
guest/log4j2-example/.gitignore
vendored
4
guest/log4j2-example/.gitignore
vendored
@ -1,4 +0,0 @@
|
|||||||
/target/
|
|
||||||
.settings/
|
|
||||||
.classpath
|
|
||||||
.project
|
|
@ -1,3 +0,0 @@
|
|||||||
14:00:35.258 INFO Programmatic Logger Message
|
|
||||||
14:03:51.178 INFO Programmatic Logger Message
|
|
||||||
14:04:11.753 INFO Programmatic Logger Message
|
|
@ -1,25 +0,0 @@
|
|||||||
[
|
|
||||||
{
|
|
||||||
"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
|
|
||||||
}
|
|
||||||
|
|
||||||
]
|
|
@ -1,48 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>log4j2-example</groupId>
|
|
||||||
<artifactId>log4j2-example</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>log4j2-example</name>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
<relativePath>../../</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<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>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<resources>
|
|
||||||
<resource>
|
|
||||||
<directory>src/main/resources/</directory>
|
|
||||||
<excludes>
|
|
||||||
<exclude>**/*.java</exclude>
|
|
||||||
</excludes>
|
|
||||||
</resource>
|
|
||||||
</resources>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<log4j-core.version>2.8.2</log4j-core.version>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,43 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,14 +0,0 @@
|
|||||||
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();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,62 +0,0 @@
|
|||||||
<?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>
|
|
@ -1,81 +0,0 @@
|
|||||||
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 MyServiceUnitTest {
|
|
||||||
|
|
||||||
private static final Logger logger = LogManager.getLogger(MyServiceUnitTest.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");
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,28 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>com.stackify</groupId>
|
|
||||||
<artifactId>logback-example</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>logback-example</name>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.baeldung</groupId>
|
|
||||||
<artifactId>parent-modules</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
<relativePath>../../</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.codehaus.janino</groupId>
|
|
||||||
<artifactId>janino</artifactId>
|
|
||||||
<version>${janino.version}</version>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<janino.version>3.0.7</janino.version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
|
@ -1,28 +0,0 @@
|
|||||||
package com.stackify.logging;
|
|
||||||
|
|
||||||
import org.slf4j.Marker;
|
|
||||||
|
|
||||||
import ch.qos.logback.classic.Level;
|
|
||||||
import ch.qos.logback.classic.Logger;
|
|
||||||
import ch.qos.logback.classic.turbo.TurboFilter;
|
|
||||||
import ch.qos.logback.core.spi.FilterReply;
|
|
||||||
|
|
||||||
public class IgnoreLoggerFilter extends TurboFilter {
|
|
||||||
|
|
||||||
private String loggerName;
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public FilterReply decide(Marker marker, Logger logger, Level level, String format, Object[] params, Throwable t) {
|
|
||||||
if (loggerName == null) {
|
|
||||||
return FilterReply.NEUTRAL;
|
|
||||||
} else if (loggerName.equals(logger.getName())) {
|
|
||||||
return FilterReply.DENY;
|
|
||||||
} else
|
|
||||||
return FilterReply.NEUTRAL;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLoggerName(String loggerName) {
|
|
||||||
this.loggerName = loggerName;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,43 +0,0 @@
|
|||||||
package com.stackify.models;
|
|
||||||
|
|
||||||
public class Employee {
|
|
||||||
|
|
||||||
private String email;
|
|
||||||
private String name;
|
|
||||||
|
|
||||||
private double salary;
|
|
||||||
|
|
||||||
public Employee() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public Employee(String email, String name, double salary) {
|
|
||||||
this.email = email;
|
|
||||||
this.name = name;
|
|
||||||
this.salary = salary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getEmail() {
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setEmail(String email) {
|
|
||||||
this.email = email;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getName() {
|
|
||||||
return name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setName(String name) {
|
|
||||||
this.name = name;
|
|
||||||
}
|
|
||||||
|
|
||||||
public double getSalary() {
|
|
||||||
return salary;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setSalary(double salary) {
|
|
||||||
this.salary = salary;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,11 +0,0 @@
|
|||||||
package com.stackify.services;
|
|
||||||
|
|
||||||
import com.stackify.models.Employee;
|
|
||||||
|
|
||||||
public class EmployeeService {
|
|
||||||
|
|
||||||
public double calculateBonus(Employee user) {
|
|
||||||
return 0.1 * user.getSalary();
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1 +0,0 @@
|
|||||||
env=dev
|
|
@ -1,151 +0,0 @@
|
|||||||
<configuration debug="true">
|
|
||||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
|
||||||
<encoder>
|
|
||||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
|
|
||||||
</encoder>
|
|
||||||
<target>System.out</target>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<property name="fileName" value="file.log" />
|
|
||||||
<property scope="context" resource="application.properties" />
|
|
||||||
|
|
||||||
<!-- configure appenders -->
|
|
||||||
<appender name="rollingFileAppender" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
|
||||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
|
||||||
<fileNamePattern>log-%d{yyyy-MM-dd}.log</fileNamePattern>
|
|
||||||
<maxHistory>30</maxHistory>
|
|
||||||
<totalSizeCap>3GB</totalSizeCap>
|
|
||||||
</rollingPolicy>
|
|
||||||
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
|
|
||||||
<maxFileSize>3MB</maxFileSize>
|
|
||||||
</triggeringPolicy>
|
|
||||||
<encoder>
|
|
||||||
<pattern>%d [%thread] %-5level %logger{50} - %msg%n</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<appender name="roleSiftingAppender" class="ch.qos.logback.classic.sift.SiftingAppender">
|
|
||||||
<discriminator>
|
|
||||||
<key>userRole</key>
|
|
||||||
<defaultValue>ANONYMOUS</defaultValue>
|
|
||||||
</discriminator>
|
|
||||||
<sift>
|
|
||||||
<appender name="fileAppender" class="ch.qos.logback.core.FileAppender">
|
|
||||||
<file>${userRole}.log</file>
|
|
||||||
<layout class="ch.qos.logback.classic.PatternLayout">
|
|
||||||
<pattern>%d [%thread] %level %mdc %logger{50} - %msg%n</pattern>
|
|
||||||
</layout>
|
|
||||||
</appender>
|
|
||||||
</sift>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<!-- configure layouts -->
|
|
||||||
<appender name="colorAppender" class="ch.qos.logback.core.ConsoleAppender">
|
|
||||||
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
|
|
||||||
<pattern>%d %green([%thread]) %highlight(%level) %logger{50} - %msg%n</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<appender name="htmlAppender" class="ch.qos.logback.core.FileAppender">
|
|
||||||
<encoder class="ch.qos.logback.core.encoder.LayoutWrappingEncoder">
|
|
||||||
<layout class="ch.qos.logback.classic.html.HTMLLayout">
|
|
||||||
<pattern>%thread%level%logger%msg</pattern>
|
|
||||||
</layout>
|
|
||||||
</encoder>
|
|
||||||
<file>log.html</file>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<!-- configure filters -->
|
|
||||||
<appender name="STDOUT_LEVEL_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
|
|
||||||
<filter class="ch.qos.logback.classic.filter.LevelFilter">
|
|
||||||
<level>ERROR</level>
|
|
||||||
<onMatch>ACCEPT</onMatch>
|
|
||||||
<onMismatch>DENY</onMismatch>
|
|
||||||
</filter>
|
|
||||||
<encoder>
|
|
||||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
|
|
||||||
</encoder>
|
|
||||||
<target>System.err</target>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<appender name="STDOUT_THRESHOLD_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
|
|
||||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
|
|
||||||
<level>WARN</level>
|
|
||||||
</filter>
|
|
||||||
<encoder>
|
|
||||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<appender name="STDOUT_EVALUATOR_FILTER_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
|
|
||||||
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
|
|
||||||
<evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
|
|
||||||
<expression>return (level > DEBUG && message.toLowerCase().contains("employee"));</expression>
|
|
||||||
</evaluator>
|
|
||||||
<OnMismatch>DENY</OnMismatch>
|
|
||||||
<OnMatch>NEUTRAL</OnMatch>
|
|
||||||
</filter>
|
|
||||||
<encoder>
|
|
||||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<!-- configure turbo filters -->
|
|
||||||
<turboFilter class="ch.qos.logback.classic.turbo.DuplicateMessageFilter">
|
|
||||||
<AllowedRepetitions>2</AllowedRepetitions>
|
|
||||||
</turboFilter>
|
|
||||||
|
|
||||||
<turboFilter class="com.stackify.logging.IgnoreLoggerFilter">
|
|
||||||
<LoggerName>ignoredColorLogger</LoggerName>
|
|
||||||
</turboFilter>
|
|
||||||
|
|
||||||
<!-- configure loggers -->
|
|
||||||
<logger level="info" name="rollingFileLogger" additivity="false">
|
|
||||||
<appender-ref ref="rollingFileAppender" />
|
|
||||||
</logger>
|
|
||||||
|
|
||||||
<logger level="info" name="htmlLogger" additivity="false">
|
|
||||||
<appender-ref ref="htmlAppender" />
|
|
||||||
</logger>
|
|
||||||
|
|
||||||
<logger level="info" name="roleSiftingLogger" additivity="false">
|
|
||||||
<appender-ref ref="roleSiftingAppender" />
|
|
||||||
</logger>
|
|
||||||
|
|
||||||
<logger level="info" name="colorLogger" additivity="false">
|
|
||||||
<appender-ref ref="colorAppender" />
|
|
||||||
</logger>
|
|
||||||
|
|
||||||
<logger level="info" name="ignoredColorLogger">
|
|
||||||
<appender-ref ref="colorAppender" />
|
|
||||||
</logger>
|
|
||||||
|
|
||||||
<logger level="info" name="levelFilterLogger" additivity="false">
|
|
||||||
<appender-ref ref="STDOUT_LEVEL_FILTER_APPENDER" />
|
|
||||||
</logger>
|
|
||||||
|
|
||||||
<logger level="info" name="thresholdFilterLogger" additivity="false">
|
|
||||||
<appender-ref ref="STDOUT_THRESHOLD_FILTER_APPENDER" />
|
|
||||||
</logger>
|
|
||||||
|
|
||||||
<logger level="info" name="evaluatorFilterLogger" additivity="false">
|
|
||||||
<appender-ref ref="STDOUT_EVALUATOR_FILTER_APPENDER" />
|
|
||||||
</logger>
|
|
||||||
|
|
||||||
<!-- configure root logger -->
|
|
||||||
<root level="INFO">
|
|
||||||
<appender-ref ref="STDOUT" />
|
|
||||||
</root>
|
|
||||||
|
|
||||||
<!-- configure root logger conditionally -->
|
|
||||||
<property scope="context" resource="application.properties" />
|
|
||||||
|
|
||||||
<if condition='property("env").equals("dev")'>
|
|
||||||
<then>
|
|
||||||
<root level="TRACE">
|
|
||||||
<appender-ref ref="STDOUT" />
|
|
||||||
</root>
|
|
||||||
</then>
|
|
||||||
</if>
|
|
||||||
|
|
||||||
</configuration>
|
|
@ -1,74 +0,0 @@
|
|||||||
package com.stackify.services;
|
|
||||||
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.slf4j.MDC;
|
|
||||||
|
|
||||||
import com.stackify.models.Employee;
|
|
||||||
|
|
||||||
import ch.qos.logback.classic.Level;
|
|
||||||
|
|
||||||
public class EmployeeServiceUnitTest {
|
|
||||||
private static final Logger logger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
|
|
||||||
|
|
||||||
private EmployeeService employeeService = new EmployeeService();
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testAppenders() {
|
|
||||||
Logger rollingFileLogger = LoggerFactory.getLogger("rollingFileLogger");
|
|
||||||
rollingFileLogger.info("Testing rolling file logger");
|
|
||||||
|
|
||||||
MDC.put("userRole", "ADMIN");
|
|
||||||
Logger siftingLogger = LoggerFactory.getLogger("roleSiftingLogger");
|
|
||||||
siftingLogger.info("Admin Action");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testLayouts() {
|
|
||||||
Logger htmlLogger = LoggerFactory.getLogger("htmlLogger");
|
|
||||||
htmlLogger.error("Employee Information Update Failed");
|
|
||||||
htmlLogger.info("New Account Created");
|
|
||||||
|
|
||||||
Logger colorLogger = LoggerFactory.getLogger("colorLogger");
|
|
||||||
colorLogger.error("Employee Information Update Failed");
|
|
||||||
colorLogger.info("New Account Created");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testLogLevel() {
|
|
||||||
ch.qos.logback.classic.Logger rollingFileLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("rollingFileLogger");
|
|
||||||
rollingFileLogger.setLevel(Level.DEBUG);
|
|
||||||
rollingFileLogger.debug("Testing Log Level");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testParameter() {
|
|
||||||
Employee employee = new Employee("john@gmail.com", "John", 2000);
|
|
||||||
if (logger.isDebugEnabled()) {
|
|
||||||
logger.debug("The bonus for employee: " + employee.getName() + " is " + employeeService.calculateBonus(employee));
|
|
||||||
}
|
|
||||||
logger.debug("The bonus for employee {} is {}", employee.getName(), employeeService.calculateBonus(employee));
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testFilters() {
|
|
||||||
Logger levelFilterLogger = LoggerFactory.getLogger("levelFilterLogger");
|
|
||||||
levelFilterLogger.error("Employee Information Update Failed");
|
|
||||||
Logger thresholdFilterLogger = LoggerFactory.getLogger("thresholdFilterLogger");
|
|
||||||
thresholdFilterLogger.trace("Employee record inserted");
|
|
||||||
Logger evaluatorFilterLogger = LoggerFactory.getLogger("evaluatorFilterLogger");
|
|
||||||
evaluatorFilterLogger.debug("Employee account deactivated");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testIgnoredLogger() {
|
|
||||||
Logger colorLogger = LoggerFactory.getLogger("ignoredColorLogger");
|
|
||||||
colorLogger.info("Ignored Log Message");
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testConditionalConfiguration() {
|
|
||||||
logger.trace("Employee record updated");
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,16 +0,0 @@
|
|||||||
## Building
|
|
||||||
|
|
||||||
To build the module, use Maven's `package` goal:
|
|
||||||
|
|
||||||
```
|
|
||||||
mvn clean package
|
|
||||||
```
|
|
||||||
|
|
||||||
The `war` file will be available at `target/remote-debugging.war`
|
|
||||||
|
|
||||||
## Running
|
|
||||||
|
|
||||||
The `war` application is deployed to Apache Tomcat 8 or any other Java Web or Application server.
|
|
||||||
To deploy it to the Apache Tomcat 8 server, drop it in the `tomcat/webapps` directory.
|
|
||||||
|
|
||||||
The service then will be accessible at http://localhost:8080/remote-debugging/hello?name=John
|
|
@ -1,44 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>com.stackify</groupId>
|
|
||||||
<artifactId>remote-debugging</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>remote-debugging</name>
|
|
||||||
<packaging>war</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
|
||||||
<version>1.5.8.RELEASE</version>
|
|
||||||
<relativePath/> <!-- lookup parent from repository -->
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-tomcat</artifactId>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<finalName>remote-debugging</finalName>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
</properties>
|
|
||||||
|
|
||||||
</project>
|
|
@ -1,12 +0,0 @@
|
|||||||
package com.stackify.debug;
|
|
||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|
||||||
|
|
||||||
@SpringBootApplication
|
|
||||||
public class JavaRemoteDebuggingApplication {
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
SpringApplication.run(JavaRemoteDebuggingApplication.class, args);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,12 +0,0 @@
|
|||||||
package com.stackify.debug.config;
|
|
||||||
|
|
||||||
import com.stackify.debug.JavaRemoteDebuggingApplication;
|
|
||||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
|
||||||
import org.springframework.boot.web.support.SpringBootServletInitializer;
|
|
||||||
|
|
||||||
public class WebInitializer extends SpringBootServletInitializer {
|
|
||||||
@Override
|
|
||||||
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
|
|
||||||
return application.sources(JavaRemoteDebuggingApplication.class);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,16 +0,0 @@
|
|||||||
package com.stackify.debug.rest;
|
|
||||||
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestParam;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
@RestController("/hello")
|
|
||||||
public class HelloController {
|
|
||||||
|
|
||||||
@GetMapping
|
|
||||||
public String hello(@RequestParam("name") String name) {
|
|
||||||
String message = "Hello, " + name;
|
|
||||||
return message;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -1,13 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<configuration>
|
|
||||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
|
||||||
<encoder>
|
|
||||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
|
||||||
</pattern>
|
|
||||||
</encoder>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<root level="INFO">
|
|
||||||
<appender-ref ref="STDOUT" />
|
|
||||||
</root>
|
|
||||||
</configuration>
|
|
@ -1,62 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<groupId>com.stackify.slf4j.guide</groupId>
|
|
||||||
<artifactId>slf4j-parent-module</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
<name>slf4j-parent-module</name>
|
|
||||||
<packaging>pom</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-parent</artifactId>
|
|
||||||
<version>2.0.6.RELEASE</version>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<modules>
|
|
||||||
<module>slf4j-logback</module>
|
|
||||||
<module>slf4j-log4j2</module>
|
|
||||||
<module>slf4j-log4j</module>
|
|
||||||
</modules>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.powermock</groupId>
|
|
||||||
<artifactId>powermock-module-junit4</artifactId>
|
|
||||||
<version>${powermock.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.powermock</groupId>
|
|
||||||
<artifactId>powermock-api-mockito2</artifactId>
|
|
||||||
<version>${powermock.version}</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<build>
|
|
||||||
<plugins>
|
|
||||||
<plugin>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
|
||||||
</plugin>
|
|
||||||
</plugins>
|
|
||||||
</build>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
|
||||||
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
|
|
||||||
<java.version>1.8</java.version>
|
|
||||||
<powermock.version>2.0.0-beta.5</powermock.version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
|
25
guest/slf4j/guide/slf4j-log4j/.gitignore
vendored
25
guest/slf4j/guide/slf4j-log4j/.gitignore
vendored
@ -1,25 +0,0 @@
|
|||||||
/target/
|
|
||||||
!.mvn/wrapper/maven-wrapper.jar
|
|
||||||
|
|
||||||
### STS ###
|
|
||||||
.apt_generated
|
|
||||||
.classpath
|
|
||||||
.factorypath
|
|
||||||
.project
|
|
||||||
.settings
|
|
||||||
.springBeans
|
|
||||||
.sts4-cache
|
|
||||||
|
|
||||||
### IntelliJ IDEA ###
|
|
||||||
.idea
|
|
||||||
*.iws
|
|
||||||
*.iml
|
|
||||||
*.ipr
|
|
||||||
|
|
||||||
### NetBeans ###
|
|
||||||
/nbproject/private/
|
|
||||||
/build/
|
|
||||||
/nbbuild/
|
|
||||||
/dist/
|
|
||||||
/nbdist/
|
|
||||||
/.nb-gradle/
|
|
@ -1,42 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<artifactId>slf4j-log4j</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>slf4j-log4j</name>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.stackify.slf4j.guide</groupId>
|
|
||||||
<artifactId>slf4j-parent-module</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
<relativePath>..</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-logging</artifactId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.slf4j</groupId>
|
|
||||||
<artifactId>slf4j-log4j12</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<slf4j.log4j.version>1.7.25</slf4j.log4j.version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
|
@ -1,12 +0,0 @@
|
|||||||
package com.stackify.slf4j.guide;
|
|
||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|
||||||
|
|
||||||
@SpringBootApplication
|
|
||||||
public class Application {
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
SpringApplication.run(Application.class, args);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,42 +0,0 @@
|
|||||||
package com.stackify.slf4j.guide.controllers;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.slf4j.MDC;
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestHeader;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
public class SimpleController {
|
|
||||||
|
|
||||||
Logger logger = LoggerFactory.getLogger(SimpleController.class);
|
|
||||||
|
|
||||||
@GetMapping("/slf4j-guide-request")
|
|
||||||
public String processList(List<String> list) {
|
|
||||||
logger.info("Client requested process the following list: {}", list);
|
|
||||||
try {
|
|
||||||
logger.debug("Starting process");
|
|
||||||
// ...processing list here...
|
|
||||||
Thread.sleep(500);
|
|
||||||
} catch (RuntimeException | InterruptedException e) {
|
|
||||||
logger.error("There was an issue processing the list.", e);
|
|
||||||
} finally {
|
|
||||||
logger.info("Finished processing");
|
|
||||||
}
|
|
||||||
return "done";
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/slf4j-guide-mdc-request")
|
|
||||||
public String clientMDCRequest(@RequestHeader String clientId) throws InterruptedException {
|
|
||||||
MDC.put("clientId", clientId);
|
|
||||||
logger.info("Client {} has made a request", clientId);
|
|
||||||
logger.info("Starting request");
|
|
||||||
Thread.sleep(500);
|
|
||||||
logger.info("Finished request");
|
|
||||||
MDC.clear();
|
|
||||||
return "finished";
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,17 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8" ?>
|
|
||||||
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
|
|
||||||
|
|
||||||
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
|
|
||||||
<appender name="console" class="org.apache.log4j.ConsoleAppender">
|
|
||||||
<param name="Target" value="System.out"/>
|
|
||||||
<layout class="org.apache.log4j.PatternLayout">
|
|
||||||
<param name="ConversionPattern" value="%5p %d{ISO8601} [%X{clientId}@%t][%x] %c - %m%n"/>
|
|
||||||
</layout>
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<root>
|
|
||||||
<priority value ="info" />
|
|
||||||
<appender-ref ref="console" />
|
|
||||||
</root>
|
|
||||||
|
|
||||||
</log4j:configuration>
|
|
@ -1,80 +0,0 @@
|
|||||||
package com.stackify.slf4j.guide.controllers;
|
|
||||||
|
|
||||||
import static org.powermock.api.mockito.PowerMockito.doNothing;
|
|
||||||
import static org.powermock.api.mockito.PowerMockito.spy;
|
|
||||||
|
|
||||||
import java.util.Collections;
|
|
||||||
|
|
||||||
import org.apache.log4j.Level;
|
|
||||||
import org.apache.log4j.spi.LoggingEvent;
|
|
||||||
import org.assertj.core.api.Condition;
|
|
||||||
import org.assertj.core.api.SoftAssertions;
|
|
||||||
import org.junit.Before;
|
|
||||||
import org.junit.Test;
|
|
||||||
import org.junit.runner.RunWith;
|
|
||||||
import org.powermock.core.classloader.annotations.PrepareForTest;
|
|
||||||
import org.powermock.modules.junit4.PowerMockRunner;
|
|
||||||
import org.slf4j.MDC;
|
|
||||||
|
|
||||||
import com.stackify.slf4j.guide.utils.ListAppender;
|
|
||||||
|
|
||||||
@RunWith(PowerMockRunner.class)
|
|
||||||
@PrepareForTest(MDC.class)
|
|
||||||
public class SimpleControllerIntegrationTest {
|
|
||||||
|
|
||||||
private SimpleController controller = new SimpleController();
|
|
||||||
|
|
||||||
@Before
|
|
||||||
public void clearLogList() {
|
|
||||||
ListAppender.clearEventList();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void whenSimpleRequestMade_thenAllRegularMessagesLogged() {
|
|
||||||
String output = controller.processList(Collections.emptyList());
|
|
||||||
|
|
||||||
SoftAssertions errorCollector = new SoftAssertions();
|
|
||||||
errorCollector.assertThat(ListAppender.getEvents())
|
|
||||||
.haveAtLeastOne(eventContains("Client requested process the following list: []", Level.INFO))
|
|
||||||
.haveAtLeastOne(eventContains("Starting process", Level.DEBUG))
|
|
||||||
.haveAtLeastOne(eventContains("Finished processing", Level.INFO))
|
|
||||||
.haveExactly(0, eventOfLevel(Level.ERROR));
|
|
||||||
errorCollector.assertThat(output)
|
|
||||||
.isEqualTo("done");
|
|
||||||
errorCollector.assertAll();
|
|
||||||
}
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void givenClientId_whenMDCRequestMade_thenMessagesWithClientIdLogged() throws Exception {
|
|
||||||
// We avoid cleaning the context so tht we can check it afterwards
|
|
||||||
spy(MDC.class);
|
|
||||||
doNothing().when(MDC.class);
|
|
||||||
MDC.clear();
|
|
||||||
String clientId = "id-1234";
|
|
||||||
|
|
||||||
String output = controller.clientMDCRequest(clientId);
|
|
||||||
|
|
||||||
SoftAssertions errorCollector = new SoftAssertions();
|
|
||||||
errorCollector.assertThat(ListAppender.getEvents())
|
|
||||||
.allMatch(entry -> {
|
|
||||||
return clientId.equals(entry.getMDC("clientId"));
|
|
||||||
})
|
|
||||||
.haveAtLeastOne(eventContains("Client id-1234 has made a request", Level.INFO))
|
|
||||||
.haveAtLeastOne(eventContains("Starting request", Level.INFO))
|
|
||||||
.haveAtLeastOne(eventContains("Finished request", Level.INFO));
|
|
||||||
errorCollector.assertThat(output)
|
|
||||||
.isEqualTo("finished");
|
|
||||||
errorCollector.assertAll();
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
private Condition<LoggingEvent> eventOfLevel(Level level) {
|
|
||||||
return eventContains(null, level);
|
|
||||||
}
|
|
||||||
|
|
||||||
private Condition<LoggingEvent> eventContains(String substring, Level level) {
|
|
||||||
|
|
||||||
return new Condition<LoggingEvent>(entry -> (substring == null || (entry.getRenderedMessage() != null && entry.getRenderedMessage()
|
|
||||||
.contains(substring))) && (level == null || level.equals(entry.getLevel())), String.format("entry with message '%s', level %s", substring, level));
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,33 +0,0 @@
|
|||||||
package com.stackify.slf4j.guide.utils;
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.apache.log4j.AppenderSkeleton;
|
|
||||||
import org.apache.log4j.spi.LoggingEvent;
|
|
||||||
|
|
||||||
public class ListAppender extends AppenderSkeleton {
|
|
||||||
public static List<LoggingEvent> events = new ArrayList<LoggingEvent>();
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public void close() {
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
public boolean requiresLayout() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
|
||||||
protected void append(LoggingEvent event) {
|
|
||||||
events.add(event);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static List<LoggingEvent> getEvents() {
|
|
||||||
return events;
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void clearEventList() {
|
|
||||||
events.clear();
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,16 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8" ?>
|
|
||||||
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
|
|
||||||
|
|
||||||
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
|
|
||||||
<appender name="console" class="org.apache.log4j.ConsoleAppender">
|
|
||||||
<param name="Target" value="System.out"/>
|
|
||||||
</appender>
|
|
||||||
<appender name="list" class="com.stackify.slf4j.guide.utils.ListAppender">
|
|
||||||
</appender>
|
|
||||||
|
|
||||||
<root>
|
|
||||||
<priority value ="trace" />
|
|
||||||
<appender-ref ref="list" />
|
|
||||||
</root>
|
|
||||||
|
|
||||||
</log4j:configuration>
|
|
25
guest/slf4j/guide/slf4j-log4j2/.gitignore
vendored
25
guest/slf4j/guide/slf4j-log4j2/.gitignore
vendored
@ -1,25 +0,0 @@
|
|||||||
/target/
|
|
||||||
!.mvn/wrapper/maven-wrapper.jar
|
|
||||||
|
|
||||||
### STS ###
|
|
||||||
.apt_generated
|
|
||||||
.classpath
|
|
||||||
.factorypath
|
|
||||||
.project
|
|
||||||
.settings
|
|
||||||
.springBeans
|
|
||||||
.sts4-cache
|
|
||||||
|
|
||||||
### IntelliJ IDEA ###
|
|
||||||
.idea
|
|
||||||
*.iws
|
|
||||||
*.iml
|
|
||||||
*.ipr
|
|
||||||
|
|
||||||
### NetBeans ###
|
|
||||||
/nbproject/private/
|
|
||||||
/build/
|
|
||||||
/nbbuild/
|
|
||||||
/dist/
|
|
||||||
/nbdist/
|
|
||||||
/.nb-gradle/
|
|
@ -1,54 +0,0 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
|
||||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
|
||||||
<modelVersion>4.0.0</modelVersion>
|
|
||||||
<artifactId>slf4j-log4j2</artifactId>
|
|
||||||
<version>0.0.1-SNAPSHOT</version>
|
|
||||||
<name>slf4j-log4j2</name>
|
|
||||||
<packaging>jar</packaging>
|
|
||||||
|
|
||||||
<parent>
|
|
||||||
<groupId>com.stackify.slf4j.guide</groupId>
|
|
||||||
<artifactId>slf4j-parent-module</artifactId>
|
|
||||||
<version>1.0.0-SNAPSHOT</version>
|
|
||||||
<relativePath>..</relativePath>
|
|
||||||
</parent>
|
|
||||||
|
|
||||||
<dependencies>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-web</artifactId>
|
|
||||||
<exclusions>
|
|
||||||
<exclusion>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-logging</artifactId>
|
|
||||||
</exclusion>
|
|
||||||
</exclusions>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-log4j2</artifactId>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.springframework.boot</groupId>
|
|
||||||
<artifactId>spring-boot-starter-test</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
|
||||||
<artifactId>log4j-core</artifactId>
|
|
||||||
<version>${log4j.version}</version>
|
|
||||||
<type>test-jar</type>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>org.apache.logging.log4j</groupId>
|
|
||||||
<artifactId>log4j-api</artifactId>
|
|
||||||
<version>${log4j.version}</version>
|
|
||||||
<type>test-jar</type>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
|
||||||
|
|
||||||
<properties>
|
|
||||||
<log4j.version>2.11.0</log4j.version>
|
|
||||||
</properties>
|
|
||||||
</project>
|
|
@ -1,12 +0,0 @@
|
|||||||
package com.stackify.slf4j.guide;
|
|
||||||
|
|
||||||
import org.springframework.boot.SpringApplication;
|
|
||||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
|
||||||
|
|
||||||
@SpringBootApplication
|
|
||||||
public class Application {
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
SpringApplication.run(Application.class, args);
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,42 +0,0 @@
|
|||||||
package com.stackify.slf4j.guide.controllers;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
import org.slf4j.Logger;
|
|
||||||
import org.slf4j.LoggerFactory;
|
|
||||||
import org.slf4j.MDC;
|
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
|
||||||
import org.springframework.web.bind.annotation.RequestHeader;
|
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
|
||||||
|
|
||||||
@RestController
|
|
||||||
public class SimpleController {
|
|
||||||
|
|
||||||
Logger logger = LoggerFactory.getLogger(SimpleController.class);
|
|
||||||
|
|
||||||
@GetMapping("/slf4j-guide-request")
|
|
||||||
public String processList(List<String> list) {
|
|
||||||
logger.info("Client requested process the following list: {}", list);
|
|
||||||
try {
|
|
||||||
logger.debug("Starting process");
|
|
||||||
// ...processing list here...
|
|
||||||
Thread.sleep(500);
|
|
||||||
} catch (RuntimeException | InterruptedException e) {
|
|
||||||
logger.error("There was an issue processing the list.", e);
|
|
||||||
} finally {
|
|
||||||
logger.info("Finished processing");
|
|
||||||
}
|
|
||||||
return "done";
|
|
||||||
}
|
|
||||||
|
|
||||||
@GetMapping("/slf4j-guide-mdc-request")
|
|
||||||
public String clientMDCRequest(@RequestHeader String clientId) throws InterruptedException {
|
|
||||||
MDC.put("clientId", clientId);
|
|
||||||
logger.info("Client {} has made a request", clientId);
|
|
||||||
logger.info("Starting request");
|
|
||||||
Thread.sleep(500);
|
|
||||||
logger.info("Finished request");
|
|
||||||
MDC.clear();
|
|
||||||
return "finished";
|
|
||||||
}
|
|
||||||
}
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user