├── .gradle
├── 6.3
│ ├── gc.properties
│ ├── fileChanges
│ │ └── last-build.bin
│ ├── fileHashes
│ │ ├── fileHashes.bin
│ │ └── fileHashes.lock
│ ├── fileContent
│ │ └── fileContent.lock
│ └── executionHistory
│ │ ├── executionHistory.bin
│ │ └── executionHistory.lock
├── 6.5
│ ├── gc.properties
│ ├── fileChanges
│ │ └── last-build.bin
│ ├── fileHashes
│ │ ├── fileHashes.bin
│ │ └── fileHashes.lock
│ ├── fileContent
│ │ └── fileContent.lock
│ └── executionHistory
│ │ ├── executionHistory.bin
│ │ └── executionHistory.lock
├── vcs-1
│ └── gc.properties
├── buildOutputCleanup
│ ├── cache.properties
│ ├── outputFiles.bin
│ └── buildOutputCleanup.lock
└── checksums
│ ├── checksums.lock
│ ├── md5-checksums.bin
│ └── sha1-checksums.bin
├── gradle.properties
├── settings.gradle
├── .idea
├── .gitignore
├── compiler.xml
├── emacs.xml
├── ClojureProjectResolveSettings.xml
├── misc.xml
├── gradle.xml
└── jarRepositories.xml
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── src
└── test
│ └── kotlin
│ ├── Calculator.kt
│ ├── Singleton.kt
│ ├── Strategy.kt
│ ├── LazyInitialization.kt
│ ├── Command.kt
│ ├── Proxy.kt
│ ├── Mediator.kt
│ ├── FactoryMethod.kt
│ ├── Composite.kt
│ ├── Facade.kt
│ ├── AbstractFactory.kt
│ ├── Decorator.kt
│ ├── Bridge.kt
│ ├── Builder.kt
│ ├── State.kt
│ ├── Memento.kt
│ ├── Adapter.kt
│ ├── Prototype.kt
│ ├── ChainOfResponsibility.kt
│ ├── Observer.kt
│ └── Visitor.kt
├── gradlew.bat
└── gradlew
/.gradle/6.3/gc.properties:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gradle/6.5/gc.properties:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gradle/vcs-1/gc.properties:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gradle/6.3/fileChanges/last-build.bin:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gradle/6.5/fileChanges/last-build.bin:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'KotlinDesignPatterns'
2 |
3 |
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.gradle/buildOutputCleanup/cache.properties:
--------------------------------------------------------------------------------
1 | #Sun Sep 13 15:00:34 EEST 2020
2 | gradle.version=6.3
3 |
--------------------------------------------------------------------------------
/.gradle/checksums/checksums.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/checksums/checksums.lock
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/.gradle/checksums/md5-checksums.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/checksums/md5-checksums.bin
--------------------------------------------------------------------------------
/.gradle/checksums/sha1-checksums.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/checksums/sha1-checksums.bin
--------------------------------------------------------------------------------
/.gradle/6.3/fileHashes/fileHashes.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/6.3/fileHashes/fileHashes.bin
--------------------------------------------------------------------------------
/.gradle/6.3/fileHashes/fileHashes.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/6.3/fileHashes/fileHashes.lock
--------------------------------------------------------------------------------
/.gradle/6.5/fileHashes/fileHashes.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/6.5/fileHashes/fileHashes.bin
--------------------------------------------------------------------------------
/.gradle/6.5/fileHashes/fileHashes.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/6.5/fileHashes/fileHashes.lock
--------------------------------------------------------------------------------
/.gradle/6.3/fileContent/fileContent.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/6.3/fileContent/fileContent.lock
--------------------------------------------------------------------------------
/.gradle/6.5/fileContent/fileContent.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/6.5/fileContent/fileContent.lock
--------------------------------------------------------------------------------
/.gradle/buildOutputCleanup/outputFiles.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/buildOutputCleanup/outputFiles.bin
--------------------------------------------------------------------------------
/.gradle/6.3/executionHistory/executionHistory.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/6.3/executionHistory/executionHistory.bin
--------------------------------------------------------------------------------
/.gradle/6.5/executionHistory/executionHistory.bin:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/6.5/executionHistory/executionHistory.bin
--------------------------------------------------------------------------------
/.gradle/6.3/executionHistory/executionHistory.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/6.3/executionHistory/executionHistory.lock
--------------------------------------------------------------------------------
/.gradle/6.5/executionHistory/executionHistory.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/6.5/executionHistory/executionHistory.lock
--------------------------------------------------------------------------------
/.gradle/buildOutputCleanup/buildOutputCleanup.lock:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/CatalinStefan/KotlinDesignPatterns/HEAD/.gradle/buildOutputCleanup/buildOutputCleanup.lock
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/emacs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/ClojureProjectResolveSettings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | IDE
5 |
6 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 |
--------------------------------------------------------------------------------
/src/test/kotlin/Calculator.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | class Calculator {
5 | fun sum(a: Int, b: Int) = a + b
6 | }
7 |
8 | class CalculatorTest {
9 | @Test
10 | fun testSum() {
11 | val calc = Calculator()
12 | Assertions.assertThat(calc.sum(3, 5)).isEqualTo(8)
13 | }
14 | }
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/src/test/kotlin/Singleton.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | object NetworkDriver {
5 | init {
6 | println("Initializing: $this")
7 | }
8 |
9 | fun log(): NetworkDriver = apply { println("Network driver: $this") }
10 | }
11 |
12 | class SingletonTest {
13 | @Test
14 | fun testSingleton() {
15 | println("Start")
16 | val networkDriver1 = NetworkDriver.log()
17 | val networkDriver2 = NetworkDriver.log()
18 |
19 | Assertions.assertThat(networkDriver1).isSameAs(NetworkDriver)
20 | Assertions.assertThat(networkDriver2).isSameAs(NetworkDriver)
21 | }
22 | }
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
18 |
19 |
--------------------------------------------------------------------------------
/src/test/kotlin/Strategy.kt:
--------------------------------------------------------------------------------
1 | import org.junit.jupiter.api.Test
2 |
3 | class Printer(private val stringFormatterStrategy: (String) -> String) {
4 | fun printString(message: String) {
5 | println(stringFormatterStrategy(message))
6 | }
7 | }
8 |
9 | val lowercaseFormatter = {it: String -> it.toLowerCase()}
10 | val uppercaseFormatter = {it: String -> it.toUpperCase()}
11 |
12 | class StrategyTest {
13 | @Test
14 | fun testStrategy() {
15 | val inputString = "LOREM ipsum DOLOR sit amet"
16 |
17 | val lowercasePrinter = Printer(lowercaseFormatter)
18 | lowercasePrinter.printString(inputString)
19 |
20 | val uppercasePrinter = Printer(uppercaseFormatter)
21 | uppercasePrinter.printString(inputString)
22 | }
23 | }
--------------------------------------------------------------------------------
/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/src/test/kotlin/LazyInitialization.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | class AlertBox {
5 | var message: String? = null
6 |
7 | fun show() {
8 | println("AlertBox $this: $message")
9 | }
10 | }
11 |
12 | class Window {
13 | val box by lazy { AlertBox() }
14 |
15 | fun showMessage(message: String) {
16 | box.message = message
17 | box.show()
18 | }
19 | }
20 |
21 | class Window2 {
22 | lateinit var box: AlertBox
23 |
24 | fun showMessage(message: String) {
25 | box = AlertBox()
26 | box.message = message
27 | box.show()
28 | }
29 | }
30 |
31 | class WindowTest {
32 | @Test
33 | fun windowTest() {
34 | val window = Window()
35 | window.showMessage("Hello window")
36 | Assertions.assertThat(window.box).isNotNull
37 |
38 | val window2 = Window2()
39 | // println(window2.box)
40 | window2.showMessage("Second window")
41 | Assertions.assertThat(window2.box).isNotNull
42 | }
43 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Command.kt:
--------------------------------------------------------------------------------
1 | import org.junit.jupiter.api.Test
2 |
3 | interface Command {
4 | fun execute()
5 | }
6 |
7 | class OrderAddCommand(val id: Long) : Command {
8 | override fun execute() {
9 | println("Adding order with id $id")
10 | }
11 | }
12 |
13 | class OrderPayCommand(val id: Long) : Command {
14 | override fun execute() {
15 | println("Paying for order with id $id")
16 | }
17 | }
18 |
19 | class CommandProcessor {
20 | private val queue = arrayListOf()
21 |
22 | fun addToQueue(command: Command): CommandProcessor = apply { queue.add(command) }
23 |
24 | fun processCommands(): CommandProcessor = apply {
25 | queue.forEach { it.execute() }
26 | queue.clear()
27 | }
28 | }
29 |
30 | class CommandTest {
31 | @Test
32 | fun testCommand() {
33 | CommandProcessor()
34 | .addToQueue(OrderAddCommand(1L))
35 | .addToQueue(OrderAddCommand(2L))
36 | .addToQueue(OrderPayCommand(2L))
37 | .addToQueue(OrderPayCommand(1L))
38 | .processCommands()
39 | }
40 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Proxy.kt:
--------------------------------------------------------------------------------
1 | import org.junit.jupiter.api.Test
2 |
3 | interface Image {
4 | fun display()
5 | }
6 |
7 | class RealImage(private val filename: String): Image {
8 | override fun display() {
9 | println("RealImage: Displaying $filename")
10 | }
11 |
12 | private fun loadFromDisk(filename: String) {
13 | println("RealImage: Loading $filename")
14 | }
15 |
16 | init {
17 | loadFromDisk(filename)
18 | }
19 | }
20 |
21 | class ProxyImage(private val filename: String): Image {
22 | private var realImage: RealImage? = null
23 |
24 | override fun display() {
25 | println("ProxyImage: Displaying $filename")
26 | if (realImage == null) {
27 | realImage = RealImage(filename)
28 | }
29 | realImage!!.display()
30 | }
31 | }
32 |
33 | class ProxyTest {
34 | @Test
35 | fun testProxy() {
36 | val image = ProxyImage("test.jpg")
37 |
38 | // load image from disk
39 | image.display()
40 | println("-------------------")
41 |
42 | //load image from "cache"
43 | image.display()
44 | }
45 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Mediator.kt:
--------------------------------------------------------------------------------
1 | import org.junit.jupiter.api.Test
2 |
3 | class ChatUser(private val mediator: Mediator, private val name: String) {
4 | fun send(msg: String) {
5 | println("$name: Sending message: $msg")
6 | mediator.sendMessage(msg, this)
7 | }
8 |
9 | fun receive(msg: String) {
10 | println("$name: Received message: $msg")
11 | }
12 | }
13 |
14 | class Mediator {
15 | private val users = arrayListOf()
16 |
17 | fun sendMessage(msg: String, user: ChatUser) {
18 | users
19 | .filter { it != user }
20 | .forEach { it.receive(msg) }
21 | }
22 |
23 | fun addUser(user: ChatUser): Mediator = apply { users.add(user) }
24 | }
25 |
26 | class MediatorTest {
27 | @Test
28 | fun testMediator() {
29 | val mediator = Mediator()
30 | val alice = ChatUser(mediator, "Alice")
31 | val bob = ChatUser(mediator, "Bob")
32 | val carol = ChatUser(mediator, "Carol")
33 |
34 | mediator.addUser(alice)
35 | .addUser(bob)
36 | .addUser(carol)
37 |
38 | carol.send("Hi everyone!")
39 | }
40 | }
--------------------------------------------------------------------------------
/src/test/kotlin/FactoryMethod.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | sealed class Country {
5 | object Canada: Country()
6 | }
7 |
8 | object Spain: Country()
9 | class Greece(val someProperty: String): Country()
10 | data class USA(val someProperty: String): Country()
11 | //class Poland: Country()
12 |
13 | class Currency (val code: String)
14 |
15 | object CurrencyFactory {
16 | fun currencyForCountry(country: Country): Currency =
17 | when(country) {
18 | is Spain -> Currency("EUR")
19 | is Greece -> Currency("EUR")
20 | is USA -> Currency("USD")
21 | is Country.Canada -> Currency("CAD")
22 | }
23 | }
24 |
25 | class FactoryMethodTest {
26 | @Test
27 | fun currencyTest() {
28 | val greekCurrency = CurrencyFactory.currencyForCountry(Greece("")).code
29 | println("Greek currency: $greekCurrency")
30 |
31 | val usaCurrency = CurrencyFactory.currencyForCountry(USA("")).code
32 | println("USA currency: $usaCurrency")
33 |
34 | Assertions.assertThat(greekCurrency).isEqualTo("EUR")
35 | Assertions.assertThat(usaCurrency).isEqualTo("USD")
36 | }
37 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Composite.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | open class Equipment(
5 | open val price: Int,
6 | val name: String
7 | )
8 |
9 | open class Composite(name: String): Equipment(0, name) {
10 | private val equipments = ArrayList()
11 |
12 | override val price: Int
13 | get() = equipments.map { it.price }.sum()
14 |
15 | fun add(equipment: Equipment) = apply { equipments.add(equipment) }
16 | }
17 |
18 | class Computer: Composite("PC")
19 | class Processor: Equipment(1000, "Processor")
20 | class HardDrive: Equipment(250, "Hard Drive")
21 | class Memory: Composite("Memory")
22 | class ROM: Equipment(100, "Read Only Memory")
23 | class RAM: Equipment(75, "Random Access Memory")
24 |
25 | class CompositeTest {
26 | @Test
27 | fun testComposite() {
28 | val memory = Memory()
29 | .add(ROM())
30 | .add(RAM())
31 | val pc = Computer()
32 | .add(memory)
33 | .add(Processor())
34 | .add(HardDrive())
35 | println("PC price: ${pc.price}")
36 |
37 | Assertions.assertThat(pc.name).isEqualTo("PC")
38 | Assertions.assertThat(pc.price).isEqualTo(1425)
39 | }
40 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Facade.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | class ComplexSystemStore (private val filePath: String) {
5 | private val cache: HashMap
6 |
7 | init {
8 | println("Reading data from the file: $filePath")
9 | cache = HashMap()
10 | // Read properties from file and put to cache
11 | }
12 |
13 | fun store(key: String, value: String) {
14 | cache[key] = value
15 | }
16 |
17 | fun read(key: String) = cache[key] ?: ""
18 |
19 | fun commit() = println("Storing cached data to file $filePath")
20 | }
21 |
22 | data class User(val login: String)
23 |
24 |
25 | // Facade
26 | class UserRepository {
27 | private val systemPreferences = ComplexSystemStore("/data/default.prefs")
28 |
29 | fun save(user: User) {
30 | systemPreferences.store("USER_KEY", user.login)
31 | systemPreferences.commit()
32 | }
33 |
34 | fun findFirst(): User = User(systemPreferences.read("USER_KEY"))
35 | }
36 |
37 | class FacadeTest {
38 | @Test
39 | fun testFacade() {
40 | val userRepo = UserRepository()
41 | val user = User("john")
42 | userRepo.save(user)
43 |
44 | val retrievedUser = userRepo.findFirst()
45 |
46 | Assertions.assertThat(retrievedUser.login).isEqualTo("john")
47 | }
48 | }
--------------------------------------------------------------------------------
/src/test/kotlin/AbstractFactory.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | interface DataSource
5 |
6 | class DatabaseDataSource: DataSource
7 |
8 | class NetworkDataSource: DataSource
9 |
10 | abstract class DataSourceFactory {
11 | abstract fun makeDataSource(): DataSource
12 |
13 | companion object {
14 | inline fun createFactory(): DataSourceFactory =
15 | when(T::class) {
16 | DatabaseDataSource::class -> DatabaseFactory()
17 | NetworkDataSource::class -> NetworkFactory()
18 | else -> throw IllegalArgumentException()
19 | }
20 | }
21 | }
22 |
23 | class NetworkFactory: DataSourceFactory() {
24 | override fun makeDataSource(): DataSource = NetworkDataSource()
25 | }
26 |
27 | class DatabaseFactory: DataSourceFactory() {
28 | override fun makeDataSource(): DataSource = DatabaseDataSource()
29 | }
30 |
31 | class AbstractFactoryTest {
32 | @Test
33 | fun aftest() {
34 | val datasourceFactory = DataSourceFactory.createFactory()
35 | val dataSource = datasourceFactory.makeDataSource()
36 | println("Created datasource $dataSource")
37 |
38 | Assertions.assertThat(dataSource).isInstanceOf(DatabaseDataSource::class.java)
39 | }
40 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Decorator.kt:
--------------------------------------------------------------------------------
1 | import org.junit.jupiter.api.Test
2 |
3 | interface CoffeeMachine {
4 | fun makeSmallCoffee()
5 | fun makeLargeCoffee()
6 | }
7 |
8 | class NormalCoffeeMachine: CoffeeMachine {
9 | override fun makeSmallCoffee() {
10 | println("Normal coffee machine: Making small coffee")
11 | }
12 |
13 | override fun makeLargeCoffee() {
14 | println("Normal coffee machine: Making large coffee")
15 | }
16 | }
17 |
18 | // Decorator
19 | class EnhancedCoffeeMachine(private val coffeeMachine: CoffeeMachine): CoffeeMachine by coffeeMachine {
20 | // Overriding behaviour
21 | override fun makeLargeCoffee() {
22 | println("Enhanced coffee machine: Making large coffee")
23 | }
24 |
25 | // Extending behaviour
26 | fun makeMilkCoffee() {
27 | println("Enhanced coffee machine: Making milk coffee")
28 | coffeeMachine.makeSmallCoffee()
29 | println("Enhanced coffee machine: Adding milk")
30 | }
31 | }
32 |
33 | class DecoratorTest {
34 | @Test
35 | fun testDecorator() {
36 | val normalMachine = NormalCoffeeMachine()
37 | val enhancedMachine = EnhancedCoffeeMachine(normalMachine)
38 |
39 | enhancedMachine.makeSmallCoffee()
40 | println("------------------")
41 | enhancedMachine.makeLargeCoffee()
42 | println("------------------")
43 | enhancedMachine.makeMilkCoffee()
44 | }
45 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Bridge.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | interface Device {
5 | var volume: Int
6 | fun getName(): String
7 | }
8 |
9 | class Radio: Device {
10 | override var volume = 0
11 | override fun getName() = "Radio $this"
12 | }
13 |
14 | class TV: Device {
15 | override var volume = 0
16 | override fun getName() = "TV $this"
17 | }
18 |
19 | interface Remote {
20 | fun volumeUp()
21 | fun volumeDown()
22 | }
23 |
24 | class BasicRemote(val device: Device): Remote {
25 | override fun volumeUp() {
26 | device.volume++
27 | println("${device.getName()} volume up: ${device.volume}")
28 | }
29 |
30 | override fun volumeDown() {
31 | device.volume--
32 | println("${device.getName()} volume down: ${device.volume}")
33 | }
34 | }
35 |
36 | class BridgeTest {
37 | @Test
38 | fun testBridge() {
39 | val tv = TV()
40 | val radio = Radio()
41 |
42 | val tvRemote = BasicRemote(tv)
43 | val radioRemote = BasicRemote(radio)
44 |
45 | tvRemote.volumeUp()
46 | tvRemote.volumeUp()
47 | tvRemote.volumeDown()
48 |
49 | radioRemote.volumeUp()
50 | radioRemote.volumeUp()
51 | radioRemote.volumeUp()
52 | radioRemote.volumeDown()
53 |
54 | Assertions.assertThat(tv.volume).isEqualTo(1)
55 | Assertions.assertThat(radio.volume).isEqualTo(2)
56 | }
57 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Builder.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | class Component private constructor(builder: Builder) {
5 | var param1: String? = null
6 | var param2: Int? = null
7 | var param3: Boolean? = null
8 |
9 | class Builder {
10 | private var param1: String? = null
11 | private var param2: Int? = null
12 | private var param3: Boolean? = null
13 |
14 | fun setParam1(param1: String) = apply { this.param1 = param1 }
15 | fun setParam2(param2: Int) = apply { this.param2 = param2 }
16 | fun setParam3(param3: Boolean) = apply { this.param3 = param3 }
17 | fun build() = Component(this)
18 |
19 | fun getParam1() = param1
20 | fun getParam2() = param2
21 | fun getParam3() = param3
22 | }
23 |
24 | init {
25 | param1 = builder.getParam1()
26 | param2 = builder.getParam2()
27 | param3 = builder.getParam3()
28 | }
29 | }
30 |
31 | class ComponentTest {
32 | @Test
33 | fun builderTest() {
34 | val component = Component.Builder()
35 | .setParam1("Some value")
36 | .setParam3(true)
37 | .build()
38 | println(component)
39 | println(component.param1)
40 | println(component.param3)
41 |
42 | Assertions.assertThat(component.param1).isEqualTo("Some value")
43 | Assertions.assertThat(component.param3).isEqualTo(true)
44 | Assertions.assertThat(component.param2).isEqualTo(null)
45 |
46 | }
47 | }
--------------------------------------------------------------------------------
/src/test/kotlin/State.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | sealed class AuthorizationState
5 |
6 | object Unauthorized : AuthorizationState()
7 |
8 | class Authorized(val username: String) : AuthorizationState()
9 |
10 | class AuthorizationPresenter {
11 | private var state: AuthorizationState = Unauthorized
12 |
13 | val isAuthorized: Boolean
14 | get() = when (state) {
15 | is Authorized -> true
16 | is Unauthorized -> false
17 | }
18 |
19 | val username: String
20 | get() {
21 | return when (val state = this.state) {
22 | is Authorized -> state.username
23 | is Unauthorized -> "Unknown"
24 | }
25 | }
26 |
27 | fun loginUser(username: String) {
28 | state = Authorized(username)
29 | }
30 |
31 | fun logoutUser() {
32 | state = Unauthorized
33 | }
34 |
35 | override fun toString() = "User $username is logged in: $isAuthorized"
36 | }
37 |
38 | class StateTest {
39 | @Test
40 | fun testState() {
41 | val authorizationPresenter = AuthorizationPresenter()
42 |
43 | authorizationPresenter.loginUser("admin")
44 | println(authorizationPresenter)
45 | Assertions.assertThat(authorizationPresenter.isAuthorized).isEqualTo(true)
46 | Assertions.assertThat(authorizationPresenter.username).isEqualTo("admin")
47 |
48 | authorizationPresenter.logoutUser()
49 | println(authorizationPresenter)
50 | Assertions.assertThat(authorizationPresenter.isAuthorized).isEqualTo(false)
51 | Assertions.assertThat(authorizationPresenter.username).isEqualTo("Unknown")
52 | }
53 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Memento.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | data class Memento(val state: String)
5 |
6 | class Originator(var state: String) {
7 | fun createMemento() = Memento(state)
8 | fun restoreMemento(memento: Memento) {
9 | state = memento.state
10 | }
11 | }
12 |
13 | class CareTaker {
14 | private val mementoList = arrayListOf()
15 |
16 | fun saveState(state: Memento) {
17 | mementoList.add(state)
18 | }
19 |
20 | fun restore(index: Int): Memento = mementoList[index]
21 | }
22 |
23 | class MementoTest {
24 | @Test
25 | fun testMemento() {
26 | val originator = Originator("initial state")
27 | val careTaker = CareTaker()
28 | careTaker.saveState(originator.createMemento())
29 | println("Current state is ${originator.state}")
30 |
31 | originator.state = "State 1"
32 | careTaker.saveState(originator.createMemento())
33 | println("Current state is ${originator.state}")
34 |
35 | originator.state = "State 2"
36 | careTaker.saveState(originator.createMemento())
37 | println("Current state is ${originator.state}")
38 |
39 | Assertions.assertThat(originator.state).isEqualTo("State 2")
40 |
41 | originator.restoreMemento(careTaker.restore(1))
42 | println("Current state is ${originator.state}")
43 | Assertions.assertThat(originator.state).isEqualTo("State 1")
44 |
45 | originator.restoreMemento(careTaker.restore(0))
46 | println("Current state is ${originator.state}")
47 | Assertions.assertThat(originator.state).isEqualTo("initial state")
48 |
49 | originator.restoreMemento(careTaker.restore(2))
50 | println("Current state is ${originator.state}")
51 | Assertions.assertThat(originator.state).isEqualTo("State 2")
52 | }
53 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Adapter.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | // 3rd party functionality
5 |
6 | data class DisplayDataType(val index: Float, val data: String)
7 |
8 | class DataDisplay {
9 | fun displayData(data: DisplayDataType) {
10 | println("Data is displayed: ${data.index} - ${data.data}")
11 | }
12 | }
13 |
14 | // ------------------------
15 | // Our code
16 |
17 | data class DatabaseData(val position: Int, val amount: Int)
18 |
19 | class DatabaseDataGenerator {
20 | fun generateData(): List {
21 | val list = arrayListOf()
22 | list.add(DatabaseData(2, 2))
23 | list.add(DatabaseData(3, 7))
24 | list.add(DatabaseData(4, 23))
25 | return list
26 | }
27 | }
28 |
29 | interface DatabaseDataConverter {
30 | fun convertData(data: List): List
31 | }
32 |
33 | class DataDisplayAdapter(val display: DataDisplay): DatabaseDataConverter {
34 | override fun convertData(data: List): List {
35 | val returnList = arrayListOf()
36 | for (datum in data) {
37 | val ddt = DisplayDataType(datum.position.toFloat(), datum.amount.toString())
38 | display.displayData(ddt)
39 | returnList.add(ddt)
40 | }
41 | return returnList
42 | }
43 | }
44 |
45 | class AdapterTest {
46 | @Test
47 | fun adapterTest() {
48 | val generator = DatabaseDataGenerator()
49 | val generatedData = generator.generateData()
50 | val adapter = DataDisplayAdapter(DataDisplay())
51 | val convertData = adapter.convertData(generatedData)
52 |
53 | Assertions.assertThat(convertData.size).isEqualTo(3)
54 | Assertions.assertThat(convertData[1].index).isEqualTo(3f)
55 | Assertions.assertThat(convertData[1].data).isEqualTo("7")
56 | }
57 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Prototype.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | abstract class Shape: Cloneable {
5 | var id: String? = null
6 | var type: String? = null
7 |
8 | abstract fun draw()
9 |
10 | public override fun clone(): Any {
11 | var clone: Any? = null
12 | try {
13 | clone = super.clone()
14 | } catch (e: CloneNotSupportedException) {
15 | e.printStackTrace()
16 | }
17 | return clone!!
18 | }
19 | }
20 |
21 | class Rectangle: Shape() {
22 | override fun draw() {
23 | println("Inside Rectangle::draw() method.")
24 | }
25 |
26 | init {
27 | type = "Rectangle"
28 | }
29 | }
30 |
31 | class Square: Shape() {
32 | override fun draw() {
33 | println("Inside Square::draw() method.")
34 | }
35 |
36 | init {
37 | type = "Square"
38 | }
39 | }
40 |
41 | class Circle: Shape() {
42 | override fun draw() {
43 | println("Inside Circle::draw() method.")
44 | }
45 |
46 | init {
47 | type = "Circle"
48 | }
49 | }
50 |
51 | object ShapeCache {
52 | private val shapeMap = hashMapOf()
53 |
54 | fun loadCache() {
55 | val circle = Circle()
56 | val square = Square()
57 | val rectangle = Rectangle()
58 |
59 | shapeMap.put("1", circle)
60 | shapeMap.put("2", square)
61 | shapeMap.put("3", rectangle)
62 | }
63 |
64 | fun getShape(shapeId: String): Shape {
65 | val cachedShape = shapeMap.get(shapeId)
66 | return cachedShape?.clone() as Shape
67 | }
68 | }
69 |
70 | class PrototypeTest {
71 | @Test
72 | fun testPrototype() {
73 | ShapeCache.loadCache()
74 | val clonedShape1 = ShapeCache.getShape("1")
75 | val clonedShape2 = ShapeCache.getShape("2")
76 | val clonedShape3 = ShapeCache.getShape("3")
77 |
78 | clonedShape1.draw()
79 | clonedShape2.draw()
80 | clonedShape3.draw()
81 |
82 | Assertions.assertThat(clonedShape1.type).isEqualTo("Circle")
83 | Assertions.assertThat(clonedShape2.type).isEqualTo("Square")
84 | Assertions.assertThat(clonedShape3.type).isEqualTo("Rectangle")
85 | }
86 | }
--------------------------------------------------------------------------------
/src/test/kotlin/ChainOfResponsibility.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | interface HandlerChain {
5 | fun addHeader(inputHeader: String): String
6 | }
7 |
8 | class AuthenticationHeader(val token: String?, var next: HandlerChain? = null): HandlerChain {
9 | override fun addHeader(inputHeader: String) =
10 | "$inputHeader\nAuthorization: $token"
11 | .let { next?.addHeader(it) ?: it }
12 | }
13 |
14 | class ContentTypeHeader(val contentType: String, var next: HandlerChain? = null): HandlerChain {
15 | override fun addHeader(inputHeader: String) =
16 | "$inputHeader\nContentType: $contentType"
17 | .let { next?.addHeader(it) ?: it }
18 | }
19 |
20 | class BodyPayloadHeader(val body: String, var next: HandlerChain? = null): HandlerChain {
21 | override fun addHeader(inputHeader: String) =
22 | "$inputHeader\n$body"
23 | .let { next?.addHeader(it) ?: it }
24 | }
25 |
26 | class ChainOfResponsibilityTest {
27 | @Test
28 | fun testChainOfResponsibility() {
29 | val authenticationHeader = AuthenticationHeader("123456")
30 | val contentTypeHeader = ContentTypeHeader("json")
31 | val bodyPayloadHeader = BodyPayloadHeader("Body: {\"username\" = \"john\"}")
32 |
33 | authenticationHeader.next = contentTypeHeader
34 | contentTypeHeader.next = bodyPayloadHeader
35 |
36 | val messageWithAuthentication = authenticationHeader.addHeader("Headers with authentication")
37 | println(messageWithAuthentication)
38 |
39 | println("-------------------------")
40 |
41 | val messageWithoutAuthentication = contentTypeHeader.addHeader("Headers without authentication")
42 | println(messageWithoutAuthentication)
43 |
44 | Assertions.assertThat(messageWithAuthentication).isEqualTo(
45 | """
46 | Headers with authentication
47 | Authorization: 123456
48 | ContentType: json
49 | Body: {"username" = "john"}
50 | """.trimIndent()
51 | )
52 |
53 | Assertions.assertThat(messageWithoutAuthentication).isEqualTo(
54 | """
55 | Headers without authentication
56 | ContentType: json
57 | Body: {"username" = "john"}
58 | """.trimIndent()
59 | )
60 | }
61 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Observer.kt:
--------------------------------------------------------------------------------
1 | import org.junit.jupiter.api.Test
2 | import java.io.File
3 |
4 | interface EventListener {
5 | fun update(eventType: String?, file: File?)
6 | }
7 |
8 | class EventManager(vararg operations: String) {
9 | var listeners = hashMapOf>()
10 |
11 | init {
12 | for (operation in operations) {
13 | listeners[operation] = ArrayList()
14 | }
15 | }
16 |
17 | fun subscribe(eventType: String?, listener: EventListener) {
18 | val users = listeners.get(eventType)
19 | users?.add(listener)
20 | }
21 |
22 | fun unsubscribe(eventType: String?, listener: EventListener) {
23 | val users = listeners.get(eventType)
24 | users?.remove(listener)
25 | }
26 |
27 | fun notify(eventType: String?, file: File?) {
28 | val users = listeners.get(eventType)
29 | users?.let {
30 | for (listener in it) {
31 | listener.update(eventType, file)
32 | }
33 | }
34 | }
35 | }
36 |
37 | class Editor {
38 | var events = EventManager("open", "save")
39 |
40 | private var file: File? = null
41 |
42 | fun openFile(filePath: String) {
43 | file = File(filePath)
44 | events.notify("open", file)
45 | }
46 |
47 | fun saveFile() {
48 | file?.let {
49 | events.notify("save", file)
50 | }
51 | }
52 | }
53 |
54 | class EmailNotificationListener(private val email: String): EventListener {
55 | override fun update(eventType: String?, file: File?) {
56 | println("Email to $email: Someone has performed $eventType operation with the file ${file?.name}")
57 | }
58 | }
59 |
60 | class LogOpenListener(var filename: String): EventListener {
61 | override fun update(eventType: String?, file: File?) {
62 | println("Save to log $filename: Someone has performed $eventType operation with the file ${file?.name}")
63 | }
64 | }
65 |
66 | class ObserverTest {
67 | @Test
68 | fun testObserver() {
69 | val editor = Editor()
70 |
71 | val logListener = LogOpenListener("path/to/log/file.txt")
72 | val emailListener = EmailNotificationListener("test@test.com")
73 |
74 | editor.events.subscribe("open", logListener)
75 | editor.events.subscribe("open", emailListener)
76 | editor.events.subscribe("save", emailListener)
77 |
78 | editor.openFile("test.txt")
79 | editor.saveFile()
80 | }
81 | }
--------------------------------------------------------------------------------
/src/test/kotlin/Visitor.kt:
--------------------------------------------------------------------------------
1 | import org.assertj.core.api.Assertions
2 | import org.junit.jupiter.api.Test
3 |
4 | interface ReportElement {
5 | fun accept(visitor: ReportVisitor): R
6 | }
7 |
8 | class FixedPriceContract(val costPerYear: Long) : ReportElement {
9 | override fun accept(visitor: ReportVisitor): R = visitor.visit(this)
10 | }
11 |
12 | class TimeAndMaterialsContract(val costPerHour: Long, val hours: Long) : ReportElement {
13 | override fun accept(visitor: ReportVisitor): R = visitor.visit(this)
14 | }
15 |
16 | class SupportContract(val costPerMonth: Long) : ReportElement {
17 | override fun accept(visitor: ReportVisitor): R = visitor.visit(this)
18 | }
19 |
20 | interface ReportVisitor {
21 | fun visit(contract: FixedPriceContract): R
22 | fun visit(contract: TimeAndMaterialsContract): R
23 | fun visit(contract: SupportContract): R
24 | }
25 |
26 | class MonthlyCostReportVisitor : ReportVisitor {
27 | override fun visit(contract: FixedPriceContract): Long = contract.costPerYear / 12
28 |
29 | override fun visit(contract: TimeAndMaterialsContract): Long = contract.costPerHour * contract.hours
30 |
31 | override fun visit(contract: SupportContract): Long = contract.costPerMonth
32 | }
33 |
34 | class YearlyCostReportVisitor : ReportVisitor {
35 | override fun visit(contract: FixedPriceContract): Long = contract.costPerYear
36 |
37 | override fun visit(contract: TimeAndMaterialsContract): Long = contract.costPerHour * contract.hours
38 |
39 | override fun visit(contract: SupportContract): Long = contract.costPerMonth * 12
40 | }
41 |
42 | class VisitorTest {
43 | @Test
44 | fun testVisitor() {
45 | val projectAlpha = FixedPriceContract(10_000)
46 | val projectBeta = SupportContract(500)
47 | val projectGamma = TimeAndMaterialsContract(150, 10)
48 | val projectKappa = TimeAndMaterialsContract(50, 50)
49 |
50 | val project = arrayListOf(projectAlpha, projectBeta, projectGamma, projectKappa)
51 |
52 | val monthlyCostVisitor = MonthlyCostReportVisitor()
53 | val monthlyCost = project.map { it.accept(monthlyCostVisitor) }.sum()
54 | println("Monthly cost: $monthlyCost")
55 | Assertions.assertThat(monthlyCost).isEqualTo(5333)
56 |
57 | val yearlyCostVisitor = YearlyCostReportVisitor()
58 | val yearlyCost = project.map { it.accept(yearlyCostVisitor) }.sum()
59 | println("Yearly cost: $yearlyCost")
60 | Assertions.assertThat(yearlyCost).isEqualTo(20_000)
61 | }
62 | }
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto init
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto init
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :init
68 | @rem Get command-line arguments, handling Windows variants
69 |
70 | if not "%OS%" == "Windows_NT" goto win9xME_args
71 |
72 | :win9xME_args
73 | @rem Slurp the command line arguments.
74 | set CMD_LINE_ARGS=
75 | set _SKIP=2
76 |
77 | :win9xME_args_slurp
78 | if "x%~1" == "x" goto execute
79 |
80 | set CMD_LINE_ARGS=%*
81 |
82 | :execute
83 | @rem Setup the command line
84 |
85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
86 |
87 |
88 | @rem Execute Gradle
89 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
90 |
91 | :end
92 | @rem End local scope for the variables with windows NT shell
93 | if "%ERRORLEVEL%"=="0" goto mainEnd
94 |
95 | :fail
96 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
97 | rem the _cmd.exe /c_ return code!
98 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
99 | exit /b 1
100 |
101 | :mainEnd
102 | if "%OS%"=="Windows_NT" endlocal
103 |
104 | :omega
105 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | #
4 | # Copyright 2015 the original author or authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | ##
21 | ## Gradle start up script for UN*X
22 | ##
23 | ##############################################################################
24 |
25 | # Attempt to set APP_HOME
26 | # Resolve links: $0 may be a link
27 | PRG="$0"
28 | # Need this for relative symlinks.
29 | while [ -h "$PRG" ] ; do
30 | ls=`ls -ld "$PRG"`
31 | link=`expr "$ls" : '.*-> \(.*\)$'`
32 | if expr "$link" : '/.*' > /dev/null; then
33 | PRG="$link"
34 | else
35 | PRG=`dirname "$PRG"`"/$link"
36 | fi
37 | done
38 | SAVED="`pwd`"
39 | cd "`dirname \"$PRG\"`/" >/dev/null
40 | APP_HOME="`pwd -P`"
41 | cd "$SAVED" >/dev/null
42 |
43 | APP_NAME="Gradle"
44 | APP_BASE_NAME=`basename "$0"`
45 |
46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
48 |
49 | # Use the maximum available, or set MAX_FD != -1 to use that value.
50 | MAX_FD="maximum"
51 |
52 | warn () {
53 | echo "$*"
54 | }
55 |
56 | die () {
57 | echo
58 | echo "$*"
59 | echo
60 | exit 1
61 | }
62 |
63 | # OS specific support (must be 'true' or 'false').
64 | cygwin=false
65 | msys=false
66 | darwin=false
67 | nonstop=false
68 | case "`uname`" in
69 | CYGWIN* )
70 | cygwin=true
71 | ;;
72 | Darwin* )
73 | darwin=true
74 | ;;
75 | MINGW* )
76 | msys=true
77 | ;;
78 | NONSTOP* )
79 | nonstop=true
80 | ;;
81 | esac
82 |
83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
84 |
85 |
86 | # Determine the Java command to use to start the JVM.
87 | if [ -n "$JAVA_HOME" ] ; then
88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
89 | # IBM's JDK on AIX uses strange locations for the executables
90 | JAVACMD="$JAVA_HOME/jre/sh/java"
91 | else
92 | JAVACMD="$JAVA_HOME/bin/java"
93 | fi
94 | if [ ! -x "$JAVACMD" ] ; then
95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
96 |
97 | Please set the JAVA_HOME variable in your environment to match the
98 | location of your Java installation."
99 | fi
100 | else
101 | JAVACMD="java"
102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
103 |
104 | Please set the JAVA_HOME variable in your environment to match the
105 | location of your Java installation."
106 | fi
107 |
108 | # Increase the maximum file descriptors if we can.
109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
110 | MAX_FD_LIMIT=`ulimit -H -n`
111 | if [ $? -eq 0 ] ; then
112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
113 | MAX_FD="$MAX_FD_LIMIT"
114 | fi
115 | ulimit -n $MAX_FD
116 | if [ $? -ne 0 ] ; then
117 | warn "Could not set maximum file descriptor limit: $MAX_FD"
118 | fi
119 | else
120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
121 | fi
122 | fi
123 |
124 | # For Darwin, add options to specify how the application appears in the dock
125 | if $darwin; then
126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
127 | fi
128 |
129 | # For Cygwin or MSYS, switch paths to Windows format before running java
130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
133 |
134 | JAVACMD=`cygpath --unix "$JAVACMD"`
135 |
136 | # We build the pattern for arguments to be converted via cygpath
137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
138 | SEP=""
139 | for dir in $ROOTDIRSRAW ; do
140 | ROOTDIRS="$ROOTDIRS$SEP$dir"
141 | SEP="|"
142 | done
143 | OURCYGPATTERN="(^($ROOTDIRS))"
144 | # Add a user-defined pattern to the cygpath arguments
145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
147 | fi
148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
149 | i=0
150 | for arg in "$@" ; do
151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
153 |
154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
156 | else
157 | eval `echo args$i`="\"$arg\""
158 | fi
159 | i=`expr $i + 1`
160 | done
161 | case $i in
162 | 0) set -- ;;
163 | 1) set -- "$args0" ;;
164 | 2) set -- "$args0" "$args1" ;;
165 | 3) set -- "$args0" "$args1" "$args2" ;;
166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;;
167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
172 | esac
173 | fi
174 |
175 | # Escape application args
176 | save () {
177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
178 | echo " "
179 | }
180 | APP_ARGS=`save "$@"`
181 |
182 | # Collect all arguments for the java command, following the shell quoting and substitution rules
183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
184 |
185 | exec "$JAVACMD" "$@"
186 |
--------------------------------------------------------------------------------