├── .gitattributes ├── src ├── main │ ├── resources │ │ └── application.properties │ └── java │ │ ├── Adopter │ │ ├── PaymentStatus.java │ │ ├── PhonePayPaymentStatus.java │ │ ├── RazorPayPaymentStatus.java │ │ ├── PaymentInterface.java │ │ ├── PhonePay.java │ │ ├── RazorPayUPI.java │ │ └── PhonePayAdopter.java │ │ ├── Factory │ │ ├── ScreenSize.java │ │ ├── Button.java │ │ ├── SquareButton.java │ │ ├── ButtonFactory.java │ │ └── RoundButton.java │ │ ├── Prototype │ │ ├── GameObjectType.java │ │ ├── BackgroundObjectType.java │ │ ├── GraphicalObject.java │ │ ├── ForegroundObject.java │ │ └── BackgroundObject.java │ │ ├── Observer │ │ ├── Observer.java │ │ ├── BitcoinManager.java │ │ ├── Bitcoin.java │ │ ├── TweetNotification.java │ │ ├── EmailNotification.java │ │ ├── BitcoinTracker.java │ │ └── Observable.java │ │ ├── Decorator │ │ ├── Datasource.java │ │ ├── BaseDecorator.java │ │ ├── FileDatasource.java │ │ ├── EncryptionDecorator.java │ │ └── CompressionDecorator.java │ │ ├── org │ │ └── example │ │ │ └── adopterr │ │ │ ├── AdopterrApplication.java │ │ │ └── ServletInitializer.java │ │ ├── Singleton │ │ └── ConnectionPool.java │ │ └── Builder │ │ ├── Student.java │ │ └── NewStudent.java └── test │ └── java │ ├── org │ └── example │ │ └── adopterr │ │ └── AdopterrApplicationTests.java │ ├── DatabaseConnectionTest.java │ ├── Observer.java │ ├── Factory.java │ ├── Decorator.java │ └── StudentBuilder.java ├── .gitignore ├── .mvn └── wrapper │ └── maven-wrapper.properties ├── pom.xml ├── mvnw.cmd └── mvnw /.gitattributes: -------------------------------------------------------------------------------- 1 | /mvnw text eol=lf 2 | *.cmd text eol=crlf 3 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=Adopterr 2 | -------------------------------------------------------------------------------- /src/main/java/Adopter/PaymentStatus.java: -------------------------------------------------------------------------------- 1 | package Adopter; 2 | 3 | public enum PaymentStatus { 4 | Success,Fail 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/Factory/ScreenSize.java: -------------------------------------------------------------------------------- 1 | package Factory; 2 | 3 | public enum ScreenSize { 4 | DESKTOP, TABLET, PHONE, WATCH 5 | } -------------------------------------------------------------------------------- /src/main/java/Adopter/PhonePayPaymentStatus.java: -------------------------------------------------------------------------------- 1 | package Adopter; 2 | 3 | public enum PhonePayPaymentStatus { 4 | OK,FAILED 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/Prototype/GameObjectType.java: -------------------------------------------------------------------------------- 1 | package Prototype; 2 | 3 | public enum GameObjectType { 4 | FOREGROUND, BACKGROUND 5 | } -------------------------------------------------------------------------------- /src/main/java/Adopter/RazorPayPaymentStatus.java: -------------------------------------------------------------------------------- 1 | package Adopter; 2 | 3 | public enum RazorPayPaymentStatus { 4 | Success,Fail 5 | } 6 | -------------------------------------------------------------------------------- /src/main/java/Observer/Observer.java: -------------------------------------------------------------------------------- 1 | package Observer; 2 | 3 | 4 | public interface Observer { 5 | 6 | public void notifyChange(); 7 | } -------------------------------------------------------------------------------- /src/main/java/Prototype/BackgroundObjectType.java: -------------------------------------------------------------------------------- 1 | package Prototype; 2 | 3 | public enum BackgroundObjectType { 4 | TREE, BUILDING 5 | } -------------------------------------------------------------------------------- /src/main/java/Prototype/GraphicalObject.java: -------------------------------------------------------------------------------- 1 | package Prototype; 2 | 3 | // Step 1 - Create a clonable interface 4 | public interface GraphicalObject { 5 | GraphicalObject clone(); 6 | } -------------------------------------------------------------------------------- /src/main/java/Decorator/Datasource.java: -------------------------------------------------------------------------------- 1 | package Decorator; 2 | // Step 1 - Create a product interface 3 | public interface Datasource { 4 | String read(); 5 | 6 | void write(String value); 7 | } -------------------------------------------------------------------------------- /src/main/java/Observer/BitcoinManager.java: -------------------------------------------------------------------------------- 1 | package Observer; 2 | 3 | public interface BitcoinManager { 4 | 5 | public Bitcoin getBitcoin(); 6 | 7 | public void setPrice(Double price); 8 | } -------------------------------------------------------------------------------- /src/main/java/Adopter/PaymentInterface.java: -------------------------------------------------------------------------------- 1 | package Adopter; 2 | 3 | public interface PaymentInterface { 4 | public void completePayment(int id,int amount); 5 | public PaymentStatus verifyPayment(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/Observer/Bitcoin.java: -------------------------------------------------------------------------------- 1 | package Observer; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | @Getter 7 | @Setter 8 | public class Bitcoin { 9 | private Double price = 0.0; 10 | } -------------------------------------------------------------------------------- /src/main/java/Observer/TweetNotification.java: -------------------------------------------------------------------------------- 1 | package Observer; 2 | 3 | public class TweetNotification implements Observer { 4 | 5 | @Override 6 | public void notifyChange() { 7 | System.out.println("Tweet"); 8 | } 9 | 10 | } -------------------------------------------------------------------------------- /src/main/java/Observer/EmailNotification.java: -------------------------------------------------------------------------------- 1 | package Observer; 2 | 3 | public class EmailNotification implements Observer { 4 | 5 | @Override 6 | public void notifyChange() { 7 | System.out.println("Send email"); 8 | } 9 | 10 | } -------------------------------------------------------------------------------- /src/main/java/Decorator/BaseDecorator.java: -------------------------------------------------------------------------------- 1 | package Decorator; 2 | 3 | import lombok.AllArgsConstructor; 4 | 5 | // Step 3 - Base decorator 6 | @AllArgsConstructor 7 | public abstract class BaseDecorator implements Datasource { 8 | protected Datasource nextLayer; 9 | } -------------------------------------------------------------------------------- /src/main/java/Prototype/ForegroundObject.java: -------------------------------------------------------------------------------- 1 | package Prototype; 2 | 3 | import lombok.NoArgsConstructor; 4 | 5 | @NoArgsConstructor 6 | public class ForegroundObject implements GraphicalObject { 7 | 8 | @Override 9 | public ForegroundObject clone() { 10 | return new ForegroundObject(); 11 | } 12 | 13 | } -------------------------------------------------------------------------------- /src/test/java/org/example/adopterr/AdopterrApplicationTests.java: -------------------------------------------------------------------------------- 1 | package org.example.adopterr; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class AdopterrApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/Decorator/FileDatasource.java: -------------------------------------------------------------------------------- 1 | package Decorator; 2 | 3 | // Step 2 - Concrete product class 4 | public class FileDatasource implements Datasource { 5 | @Override 6 | public String read() { 7 | return "Base"; 8 | } 9 | 10 | @Override 11 | public void write(String value) { 12 | System.out.println(value); 13 | } 14 | } -------------------------------------------------------------------------------- /src/main/java/Factory/Button.java: -------------------------------------------------------------------------------- 1 | package Factory; 2 | 3 | 4 | import lombok.AllArgsConstructor; 5 | import lombok.Getter; 6 | 7 | // Step 1 - Create a common product interface 8 | @AllArgsConstructor 9 | @Getter 10 | public abstract class Button { 11 | 12 | private Double border; 13 | 14 | public abstract void render(); 15 | 16 | public abstract void onClick(); 17 | } -------------------------------------------------------------------------------- /src/main/java/Adopter/PhonePay.java: -------------------------------------------------------------------------------- 1 | package Adopter; 2 | 3 | public class PhonePay { 4 | private int id; 5 | private int amount; 6 | private String name; 7 | public void completePayment(int amount, String name, int id) { 8 | System.out.println("PhonePay payment completed"); 9 | } 10 | public PhonePayPaymentStatus validatePayment(){ 11 | return PhonePayPaymentStatus.FAILED; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/example/adopterr/AdopterrApplication.java: -------------------------------------------------------------------------------- 1 | package org.example.adopterr; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class AdopterrApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(AdopterrApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/Observer/BitcoinTracker.java: -------------------------------------------------------------------------------- 1 | package Observer; 2 | 3 | 4 | public class BitcoinTracker extends Observable implements BitcoinManager { 5 | 6 | Bitcoin bitcoin = new Bitcoin(); 7 | 8 | @Override 9 | public Bitcoin getBitcoin() { 10 | return this.bitcoin; 11 | } 12 | 13 | @Override 14 | public void setPrice(Double price) { 15 | bitcoin.setPrice(price); 16 | notifyChange(); 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /src/main/java/Factory/SquareButton.java: -------------------------------------------------------------------------------- 1 | package Factory; 2 | import lombok.Getter; 3 | 4 | @Getter 5 | public class SquareButton extends Button { 6 | private Double length; 7 | 8 | public SquareButton(Double border, Double length) { 9 | super(border); 10 | this.length = length; 11 | } 12 | 13 | public void onClick() { 14 | System.out.println("Square Btn was clicked!"); 15 | } 16 | 17 | public void render() { 18 | System.out.println("Rendered!"); 19 | } 20 | 21 | } -------------------------------------------------------------------------------- /src/main/java/org/example/adopterr/ServletInitializer.java: -------------------------------------------------------------------------------- 1 | package org.example.adopterr; 2 | 3 | import org.springframework.boot.builder.SpringApplicationBuilder; 4 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 5 | 6 | public class ServletInitializer extends SpringBootServletInitializer { 7 | 8 | @Override 9 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 10 | return application.sources(AdopterrApplication.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | .mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | -------------------------------------------------------------------------------- /src/main/java/Adopter/RazorPayUPI.java: -------------------------------------------------------------------------------- 1 | package Adopter; 2 | 3 | public class RazorPayUPI { 4 | private int id; 5 | private int amount; 6 | private String description; 7 | 8 | public void makePayment(int id,int amount,String description) { 9 | System.out.println("Succesfully completed the payment"); 10 | } 11 | public RazorPayPaymentStatus verifyPayment(int id){ 12 | if(id>0){ 13 | return RazorPayPaymentStatus.Success; 14 | } 15 | return RazorPayPaymentStatus.Fail; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/Factory/ButtonFactory.java: -------------------------------------------------------------------------------- 1 | package Factory; 2 | 3 | public class ButtonFactory { 4 | 5 | // Step 3 - Create a static factory method 6 | public static Button createButton(ScreenSize screenSize, Double border, Double radius, Double length) { 7 | switch (screenSize) { 8 | case PHONE: 9 | case TABLET: return new RoundButton(border, radius); 10 | case DESKTOP: return new SquareButton(border, length); 11 | } 12 | 13 | throw new IllegalArgumentException("Invalid type: " + screenSize); 14 | 15 | } 16 | } -------------------------------------------------------------------------------- /src/main/java/Observer/Observable.java: -------------------------------------------------------------------------------- 1 | package Observer; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | public abstract class Observable { 7 | 8 | List observers = new ArrayList<>(); 9 | 10 | public void register(Observer observer) { 11 | observers.add(observer); 12 | } 13 | 14 | public void deregister(Observer observer) { 15 | observers.remove(observer); 16 | } 17 | 18 | public void notifyChange() { 19 | for (Observer observer : observers) { 20 | observer.notifyChange(); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /src/main/java/Factory/RoundButton.java: -------------------------------------------------------------------------------- 1 | package Factory; 2 | 3 | import lombok.Getter; 4 | 5 | // Step 2 - Create the concrete product classes 6 | @Getter 7 | 8 | public class RoundButton extends Button { 9 | private Double radius; 10 | 11 | public RoundButton(Double border, Double radius) { 12 | super(border); 13 | this.radius = radius; 14 | } 15 | 16 | @Override 17 | public void onClick() { 18 | System.out.println("Round Btn was clicked!"); 19 | } 20 | 21 | @Override 22 | public void render() { 23 | System.out.println("Rendered!"); 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /src/test/java/DatabaseConnectionTest.java: -------------------------------------------------------------------------------- 1 | import Singleton.ConnectionPool; 2 | import org.junit.jupiter.api.BeforeEach; 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.assertEquals; 6 | import static org.junit.jupiter.api.Assertions.assertTrue; 7 | 8 | public class DatabaseConnectionTest { 9 | 10 | @Test 11 | public void test() { 12 | 13 | ConnectionPool pool = ConnectionPool.getInstance(); 14 | ConnectionPool pool2 = ConnectionPool.getInstance(); 15 | 16 | assertTrue(pool == pool2, "If a new instance is created, it should be the same as the older one"); 17 | } 18 | } -------------------------------------------------------------------------------- /src/main/java/Adopter/PhonePayAdopter.java: -------------------------------------------------------------------------------- 1 | package Adopter; 2 | 3 | public class PhonePayAdopter implements PaymentInterface{ 4 | PhonePay phonepay=new PhonePay(); 5 | @Override 6 | public void completePayment(int id, int amount) { 7 | phonepay.completePayment(amount,"varun",23); 8 | } 9 | 10 | @Override 11 | public PaymentStatus verifyPayment() { 12 | PhonePayPaymentStatus status=phonepay.validatePayment(); 13 | return validateStatus(status); 14 | } 15 | 16 | private PaymentStatus validateStatus(PhonePayPaymentStatus status) { 17 | if(status.equals(PhonePayPaymentStatus.FAILED)){ 18 | return PaymentStatus.Fail; 19 | } 20 | return PaymentStatus.Success; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/test/java/Observer.java: -------------------------------------------------------------------------------- 1 | 2 | import org.junit.jupiter.api.BeforeEach; 3 | import org.junit.jupiter.api.Test; 4 | import EmailNotification 5 | import static org.junit.jupiter.api.Assertions.assertEquals; 6 | 7 | public class Observer { 8 | private BitcoinTracker tracker; 9 | 10 | @BeforeEach 11 | public void setUp() { 12 | tracker = new BitcoinTracker(); 13 | EmailNotification emailNotifier = new EmailNotification(); 14 | 15 | tracker.register(emailNotifier); 16 | tracker.register(new TweetService()); 17 | } 18 | 19 | @Test 20 | public void testPrice() { 21 | tracker.setPrice(100.0); 22 | Bitcoin bitcoin = tracker.getBitcoin(); 23 | assertEquals(100.0, bitcoin.getPrice(), 0.0); 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /src/main/java/Decorator/EncryptionDecorator.java: -------------------------------------------------------------------------------- 1 | package Decorator; 2 | // Step 4 - Create concrete decorators 3 | public class EncryptionDecorator extends BaseDecorator { 4 | public EncryptionDecorator(Datasource nextLayer) { 5 | super(nextLayer); 6 | } 7 | 8 | @Override 9 | public String read() { 10 | String value = nextLayer.read(); 11 | return decrypt(value); 12 | } 13 | 14 | private String decrypt(String value) { 15 | return value + " - Decrypted"; 16 | } 17 | 18 | @Override 19 | public void write(String value) { 20 | String encrypted = encrypt(value); 21 | nextLayer.write(encrypted); 22 | } 23 | 24 | private String encrypt(String value) { 25 | return value + " - Encrypted"; 26 | } 27 | } -------------------------------------------------------------------------------- /src/main/java/Decorator/CompressionDecorator.java: -------------------------------------------------------------------------------- 1 | package Decorator; 2 | 3 | public class CompressionDecorator extends BaseDecorator { 4 | 5 | public CompressionDecorator(Datasource datasource) { 6 | super(datasource); 7 | } 8 | 9 | @Override 10 | public String read() { 11 | String compressed = nextLayer.read(); 12 | return decompress(compressed); 13 | } 14 | 15 | private String decompress(String compressed) { 16 | return compressed + " - Decompressed"; 17 | } 18 | 19 | @Override 20 | public void write(String value) { 21 | String compressed = compress(value); 22 | nextLayer.write(compressed); 23 | } 24 | 25 | private String compress(String value) { 26 | return value + " - Compressed"; 27 | } 28 | } -------------------------------------------------------------------------------- /src/main/java/Singleton/ConnectionPool.java: -------------------------------------------------------------------------------- 1 | package Singleton; 2 | 3 | public class ConnectionPool { 4 | // Step 3 5 | private static ConnectionPool INSTANCE = null; // Eager initialization - slow startup 6 | 7 | private ConnectionPool() { 8 | // Step 1 - private constructor 9 | } 10 | 11 | public static ConnectionPool getInstance() { 12 | // Step 2 - public static method 13 | if (INSTANCE == null) { 14 | // Step 4 15 | synchronized (ConnectionPool.class) { 16 | if (INSTANCE == null) { 17 | INSTANCE = new ConnectionPool(); 18 | } 19 | } 20 | } 21 | 22 | return INSTANCE; 23 | } 24 | 25 | } 26 | 27 | // Cons of this approach: 28 | // 1. SRP violation 29 | // 2. Thread safety is not guaranteed 30 | // 3. Performance is not guaranteed in thread-safe mode - Double checked locking 31 | // Enum implementation, inner static class -------------------------------------------------------------------------------- /src/main/java/Builder/Student.java: -------------------------------------------------------------------------------- 1 | package Builder; 2 | 3 | import java.util.Map; 4 | 5 | import lombok.AllArgsConstructor; 6 | import lombok.Builder; 7 | import lombok.Getter; 8 | import lombok.Setter; 9 | 10 | @Getter 11 | @Setter 12 | @AllArgsConstructor 13 | @Builder 14 | public class Student { 15 | 16 | String fname; 17 | String lname; 18 | String email; 19 | String phone; 20 | String address; 21 | 22 | 23 | public Student(Map studentValues) throws Exception { 24 | fname = (String) studentValues.get("fname"); 25 | 26 | if (fname == null) { 27 | throw new Exception("fname is required"); 28 | } 29 | this.lname = (String) studentValues.get("lname"); 30 | this.email = (String) studentValues.get("email"); 31 | this.phone = (String) studentValues.get("phone"); 32 | this.address = (String) studentValues.get("address"); 33 | } 34 | 35 | 36 | } 37 | 38 | // Type safety 39 | // try catch 40 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | # Licensed to the Apache Software Foundation (ASF) under one 2 | # or more contributor license agreements. See the NOTICE file 3 | # distributed with this work for additional information 4 | # regarding copyright ownership. The ASF licenses this file 5 | # to you under the Apache License, Version 2.0 (the 6 | # "License"); you may not use this file except in compliance 7 | # with the License. You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, 12 | # software distributed under the License is distributed on an 13 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 | # KIND, either express or implied. See the License for the 15 | # specific language governing permissions and limitations 16 | # under the License. 17 | wrapperVersion=3.3.2 18 | distributionType=only-script 19 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.10/apache-maven-3.9.10-bin.zip 20 | -------------------------------------------------------------------------------- /src/test/java/Factory.java: -------------------------------------------------------------------------------- 1 | 2 | import Factory.*; 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.assertTrue; 6 | 7 | 8 | public class Factory { 9 | 10 | @Test 11 | public void testRoundButton() { 12 | Button button = ButtonFactory.createButton(ScreenSize.PHONE, 10.0, 1.0, null); 13 | assertTrue(button instanceof RoundButton, "If the screen size is of a phone, the btn should be round"); 14 | } 15 | 16 | @Test 17 | public void testSquareButton() { 18 | Button button = ButtonFactory.createButton(ScreenSize.DESKTOP, 10.0, null, 10.0); 19 | assertTrue(button instanceof SquareButton, "If the screen size is of a desktop, the btn should be square"); 20 | } 21 | } 22 | 23 | // Why the factory pattern? 24 | // 1. SRP and OCP =>> Done 25 | // 2. Complex construction logic ==> Done 26 | // 3. Reduce usage of subclasses ==> Done 27 | 28 | // What are the downsides of the simple factory? 29 | // 1. Parameter explosion -> Assignment => Builder 30 | // 2. SRP + OCP violation in library code -------------------------------------------------------------------------------- /src/main/java/Prototype/BackgroundObject.java: -------------------------------------------------------------------------------- 1 | package Prototype; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import lombok.AccessLevel; 7 | import lombok.Getter; 8 | import lombok.NoArgsConstructor; 9 | import lombok.Setter; 10 | 11 | // Step 2 - Create a concrete class 12 | @Getter 13 | @Setter 14 | @NoArgsConstructor 15 | public class BackgroundObject implements GraphicalObject { 16 | private Integer x; 17 | private Integer y; 18 | private Integer width; 19 | private Integer height; 20 | private BackgroundObjectType type; 21 | 22 | @Getter(AccessLevel.NONE) // Hide field from getter 23 | @Setter(AccessLevel.NONE) // Hide field from setter 24 | private List pixels = new ArrayList<>(); 25 | 26 | public BackgroundObject(Integer x, Integer y, Integer width, Integer height, BackgroundObjectType type) { 27 | this.x = x; 28 | this.y = y; 29 | this.width = width; 30 | this.height = height; 31 | this.type = type; 32 | } 33 | 34 | public BackgroundObject(Integer x, Integer y, Integer width, Integer height, BackgroundObjectType type, List pixels) { 35 | this.x = x; 36 | this.y = y; 37 | this.width = width; 38 | this.height = height; 39 | this.type = type; 40 | this.pixels = pixels; 41 | } 42 | 43 | @Override 44 | public BackgroundObject clone() { 45 | return new BackgroundObject(x, y, width, height, type, pixels); 46 | } 47 | } -------------------------------------------------------------------------------- /src/test/java/Decorator.java: -------------------------------------------------------------------------------- 1 | import org.junit.jupiter.api.BeforeEach; 2 | import org.junit.jupiter.api.Test; 3 | 4 | import static org.junit.jupiter.api.Assertions.assertEquals; 5 | 6 | 7 | public class Decorator { 8 | 9 | Datasource dataSource = null; 10 | 11 | @BeforeEach 12 | public void setUp() { 13 | dataSource = new FileDatasource(); 14 | } 15 | 16 | @Test 17 | public void testBaseDataSource() { 18 | String value = dataSource.read(); 19 | assertEquals("Base", value, "If base data source is used, it should return Base"); 20 | } 21 | 22 | @Test 23 | public void testCompressionDecorator() { 24 | Datasource compressedDataSource = new CompressionDecorator(dataSource); 25 | assertEquals("Base - Decompressed", 26 | compressedDataSource.read(), "If compressed data source is used, it should return Decompress"); 27 | 28 | } 29 | 30 | @Test 31 | public void testEncryptionDecorator() { 32 | Datasource encryptedDataSource = new EncryptionDecorator(dataSource); 33 | assertEquals("Base - Decrypted", 34 | encryptedDataSource.read(), "If encrypted data source is used, it should return Encrypted"); 35 | } 36 | 37 | @Test 38 | public void testCompressionAndEncryptionDecorator() { 39 | Datasource compressedDataSource = new CompressionDecorator(dataSource); 40 | Datasource encryptedDataSource = new EncryptionDecorator(compressedDataSource); 41 | assertEquals( 42 | "Base - Decompressed - Decrypted", encryptedDataSource.read(), "If compressed and encrypted data source is used, it should return Encrypted - Decompress"); 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /src/test/java/StudentBuilder.java: -------------------------------------------------------------------------------- 1 | import Builder.NewStudent; 2 | import Builder.Student; 3 | import org.junit.jupiter.api.Test; 4 | 5 | import static org.junit.jupiter.api.Assertions.assertEquals; 6 | import static org.junit.jupiter.api.Assertions.assertThrows; 7 | 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | 12 | public class StudentBuilder { 13 | 14 | @Test 15 | public void testStudent() { 16 | Map values = new HashMap<>(); 17 | values.put("fname", "John"); 18 | values.put("lname", "Doe"); 19 | values.put("email", ""); 20 | values.put("phone", ""); 21 | Student student = null; 22 | try { 23 | student = new Student(values); 24 | } catch (Exception e) { 25 | // TODO Auto-generated catch block 26 | e.printStackTrace(); 27 | } 28 | 29 | assertEquals("John", student.getFname(), "If name is set, on fetching it should be the same"); 30 | 31 | } 32 | 33 | @Test 34 | public void testNewStudent() { 35 | NewStudent.NewStudentBuilder builder = new NewStudent.NewStudentBuilder(); 36 | builder.setFname("John") 37 | .setLname("Doe") 38 | .setEmail("") 39 | .setPhone("") 40 | .setAddress(""); 41 | NewStudent student = builder.build(); 42 | assertEquals("John", student.fname, "If name is set, on fetching it should be the same"); 43 | 44 | } 45 | 46 | @Test 47 | public void testValidStudent() { 48 | NewStudent.NewStudentBuilder builder = new NewStudent.NewStudentBuilder(); 49 | builder.setEmail("") 50 | .setPhone("") 51 | .setAddress(""); 52 | assertThrows(IllegalArgumentException.class, builder::build); 53 | 54 | } 55 | } -------------------------------------------------------------------------------- /src/main/java/Builder/NewStudent.java: -------------------------------------------------------------------------------- 1 | package Builder; 2 | 3 | public class NewStudent { 4 | 5 | public String fname; 6 | String lname; 7 | String email; 8 | String phone; 9 | String address; 10 | int age; 11 | 12 | // Step 1 - Create an inner class with same fields as the outer class 13 | public static class NewStudentBuilder { 14 | 15 | String fname; 16 | String lname; 17 | String email; 18 | String phone; 19 | String address; 20 | 21 | 22 | public String getFname() { 23 | return this.fname; 24 | } 25 | 26 | public NewStudentBuilder setFname(String fname) { 27 | this.fname = fname; 28 | return this; 29 | } 30 | 31 | public String getLname() { 32 | return this.lname; 33 | } 34 | 35 | public NewStudentBuilder setLname(String lname) { 36 | this.lname = lname; 37 | return this; 38 | } 39 | 40 | public String getEmail() { 41 | return this.email; 42 | } 43 | 44 | public NewStudentBuilder setEmail(String email) { 45 | this.email = email; 46 | return this; 47 | } 48 | 49 | public String getPhone() { 50 | return this.phone; 51 | } 52 | 53 | public NewStudentBuilder setPhone(String phone) { 54 | this.phone = phone; 55 | return this; 56 | } 57 | 58 | public String getAddress() { 59 | return this.address; 60 | } 61 | 62 | public NewStudentBuilder setAddress(String address) { 63 | this.address = address; 64 | return this; 65 | } 66 | 67 | private boolean validate() { 68 | if (fname == null || lname == null) { 69 | return false; 70 | } 71 | 72 | return true; 73 | } 74 | 75 | // Step 2 - Add a build method to create outer class 76 | public NewStudent build() { 77 | 78 | // Step 4 - Validation 79 | boolean isValid = validate(); 80 | if (!isValid) { 81 | throw new IllegalArgumentException("Invalid student"); 82 | } 83 | 84 | NewStudent student = new NewStudent(); 85 | student.fname = this.fname; 86 | student.lname = this.lname; 87 | student.email = this.email; 88 | student.phone = this.phone; 89 | student.address = this.address; 90 | return student; 91 | } 92 | 93 | } 94 | } -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 3.5.3 9 | 10 | 11 | org.example 12 | DesignPatterns 13 | 0.0.1-SNAPSHOT 14 | war 15 | Adopterr 16 | Adopterr 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 17 32 | 33 | 34 | 35 | org.springframework.boot 36 | spring-boot-starter-web 37 | 38 | 39 | 40 | org.projectlombok 41 | lombok 42 | true 43 | 44 | 45 | org.springframework.boot 46 | spring-boot-starter-tomcat 47 | provided 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-test 52 | test 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.apache.maven.plugins 60 | maven-compiler-plugin 61 | 62 | 63 | 64 | org.projectlombok 65 | lombok 66 | 67 | 68 | 69 | 70 | 71 | org.springframework.boot 72 | spring-boot-maven-plugin 73 | 74 | 75 | 76 | org.projectlombok 77 | lombok 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | <# : batch portion 2 | @REM ---------------------------------------------------------------------------- 3 | @REM Licensed to the Apache Software Foundation (ASF) under one 4 | @REM or more contributor license agreements. See the NOTICE file 5 | @REM distributed with this work for additional information 6 | @REM regarding copyright ownership. The ASF licenses this file 7 | @REM to you under the Apache License, Version 2.0 (the 8 | @REM "License"); you may not use this file except in compliance 9 | @REM with the License. You may obtain a copy of the License at 10 | @REM 11 | @REM http://www.apache.org/licenses/LICENSE-2.0 12 | @REM 13 | @REM Unless required by applicable law or agreed to in writing, 14 | @REM software distributed under the License is distributed on an 15 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | @REM KIND, either express or implied. See the License for the 17 | @REM specific language governing permissions and limitations 18 | @REM under the License. 19 | @REM ---------------------------------------------------------------------------- 20 | 21 | @REM ---------------------------------------------------------------------------- 22 | @REM Apache Maven Wrapper startup batch script, version 3.3.2 23 | @REM 24 | @REM Optional ENV vars 25 | @REM MVNW_REPOURL - repo url base for downloading maven distribution 26 | @REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 27 | @REM MVNW_VERBOSE - true: enable verbose log; others: silence the output 28 | @REM ---------------------------------------------------------------------------- 29 | 30 | @IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) 31 | @SET __MVNW_CMD__= 32 | @SET __MVNW_ERROR__= 33 | @SET __MVNW_PSMODULEP_SAVE=%PSModulePath% 34 | @SET PSModulePath= 35 | @FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( 36 | IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) 37 | ) 38 | @SET PSModulePath=%__MVNW_PSMODULEP_SAVE% 39 | @SET __MVNW_PSMODULEP_SAVE= 40 | @SET __MVNW_ARG0_NAME__= 41 | @SET MVNW_USERNAME= 42 | @SET MVNW_PASSWORD= 43 | @IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) 44 | @echo Cannot start maven from wrapper >&2 && exit /b 1 45 | @GOTO :EOF 46 | : end batch / begin powershell #> 47 | 48 | $ErrorActionPreference = "Stop" 49 | if ($env:MVNW_VERBOSE -eq "true") { 50 | $VerbosePreference = "Continue" 51 | } 52 | 53 | # calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties 54 | $distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl 55 | if (!$distributionUrl) { 56 | Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" 57 | } 58 | 59 | switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { 60 | "maven-mvnd-*" { 61 | $USE_MVND = $true 62 | $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" 63 | $MVN_CMD = "mvnd.cmd" 64 | break 65 | } 66 | default { 67 | $USE_MVND = $false 68 | $MVN_CMD = $script -replace '^mvnw','mvn' 69 | break 70 | } 71 | } 72 | 73 | # apply MVNW_REPOURL and calculate MAVEN_HOME 74 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 75 | if ($env:MVNW_REPOURL) { 76 | $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } 77 | $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" 78 | } 79 | $distributionUrlName = $distributionUrl -replace '^.*/','' 80 | $distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' 81 | $MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" 82 | if ($env:MAVEN_USER_HOME) { 83 | $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" 84 | } 85 | $MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' 86 | $MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" 87 | 88 | if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { 89 | Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" 90 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 91 | exit $? 92 | } 93 | 94 | if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { 95 | Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" 96 | } 97 | 98 | # prepare tmp dir 99 | $TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile 100 | $TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" 101 | $TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null 102 | trap { 103 | if ($TMP_DOWNLOAD_DIR.Exists) { 104 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 105 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 106 | } 107 | } 108 | 109 | New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null 110 | 111 | # Download and Install Apache Maven 112 | Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 113 | Write-Verbose "Downloading from: $distributionUrl" 114 | Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 115 | 116 | $webclient = New-Object System.Net.WebClient 117 | if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { 118 | $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) 119 | } 120 | [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 121 | $webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null 122 | 123 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 124 | $distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum 125 | if ($distributionSha256Sum) { 126 | if ($USE_MVND) { 127 | Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." 128 | } 129 | Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash 130 | if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { 131 | Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." 132 | } 133 | } 134 | 135 | # unzip and move 136 | Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null 137 | Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null 138 | try { 139 | Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null 140 | } catch { 141 | if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { 142 | Write-Error "fail to move MAVEN_HOME" 143 | } 144 | } finally { 145 | try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } 146 | catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } 147 | } 148 | 149 | Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" 150 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Apache Maven Wrapper startup batch script, version 3.3.2 23 | # 24 | # Optional ENV vars 25 | # ----------------- 26 | # JAVA_HOME - location of a JDK home dir, required when download maven via java source 27 | # MVNW_REPOURL - repo url base for downloading maven distribution 28 | # MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven 29 | # MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output 30 | # ---------------------------------------------------------------------------- 31 | 32 | set -euf 33 | [ "${MVNW_VERBOSE-}" != debug ] || set -x 34 | 35 | # OS specific support. 36 | native_path() { printf %s\\n "$1"; } 37 | case "$(uname)" in 38 | CYGWIN* | MINGW*) 39 | [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" 40 | native_path() { cygpath --path --windows "$1"; } 41 | ;; 42 | esac 43 | 44 | # set JAVACMD and JAVACCMD 45 | set_java_home() { 46 | # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched 47 | if [ -n "${JAVA_HOME-}" ]; then 48 | if [ -x "$JAVA_HOME/jre/sh/java" ]; then 49 | # IBM's JDK on AIX uses strange locations for the executables 50 | JAVACMD="$JAVA_HOME/jre/sh/java" 51 | JAVACCMD="$JAVA_HOME/jre/sh/javac" 52 | else 53 | JAVACMD="$JAVA_HOME/bin/java" 54 | JAVACCMD="$JAVA_HOME/bin/javac" 55 | 56 | if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then 57 | echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 58 | echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 59 | return 1 60 | fi 61 | fi 62 | else 63 | JAVACMD="$( 64 | 'set' +e 65 | 'unset' -f command 2>/dev/null 66 | 'command' -v java 67 | )" || : 68 | JAVACCMD="$( 69 | 'set' +e 70 | 'unset' -f command 2>/dev/null 71 | 'command' -v javac 72 | )" || : 73 | 74 | if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then 75 | echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 76 | return 1 77 | fi 78 | fi 79 | } 80 | 81 | # hash string like Java String::hashCode 82 | hash_string() { 83 | str="${1:-}" h=0 84 | while [ -n "$str" ]; do 85 | char="${str%"${str#?}"}" 86 | h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) 87 | str="${str#?}" 88 | done 89 | printf %x\\n $h 90 | } 91 | 92 | verbose() { :; } 93 | [ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } 94 | 95 | die() { 96 | printf %s\\n "$1" >&2 97 | exit 1 98 | } 99 | 100 | trim() { 101 | # MWRAPPER-139: 102 | # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. 103 | # Needed for removing poorly interpreted newline sequences when running in more 104 | # exotic environments such as mingw bash on Windows. 105 | printf "%s" "${1}" | tr -d '[:space:]' 106 | } 107 | 108 | # parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties 109 | while IFS="=" read -r key value; do 110 | case "${key-}" in 111 | distributionUrl) distributionUrl=$(trim "${value-}") ;; 112 | distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; 113 | esac 114 | done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" 115 | [ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" 116 | 117 | case "${distributionUrl##*/}" in 118 | maven-mvnd-*bin.*) 119 | MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ 120 | case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in 121 | *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; 122 | :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; 123 | :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; 124 | :Linux*x86_64*) distributionPlatform=linux-amd64 ;; 125 | *) 126 | echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 127 | distributionPlatform=linux-amd64 128 | ;; 129 | esac 130 | distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" 131 | ;; 132 | maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; 133 | *) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; 134 | esac 135 | 136 | # apply MVNW_REPOURL and calculate MAVEN_HOME 137 | # maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ 138 | [ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" 139 | distributionUrlName="${distributionUrl##*/}" 140 | distributionUrlNameMain="${distributionUrlName%.*}" 141 | distributionUrlNameMain="${distributionUrlNameMain%-bin}" 142 | MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" 143 | MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" 144 | 145 | exec_maven() { 146 | unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : 147 | exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" 148 | } 149 | 150 | if [ -d "$MAVEN_HOME" ]; then 151 | verbose "found existing MAVEN_HOME at $MAVEN_HOME" 152 | exec_maven "$@" 153 | fi 154 | 155 | case "${distributionUrl-}" in 156 | *?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; 157 | *) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; 158 | esac 159 | 160 | # prepare tmp dir 161 | if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then 162 | clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } 163 | trap clean HUP INT TERM EXIT 164 | else 165 | die "cannot create temp dir" 166 | fi 167 | 168 | mkdir -p -- "${MAVEN_HOME%/*}" 169 | 170 | # Download and Install Apache Maven 171 | verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." 172 | verbose "Downloading from: $distributionUrl" 173 | verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" 174 | 175 | # select .zip or .tar.gz 176 | if ! command -v unzip >/dev/null; then 177 | distributionUrl="${distributionUrl%.zip}.tar.gz" 178 | distributionUrlName="${distributionUrl##*/}" 179 | fi 180 | 181 | # verbose opt 182 | __MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' 183 | [ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v 184 | 185 | # normalize http auth 186 | case "${MVNW_PASSWORD:+has-password}" in 187 | '') MVNW_USERNAME='' MVNW_PASSWORD='' ;; 188 | has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; 189 | esac 190 | 191 | if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then 192 | verbose "Found wget ... using wget" 193 | wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" 194 | elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then 195 | verbose "Found curl ... using curl" 196 | curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" 197 | elif set_java_home; then 198 | verbose "Falling back to use Java to download" 199 | javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" 200 | targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" 201 | cat >"$javaSource" <<-END 202 | public class Downloader extends java.net.Authenticator 203 | { 204 | protected java.net.PasswordAuthentication getPasswordAuthentication() 205 | { 206 | return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); 207 | } 208 | public static void main( String[] args ) throws Exception 209 | { 210 | setDefault( new Downloader() ); 211 | java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); 212 | } 213 | } 214 | END 215 | # For Cygwin/MinGW, switch paths to Windows format before running javac and java 216 | verbose " - Compiling Downloader.java ..." 217 | "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" 218 | verbose " - Running Downloader.java ..." 219 | "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" 220 | fi 221 | 222 | # If specified, validate the SHA-256 sum of the Maven distribution zip file 223 | if [ -n "${distributionSha256Sum-}" ]; then 224 | distributionSha256Result=false 225 | if [ "$MVN_CMD" = mvnd.sh ]; then 226 | echo "Checksum validation is not supported for maven-mvnd." >&2 227 | echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 228 | exit 1 229 | elif command -v sha256sum >/dev/null; then 230 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then 231 | distributionSha256Result=true 232 | fi 233 | elif command -v shasum >/dev/null; then 234 | if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then 235 | distributionSha256Result=true 236 | fi 237 | else 238 | echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 239 | echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 240 | exit 1 241 | fi 242 | if [ $distributionSha256Result = false ]; then 243 | echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 244 | echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 245 | exit 1 246 | fi 247 | fi 248 | 249 | # unzip and move 250 | if command -v unzip >/dev/null; then 251 | unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" 252 | else 253 | tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" 254 | fi 255 | printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" 256 | mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" 257 | 258 | clean || : 259 | exec_maven "$@" 260 | --------------------------------------------------------------------------------