├── target ├── classes │ ├── application.properties │ └── com │ │ └── amigoscode │ │ └── testing │ │ ├── TestingApplication.class │ │ └── customer │ │ ├── Customer.class │ │ ├── CustomerRepository.class │ │ ├── CustomerRegistrationRequest.class │ │ ├── CustomerRegistrationService.class │ │ └── CustomerRegistrationController.class └── test-classes │ └── com │ └── amigoscode │ └── testing │ ├── TestingApplicationTests.class │ └── customer │ ├── CustomerRepositoryTest.class │ └── CustomerRegistrationServiceTest.class ├── .gitignore ├── src ├── main │ ├── resources │ │ └── application.properties │ └── java │ │ └── com │ │ └── amigoscode │ │ └── testing │ │ ├── payment │ │ ├── Currency.java │ │ ├── PaymentRepository.java │ │ ├── CardPaymentCharger.java │ │ ├── stripe │ │ │ ├── StripeApi.java │ │ │ ├── MockStripeService.java │ │ │ └── StripeService.java │ │ ├── CardPaymentCharge.java │ │ ├── PaymentRequest.java │ │ ├── PaymentController.java │ │ ├── PaymentService.java │ │ └── Payment.java │ │ ├── TestingApplication.java │ │ ├── utils │ │ └── PhoneNumberValidator.java │ │ └── customer │ │ ├── CustomerRegistrationRequest.java │ │ ├── CustomerRepository.java │ │ ├── CustomerRegistrationController.java │ │ ├── Customer.java │ │ └── CustomerRegistrationService.java └── test │ └── java │ └── com │ └── amigoscode │ └── testing │ ├── TestingApplicationTests.java │ ├── utils │ └── PhoneNumberValidatorTest.java │ ├── payment │ ├── PaymentRepositoryTest.java │ ├── PaymentIntegrationTest.java │ ├── stripe │ │ └── StripeServiceTest.java │ └── PaymentServiceTest.java │ └── customer │ ├── CustomerRepositoryTest.java │ └── CustomerRegistrationServiceTest.java ├── .mvn └── wrapper │ ├── maven-wrapper.jar │ ├── maven-wrapper.properties │ └── MavenWrapperDownloader.java ├── HELP.md ├── README.md ├── pom.xml ├── mvnw.cmd ├── testing.iml └── mvnw /target/classes/application.properties: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | *.iml 3 | .idea/ 4 | testing.iml -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | stripe.enabled=false 2 | -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amigoscode/software-testing/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/payment/Currency.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment; 2 | 3 | public enum Currency { 4 | USD, 5 | GBP, 6 | EUR 7 | } 8 | -------------------------------------------------------------------------------- /target/classes/com/amigoscode/testing/TestingApplication.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amigoscode/software-testing/HEAD/target/classes/com/amigoscode/testing/TestingApplication.class -------------------------------------------------------------------------------- /target/classes/com/amigoscode/testing/customer/Customer.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amigoscode/software-testing/HEAD/target/classes/com/amigoscode/testing/customer/Customer.class -------------------------------------------------------------------------------- /target/classes/com/amigoscode/testing/customer/CustomerRepository.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amigoscode/software-testing/HEAD/target/classes/com/amigoscode/testing/customer/CustomerRepository.class -------------------------------------------------------------------------------- /target/test-classes/com/amigoscode/testing/TestingApplicationTests.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amigoscode/software-testing/HEAD/target/test-classes/com/amigoscode/testing/TestingApplicationTests.class -------------------------------------------------------------------------------- /target/classes/com/amigoscode/testing/customer/CustomerRegistrationRequest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amigoscode/software-testing/HEAD/target/classes/com/amigoscode/testing/customer/CustomerRegistrationRequest.class -------------------------------------------------------------------------------- /target/classes/com/amigoscode/testing/customer/CustomerRegistrationService.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amigoscode/software-testing/HEAD/target/classes/com/amigoscode/testing/customer/CustomerRegistrationService.class -------------------------------------------------------------------------------- /target/test-classes/com/amigoscode/testing/customer/CustomerRepositoryTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amigoscode/software-testing/HEAD/target/test-classes/com/amigoscode/testing/customer/CustomerRepositoryTest.class -------------------------------------------------------------------------------- /target/classes/com/amigoscode/testing/customer/CustomerRegistrationController.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amigoscode/software-testing/HEAD/target/classes/com/amigoscode/testing/customer/CustomerRegistrationController.class -------------------------------------------------------------------------------- /target/test-classes/com/amigoscode/testing/customer/CustomerRegistrationServiceTest.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amigoscode/software-testing/HEAD/target/test-classes/com/amigoscode/testing/customer/CustomerRegistrationServiceTest.class -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip 2 | wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar 3 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/payment/PaymentRepository.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment; 2 | 3 | import org.springframework.data.repository.CrudRepository; 4 | 5 | public interface PaymentRepository extends CrudRepository { 6 | } 7 | -------------------------------------------------------------------------------- /src/test/java/com/amigoscode/testing/TestingApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.boot.test.context.SpringBootTest; 5 | 6 | @SpringBootTest 7 | class TestingApplicationTests { 8 | 9 | @Test 10 | void contextLoads() { 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/payment/CardPaymentCharger.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment; 2 | 3 | import java.math.BigDecimal; 4 | 5 | public interface CardPaymentCharger { 6 | 7 | CardPaymentCharge chargeCard( 8 | String cardSource, 9 | BigDecimal amount, 10 | Currency currency, 11 | String description 12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/TestingApplication.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class TestingApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(TestingApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/utils/PhoneNumberValidator.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.utils; 2 | 3 | import org.springframework.stereotype.Service; 4 | 5 | import java.util.function.Predicate; 6 | 7 | @Service 8 | public class PhoneNumberValidator implements Predicate { 9 | 10 | @Override 11 | public boolean test(String phoneNumber) { 12 | return phoneNumber.startsWith("+44") && 13 | phoneNumber.length() == 13; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/payment/stripe/StripeApi.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment.stripe; 2 | 3 | import com.stripe.exception.StripeException; 4 | import com.stripe.model.Charge; 5 | import com.stripe.net.RequestOptions; 6 | import org.springframework.stereotype.Service; 7 | 8 | import java.util.Map; 9 | 10 | @Service 11 | public class StripeApi { 12 | 13 | public Charge create(Map requestMap, RequestOptions options) throws StripeException { 14 | return Charge.create(requestMap, options); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/payment/CardPaymentCharge.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment; 2 | 3 | public class CardPaymentCharge { 4 | 5 | private final boolean isCardDebited; 6 | 7 | public CardPaymentCharge(boolean isCardDebited) { 8 | this.isCardDebited = isCardDebited; 9 | } 10 | 11 | public boolean isCardDebited() { 12 | return isCardDebited; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return "CardPaymentCharge{" + 18 | "isCardDebited=" + isCardDebited + 19 | '}'; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/payment/PaymentRequest.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | public class PaymentRequest { 6 | 7 | private final Payment payment; 8 | 9 | public PaymentRequest(@JsonProperty("payment") Payment payment) { 10 | this.payment = payment; 11 | } 12 | 13 | public Payment getPayment() { 14 | return payment; 15 | } 16 | 17 | @Override 18 | public String toString() { 19 | return "PaymentRequest{" + 20 | "payment=" + payment + 21 | '}'; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/customer/CustomerRegistrationRequest.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.customer; 2 | 3 | import com.fasterxml.jackson.annotation.JsonProperty; 4 | 5 | public class CustomerRegistrationRequest { 6 | 7 | private final Customer customer; 8 | 9 | public CustomerRegistrationRequest( 10 | @JsonProperty("customer") Customer customer) { 11 | this.customer = customer; 12 | } 13 | 14 | public Customer getCustomer() { 15 | return customer; 16 | } 17 | 18 | @Override 19 | public String toString() { 20 | return "CustomerRegistrationRequest{" + 21 | "customer=" + customer + 22 | '}'; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/customer/CustomerRepository.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.customer; 2 | 3 | import org.springframework.data.jpa.repository.Query; 4 | import org.springframework.data.repository.CrudRepository; 5 | import org.springframework.data.repository.query.Param; 6 | 7 | import java.util.Optional; 8 | import java.util.UUID; 9 | 10 | public interface CustomerRepository extends CrudRepository { 11 | 12 | @Query( 13 | value = "select id, name, phone_number " + 14 | "from customer where phone_number = :phone_number", 15 | nativeQuery = true 16 | ) 17 | Optional selectCustomerByPhoneNumber( 18 | @Param("phone_number") String phoneNumber); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/payment/PaymentController.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.web.bind.annotation.RequestBody; 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | @RestController 9 | @RequestMapping("api/v1/payment") 10 | public class PaymentController { 11 | 12 | private final PaymentService paymentService; 13 | 14 | @Autowired 15 | public PaymentController(PaymentService paymentService) { 16 | this.paymentService = paymentService; 17 | } 18 | 19 | @RequestMapping 20 | public void makePayment(@RequestBody PaymentRequest paymentRequest) { 21 | paymentService.chargeCard(paymentRequest.getPayment().getCustomerId(), paymentRequest); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/test/java/com/amigoscode/testing/utils/PhoneNumberValidatorTest.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.utils; 2 | 3 | import org.junit.jupiter.api.BeforeEach; 4 | import org.junit.jupiter.params.ParameterizedTest; 5 | import org.junit.jupiter.params.provider.CsvSource; 6 | 7 | import static org.assertj.core.api.Assertions.assertThat; 8 | 9 | class PhoneNumberValidatorTest { 10 | 11 | private PhoneNumberValidator underTest; 12 | 13 | @BeforeEach 14 | void setUp() { 15 | underTest = new PhoneNumberValidator(); 16 | } 17 | 18 | @ParameterizedTest 19 | @CsvSource({ 20 | "+447000000000,true", 21 | "+44700000000088878, false", 22 | "447000000000, false" 23 | }) 24 | void itShouldValidatePhoneNumber(String phoneNumber, boolean expected) { 25 | // When 26 | boolean isValid = underTest.test(phoneNumber); 27 | 28 | // Then 29 | assertThat(isValid).isEqualTo(expected); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/payment/stripe/MockStripeService.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment.stripe; 2 | 3 | import com.amigoscode.testing.payment.CardPaymentCharge; 4 | import com.amigoscode.testing.payment.CardPaymentCharger; 5 | import com.amigoscode.testing.payment.Currency; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 7 | import org.springframework.stereotype.Service; 8 | 9 | import java.math.BigDecimal; 10 | 11 | @Service 12 | @ConditionalOnProperty( 13 | value = "stripe.enabled", 14 | havingValue = "false" 15 | ) 16 | public class MockStripeService implements CardPaymentCharger { 17 | @Override 18 | public CardPaymentCharge chargeCard(String cardSource, 19 | BigDecimal amount, 20 | Currency currency, 21 | String description) { 22 | return new CardPaymentCharge(true); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /HELP.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | ### Reference Documentation 4 | For further reference, please consider the following sections: 5 | 6 | * [Official Apache Maven documentation](https://maven.apache.org/guides/index.html) 7 | * [Spring Boot Maven Plugin Reference Guide](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/maven-plugin/) 8 | * [Spring Web](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications) 9 | * [Spring Data JPA](https://docs.spring.io/spring-boot/docs/2.2.6.RELEASE/reference/htmlsingle/#boot-features-jpa-and-spring-data) 10 | 11 | ### Guides 12 | The following guides illustrate how to use some features concretely: 13 | 14 | * [Building a RESTful Web Service](https://spring.io/guides/gs/rest-service/) 15 | * [Serving Web Content with Spring MVC](https://spring.io/guides/gs/serving-web-content/) 16 | * [Building REST services with Spring](https://spring.io/guides/tutorials/bookmarks/) 17 | * [Accessing Data with JPA](https://spring.io/guides/gs/accessing-data-jpa/) 18 | 19 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/customer/CustomerRegistrationController.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.customer; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.web.bind.annotation.PutMapping; 5 | import org.springframework.web.bind.annotation.RequestBody; 6 | import org.springframework.web.bind.annotation.RequestMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | 10 | @RestController 11 | @RequestMapping("api/v1/customer-registration") 12 | public class CustomerRegistrationController { 13 | 14 | private final CustomerRegistrationService customerRegistrationService; 15 | 16 | @Autowired 17 | public CustomerRegistrationController(CustomerRegistrationService customerRegistrationService) { 18 | this.customerRegistrationService = customerRegistrationService; 19 | } 20 | 21 | @PutMapping 22 | public void registerNewCustomer( 23 | @RequestBody CustomerRegistrationRequest request) { 24 | customerRegistrationService.registerNewCustomer(request); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # software-testing 2 | 3 | Enrol here 👉🏿 https://amigoscode.com/courses/software-testing 4 | 5 | Writing code without tests? Really? Oh boy. 6 | 7 | Software Testing is a skill that you must fully grasp as a software engineer. It ensures that any code you write to production is more likely to contain less bugs. 8 | 9 | In this course you will learn everything about testing. Starling from 10 | 11 | - Unit Testing 12 | - Integration Testing 13 | - Testing External Services 14 | - Mocking with Mockito 15 | - Test Driven Development 16 | - and much more 17 | 18 | Writing code to test my own code? I know but trust me I am going to break it down nice and easy for you. 19 | 20 | This course will take through a real example code using Stripe and Twilio and we will be writing every single piece of code from scratch 21 | 22 | So, without further a do Lets get started 23 | 24 | # Course Cover 25 | 26 | Enrol here 👉🏿 https://amigoscode.com/courses/software-testing 27 | ![software-testing](https://user-images.githubusercontent.com/40702606/83341657-d435f700-a2dd-11ea-9b8a-eb525da80698.png) 28 | 29 | # Architecture Diagram 30 | 31 | Screenshot 2020-05-31 at 01 26 37 32 | -------------------------------------------------------------------------------- /src/test/java/com/amigoscode/testing/payment/PaymentRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 6 | 7 | import java.math.BigDecimal; 8 | import java.util.Optional; 9 | import java.util.UUID; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | 13 | @DataJpaTest( 14 | properties = { 15 | "spring.jpa.properties.javax.persistence.validation.mode=none" 16 | } 17 | ) 18 | class PaymentRepositoryTest { 19 | 20 | @Autowired 21 | private PaymentRepository underTest; 22 | 23 | 24 | @Test 25 | void itShouldInsertPayment() { 26 | // Given 27 | long paymentId = 1L; 28 | Payment payment = new Payment( 29 | null, 30 | UUID.randomUUID(), 31 | new BigDecimal("10.00"), 32 | Currency.USD, "card123", 33 | "Donation"); 34 | // When 35 | underTest.save(payment); 36 | 37 | // Then 38 | Optional paymentOptional = underTest.findById(paymentId); 39 | assertThat(paymentOptional) 40 | .isPresent() 41 | .hasValueSatisfying(p -> assertThat(p).isEqualTo(payment)); 42 | } 43 | } -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/customer/Customer.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.customer; 2 | 3 | import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 4 | 5 | import javax.persistence.Column; 6 | import javax.persistence.Entity; 7 | import javax.persistence.Id; 8 | import javax.validation.constraints.NotBlank; 9 | import java.util.UUID; 10 | 11 | @Entity 12 | @JsonIgnoreProperties(allowGetters = true) 13 | public class Customer { 14 | 15 | @Id 16 | private UUID id; 17 | 18 | @NotBlank 19 | @Column(nullable = false) 20 | private String name; 21 | 22 | @NotBlank 23 | @Column(nullable = false, unique = true) 24 | private String phoneNumber; 25 | 26 | public Customer(UUID id, String name, String phoneNumber) { 27 | this.id = id; 28 | this.name = name; 29 | this.phoneNumber = phoneNumber; 30 | } 31 | 32 | public Customer() { 33 | } 34 | 35 | public UUID getId() { 36 | return id; 37 | } 38 | 39 | public void setId(UUID id) { 40 | this.id = id; 41 | } 42 | 43 | public String getName() { 44 | return name; 45 | } 46 | 47 | public void setName(String name) { 48 | this.name = name; 49 | } 50 | 51 | public String getPhoneNumber() { 52 | return phoneNumber; 53 | } 54 | 55 | public void setPhoneNumber(String phoneNumber) { 56 | this.phoneNumber = phoneNumber; 57 | } 58 | 59 | @Override 60 | public String toString() { 61 | return "Customer{" + 62 | "id=" + id + 63 | ", name='" + name + '\'' + 64 | ", phoneNumber='" + phoneNumber + '\'' + 65 | '}'; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/customer/CustomerRegistrationService.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.customer; 2 | 3 | import com.amigoscode.testing.utils.PhoneNumberValidator; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Service; 6 | 7 | import java.util.Optional; 8 | import java.util.UUID; 9 | 10 | @Service 11 | public class CustomerRegistrationService { 12 | 13 | private final CustomerRepository customerRepository; 14 | private final PhoneNumberValidator phoneNumberValidator; 15 | 16 | @Autowired 17 | public CustomerRegistrationService(CustomerRepository customerRepository, 18 | PhoneNumberValidator phoneNumberValidator) { 19 | this.customerRepository = customerRepository; 20 | this.phoneNumberValidator = phoneNumberValidator; 21 | } 22 | 23 | public void registerNewCustomer(CustomerRegistrationRequest request) { 24 | String phoneNumber = request.getCustomer().getPhoneNumber(); 25 | 26 | if (!phoneNumberValidator.test(phoneNumber)) { 27 | throw new IllegalStateException("Phone Number " + phoneNumber + " is not valid"); 28 | } 29 | 30 | Optional customerOptional = customerRepository 31 | .selectCustomerByPhoneNumber(phoneNumber); 32 | 33 | if (customerOptional.isPresent()) { 34 | Customer customer = customerOptional.get(); 35 | if (customer.getName().equals(request.getCustomer().getName())) { 36 | return; 37 | } 38 | throw new IllegalStateException(String.format("phone number [%s] is taken", phoneNumber)); 39 | } 40 | 41 | if(request.getCustomer().getId() == null) { 42 | request.getCustomer().setId(UUID.randomUUID()); 43 | } 44 | 45 | customerRepository.save(request.getCustomer()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | org.springframework.boot 7 | spring-boot-starter-parent 8 | 2.2.6.RELEASE 9 | 10 | 11 | com.amigoscode 12 | testing 13 | 0.0.1-SNAPSHOT 14 | testing 15 | Demo project for Spring Boot 16 | 17 | 18 | 11 19 | 20 | 21 | 22 | 23 | org.springframework.boot 24 | spring-boot-starter-data-jpa 25 | 26 | 27 | org.springframework.boot 28 | spring-boot-starter-web 29 | 30 | 31 | 32 | com.h2database 33 | h2 34 | runtime 35 | 36 | 37 | 38 | com.stripe 39 | stripe-java 40 | 19.2.0 41 | 42 | 43 | 44 | org.springframework.boot 45 | spring-boot-starter-test 46 | test 47 | 48 | 49 | org.junit.vintage 50 | junit-vintage-engine 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-maven-plugin 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/payment/stripe/StripeService.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment.stripe; 2 | 3 | import com.amigoscode.testing.payment.CardPaymentCharge; 4 | import com.amigoscode.testing.payment.CardPaymentCharger; 5 | import com.amigoscode.testing.payment.Currency; 6 | import com.stripe.exception.StripeException; 7 | import com.stripe.model.Charge; 8 | import com.stripe.net.RequestOptions; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.math.BigDecimal; 14 | import java.util.HashMap; 15 | import java.util.Map; 16 | 17 | @Service 18 | @ConditionalOnProperty( 19 | value = "stripe.enabled", 20 | havingValue = "true" 21 | ) 22 | public class StripeService implements CardPaymentCharger { 23 | 24 | private final StripeApi stripeApi; 25 | 26 | private final static RequestOptions requestOptions = RequestOptions.builder() 27 | .setApiKey("sk_test_4eC39HqLyjWDarjtT1zdp7dc") 28 | .build(); 29 | 30 | @Autowired 31 | public StripeService(StripeApi stripeApi) { 32 | this.stripeApi = stripeApi; 33 | } 34 | 35 | @Override 36 | public CardPaymentCharge chargeCard(String cardSource, 37 | BigDecimal amount, 38 | Currency currency, 39 | String description) { 40 | Map params = new HashMap<>(); 41 | params.put("amount", amount); 42 | params.put("currency", currency); 43 | params.put("source", cardSource); 44 | params.put("description", description); 45 | 46 | try { 47 | Charge charge = stripeApi.create(params, requestOptions); 48 | return new CardPaymentCharge(charge.getPaid()); 49 | } catch (StripeException e) { 50 | throw new IllegalStateException("Cannot make stripe charge", e); 51 | } 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/payment/PaymentService.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment; 2 | 3 | import com.amigoscode.testing.customer.CustomerRepository; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.stereotype.Service; 6 | 7 | import java.util.List; 8 | import java.util.UUID; 9 | 10 | @Service 11 | public class PaymentService { 12 | 13 | private static final List ACCEPTED_CURRENCIES = List.of(Currency.USD, Currency.GBP); 14 | 15 | private final CustomerRepository customerRepository; 16 | private final PaymentRepository paymentRepository; 17 | private final CardPaymentCharger cardPaymentCharger; 18 | 19 | @Autowired 20 | public PaymentService(CustomerRepository customerRepository, 21 | PaymentRepository paymentRepository, 22 | CardPaymentCharger cardPaymentCharger) { 23 | this.customerRepository = customerRepository; 24 | this.paymentRepository = paymentRepository; 25 | this.cardPaymentCharger = cardPaymentCharger; 26 | } 27 | 28 | void chargeCard(UUID customerId, PaymentRequest paymentRequest) { 29 | // 1. Does customer exists if not throw 30 | boolean isCustomerFound = customerRepository.findById(customerId).isPresent(); 31 | if (!isCustomerFound) { 32 | throw new IllegalStateException(String.format("Customer with id [%s] not found", customerId)); 33 | } 34 | 35 | // 2. Do we support the currency if not throw 36 | boolean isCurrencySupported = ACCEPTED_CURRENCIES.contains(paymentRequest.getPayment().getCurrency()); 37 | 38 | if (!isCurrencySupported) { 39 | String message = String.format( 40 | "Currency [%s] not supported", 41 | paymentRequest.getPayment().getCurrency()); 42 | throw new IllegalStateException(message); 43 | } 44 | 45 | // 3. Charge card 46 | CardPaymentCharge cardPaymentCharge = cardPaymentCharger.chargeCard( 47 | paymentRequest.getPayment().getSource(), 48 | paymentRequest.getPayment().getAmount(), 49 | paymentRequest.getPayment().getCurrency(), 50 | paymentRequest.getPayment().getDescription() 51 | ); 52 | 53 | // 4. If not debited throw 54 | if (!cardPaymentCharge.isCardDebited()) { 55 | throw new IllegalStateException(String.format("Card not debited for customer %s", customerId)); 56 | } 57 | 58 | // 5. Insert payment 59 | paymentRequest.getPayment().setCustomerId(customerId); 60 | 61 | paymentRepository.save(paymentRequest.getPayment()); 62 | 63 | // 6. TODO: send sms 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/com/amigoscode/testing/payment/Payment.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.GeneratedValue; 5 | import javax.persistence.Id; 6 | import java.math.BigDecimal; 7 | import java.util.Objects; 8 | import java.util.UUID; 9 | 10 | @Entity 11 | public class Payment { 12 | 13 | @Id 14 | @GeneratedValue 15 | private Long paymentId; 16 | 17 | private UUID customerId; 18 | 19 | private BigDecimal amount; 20 | 21 | private Currency currency; 22 | 23 | private String source; 24 | 25 | private String description; 26 | 27 | public Payment(Long paymentId, 28 | UUID customerId, 29 | BigDecimal amount, 30 | Currency currency, 31 | String source, 32 | String description) { 33 | this.paymentId = paymentId; 34 | this.customerId = customerId; 35 | this.amount = amount; 36 | this.currency = currency; 37 | this.source = source; 38 | this.description = description; 39 | } 40 | 41 | public Payment() { 42 | } 43 | 44 | public Long getPaymentId() { 45 | return paymentId; 46 | } 47 | 48 | public void setPaymentId(Long paymentId) { 49 | this.paymentId = paymentId; 50 | } 51 | 52 | public UUID getCustomerId() { 53 | return customerId; 54 | } 55 | 56 | public void setCustomerId(UUID customerId) { 57 | this.customerId = customerId; 58 | } 59 | 60 | public BigDecimal getAmount() { 61 | return amount; 62 | } 63 | 64 | public void setAmount(BigDecimal amount) { 65 | this.amount = amount; 66 | } 67 | 68 | public Currency getCurrency() { 69 | return currency; 70 | } 71 | 72 | public void setCurrency(Currency currency) { 73 | this.currency = currency; 74 | } 75 | 76 | public String getSource() { 77 | return source; 78 | } 79 | 80 | public void setSource(String source) { 81 | this.source = source; 82 | } 83 | 84 | public String getDescription() { 85 | return description; 86 | } 87 | 88 | public void setDescription(String description) { 89 | this.description = description; 90 | } 91 | 92 | @Override 93 | public String toString() { 94 | return "Payment{" + 95 | "paymentId=" + paymentId + 96 | ", customerId=" + customerId + 97 | ", amount=" + amount + 98 | ", currency=" + currency + 99 | ", source='" + source + '\'' + 100 | ", description='" + description + '\'' + 101 | '}'; 102 | } 103 | 104 | @Override 105 | public boolean equals(Object o) { 106 | if (this == o) return true; 107 | if (o == null || getClass() != o.getClass()) return false; 108 | Payment payment = (Payment) o; 109 | return paymentId.equals(payment.paymentId) && 110 | customerId.equals(payment.customerId) && 111 | amount.equals(payment.amount) && 112 | currency == payment.currency && 113 | source.equals(payment.source) && 114 | description.equals(payment.description); 115 | } 116 | 117 | @Override 118 | public int hashCode() { 119 | return Objects.hash(paymentId, customerId, amount, currency, source, description); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/test/java/com/amigoscode/testing/payment/PaymentIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment; 2 | 3 | import com.amigoscode.testing.customer.Customer; 4 | import com.amigoscode.testing.customer.CustomerRegistrationRequest; 5 | import com.fasterxml.jackson.core.JsonProcessingException; 6 | import com.fasterxml.jackson.databind.ObjectMapper; 7 | import org.junit.jupiter.api.Test; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; 10 | import org.springframework.boot.test.context.SpringBootTest; 11 | import org.springframework.http.MediaType; 12 | import org.springframework.test.web.servlet.MockMvc; 13 | import org.springframework.test.web.servlet.ResultActions; 14 | 15 | import java.math.BigDecimal; 16 | import java.util.Objects; 17 | import java.util.UUID; 18 | 19 | import static org.assertj.core.api.Assertions.assertThat; 20 | import static org.junit.jupiter.api.Assertions.fail; 21 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 22 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; 23 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 24 | 25 | @SpringBootTest 26 | @AutoConfigureMockMvc 27 | class PaymentIntegrationTest { 28 | 29 | @Autowired 30 | private PaymentRepository paymentRepository; 31 | 32 | @Autowired 33 | private MockMvc mockMvc; 34 | 35 | @Test 36 | void itShouldCreatePaymentSuccessfully() throws Exception { 37 | // Given a customer 38 | UUID customerId = UUID.randomUUID(); 39 | Customer customer = new Customer(customerId, "James", "+447000000000"); 40 | 41 | CustomerRegistrationRequest customerRegistrationRequest = new CustomerRegistrationRequest(customer); 42 | 43 | // Register 44 | ResultActions customerRegResultActions = mockMvc.perform(put("/api/v1/customer-registration") 45 | .contentType(MediaType.APPLICATION_JSON) 46 | .content(Objects.requireNonNull(objectToJson(customerRegistrationRequest)))); 47 | 48 | // ... Payment 49 | long paymentId = 1L; 50 | 51 | Payment payment = new Payment( 52 | paymentId, 53 | customerId, 54 | new BigDecimal("100.00"), 55 | Currency.GBP, 56 | "x0x0x0x0", 57 | "Zakat" 58 | ); 59 | 60 | // ... Payment request 61 | PaymentRequest paymentRequest = new PaymentRequest(payment); 62 | 63 | // ... When payment is sent 64 | ResultActions paymentResultActions = mockMvc.perform(post("/api/v1/payment") 65 | .contentType(MediaType.APPLICATION_JSON) 66 | .content(Objects.requireNonNull(objectToJson(paymentRequest)))); 67 | 68 | // Then both customer registration and payment requests are 200 status code 69 | customerRegResultActions.andExpect(status().isOk()); 70 | paymentResultActions.andExpect(status().isOk()); 71 | 72 | // Payment is stored in db 73 | // TODO: Do not use paymentRepository instead create an endpoint to retrieve payments for customers 74 | assertThat(paymentRepository.findById(paymentId)) 75 | .isPresent() 76 | .hasValueSatisfying(p -> assertThat(p).isEqualToComparingFieldByField(payment)); 77 | 78 | // TODO: Ensure sms is delivered 79 | } 80 | 81 | private String objectToJson(Object object) { 82 | try { 83 | return new ObjectMapper().writeValueAsString(object); 84 | } catch (JsonProcessingException e) { 85 | fail("Failed to convert object to json"); 86 | return null; 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/com/amigoscode/testing/customer/CustomerRepositoryTest.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.customer; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.springframework.beans.factory.annotation.Autowired; 5 | import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; 6 | import org.springframework.dao.DataIntegrityViolationException; 7 | 8 | import java.util.Optional; 9 | import java.util.UUID; 10 | 11 | import static org.assertj.core.api.Assertions.assertThat; 12 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 13 | 14 | @DataJpaTest( 15 | properties = { 16 | "spring.jpa.properties.javax.persistence.validation.mode=none" 17 | } 18 | ) 19 | class CustomerRepositoryTest { 20 | 21 | @Autowired 22 | private CustomerRepository underTest; 23 | 24 | @Test 25 | void itShouldSelectCustomerByPhoneNumber() { 26 | // Given 27 | UUID id = UUID.randomUUID(); 28 | String phoneNumber = "0000"; 29 | Customer customer = new Customer(id, "Abel", phoneNumber); 30 | 31 | // When 32 | underTest.save(customer); 33 | 34 | // Then 35 | Optional optionalCustomer = underTest.selectCustomerByPhoneNumber(phoneNumber); 36 | assertThat(optionalCustomer) 37 | .isPresent() 38 | .hasValueSatisfying(c -> { 39 | assertThat(c).isEqualToComparingFieldByField(customer); 40 | }); 41 | } 42 | 43 | @Test 44 | void itNotShouldSelectCustomerByPhoneNumberWhenNumberDoesNotExists() { 45 | // Given 46 | String phoneNumber = "0000"; 47 | 48 | // When 49 | Optional optionalCustomer = underTest.selectCustomerByPhoneNumber(phoneNumber); 50 | 51 | // Then 52 | assertThat(optionalCustomer).isNotPresent(); 53 | } 54 | 55 | @Test 56 | void itShouldSaveCustomer() { 57 | // Given 58 | UUID id = UUID.randomUUID(); 59 | Customer customer = new Customer(id, "Abel", "0000"); 60 | 61 | // When 62 | underTest.save(customer); 63 | 64 | // Then 65 | Optional optionalCustomer = underTest.findById(id); 66 | assertThat(optionalCustomer) 67 | .isPresent() 68 | .hasValueSatisfying(c -> { 69 | // assertThat(c.getId()).isEqualTo(id); 70 | // assertThat(c.getName()).isEqualTo("Abel"); 71 | // assertThat(c.getPhoneNumber()).isEqualTo("1111"); 72 | assertThat(c).isEqualToComparingFieldByField(customer); 73 | }); 74 | } 75 | 76 | @Test 77 | void itShouldNotSaveCustomerWhenNameIsNull() { 78 | // Given 79 | UUID id = UUID.randomUUID(); 80 | Customer customer = new Customer(id, null, "0000"); 81 | 82 | // When 83 | // Then 84 | assertThatThrownBy(() -> underTest.save(customer)) 85 | .hasMessageContaining("not-null property references a null or transient value : com.amigoscode.testing.customer.Customer.name") 86 | .isInstanceOf(DataIntegrityViolationException.class); 87 | 88 | } 89 | 90 | @Test 91 | void itShouldNotSaveCustomerWhenPhoneNumberIsNull() { 92 | // Given 93 | UUID id = UUID.randomUUID(); 94 | Customer customer = new Customer(id, "Alex", null); 95 | 96 | // When 97 | // Then 98 | assertThatThrownBy(() -> underTest.save(customer)) 99 | .hasMessageContaining("not-null property references a null or transient value : com.amigoscode.testing.customer.Customer.phoneNumber") 100 | .isInstanceOf(DataIntegrityViolationException.class); 101 | 102 | } 103 | 104 | } -------------------------------------------------------------------------------- /src/test/java/com/amigoscode/testing/payment/stripe/StripeServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment.stripe; 2 | 3 | import com.amigoscode.testing.payment.CardPaymentCharge; 4 | import com.amigoscode.testing.payment.Currency; 5 | import com.stripe.exception.StripeException; 6 | import com.stripe.model.Charge; 7 | import com.stripe.net.RequestOptions; 8 | import org.junit.jupiter.api.BeforeEach; 9 | import org.junit.jupiter.api.Test; 10 | import org.mockito.ArgumentCaptor; 11 | import org.mockito.Mock; 12 | import org.mockito.MockitoAnnotations; 13 | 14 | import java.math.BigDecimal; 15 | import java.util.Map; 16 | 17 | import static org.assertj.core.api.Assertions.assertThat; 18 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 19 | import static org.mockito.ArgumentMatchers.any; 20 | import static org.mockito.ArgumentMatchers.anyMap; 21 | import static org.mockito.BDDMockito.given; 22 | import static org.mockito.BDDMockito.then; 23 | import static org.mockito.Mockito.doThrow; 24 | import static org.mockito.Mockito.mock; 25 | 26 | class StripeServiceTest { 27 | 28 | private StripeService underTest; 29 | 30 | @Mock 31 | private StripeApi stripeApi; 32 | 33 | @BeforeEach 34 | void setUp() { 35 | MockitoAnnotations.initMocks(this); 36 | underTest = new StripeService(stripeApi); 37 | } 38 | 39 | @Test 40 | void itShouldChargeCard() throws StripeException { 41 | // Given 42 | String cardSource = "0x0x0x"; 43 | BigDecimal amount = new BigDecimal("10.00"); 44 | Currency currency = Currency.USD; 45 | String description = "Zakat"; 46 | 47 | // Successful charge 48 | Charge charge = new Charge(); 49 | charge.setPaid(true); 50 | given(stripeApi.create(anyMap(), any())).willReturn(charge); 51 | 52 | // When 53 | CardPaymentCharge cardPaymentCharge = underTest.chargeCard(cardSource, amount, currency, description); 54 | 55 | // Then 56 | ArgumentCaptor> mapArgumentCaptor = ArgumentCaptor.forClass(Map.class); 57 | ArgumentCaptor optionsArgumentCaptor = ArgumentCaptor.forClass(RequestOptions.class); 58 | 59 | // Captor requestMap and options 60 | then(stripeApi).should().create(mapArgumentCaptor.capture(), optionsArgumentCaptor.capture()); 61 | 62 | // Assert on requestMap 63 | Map requestMap = mapArgumentCaptor.getValue(); 64 | 65 | assertThat(requestMap.keySet()).hasSize(4); 66 | 67 | assertThat(requestMap.get("amount")).isEqualTo(amount); 68 | assertThat(requestMap.get("currency")).isEqualTo(currency); 69 | assertThat(requestMap.get("source")).isEqualTo(cardSource); 70 | assertThat(requestMap.get("description")).isEqualTo(description); 71 | 72 | // Assert on options 73 | RequestOptions options = optionsArgumentCaptor.getValue(); 74 | 75 | assertThat(options).isNotNull(); 76 | 77 | // card is debited successfully 78 | assertThat(cardPaymentCharge).isNotNull(); 79 | assertThat(cardPaymentCharge.isCardDebited()).isTrue(); 80 | } 81 | 82 | @Test 83 | void itShouldNotChargeWhenApiThrowsException() throws StripeException { 84 | // Given 85 | String cardSource = "0x0x0x"; 86 | BigDecimal amount = new BigDecimal("10.00"); 87 | Currency currency = Currency.USD; 88 | String description = "Zakat"; 89 | 90 | // Throw exception when stripe api is called 91 | StripeException stripeException = mock(StripeException.class); 92 | doThrow(stripeException).when(stripeApi).create(anyMap(), any()); 93 | 94 | // When 95 | // Then 96 | assertThatThrownBy(() -> underTest.chargeCard(cardSource, amount, currency, description)) 97 | .isInstanceOf(IllegalStateException.class) 98 | .hasRootCause(stripeException) 99 | .hasMessageContaining("Cannot make stripe charge"); 100 | } 101 | } -------------------------------------------------------------------------------- /.mvn/wrapper/MavenWrapperDownloader.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2007-present the original author or authors. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * https://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | import java.net.*; 17 | import java.io.*; 18 | import java.nio.channels.*; 19 | import java.util.Properties; 20 | 21 | public class MavenWrapperDownloader { 22 | 23 | private static final String WRAPPER_VERSION = "0.5.6"; 24 | /** 25 | * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. 26 | */ 27 | private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/" 28 | + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar"; 29 | 30 | /** 31 | * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to 32 | * use instead of the default one. 33 | */ 34 | private static final String MAVEN_WRAPPER_PROPERTIES_PATH = 35 | ".mvn/wrapper/maven-wrapper.properties"; 36 | 37 | /** 38 | * Path where the maven-wrapper.jar will be saved to. 39 | */ 40 | private static final String MAVEN_WRAPPER_JAR_PATH = 41 | ".mvn/wrapper/maven-wrapper.jar"; 42 | 43 | /** 44 | * Name of the property which should be used to override the default download url for the wrapper. 45 | */ 46 | private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; 47 | 48 | public static void main(String args[]) { 49 | System.out.println("- Downloader started"); 50 | File baseDirectory = new File(args[0]); 51 | System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); 52 | 53 | // If the maven-wrapper.properties exists, read it and check if it contains a custom 54 | // wrapperUrl parameter. 55 | File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); 56 | String url = DEFAULT_DOWNLOAD_URL; 57 | if(mavenWrapperPropertyFile.exists()) { 58 | FileInputStream mavenWrapperPropertyFileInputStream = null; 59 | try { 60 | mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); 61 | Properties mavenWrapperProperties = new Properties(); 62 | mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); 63 | url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); 64 | } catch (IOException e) { 65 | System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); 66 | } finally { 67 | try { 68 | if(mavenWrapperPropertyFileInputStream != null) { 69 | mavenWrapperPropertyFileInputStream.close(); 70 | } 71 | } catch (IOException e) { 72 | // Ignore ... 73 | } 74 | } 75 | } 76 | System.out.println("- Downloading from: " + url); 77 | 78 | File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); 79 | if(!outputFile.getParentFile().exists()) { 80 | if(!outputFile.getParentFile().mkdirs()) { 81 | System.out.println( 82 | "- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'"); 83 | } 84 | } 85 | System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); 86 | try { 87 | downloadFileFromURL(url, outputFile); 88 | System.out.println("Done"); 89 | System.exit(0); 90 | } catch (Throwable e) { 91 | System.out.println("- Error downloading"); 92 | e.printStackTrace(); 93 | System.exit(1); 94 | } 95 | } 96 | 97 | private static void downloadFileFromURL(String urlString, File destination) throws Exception { 98 | if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { 99 | String username = System.getenv("MVNW_USERNAME"); 100 | char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); 101 | Authenticator.setDefault(new Authenticator() { 102 | @Override 103 | protected PasswordAuthentication getPasswordAuthentication() { 104 | return new PasswordAuthentication(username, password); 105 | } 106 | }); 107 | } 108 | URL website = new URL(urlString); 109 | ReadableByteChannel rbc; 110 | rbc = Channels.newChannel(website.openStream()); 111 | FileOutputStream fos = new FileOutputStream(destination); 112 | fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); 113 | fos.close(); 114 | rbc.close(); 115 | } 116 | 117 | } 118 | -------------------------------------------------------------------------------- /src/test/java/com/amigoscode/testing/customer/CustomerRegistrationServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.customer; 2 | 3 | import com.amigoscode.testing.utils.PhoneNumberValidator; 4 | import org.junit.jupiter.api.BeforeEach; 5 | import org.junit.jupiter.api.Test; 6 | import org.mockito.ArgumentCaptor; 7 | import org.mockito.Captor; 8 | import org.mockito.Mock; 9 | import org.mockito.MockitoAnnotations; 10 | 11 | import java.util.Optional; 12 | import java.util.UUID; 13 | 14 | import static org.assertj.core.api.Assertions.assertThat; 15 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 16 | import static org.mockito.ArgumentMatchers.any; 17 | import static org.mockito.BDDMockito.given; 18 | import static org.mockito.BDDMockito.then; 19 | import static org.mockito.Mockito.never; 20 | 21 | class CustomerRegistrationServiceTest { 22 | 23 | @Mock 24 | private CustomerRepository customerRepository; 25 | 26 | @Mock 27 | private PhoneNumberValidator phoneNumberValidator; 28 | 29 | @Captor 30 | private ArgumentCaptor customerArgumentCaptor; 31 | 32 | private CustomerRegistrationService underTest; 33 | 34 | @BeforeEach 35 | void setUp() { 36 | MockitoAnnotations.initMocks(this); 37 | underTest = new CustomerRegistrationService(customerRepository, phoneNumberValidator); 38 | } 39 | 40 | @Test 41 | void itShouldSaveNewCustomer() { 42 | // Given a phone number and a customer 43 | String phoneNumber = "000099"; 44 | Customer customer = new Customer(UUID.randomUUID(), "Maryam", phoneNumber); 45 | 46 | // ... a request 47 | CustomerRegistrationRequest request = new CustomerRegistrationRequest(customer); 48 | 49 | // ... No customer with phone number passed 50 | given(customerRepository.selectCustomerByPhoneNumber(phoneNumber)) 51 | .willReturn(Optional.empty()); 52 | 53 | //... Valid phone number 54 | given(phoneNumberValidator.test(phoneNumber)).willReturn(true); 55 | 56 | // When 57 | underTest.registerNewCustomer(request); 58 | 59 | // Then 60 | then(customerRepository).should().save(customerArgumentCaptor.capture()); 61 | Customer customerArgumentCaptorValue = customerArgumentCaptor.getValue(); 62 | assertThat(customerArgumentCaptorValue).isEqualTo(customer); 63 | } 64 | 65 | @Test 66 | void itShouldNotSaveNewCustomerWhenPhoneNumberIsInvalid() { 67 | // Given a phone number and a customer 68 | String phoneNumber = "000099"; 69 | Customer customer = new Customer(UUID.randomUUID(), "Maryam", phoneNumber); 70 | 71 | // ... a request 72 | CustomerRegistrationRequest request = new CustomerRegistrationRequest(customer); 73 | 74 | 75 | //... Valid phone number 76 | given(phoneNumberValidator.test(phoneNumber)).willReturn(false); 77 | 78 | // When 79 | assertThatThrownBy(() -> underTest.registerNewCustomer(request)) 80 | .isInstanceOf(IllegalStateException.class) 81 | .hasMessageContaining("Phone Number " + phoneNumber + " is not valid"); 82 | 83 | // Then 84 | then(customerRepository).shouldHaveNoInteractions(); 85 | } 86 | 87 | @Test 88 | void itShouldSaveNewCustomerWhenIdIsNull() { 89 | // Given a phone number and a customer 90 | String phoneNumber = "000099"; 91 | Customer customer = new Customer(null, "Maryam", phoneNumber); 92 | 93 | // ... a request 94 | CustomerRegistrationRequest request = new CustomerRegistrationRequest(customer); 95 | 96 | // ... No customer with phone number passed 97 | given(customerRepository.selectCustomerByPhoneNumber(phoneNumber)) 98 | .willReturn(Optional.empty()); 99 | 100 | //... Valid phone number 101 | given(phoneNumberValidator.test(phoneNumber)).willReturn(true); 102 | 103 | // When 104 | underTest.registerNewCustomer(request); 105 | 106 | // Then 107 | then(customerRepository).should().save(customerArgumentCaptor.capture()); 108 | Customer customerArgumentCaptorValue = customerArgumentCaptor.getValue(); 109 | assertThat(customerArgumentCaptorValue) 110 | .isEqualToIgnoringGivenFields(customer, "id"); 111 | assertThat(customerArgumentCaptorValue.getId()).isNotNull(); 112 | } 113 | 114 | @Test 115 | void itShouldNotSaveCustomerWhenCustomerExists() { 116 | // Given a phone number and a customer 117 | String phoneNumber = "000099"; 118 | Customer customer = new Customer(UUID.randomUUID(), "Maryam", phoneNumber); 119 | 120 | // ... a request 121 | CustomerRegistrationRequest request = new CustomerRegistrationRequest(customer); 122 | 123 | // ... an existing customer is retuned 124 | given(customerRepository.selectCustomerByPhoneNumber(phoneNumber)) 125 | .willReturn(Optional.of(customer)); 126 | 127 | //... Valid phone number 128 | given(phoneNumberValidator.test(phoneNumber)).willReturn(true); 129 | 130 | // When 131 | underTest.registerNewCustomer(request); 132 | 133 | // Then 134 | then(customerRepository).should(never()).save(any()); 135 | } 136 | 137 | @Test 138 | void itShouldThrowWhenPhoneNumberIsTaken() { 139 | // Given a phone number and a customer 140 | String phoneNumber = "000099"; 141 | Customer customer = new Customer(UUID.randomUUID(), "Maryam", phoneNumber); 142 | Customer customerTwo = new Customer(UUID.randomUUID(), "John", phoneNumber); 143 | 144 | // ... a request 145 | CustomerRegistrationRequest request = new CustomerRegistrationRequest(customer); 146 | 147 | // ... No customer with phone number passed 148 | given(customerRepository.selectCustomerByPhoneNumber(phoneNumber)) 149 | .willReturn(Optional.of(customerTwo)); 150 | 151 | //... Valid phone number 152 | given(phoneNumberValidator.test(phoneNumber)).willReturn(true); 153 | 154 | // When 155 | // Then 156 | assertThatThrownBy(() -> underTest.registerNewCustomer(request)) 157 | .isInstanceOf(IllegalStateException.class) 158 | .hasMessageContaining(String.format("phone number [%s] is taken", phoneNumber)); 159 | 160 | // Finally 161 | then(customerRepository).should(never()).save(any(Customer.class)); 162 | 163 | } 164 | } -------------------------------------------------------------------------------- /src/test/java/com/amigoscode/testing/payment/PaymentServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.amigoscode.testing.payment; 2 | 3 | import com.amigoscode.testing.customer.Customer; 4 | import com.amigoscode.testing.customer.CustomerRepository; 5 | import org.junit.jupiter.api.BeforeEach; 6 | import org.junit.jupiter.api.Test; 7 | import org.mockito.ArgumentCaptor; 8 | import org.mockito.Mock; 9 | import org.mockito.MockitoAnnotations; 10 | 11 | import java.math.BigDecimal; 12 | import java.util.Optional; 13 | import java.util.UUID; 14 | 15 | import static org.assertj.core.api.Assertions.assertThat; 16 | import static org.assertj.core.api.Assertions.assertThatThrownBy; 17 | import static org.mockito.BDDMockito.given; 18 | import static org.mockito.BDDMockito.then; 19 | import static org.mockito.Mockito.mock; 20 | 21 | class PaymentServiceTest { 22 | 23 | @Mock 24 | private CustomerRepository customerRepository; 25 | @Mock 26 | private PaymentRepository paymentRepository; 27 | @Mock 28 | private CardPaymentCharger cardPaymentCharger; 29 | 30 | private PaymentService underTest; 31 | 32 | @BeforeEach 33 | void setUp() { 34 | MockitoAnnotations.initMocks(this); 35 | underTest = new PaymentService(customerRepository, paymentRepository, cardPaymentCharger); 36 | } 37 | 38 | @Test 39 | void itShouldChargeCardSuccessfully() { 40 | // Given 41 | UUID customerId = UUID.randomUUID(); 42 | 43 | // ... Customer exists 44 | given(customerRepository.findById(customerId)).willReturn(Optional.of(mock(Customer.class))); 45 | 46 | // ... Payment request 47 | PaymentRequest paymentRequest = new PaymentRequest( 48 | new Payment( 49 | null, 50 | null, 51 | new BigDecimal("100.00"), 52 | Currency.USD, 53 | "card123xx", 54 | "Donation" 55 | ) 56 | ); 57 | 58 | // ... Card is charged successfully 59 | given(cardPaymentCharger.chargeCard( 60 | paymentRequest.getPayment().getSource(), 61 | paymentRequest.getPayment().getAmount(), 62 | paymentRequest.getPayment().getCurrency(), 63 | paymentRequest.getPayment().getDescription() 64 | )).willReturn(new CardPaymentCharge(true)); 65 | 66 | // When 67 | underTest.chargeCard(customerId, paymentRequest); 68 | 69 | // Then 70 | ArgumentCaptor paymentArgumentCaptor = 71 | ArgumentCaptor.forClass(Payment.class); 72 | 73 | then(paymentRepository).should().save(paymentArgumentCaptor.capture()); 74 | 75 | Payment paymentArgumentCaptorValue = paymentArgumentCaptor.getValue(); 76 | assertThat(paymentArgumentCaptorValue) 77 | .isEqualToIgnoringGivenFields( 78 | paymentRequest.getPayment(), 79 | "customerId"); 80 | 81 | assertThat(paymentArgumentCaptorValue.getCustomerId()).isEqualTo(customerId); 82 | } 83 | 84 | @Test 85 | void itShouldThrowWhenCardIsNotCharged() { 86 | // Given 87 | UUID customerId = UUID.randomUUID(); 88 | 89 | // ... Customer exists 90 | given(customerRepository.findById(customerId)).willReturn(Optional.of(mock(Customer.class))); 91 | 92 | // ... Payment request 93 | PaymentRequest paymentRequest = new PaymentRequest( 94 | new Payment( 95 | null, 96 | null, 97 | new BigDecimal("100.00"), 98 | Currency.USD, 99 | "card123xx", 100 | "Donation" 101 | ) 102 | ); 103 | 104 | // ... Card is not charged successfully 105 | given(cardPaymentCharger.chargeCard( 106 | paymentRequest.getPayment().getSource(), 107 | paymentRequest.getPayment().getAmount(), 108 | paymentRequest.getPayment().getCurrency(), 109 | paymentRequest.getPayment().getDescription() 110 | )).willReturn(new CardPaymentCharge(false)); 111 | 112 | // When 113 | // Then 114 | assertThatThrownBy(() -> underTest.chargeCard(customerId, paymentRequest)) 115 | .isInstanceOf(IllegalStateException.class) 116 | .hasMessageContaining("Card not debited for customer " + customerId); 117 | 118 | // ... No interaction with paymentRepository 119 | then(paymentRepository).shouldHaveNoInteractions(); } 120 | 121 | @Test 122 | void itShouldNotChargeCardAndThrowWhenCurrencyNotSupported() { 123 | // Given 124 | UUID customerId = UUID.randomUUID(); 125 | 126 | // ... Customer exists 127 | given(customerRepository.findById(customerId)).willReturn(Optional.of(mock(Customer.class))); 128 | 129 | // ... Euros 130 | Currency currency = Currency.EUR; 131 | 132 | // ... Payment request 133 | PaymentRequest paymentRequest = new PaymentRequest( 134 | new Payment( 135 | null, 136 | null, 137 | new BigDecimal("100.00"), 138 | currency, 139 | "card123xx", 140 | "Donation" 141 | ) 142 | ); 143 | 144 | // When 145 | assertThatThrownBy(() -> underTest.chargeCard(customerId, paymentRequest)) 146 | .isInstanceOf(IllegalStateException.class) 147 | .hasMessageContaining("Currency [" + currency + "] not supported"); 148 | 149 | // Then 150 | 151 | // ... No interaction with cardPaymentCharger 152 | then(cardPaymentCharger).shouldHaveNoInteractions(); 153 | 154 | // ... No interaction with paymentRepository 155 | then(paymentRepository).shouldHaveNoInteractions(); 156 | } 157 | 158 | @Test 159 | void itShouldNotChargeAndThrowWhenCustomerNotFound() { 160 | // Given 161 | UUID customerId = UUID.randomUUID(); 162 | 163 | // Customer not found in db 164 | given(customerRepository.findById(customerId)).willReturn(Optional.empty()); 165 | 166 | // When 167 | // Then 168 | assertThatThrownBy(() -> underTest.chargeCard(customerId, new PaymentRequest(new Payment()))) 169 | .isInstanceOf(IllegalStateException.class) 170 | .hasMessageContaining("Customer with id [" + customerId + "] not found"); 171 | 172 | // ... No interactions with PaymentCharger not PaymentRepository 173 | then(cardPaymentCharger).shouldHaveNoInteractions(); 174 | then(paymentRepository).shouldHaveNoInteractions(); 175 | } 176 | } -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM https://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM set title of command window 39 | title %0 40 | @REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' 41 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 42 | 43 | @REM set %HOME% to equivalent of $HOME 44 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 45 | 46 | @REM Execute a user defined script before this one 47 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 48 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 49 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 50 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 51 | :skipRcPre 52 | 53 | @setlocal 54 | 55 | set ERROR_CODE=0 56 | 57 | @REM To isolate internal variables from possible post scripts, we use another setlocal 58 | @setlocal 59 | 60 | @REM ==== START VALIDATION ==== 61 | if not "%JAVA_HOME%" == "" goto OkJHome 62 | 63 | echo. 64 | echo Error: JAVA_HOME not found in your environment. >&2 65 | echo Please set the JAVA_HOME variable in your environment to match the >&2 66 | echo location of your Java installation. >&2 67 | echo. 68 | goto error 69 | 70 | :OkJHome 71 | if exist "%JAVA_HOME%\bin\java.exe" goto init 72 | 73 | echo. 74 | echo Error: JAVA_HOME is set to an invalid directory. >&2 75 | echo JAVA_HOME = "%JAVA_HOME%" >&2 76 | echo Please set the JAVA_HOME variable in your environment to match the >&2 77 | echo location of your Java installation. >&2 78 | echo. 79 | goto error 80 | 81 | @REM ==== END VALIDATION ==== 82 | 83 | :init 84 | 85 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 86 | @REM Fallback to current working directory if not found. 87 | 88 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 89 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 90 | 91 | set EXEC_DIR=%CD% 92 | set WDIR=%EXEC_DIR% 93 | :findBaseDir 94 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 95 | cd .. 96 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 97 | set WDIR=%CD% 98 | goto findBaseDir 99 | 100 | :baseDirFound 101 | set MAVEN_PROJECTBASEDIR=%WDIR% 102 | cd "%EXEC_DIR%" 103 | goto endDetectBaseDir 104 | 105 | :baseDirNotFound 106 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 107 | cd "%EXEC_DIR%" 108 | 109 | :endDetectBaseDir 110 | 111 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 112 | 113 | @setlocal EnableExtensions EnableDelayedExpansion 114 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 115 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 116 | 117 | :endReadAdditionalConfig 118 | 119 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 120 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 121 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 122 | 123 | set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 124 | 125 | FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( 126 | IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B 127 | ) 128 | 129 | @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 130 | @REM This allows using the maven wrapper in projects that prohibit checking in binary data. 131 | if exist %WRAPPER_JAR% ( 132 | if "%MVNW_VERBOSE%" == "true" ( 133 | echo Found %WRAPPER_JAR% 134 | ) 135 | ) else ( 136 | if not "%MVNW_REPOURL%" == "" ( 137 | SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 138 | ) 139 | if "%MVNW_VERBOSE%" == "true" ( 140 | echo Couldn't find %WRAPPER_JAR%, downloading it ... 141 | echo Downloading from: %DOWNLOAD_URL% 142 | ) 143 | 144 | powershell -Command "&{"^ 145 | "$webclient = new-object System.Net.WebClient;"^ 146 | "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ 147 | "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ 148 | "}"^ 149 | "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ 150 | "}" 151 | if "%MVNW_VERBOSE%" == "true" ( 152 | echo Finished downloading %WRAPPER_JAR% 153 | ) 154 | ) 155 | @REM End of extension 156 | 157 | @REM Provide a "standardized" way to retrieve the CLI args that will 158 | @REM work with both Windows and non-Windows executions. 159 | set MAVEN_CMD_LINE_ARGS=%* 160 | 161 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 162 | if ERRORLEVEL 1 goto error 163 | goto end 164 | 165 | :error 166 | set ERROR_CODE=1 167 | 168 | :end 169 | @endlocal & set ERROR_CODE=%ERROR_CODE% 170 | 171 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 172 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 173 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 174 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 175 | :skipRcPost 176 | 177 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 178 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 179 | 180 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 181 | 182 | exit /B %ERROR_CODE% 183 | -------------------------------------------------------------------------------- /testing.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /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 | # https://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 | # Maven Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Mingw, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | fi 118 | 119 | if [ -z "$JAVA_HOME" ]; then 120 | javaExecutable="`which javac`" 121 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 122 | # readlink(1) is not available as standard on Solaris 10. 123 | readLink=`which readlink` 124 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 125 | if $darwin ; then 126 | javaHome="`dirname \"$javaExecutable\"`" 127 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 128 | else 129 | javaExecutable="`readlink -f \"$javaExecutable\"`" 130 | fi 131 | javaHome="`dirname \"$javaExecutable\"`" 132 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 133 | JAVA_HOME="$javaHome" 134 | export JAVA_HOME 135 | fi 136 | fi 137 | fi 138 | 139 | if [ -z "$JAVACMD" ] ; then 140 | if [ -n "$JAVA_HOME" ] ; then 141 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 142 | # IBM's JDK on AIX uses strange locations for the executables 143 | JAVACMD="$JAVA_HOME/jre/sh/java" 144 | else 145 | JAVACMD="$JAVA_HOME/bin/java" 146 | fi 147 | else 148 | JAVACMD="`which java`" 149 | fi 150 | fi 151 | 152 | if [ ! -x "$JAVACMD" ] ; then 153 | echo "Error: JAVA_HOME is not defined correctly." >&2 154 | echo " We cannot execute $JAVACMD" >&2 155 | exit 1 156 | fi 157 | 158 | if [ -z "$JAVA_HOME" ] ; then 159 | echo "Warning: JAVA_HOME environment variable is not set." 160 | fi 161 | 162 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 163 | 164 | # traverses directory structure from process work directory to filesystem root 165 | # first directory with .mvn subdirectory is considered project base directory 166 | find_maven_basedir() { 167 | 168 | if [ -z "$1" ] 169 | then 170 | echo "Path not specified to find_maven_basedir" 171 | return 1 172 | fi 173 | 174 | basedir="$1" 175 | wdir="$1" 176 | while [ "$wdir" != '/' ] ; do 177 | if [ -d "$wdir"/.mvn ] ; then 178 | basedir=$wdir 179 | break 180 | fi 181 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 182 | if [ -d "${wdir}" ]; then 183 | wdir=`cd "$wdir/.."; pwd` 184 | fi 185 | # end of workaround 186 | done 187 | echo "${basedir}" 188 | } 189 | 190 | # concatenates all lines of a file 191 | concat_lines() { 192 | if [ -f "$1" ]; then 193 | echo "$(tr -s '\n' ' ' < "$1")" 194 | fi 195 | } 196 | 197 | BASE_DIR=`find_maven_basedir "$(pwd)"` 198 | if [ -z "$BASE_DIR" ]; then 199 | exit 1; 200 | fi 201 | 202 | ########################################################################################## 203 | # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central 204 | # This allows using the maven wrapper in projects that prohibit checking in binary data. 205 | ########################################################################################## 206 | if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then 207 | if [ "$MVNW_VERBOSE" = true ]; then 208 | echo "Found .mvn/wrapper/maven-wrapper.jar" 209 | fi 210 | else 211 | if [ "$MVNW_VERBOSE" = true ]; then 212 | echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." 213 | fi 214 | if [ -n "$MVNW_REPOURL" ]; then 215 | jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 216 | else 217 | jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" 218 | fi 219 | while IFS="=" read key value; do 220 | case "$key" in (wrapperUrl) jarUrl="$value"; break ;; 221 | esac 222 | done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" 223 | if [ "$MVNW_VERBOSE" = true ]; then 224 | echo "Downloading from: $jarUrl" 225 | fi 226 | wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" 227 | if $cygwin; then 228 | wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` 229 | fi 230 | 231 | if command -v wget > /dev/null; then 232 | if [ "$MVNW_VERBOSE" = true ]; then 233 | echo "Found wget ... using wget" 234 | fi 235 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 236 | wget "$jarUrl" -O "$wrapperJarPath" 237 | else 238 | wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" 239 | fi 240 | elif command -v curl > /dev/null; then 241 | if [ "$MVNW_VERBOSE" = true ]; then 242 | echo "Found curl ... using curl" 243 | fi 244 | if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then 245 | curl -o "$wrapperJarPath" "$jarUrl" -f 246 | else 247 | curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f 248 | fi 249 | 250 | else 251 | if [ "$MVNW_VERBOSE" = true ]; then 252 | echo "Falling back to using Java to download" 253 | fi 254 | javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" 255 | # For Cygwin, switch paths to Windows format before running javac 256 | if $cygwin; then 257 | javaClass=`cygpath --path --windows "$javaClass"` 258 | fi 259 | if [ -e "$javaClass" ]; then 260 | if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 261 | if [ "$MVNW_VERBOSE" = true ]; then 262 | echo " - Compiling MavenWrapperDownloader.java ..." 263 | fi 264 | # Compiling the Java class 265 | ("$JAVA_HOME/bin/javac" "$javaClass") 266 | fi 267 | if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then 268 | # Running the downloader 269 | if [ "$MVNW_VERBOSE" = true ]; then 270 | echo " - Running MavenWrapperDownloader.java ..." 271 | fi 272 | ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") 273 | fi 274 | fi 275 | fi 276 | fi 277 | ########################################################################################## 278 | # End of extension 279 | ########################################################################################## 280 | 281 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 282 | if [ "$MVNW_VERBOSE" = true ]; then 283 | echo $MAVEN_PROJECTBASEDIR 284 | fi 285 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 286 | 287 | # For Cygwin, switch paths to Windows format before running java 288 | if $cygwin; then 289 | [ -n "$M2_HOME" ] && 290 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 291 | [ -n "$JAVA_HOME" ] && 292 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 293 | [ -n "$CLASSPATH" ] && 294 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 295 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 296 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 297 | fi 298 | 299 | # Provide a "standardized" way to retrieve the CLI args that will 300 | # work with both Windows and non-Windows executions. 301 | MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" 302 | export MAVEN_CMD_LINE_ARGS 303 | 304 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 305 | 306 | exec "$JAVACMD" \ 307 | $MAVEN_OPTS \ 308 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 309 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 310 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 311 | --------------------------------------------------------------------------------