New unit test format

This commit is contained in:
Nick
2019-08-30 21:11:18 +01:00
parent db85c8f275
commit 6cd385e4c0
19972 changed files with 1626600 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
### Relevant Articles:
- [Facade Design Pattern in Java](http://www.baeldung.com/java-facade-pattern)
- [Singletons in Java](http://www.baeldung.com/java-singleton)
- [Proxy, Decorator, Adapter and Bridge Patterns](http://www.baeldung.com/java-structural-design-patterns)
- [Introduction to Creational Design Patterns](http://www.baeldung.com/creational-design-patterns)
- [The Observer Pattern in Java](http://www.baeldung.com/java-observer-pattern)
- [Flyweight Pattern in Java](http://www.baeldung.com/java-flyweight)
- [Service Locator Pattern](http://www.baeldung.com/java-service-locator-pattern)
- [Double-Checked Locking with Singleton](http://www.baeldung.com/java-singleton-double-checked-locking)
- [Composite Design Pattern in Java](http://www.baeldung.com/java-composite-pattern)
- [Visitor Design Pattern in Java](http://www.baeldung.com/java-visitor-pattern)
- [The DAO Pattern in Java](http://www.baeldung.com/java-dao-pattern)
- [Interpreter Design Pattern in Java](http://www.baeldung.com/java-interpreter-pattern)
- [State Design Pattern in Java](https://www.baeldung.com/java-state-design-pattern)
- [The Decorator Pattern in Java](https://www.baeldung.com/java-decorator-pattern)
- [Abstract Factory Pattern in Java](https://www.baeldung.com/java-abstract-factory-pattern)
- [Implementing the Template Method Pattern in Java](http://www.baeldung.com/java-template-method-pattern)
- [Chain of Responsibility Design Pattern in Java](http://www.baeldung.com/chain-of-responsibility-pattern)
- [The Command Pattern in Java](http://www.baeldung.com/java-command-pattern)
- [Java Constructors vs Static Factory Methods](https://www.baeldung.com/java-constructors-vs-static-factory-methods)
- [The Adapter Pattern in Java](https://www.baeldung.com/java-adapter-pattern)
- [Currying in Java](https://www.baeldung.com/java-currying)
- [The Proxy Pattern in Java](https://www.baeldung.com/java-proxy-pattern)
+62
View File
@@ -0,0 +1,62 @@
<?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>design-patterns</artifactId>
<version>1.0</version>
<name>design-patterns</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>patterns</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javaee.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-core.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector.version}</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<grep4j.version>1.8.7</grep4j.version>
<assertj-core.version>3.9.1</assertj-core.version>
<javaee.version>8.0</javaee.version>
<hibernate-core.version>5.2.16.Final</hibernate-core.version>
<mysql-connector.version>6.0.6</mysql-connector.version>
</properties>
</project>
@@ -0,0 +1,20 @@
package com.baeldung.adapter;
import static com.baeldung.util.LogerUtil.LOG;
public class AdapterPatternDriver {
public static void main(String args[]) {
Movable bugattiVeyron = new BugattiVeyron();
MovableAdapter bugattiVeyronAdapter = new MovableAdapterImpl(bugattiVeyron);
LOG.info("Bugatti Veyron Super Sport's top speed is " + bugattiVeyronAdapter.getSpeed() + " Kmph.");
Movable mcLaren = new McLaren();
MovableAdapter mcLarenAdapter = new MovableAdapterImpl(mcLaren);
LOG.info("McLaren F1 top speed is " + mcLarenAdapter.getSpeed() + " Kmph.");
Movable astonMartin = new AstonMartin();
MovableAdapter astonMartinAdapter = new MovableAdapterImpl(astonMartin);
LOG.info("McLaren F1 top speed is " + astonMartinAdapter.getSpeed() + " Kmph.");
}
}
@@ -0,0 +1,8 @@
package com.baeldung.adapter;
public class AstonMartin implements Movable {
@Override
public double getSpeed() {
return 220;
}
}
@@ -0,0 +1,8 @@
package com.baeldung.adapter;
public class BugattiVeyron implements Movable {
@Override
public double getSpeed() {
return 268;
}
}
@@ -0,0 +1,8 @@
package com.baeldung.adapter;
public class McLaren implements Movable {
@Override
public double getSpeed() {
return 241;
}
}
@@ -0,0 +1,6 @@
package com.baeldung.adapter;
public interface Movable {
// returns speed in MPH
double getSpeed();
}
@@ -0,0 +1,6 @@
package com.baeldung.adapter;
public interface MovableAdapter {
// returns speed in KMPH
double getSpeed();
}
@@ -0,0 +1,19 @@
package com.baeldung.adapter;
public class MovableAdapterImpl implements MovableAdapter {
private Movable luxuryCars;
public MovableAdapterImpl(Movable luxuryCars) {
this.luxuryCars = luxuryCars;
}
@Override
public double getSpeed() {
double mph = luxuryCars.getSpeed();
return convertMPHtoKMPH(mph);
}
private double convertMPHtoKMPH(double mph) {
return mph * 1.60934;
}
}
@@ -0,0 +1,8 @@
package com.baeldung.bridge;
public class Blue implements Color {
@Override
public String fill() {
return "Color is Blue";
}
}
@@ -0,0 +1,14 @@
package com.baeldung.bridge;
public class BridgePatternDriver {
public static void main(String[] args) {
//a square with red color
Shape square = new Square(new Red());
System.out.println(square.draw());
//a triangle with blue color
Shape triangle = new Triangle(new Blue());
System.out.println(triangle.draw());
}
}
@@ -0,0 +1,5 @@
package com.baeldung.bridge;
public interface Color {
String fill();
}
@@ -0,0 +1,10 @@
package com.baeldung.bridge;
public class Red implements Color {
@Override
public String fill() {
return "Color is Red";
}
}
@@ -0,0 +1,11 @@
package com.baeldung.bridge;
public abstract class Shape {
protected Color color;
public Shape(Color color) {
this.color = color;
}
abstract public String draw();
}
@@ -0,0 +1,13 @@
package com.baeldung.bridge;
public class Square extends Shape {
public Square(Color color) {
super(color);
}
@Override
public String draw() {
return "Square drawn. " + color.fill();
}
}
@@ -0,0 +1,13 @@
package com.baeldung.bridge;
public class Triangle extends Shape {
public Triangle(Color color) {
super(color);
}
@Override
public String draw() {
return "Triangle drawn. "+ color.fill();
}
}
@@ -0,0 +1,13 @@
package com.baeldung.chainofresponsibility;
public abstract class AuthenticationProcessor {
// next element in chain or responsibility
public AuthenticationProcessor nextProcessor;
public AuthenticationProcessor(AuthenticationProcessor nextProcessor) {
this.nextProcessor = nextProcessor;
}
public abstract boolean isAuthorized(AuthenticationProvider authProvider);
}
@@ -0,0 +1,5 @@
package com.baeldung.chainofresponsibility;
public interface AuthenticationProvider {
}
@@ -0,0 +1,21 @@
package com.baeldung.chainofresponsibility;
public class OAuthAuthenticationProcessor extends AuthenticationProcessor {
public OAuthAuthenticationProcessor(AuthenticationProcessor nextProcessor) {
super(nextProcessor);
}
@Override
public boolean isAuthorized(AuthenticationProvider authProvider) {
if (authProvider instanceof OAuthTokenProvider) {
return Boolean.TRUE;
} else if (nextProcessor != null) {
return nextProcessor.isAuthorized(authProvider);
} else {
return Boolean.FALSE;
}
}
}
@@ -0,0 +1,5 @@
package com.baeldung.chainofresponsibility;
public class OAuthTokenProvider implements AuthenticationProvider {
}
@@ -0,0 +1,5 @@
package com.baeldung.chainofresponsibility;
public class SamlAuthenticationProvider implements AuthenticationProvider {
}
@@ -0,0 +1,20 @@
package com.baeldung.chainofresponsibility;
public class UsernamePasswordAuthenticationProcessor extends AuthenticationProcessor {
public UsernamePasswordAuthenticationProcessor(AuthenticationProcessor nextProcessor) {
super(nextProcessor);
}
@Override
public boolean isAuthorized(AuthenticationProvider authProvider) {
if (authProvider instanceof UsernamePasswordProvider) {
return Boolean.TRUE;
} else if (nextProcessor != null) {
return nextProcessor.isAuthorized(authProvider);
} else {
return Boolean.FALSE;
}
}
}
@@ -0,0 +1,5 @@
package com.baeldung.chainofresponsibility;
public class UsernamePasswordProvider implements AuthenticationProvider {
}
@@ -0,0 +1,19 @@
package com.baeldung.command.client;
import com.baeldung.command.command.OpenTextFileOperation;
import com.baeldung.command.command.SaveTextFileOperation;
import com.baeldung.command.command.TextFileOperation;
import com.baeldung.command.invoker.TextFileOperationExecutor;
import com.baeldung.command.receiver.TextFile;
public class TextFileApplication {
public static void main(String[] args) {
TextFileOperation openTextFileOperation = new OpenTextFileOperation(new TextFile("file1.txt"));
TextFileOperation saveTextFileOperation = new SaveTextFileOperation(new TextFile("file2.txt"));
TextFileOperationExecutor textFileOperationExecutor = new TextFileOperationExecutor();
System.out.println(textFileOperationExecutor.executeOperation(openTextFileOperation));
System.out.println(textFileOperationExecutor.executeOperation(saveTextFileOperation));
}
}
@@ -0,0 +1,17 @@
package com.baeldung.command.command;
import com.baeldung.command.receiver.TextFile;
public class OpenTextFileOperation implements TextFileOperation {
private final TextFile textFile;
public OpenTextFileOperation(TextFile textFile) {
this.textFile = textFile;
}
@Override
public String execute() {
return textFile.open();
}
}
@@ -0,0 +1,17 @@
package com.baeldung.command.command;
import com.baeldung.command.receiver.TextFile;
public class SaveTextFileOperation implements TextFileOperation {
private final TextFile textFile;
public SaveTextFileOperation(TextFile textFile) {
this.textFile = textFile;
}
@Override
public String execute() {
return textFile.save();
}
}
@@ -0,0 +1,8 @@
package com.baeldung.command.command;
@FunctionalInterface
public interface TextFileOperation {
String execute();
}
@@ -0,0 +1,15 @@
package com.baeldung.command.invoker;
import com.baeldung.command.command.TextFileOperation;
import java.util.ArrayList;
import java.util.List;
public class TextFileOperationExecutor {
private final List<TextFileOperation> textFileOperations = new ArrayList<>();
public String executeOperation(TextFileOperation textFileOperation) {
textFileOperations.add(textFileOperation);
return textFileOperation.execute();
}
}
@@ -0,0 +1,34 @@
package com.baeldung.command.receiver;
public class TextFile {
private final String name;
public TextFile(String name) {
this.name = name;
}
public String open() {
return "Opening file " + name;
}
public String read() {
return "Reading file " + name;
}
public String write() {
return "Writing to file " + name;
}
public String save() {
return "Saving file " + name;
}
public String copy() {
return "Copying file " + name;
}
public String paste() {
return "Pasting file " + name;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.composite;
/**
* Created by Gebruiker on 5/3/2018.
*/
public class CompositeDemo {
public static void main(String args[]) {
Department salesDepartment = new SalesDepartment(1, "Sales department");
Department financialDepartment = new FinancialDepartment(2, "Financial department");
HeadDepartment headDepartment = new HeadDepartment(3, "Head department");
headDepartment.addDepartMent(salesDepartment);
headDepartment.addDepartMent(financialDepartment);
headDepartment.printDepartmentName();
}
}
@@ -0,0 +1,9 @@
package com.baeldung.composite;
/**
* Created by Gebruiker on 5/1/2018.
*/
public interface Department {
void printDepartmentName();
}
@@ -0,0 +1,35 @@
package com.baeldung.composite;
/**
* Created by Gebruiker on 5/1/2018.
*/
public class FinancialDepartment implements Department {
private Integer id;
private String name;
public FinancialDepartment(Integer id, String name) {
this.id = id;
this.name = name;
}
public void printDepartmentName() {
System.out.println(getClass().getSimpleName());
}
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;
}
}
@@ -0,0 +1,33 @@
package com.baeldung.composite;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Gebruiker on 5/1/2018.
*/
public class HeadDepartment implements Department {
private Integer id;
private String name;
private List<Department> childDepartments;
public HeadDepartment(Integer id, String name) {
this.id = id;
this.name = name;
this.childDepartments = new ArrayList<Department>();
}
public void printDepartmentName() {
childDepartments.forEach(Department::printDepartmentName);
}
public void addDepartMent(Department department) {
childDepartments.add(department);
}
public void removeDepartment(Department department) {
childDepartments.remove(department);
}
}
@@ -0,0 +1,35 @@
package com.baeldung.composite;
/**
* Created by Gebruiker on 5/1/2018.
*/
public class SalesDepartment implements Department {
private Integer id;
private String name;
public SalesDepartment(Integer id, String name) {
this.id = id;
this.name = name;
}
public void printDepartmentName() {
System.out.println(getClass().getSimpleName());
}
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;
}
}
@@ -0,0 +1,12 @@
package com.baeldung.constructorsstaticfactorymethods.application;
import com.baeldung.constructorsstaticfactorymethods.entities.User;
public class Application {
public static void main(String[] args) {
User user1 = User.createWithDefaultCountry("John", "john@domain.com");
User user2 = User.createWithLoggedInstantiationTime("John", "john@domain.com", "Argentina");
User user3 = User.getSingletonInstance("John", "john@domain.com", "Argentina");
}
}
@@ -0,0 +1,63 @@
package com.baeldung.constructorsstaticfactorymethods.entities;
import java.time.LocalTime;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class User {
private static volatile User instance = null;
private static final Logger LOGGER = Logger.getLogger(User.class.getName());
private final String name;
private final String email;
private final String country;
public static User createWithDefaultCountry(String name, String email) {
return new User(name, email, "Argentina");
}
public static User createWithLoggedInstantiationTime(String name, String email, String country) {
setLoggerProperties();
LOGGER.log(Level.INFO, "Creating User instance at : {0}", LocalTime.now());
return new User(name, email, country);
}
public static User getSingletonInstance(String name, String email, String country) {
if (instance == null) {
synchronized (User.class) {
if (instance == null) {
instance = new User(name, email, country);
}
}
}
return instance;
}
private User(String name, String email, String country) {
this.name = name;
this.email = email;
this.country = country;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getCountry() {
return country;
}
private static void setLoggerProperties() {
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.INFO);
handler.setFormatter(new SimpleFormatter());
LOGGER.addHandler(handler);
}
}
@@ -0,0 +1,5 @@
package com.baeldung.creational.abstractfactory;
public interface AbstractFactory<T> {
T create(String type) ;
}
@@ -0,0 +1,18 @@
package com.baeldung.creational.abstractfactory;
public class AbstractPatternDriver {
public static void main(String[] args) {
AbstractFactory abstractFactory;
//creating a brown toy dog
abstractFactory = FactoryProvider.getFactory("Toy");
Animal toy =(Animal) abstractFactory.create("Dog");
abstractFactory = FactoryProvider.getFactory("Color");
Color color =(Color) abstractFactory.create("Brown");
String result = "A " + toy.getType() + " with " + color.getColor() + " color " + toy.makeSound();
System.out.println(result);
}
}
@@ -0,0 +1,6 @@
package com.baeldung.creational.abstractfactory;
public interface Animal {
String getType();
String makeSound();
}
@@ -0,0 +1,16 @@
package com.baeldung.creational.abstractfactory;
public class AnimalFactory implements AbstractFactory<Animal> {
@Override
public Animal create(String animalType) {
if ("Dog".equalsIgnoreCase(animalType)) {
return new Dog();
} else if ("Duck".equalsIgnoreCase(animalType)) {
return new Duck();
}
return null;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.abstractfactory;
public class Brown implements Color {
@Override
public String getColor() {
return "brown";
}
}
@@ -0,0 +1,5 @@
package com.baeldung.creational.abstractfactory;
public interface Color {
String getColor();
}
@@ -0,0 +1,16 @@
package com.baeldung.creational.abstractfactory;
public class ColorFactory implements AbstractFactory<Color> {
@Override
public Color create(String colorType) {
if ("Brown".equalsIgnoreCase(colorType)) {
return new Brown();
} else if ("White".equalsIgnoreCase(colorType)) {
return new White();
}
return null;
}
}
@@ -0,0 +1,15 @@
package com.baeldung.creational.abstractfactory;
public class Dog implements Animal {
@Override
public String getType() {
return "Dog";
}
@Override
public String makeSound() {
return "Barks";
}
}
@@ -0,0 +1,15 @@
package com.baeldung.creational.abstractfactory;
public class Duck implements Animal {
@Override
public String getType() {
return "Duck";
}
@Override
public String makeSound() {
return "Squeks";
}
}
@@ -0,0 +1,15 @@
package com.baeldung.creational.abstractfactory;
public class FactoryProvider {
public static AbstractFactory getFactory(String choice){
if("Toy".equalsIgnoreCase(choice)){
return new AnimalFactory();
}
else if("Color".equalsIgnoreCase(choice)){
return new ColorFactory();
}
return null;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.abstractfactory;
public class White implements Color {
@Override
public String getColor() {
return "White";
}
}
@@ -0,0 +1,64 @@
package com.baeldung.creational.builder;
public class BankAccount {
private String name;
private String accountNumber;
private String email;
private boolean newsletter;
//The constructor that takes a builder from which it will create object
//the access to this is only provided to builder
private BankAccount(BankAccountBuilder builder) {
this.name = builder.name;
this.accountNumber = builder.accountNumber;
this.email = builder.email;
this.newsletter = builder.newsletter;
}
public static class BankAccountBuilder {
private String name;
private String accountNumber;
private String email;
private boolean newsletter;
//All Mandatory parameters goes with this constructor
public BankAccountBuilder(String name, String accountNumber) {
this.name = name;
this.accountNumber = accountNumber;
}
//setters for optional parameters which returns this same builder
//to support fluent design
public BankAccountBuilder withEmail(String email) {
this.email = email;
return this;
}
public BankAccountBuilder wantNewsletter(boolean newsletter) {
this.newsletter = newsletter;
return this;
}
//the actual build method that prepares and returns a BankAccount object
public BankAccount build() {
return new BankAccount(this);
}
}
//getters
public String getName() {
return name;
}
public String getAccountNumber() {
return accountNumber;
}
public String getEmail() {
return email;
}
public boolean isNewsletter() {
return newsletter;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.creational.builder;
public class BuilderPatternDriver {
public static void main(String[] args) {
BankAccount newAccount = new BankAccount
.BankAccountBuilder("Jon", "22738022275")
.withEmail("jon@example.com")
.wantNewsletter(true)
.build();
System.out.println("Name: " + newAccount.getName());
System.out.println("AccountNumber:" + newAccount.getAccountNumber());
System.out.println("Email: " + newAccount.getEmail());
System.out.println("Want News letter?: " + newAccount.isNewsletter());
}
}
@@ -0,0 +1,16 @@
package com.baeldung.creational.factory;
public class FactoryDriver {
public static void main(String[] args) {
Polygon p;
PolygonFactory factory = new PolygonFactory();
//get the shape which has 4 sides
p = factory.getPolygon(4);
System.out.println("The shape with 4 sides is a " + p.getType());
//get the shape which has 4 sides
p = factory.getPolygon(8);
System.out.println("The shape with 8 sides is a " + p.getType());
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.factory;
public class Heptagon implements Polygon {
@Override
public String getType() {
return "Heptagon";
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.factory;
public class Octagon implements Polygon {
@Override
public String getType() {
return "Octagon";
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.factory;
public class Pentagon implements Polygon {
@Override
public String getType() {
return "Pentagon";
}
}
@@ -0,0 +1,5 @@
package com.baeldung.creational.factory;
public interface Polygon {
String getType();
}
@@ -0,0 +1,22 @@
package com.baeldung.creational.factory;
public class PolygonFactory {
public Polygon getPolygon(int numberOfSides) {
if(numberOfSides == 3) {
return new Triangle();
}
if(numberOfSides == 4) {
return new Square();
}
if(numberOfSides == 5) {
return new Pentagon();
}
if(numberOfSides == 7) {
return new Heptagon();
}
else if(numberOfSides == 8) {
return new Octagon();
}
return null;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.factory;
public class Square implements Polygon {
@Override
public String getType() {
return "Square";
}
}
@@ -0,0 +1,10 @@
package com.baeldung.creational.factory;
public class Triangle implements Polygon {
@Override
public String getType() {
return "Triangle";
}
}
@@ -0,0 +1,13 @@
package com.baeldung.creational.singleton;
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
public static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
@@ -0,0 +1,8 @@
package com.baeldung.creational.singleton;
public class SingletonDriver {
public static void main(String[] args) {
Singleton instance = Singleton.getInstance();
System.out.println(instance.toString());
}
}
@@ -0,0 +1,110 @@
package com.baeldung.currying;
import java.time.LocalDate;
import java.util.Objects;
import java.util.function.BiFunction;
import java.util.function.Function;
public class Letter {
private String returningAddress;
private String insideAddress;
private LocalDate dateOfLetter;
private String salutation;
private String body;
private String closing;
Letter(String returningAddress, String insideAddress, LocalDate dateOfLetter, String salutation, String body, String closing) {
this.returningAddress = returningAddress;
this.insideAddress = insideAddress;
this.dateOfLetter = dateOfLetter;
this.salutation = salutation;
this.body = body;
this.closing = closing;
}
Letter(String salutation, String body) {
this(null, null, LocalDate.now(), salutation, body, null);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Letter letter = (Letter) o;
return Objects.equals(returningAddress, letter.returningAddress) &&
Objects.equals(insideAddress, letter.insideAddress) &&
Objects.equals(dateOfLetter, letter.dateOfLetter) &&
Objects.equals(salutation, letter.salutation) &&
Objects.equals(body, letter.body) &&
Objects.equals(closing, letter.closing);
}
@Override
public int hashCode() {
return Objects.hash(returningAddress, insideAddress, dateOfLetter, salutation, body, closing);
}
@Override
public String toString() {
return "Letter{" + "returningAddress='" + returningAddress + '\'' + ", insideAddress='" + insideAddress + '\''
+ ", dateOfLetter=" + dateOfLetter + ", salutation='" + salutation + '\'' + ", body='" + body + '\''
+ ", closing='" + closing + '\'' + '}';
}
static Letter createLetter(String salutation, String body) {
return new Letter(salutation, body);
}
static BiFunction<String, String, Letter> SIMPLE_LETTER_CREATOR = //
(salutation, body) -> new Letter(salutation, body);
static Function<String, Function<String, Letter>> SIMPLE_CURRIED_LETTER_CREATOR = //
saluation -> body -> new Letter(saluation, body);
static Function<String, Function<String, Function<LocalDate, Function<String, Function<String, Function<String, Letter>>>>>> LETTER_CREATOR = //
returnAddress
-> closing
-> dateOfLetter
-> insideAddress
-> salutation
-> body
-> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing);
static AddReturnAddress builder() {
return returnAddress
-> closing
-> dateOfLetter
-> insideAddress
-> salutation
-> body
-> new Letter(returnAddress, insideAddress, dateOfLetter, salutation, body, closing);
}
interface AddReturnAddress {
Letter.AddClosing withReturnAddress(String returnAddress);
}
interface AddClosing {
Letter.AddDateOfLetter withClosing(String closing);
}
interface AddDateOfLetter {
Letter.AddInsideAddress withDateOfLetter(LocalDate dateOfLetter);
}
interface AddInsideAddress {
Letter.AddSalutation withInsideAddress(String insideAddress);
}
interface AddSalutation {
Letter.AddBody withSalutation(String salutation);
}
interface AddBody {
Letter withBody(String body);
}
}
@@ -0,0 +1,53 @@
package com.baeldung.daopattern.application;
import com.baeldung.daopattern.config.JpaEntityManagerFactory;
import com.baeldung.daopattern.daos.Dao;
import com.baeldung.daopattern.daos.JpaUserDao;
import com.baeldung.daopattern.entities.User;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
public class UserApplication {
private static JpaUserDao jpaUserDao;
public static void main(String[] args) {
User user1 = getUser(1);
System.out.println(user1);
updateUser(user1, new String[]{"John", "john@domain.com"});
saveUser(new User("Monica", "monica@domain.com"));
deleteUser(getUser(2));
getAllUsers().forEach(user -> System.out.println(user.getName()));
}
private static class JpaUserDaoHolder {
private static final JpaUserDao jpaUserDao = new JpaUserDao(new JpaEntityManagerFactory().getEntityManager());
}
public static Dao getJpaUserDao() {
return JpaUserDaoHolder.jpaUserDao;
}
public static User getUser(long id) {
Optional<User> user = getJpaUserDao().get(id);
return user.orElseGet(()-> {return new User("non-existing user", "no-email");});
}
public static List<User> getAllUsers() {
return getJpaUserDao().getAll();
}
public static void updateUser(User user, String[] params){
getJpaUserDao().update(user, params);
}
public static void saveUser(User user) {
getJpaUserDao().save(user);
}
public static void deleteUser(User user) {
getJpaUserDao().delete(user);
}
}
@@ -0,0 +1,65 @@
package com.baeldung.daopattern.config;
import com.baeldung.daopattern.entities.User;
import com.mysql.cj.jdbc.MysqlDataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceUnitInfo;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
public class JpaEntityManagerFactory {
private final String DB_URL = "jdbc:mysql://databaseurl";
private final String DB_USER_NAME = "username";
private final String DB_PASSWORD = "password";
public EntityManager getEntityManager() {
return getEntityManagerFactory().createEntityManager();
}
protected EntityManagerFactory getEntityManagerFactory() {
PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName());
Map<String, Object> configuration = new HashMap<>();
return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration)
.build();
}
protected PersistenceUnitInfoImpl getPersistenceUnitInfo(String name) {
return new PersistenceUnitInfoImpl(name, getEntityClassNames(), getProperties());
}
protected List<String> getEntityClassNames() {
return Arrays.asList(getEntities())
.stream()
.map(Class::getName)
.collect(Collectors.toList());
}
protected Properties getProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.id.new_generator_mappings", false);
properties.put("hibernate.connection.datasource", getMysqlDataSource());
return properties;
}
protected Class[] getEntities() {
return new Class[]{User.class};
}
protected DataSource getMysqlDataSource() {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL(DB_URL);
mysqlDataSource.setUser(DB_USER_NAME);
mysqlDataSource.setPassword(DB_PASSWORD);
return mysqlDataSource;
}
}
@@ -0,0 +1,130 @@
package com.baeldung.daopattern.config;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.sql.DataSource;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.jpa.HibernatePersistenceProvider;
public class PersistenceUnitInfoImpl implements PersistenceUnitInfo {
public static final String JPA_VERSION = "2.1";
private final String persistenceUnitName;
private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
private final List<String> managedClassNames;
private final List<String> mappingFileNames = new ArrayList<>();
private final Properties properties;
private DataSource jtaDataSource;
private DataSource nonJtaDataSource;
public PersistenceUnitInfoImpl(String persistenceUnitName, List<String> managedClassNames, Properties properties) {
this.persistenceUnitName = persistenceUnitName;
this.managedClassNames = managedClassNames;
this.properties = properties;
}
@Override
public String getPersistenceUnitName() {
return persistenceUnitName;
}
@Override
public String getPersistenceProviderClassName() {
return HibernatePersistenceProvider.class.getName();
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return transactionType;
}
@Override
public DataSource getJtaDataSource() {
return jtaDataSource;
}
public PersistenceUnitInfoImpl setJtaDataSource(DataSource jtaDataSource) {
this.jtaDataSource = jtaDataSource;
this.nonJtaDataSource = null;
transactionType = PersistenceUnitTransactionType.JTA;
return this;
}
@Override
public DataSource getNonJtaDataSource() {
return nonJtaDataSource;
}
public PersistenceUnitInfoImpl setNonJtaDataSource(DataSource nonJtaDataSource) {
this.nonJtaDataSource = nonJtaDataSource;
this.jtaDataSource = null;
transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
return this;
}
@Override
public List<String> getMappingFileNames() {
return mappingFileNames;
}
@Override
public List<URL> getJarFileUrls() {
return Collections.emptyList();
}
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return managedClassNames;
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return SharedCacheMode.UNSPECIFIED;
}
@Override
public ValidationMode getValidationMode() {
return ValidationMode.AUTO;
}
public Properties getProperties() {
return properties;
}
@Override
public String getPersistenceXMLSchemaVersion() {
return JPA_VERSION;
}
@Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
@Override
public void addTransformer(ClassTransformer transformer) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
}
@@ -0,0 +1,17 @@
package com.baeldung.daopattern.daos;
import java.util.List;
import java.util.Optional;
public interface Dao<T> {
Optional<T> get(long id);
List<T> getAll();
void save(T t);
void update(T t, String[] params);
void delete(T t);
}
@@ -0,0 +1,60 @@
package com.baeldung.daopattern.daos;
import com.baeldung.daopattern.entities.User;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
public class JpaUserDao implements Dao<User> {
private final EntityManager entityManager;
public JpaUserDao(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public Optional<User> get(long id) {
return Optional.ofNullable(entityManager.find(User.class, id));
}
@Override
public List<User> getAll() {
Query query = entityManager.createQuery("SELECT e FROM User e");
return query.getResultList();
}
@Override
public void save(User user) {
executeInsideTransaction(entityManager -> entityManager.persist(user));
}
@Override
public void update(User user, String[] params) {
user.setName(Objects.requireNonNull(params[0], "Name cannot be null"));
user.setEmail(Objects.requireNonNull(params[1], "Email cannot be null"));
executeInsideTransaction(entityManager -> entityManager.merge(user));
}
@Override
public void delete(User user) {
executeInsideTransaction(entityManager -> entityManager.remove(user));
}
private void executeInsideTransaction(Consumer<EntityManager> action) {
final EntityTransaction tx = entityManager.getTransaction();
try {
tx.begin();
action.accept(entityManager);
tx.commit();
}
catch (RuntimeException e) {
tx.rollback();
throw e;
}
}
}
@@ -0,0 +1,44 @@
package com.baeldung.daopattern.daos;
import com.baeldung.daopattern.entities.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public class UserDao implements Dao<User> {
private List<User> users = new ArrayList<>();
public UserDao() {
users.add(new User("John", "john@domain.com"));
users.add(new User("Susan", "susan@domain.com"));
}
@Override
public Optional<User> get(long id) {
return Optional.ofNullable(users.get((int) id));
}
@Override
public List<User> getAll() {
return users;
}
@Override
public void save(User user) {
users.add(user);
}
@Override
public void update(User user, String[] params) {
user.setName(Objects.requireNonNull(params[0], "Name cannot be null"));
user.setEmail(Objects.requireNonNull(params[1], "Email cannot be null"));
users.add(user);
}
@Override
public void delete(User user) {
users.remove(user);
}
}
@@ -0,0 +1,45 @@
package com.baeldung.daopattern.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String email;
public User(){}
public User(String name, String email) {
this.name = name;
this.email = email;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
}
@@ -0,0 +1,16 @@
package com.baeldung.decorator;
public class BubbleLights extends TreeDecorator {
public BubbleLights(ChristmasTree tree) {
super(tree);
}
public String decorate() {
return super.decorate() + decorateWithBubbleLights();
}
private String decorateWithBubbleLights() {
return " with Bubble Lights";
}
}
@@ -0,0 +1,5 @@
package com.baeldung.decorator;
public interface ChristmasTree {
String decorate();
}
@@ -0,0 +1,10 @@
package com.baeldung.decorator;
public class ChristmasTreeImpl implements ChristmasTree {
@Override
public String decorate() {
return "Christmas tree";
}
}
@@ -0,0 +1,18 @@
package com.baeldung.decorator;
import static com.baeldung.util.LogerUtil.LOG;
public class DecoratorPatternDriver {
public static void main(String[] args) {
// christmas tree with just one Garland
ChristmasTree tree1 = new Garland(new ChristmasTreeImpl());
LOG.info(tree1.decorate());
// christmas tree with two Garlands and one Bubble lights
ChristmasTree tree2 = new BubbleLights(new Garland(new Garland(new ChristmasTreeImpl())));
LOG.info(tree2.decorate());
}
}
@@ -0,0 +1,16 @@
package com.baeldung.decorator;
public class Garland extends TreeDecorator {
public Garland(ChristmasTree tree) {
super(tree);
}
public String decorate() {
return super.decorate() + decorateWithGarland();
}
private String decorateWithGarland() {
return " with Garland";
}
}
@@ -0,0 +1,15 @@
package com.baeldung.decorator;
public abstract class TreeDecorator implements ChristmasTree {
private ChristmasTree tree;
public TreeDecorator(ChristmasTree tree) {
this.tree = tree;
}
@Override
public String decorate() {
return tree.decorate();
}
}
@@ -0,0 +1,32 @@
package com.baeldung.facade;
import com.baeldung.facade.carsystem.*;
public class CarEngineFacade {
private static final Integer DEFAULT_COOLING_TEMP = 90;
private static final Integer MAX_ALLOWED_TEMP = 50;
private FuelInjector fuelInjector = new FuelInjector();
private AirFlowController airFlowController = new AirFlowController();
private Starter starter = new Starter();
private CoolingController coolingController = new CoolingController();
private CatalyticConverter catalyticConverter = new CatalyticConverter();
public void startEngine(){
fuelInjector.on();
airFlowController.takeAir();
fuelInjector.on();
fuelInjector.inject();
starter.start();
coolingController.setTemperatureUpperLimit(DEFAULT_COOLING_TEMP);
coolingController.run();
catalyticConverter.on();
}
public void stopEngine(){
fuelInjector.off();
catalyticConverter.off();
coolingController.cool(MAX_ALLOWED_TEMP);
coolingController.stop();
airFlowController.off();
}
}
@@ -0,0 +1,19 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AirFlowController {
private static final Logger LOGGER = LoggerFactory.getLogger(AirFlowController.class);
private AirFlowMeter airFlowMeter = new AirFlowMeter();
public void takeAir() {
airFlowMeter.getMeasurements();
LOGGER.info("Air provided!");
}
public void off() {
LOGGER.info("Air controller switched off.");
}
}
@@ -0,0 +1,13 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AirFlowMeter {
private static final Logger LOGGER = LoggerFactory.getLogger(AirFlowMeter.class);
public void getMeasurements() {
LOGGER.info("Getting air measurements..");
}
}
@@ -0,0 +1,17 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CatalyticConverter {
private static final Logger LOGGER = LoggerFactory.getLogger(CatalyticConverter.class);
public void on() {
LOGGER.info("Catalytic Converter switched on!");
}
public void off() {
LOGGER.info("Catalytic Converter switched off!");
}
}
@@ -0,0 +1,34 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CoolingController {
private static final Logger LOGGER = LoggerFactory.getLogger(CoolingController.class);
private static final Integer DEFAULT_RADIATOR_SPEED = 10;
private Integer temperatureUpperLimit;
private Radiator radiator = new Radiator();
private TemperatureSensor temperatureSensor = new TemperatureSensor();
public void setTemperatureUpperLimit(Integer temperatureUpperLimit) {
LOGGER.info("Setting temperature upper limit to {}", temperatureUpperLimit);
this.temperatureUpperLimit = temperatureUpperLimit;
}
public void run() {
LOGGER.info("Cooling Controller ready!");
radiator.setSpeed(DEFAULT_RADIATOR_SPEED);
}
public void cool(Integer maxAllowedTemp) {
LOGGER.info("Scheduled cooling with maximum allowed temperature {}", maxAllowedTemp);
temperatureSensor.getTemperature();
radiator.on();
}
public void stop() {
LOGGER.info("Stopping Cooling Controller..");
radiator.off();
}
}
@@ -0,0 +1,23 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FuelInjector {
private static final Logger LOGGER = LoggerFactory.getLogger(FuelInjector.class);
private FuelPump fuelPump = new FuelPump();
public void on(){
LOGGER.info("Fuel injector ready to inject fuel.");
}
public void inject() {
fuelPump.pump();
LOGGER.info("Fuel injected.");
}
public void off() {
LOGGER.info("Stopping Fuel injector..");
}
}
@@ -0,0 +1,13 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FuelPump {
private static final Logger LOGGER = LoggerFactory.getLogger(FuelPump.class);
public void pump() {
LOGGER.info("Fuel Pump is pumping fuel..");
}
}
@@ -0,0 +1,21 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Radiator {
private static final Logger LOGGER = LoggerFactory.getLogger(Radiator.class);
public void on(){
LOGGER.info("Radiator switched on!");
}
public void off(){
LOGGER.info("Radiator switched off!");
}
public void setSpeed(Integer speed){
LOGGER.info("Setting radiator speed to {}",speed);
}
}
@@ -0,0 +1,13 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Starter {
private static final Logger LOGGER = LoggerFactory.getLogger(Starter.class);
public void start() {
LOGGER.info("Starting..");
}
}
@@ -0,0 +1,13 @@
package com.baeldung.facade.carsystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TemperatureSensor {
private static final Logger LOGGER = LoggerFactory.getLogger(TemperatureSensor.class);
public void getTemperature(){
LOGGER.info("Getting temperature from the sensor..");
}
}
@@ -0,0 +1,85 @@
package com.baeldung.flyweight;
import java.awt.Color;
import javax.annotation.concurrent.Immutable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Represents a car. This class is immutable.
*
* @author Donato Rimenti
*/
@Immutable
public class Car implements Vehicle {
/**
* Logger.
*/
private final static Logger LOG = LoggerFactory.getLogger(Car.class);
/**
* The car's engine.
*/
private Engine engine;
/**
* The car's color.
*/
private Color color;
/**
* Instantiates a new Car.
*
* @param engine
* the {@link #engine}
* @param color
* the {@link #color}
*/
public Car(Engine engine, Color color) {
this.engine = engine;
this.color = color;
// Building a new car is a very expensive operation!
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
LOG.error("Error while creating a new car", e);
}
}
/*
* (non-Javadoc)
*
* @see com.baeldung.flyweight.Vehicle#start()
*/
@Override
public void start() {
LOG.info("Car is starting!");
engine.start();
}
/*
* (non-Javadoc)
*
* @see com.baeldung.flyweight.Vehicle#stop()
*/
@Override
public void stop() {
LOG.info("Car is stopping!");
engine.stop();
}
/*
* (non-Javadoc)
*
* @see com.baeldung.flyweight.Vehicle#getColor()
*/
@Override
public Color getColor() {
return this.color;
}
}
@@ -0,0 +1,31 @@
package com.baeldung.flyweight;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Engine for a vehicle.
*
* @author Donato Rimenti
*/
public class Engine {
/**
* Logger.
*/
private final static Logger LOG = LoggerFactory.getLogger(Engine.class);
/**
* Starts the engine.
*/
public void start() {
LOG.info("Engine is starting!");
}
/**
* Stops the engine.
*/
public void stop() {
LOG.info("Engine is stopping!");
}
}
@@ -0,0 +1,29 @@
package com.baeldung.flyweight;
import java.awt.Color;
/**
* Interface for a vehicle.
*
* @author Donato Rimenti
*/
public interface Vehicle {
/**
* Starts the vehicle.
*/
public void start();
/**
* Stops the vehicle.
*/
public void stop();
/**
* Gets the color of the vehicle.
*
* @return the color of the vehicle
*/
public Color getColor();
}
@@ -0,0 +1,45 @@
package com.baeldung.flyweight;
import java.awt.Color;
import java.util.HashMap;
import java.util.Map;
/**
* Factory which implements the Flyweight pattern to return an existing vehicle
* if present or a new one otherwise.
*
* @author Donato Rimenti
*/
public class VehicleFactory {
/**
* Stores the already created vehicles.
*/
private static Map<Color, Vehicle> vehiclesCache = new HashMap<Color, Vehicle>();
/**
* Private constructor to prevent this class instantiation.
*/
private VehicleFactory() {
}
/**
* Returns a vehicle of the same color passed as argument. If that vehicle
* was already created by this factory, that vehicle is returned, otherwise
* a new one is created and returned.
*
* @param color
* the color of the vehicle to return
* @return a vehicle of the specified color
*/
public static Vehicle createVehicle(Color color) {
// Looks for the requested vehicle into the cache.
// If the vehicle doesn't exist, a new one is created.
Vehicle newVehicle = vehiclesCache.computeIfAbsent(color, newColor -> {
// Creates the new car.
Engine newEngine = new Engine();
return new Car(newEngine, newColor);
});
return newVehicle;
}
}
@@ -0,0 +1,107 @@
package com.baeldung.interpreter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Context {
private static Map<String, List<Row>> tables = new HashMap<>();
static {
List<Row> list = new ArrayList<>();
list.add(new Row("John", "Doe"));
list.add(new Row("Jan", "Kowalski"));
list.add(new Row("Dominic", "Doom"));
tables.put("people", list);
}
private String table;
private String column;
/**
* Index of column to be shown in result.
* Calculated in {@link #setColumnMapper()}
*/
private int colIndex = -1;
/**
* Default setup, used for clearing the context for next queries.
* See {@link Context#clear()}
*/
private static final Predicate<String> matchAnyString = s -> s.length() > 0;
private static final Function<String, Stream<? extends String>> matchAllColumns = Stream::of;
/**
* Varies based on setup in subclasses of {@link Expression}
*/
private Predicate<String> whereFilter = matchAnyString;
private Function<String, Stream<? extends String>> columnMapper = matchAllColumns;
void setColumn(String column) {
this.column = column;
setColumnMapper();
}
void setTable(String table) {
this.table = table;
}
void setFilter(Predicate<String> filter) {
whereFilter = filter;
}
/**
* Clears the context to defaults.
* No filters, match all columns.
*/
void clear() {
column = "";
columnMapper = matchAllColumns;
whereFilter = matchAnyString;
}
List<String> search() {
List<String> result = tables.entrySet()
.stream()
.filter(entry -> entry.getKey().equalsIgnoreCase(table))
.flatMap(entry -> Stream.of(entry.getValue()))
.flatMap(Collection::stream)
.map(Row::toString)
.flatMap(columnMapper)
.filter(whereFilter)
.collect(Collectors.toList());
clear();
return result;
}
/**
* Sets column mapper based on {@link #column} attribute.
* Note: If column is unknown, will remain to look for all columns.
*/
private void setColumnMapper() {
switch (column) {
case "*":
colIndex = -1;
break;
case "name":
colIndex = 0;
break;
case "surname":
colIndex = 1;
break;
}
if (colIndex != -1) {
columnMapper = s -> Stream.of(s.split(" ")[colIndex]);
}
}
}
@@ -0,0 +1,7 @@
package com.baeldung.interpreter;
import java.util.List;
interface Expression {
List<String> interpret(Context ctx);
}
@@ -0,0 +1,27 @@
package com.baeldung.interpreter;
import java.util.List;
class From implements Expression {
private String table;
private Where where;
From(String table) {
this.table = table;
}
From(String table, Where where) {
this.table = table;
this.where = where;
}
@Override
public List<String> interpret(Context ctx) {
ctx.setTable(table);
if (where == null) {
return ctx.search();
}
return where.interpret(ctx);
}
}
@@ -0,0 +1,23 @@
package com.baeldung.interpreter;
import java.util.List;
public class InterpreterDemo {
public static void main(String[] args) {
Expression query = new Select("name", new From("people"));
Context ctx = new Context();
List<String> result = query.interpret(ctx);
System.out.println(result);
Expression query2 = new Select("*", new From("people"));
List<String> result2 = query2.interpret(ctx);
System.out.println(result2);
Expression query3 = new Select("name", new From("people", new Where(name -> name.toLowerCase().startsWith("d"))));
List<String> result3 = query3.interpret(ctx);
System.out.println(result3);
}
}
@@ -0,0 +1,17 @@
package com.baeldung.interpreter;
class Row {
private String name;
private String surname;
Row(String name, String surname) {
this.name = name;
this.surname = surname;
}
@Override
public String toString() {
return name + " " + surname;
}
}
@@ -0,0 +1,20 @@
package com.baeldung.interpreter;
import java.util.List;
class Select implements Expression {
private String column;
private From from;
Select(String column, From from) {
this.column = column;
this.from = from;
}
@Override
public List<String> interpret(Context ctx) {
ctx.setColumn(column);
return from.interpret(ctx);
}
}
@@ -0,0 +1,19 @@
package com.baeldung.interpreter;
import java.util.List;
import java.util.function.Predicate;
class Where implements Expression {
private Predicate<String> filter;
Where(Predicate<String> filter) {
this.filter = filter;
}
@Override
public List<String> interpret(Context ctx) {
ctx.setFilter(filter);
return ctx.search();
}
}
@@ -0,0 +1,5 @@
package com.baeldung.observer;
public interface Channel {
public void update(Object o);
}
@@ -0,0 +1,24 @@
package com.baeldung.observer;
import java.util.ArrayList;
import java.util.List;
public class NewsAgency {
private String news;
private List<Channel> channels = new ArrayList<>();
public void addObserver(Channel channel) {
this.channels.add(channel);
}
public void removeObserver(Channel channel) {
this.channels.remove(channel);
}
public void setNews(String news) {
this.news = news;
for (Channel channel : this.channels) {
channel.update(this.news);
}
}
}
@@ -0,0 +1,20 @@
package com.baeldung.observer;
public class NewsChannel implements Channel {
private String news;
@Override
public void update(Object news) {
this.setNews((String) news);
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
}
@@ -0,0 +1,13 @@
package com.baeldung.observer;
import java.util.Observable;
public class ONewsAgency extends Observable {
private String news;
public void setNews(String news) {
this.news = news;
setChanged();
notifyObservers(news);
}
}
@@ -0,0 +1,22 @@
package com.baeldung.observer;
import java.util.Observable;
import java.util.Observer;
public class ONewsChannel implements Observer {
private String news;
@Override
public void update(Observable o, Object news) {
this.setNews((String) news);
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
}
@@ -0,0 +1,28 @@
package com.baeldung.observer;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
public class PCLNewsAgency {
private String news;
private PropertyChangeSupport support;
public PCLNewsAgency() {
support = new PropertyChangeSupport(this);
}
public void addPropertyChangeListener(PropertyChangeListener pcl) {
support.addPropertyChangeListener(pcl);
}
public void removePropertyChangeListener(PropertyChangeListener pcl) {
support.removePropertyChangeListener(pcl);
}
public void setNews(String value) {
support.firePropertyChange("news", this.news, value);
this.news = value;
}
}

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