JAVA-12098: Moved core-groovy inside core-groovy-modules
This commit is contained in:
1
core-groovy-modules/core-groovy/.gitignore
vendored
Normal file
1
core-groovy-modules/core-groovy/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
||||
/src/main/resources/ioSerializedObject.txt
|
||||
17
core-groovy-modules/core-groovy/README.md
Normal file
17
core-groovy-modules/core-groovy/README.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Core Groovy
|
||||
|
||||
This module contains articles about core Groovy concepts
|
||||
|
||||
## Relevant articles:
|
||||
|
||||
- [JDBC with Groovy](https://www.baeldung.com/jdbc-groovy)
|
||||
- [Working with JSON in Groovy](https://www.baeldung.com/groovy-json)
|
||||
- [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read)
|
||||
- [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings)
|
||||
- [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits)
|
||||
- [Closures in Groovy](https://www.baeldung.com/groovy-closures)
|
||||
- [Converting a String to a Date in Groovy](https://www.baeldung.com/groovy-string-to-date)
|
||||
- [Guide to I/O in Groovy](https://www.baeldung.com/groovy-io)
|
||||
- [Convert String to Integer in Groovy](https://www.baeldung.com/groovy-convert-string-to-integer)
|
||||
- [Groovy Variable Scope](https://www.baeldung.com/groovy/variable-scope)
|
||||
- [[More -->]](/core-groovy-2)
|
||||
13
core-groovy-modules/core-groovy/build.gradle
Normal file
13
core-groovy-modules/core-groovy/build.gradle
Normal file
@@ -0,0 +1,13 @@
|
||||
group 'com.baeldung'
|
||||
version '1.0-SNAPSHOT'
|
||||
|
||||
apply plugin: 'groovy'
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
compile 'org.codehaus.groovy:groovy-all:2.4.13'
|
||||
testCompile 'org.spockframework:spock-core:1.1-groovy-2.4'
|
||||
}
|
||||
120
core-groovy-modules/core-groovy/pom.xml
Normal file
120
core-groovy-modules/core-groovy/pom.xml
Normal file
@@ -0,0 +1,120 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>core-groovy</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy</name>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<parent>
|
||||
<groupId>com.baeldung</groupId>
|
||||
<artifactId>core-groovy-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>${groovy-all.version}</version>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-dateutil</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-sql</artifactId>
|
||||
<version>${groovy-sql.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-runner</artifactId>
|
||||
<version>${junit-platform.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.hsqldb</groupId>
|
||||
<artifactId>hsqldb</artifactId>
|
||||
<version>${hsqldb.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.spockframework</groupId>
|
||||
<artifactId>spock-core</artifactId>
|
||||
<version>${spock-core.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmavenplus</groupId>
|
||||
<artifactId>gmavenplus-plugin</artifactId>
|
||||
<version>${gmavenplus-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>addSources</goal>
|
||||
<goal>addTestSources</goal>
|
||||
<goal>compile</goal>
|
||||
<goal>compileTests</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-failsafe-plugin</artifactId>
|
||||
<version>${maven-failsafe-plugin.version}</version>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.junit.platform</groupId>
|
||||
<artifactId>junit-platform-surefire-provider</artifactId>
|
||||
<version>${junit-platform-surefire-provider.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>junit5</id>
|
||||
<goals>
|
||||
<goal>integration-test</goal>
|
||||
<goal>verify</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<includes>
|
||||
<include>**/*Test5.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
<url>https://jcenter.bintray.com</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<groovy.version>2.5.6</groovy.version>
|
||||
<groovy-all.version>2.5.6</groovy-all.version>
|
||||
<groovy-sql.version>2.5.6</groovy-sql.version>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,87 @@
|
||||
package com.baeldung.closures
|
||||
|
||||
class Closures {
|
||||
|
||||
def printWelcome = {
|
||||
println "Welcome to Closures!"
|
||||
}
|
||||
|
||||
def print = { name ->
|
||||
println name
|
||||
}
|
||||
|
||||
def formatToLowerCase(name) {
|
||||
return name.toLowerCase()
|
||||
}
|
||||
def formatToLowerCaseClosure = { name ->
|
||||
return name.toLowerCase()
|
||||
}
|
||||
|
||||
def count=0
|
||||
|
||||
def increaseCount = {
|
||||
count++
|
||||
}
|
||||
|
||||
def greet = {
|
||||
return "Hello! ${it}"
|
||||
}
|
||||
|
||||
def multiply = { x, y ->
|
||||
return x*y
|
||||
}
|
||||
|
||||
def calculate = {int x, int y, String operation ->
|
||||
|
||||
//log closure
|
||||
def log = {
|
||||
println "Performing $it"
|
||||
}
|
||||
|
||||
def result = 0
|
||||
switch(operation) {
|
||||
case "ADD":
|
||||
log("Addition")
|
||||
result = x+y
|
||||
break
|
||||
case "SUB":
|
||||
log("Subtraction")
|
||||
result = x-y
|
||||
break
|
||||
case "MUL":
|
||||
log("Multiplication")
|
||||
result = x*y
|
||||
break
|
||||
case "DIV":
|
||||
log("Division")
|
||||
result = x/y
|
||||
break
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
def addAll = { int... args ->
|
||||
return args.sum()
|
||||
}
|
||||
|
||||
def volume(Closure areaCalculator, int... dimensions) {
|
||||
if(dimensions.size() == 3) {
|
||||
|
||||
//consider dimension[0] = length, dimension[1] = breadth, dimension[2] = height
|
||||
//for cube and cuboid
|
||||
return areaCalculator(dimensions[0], dimensions[1]) * dimensions[2]
|
||||
} else if(dimensions.size() == 2) {
|
||||
|
||||
//consider dimension[0] = radius, dimension[1] = height
|
||||
//for cylinder and cone
|
||||
return areaCalculator(dimensions[0]) * dimensions[1]
|
||||
} else if(dimensions.size() == 1) {
|
||||
|
||||
//consider dimension[0] = radius
|
||||
//for sphere
|
||||
return areaCalculator(dimensions[0]) * dimensions[0]
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.closures
|
||||
|
||||
class Employee {
|
||||
|
||||
String fullName
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package com.baeldung.file
|
||||
|
||||
class ReadFile {
|
||||
|
||||
/**
|
||||
* reads file content line by line using withReader and reader.readLine
|
||||
* @param filePath
|
||||
* @return
|
||||
*/
|
||||
int readFileLineByLine(String filePath) {
|
||||
File file = new File(filePath)
|
||||
def line, noOfLines = 0;
|
||||
file.withReader { reader ->
|
||||
while ((line = reader.readLine())!=null)
|
||||
{
|
||||
println "${line}"
|
||||
noOfLines++
|
||||
}
|
||||
}
|
||||
return noOfLines
|
||||
}
|
||||
|
||||
/**
|
||||
* reads file content in list of lines
|
||||
* @param filePath
|
||||
* @return
|
||||
*/
|
||||
List<String> readFileInList(String filePath) {
|
||||
File file = new File(filePath)
|
||||
def lines = file.readLines()
|
||||
return lines
|
||||
}
|
||||
|
||||
/**
|
||||
* reads file content in string using File.text
|
||||
* @param filePath
|
||||
* @return
|
||||
*/
|
||||
String readFileString(String filePath) {
|
||||
File file = new File(filePath)
|
||||
String fileContent = file.text
|
||||
return fileContent
|
||||
}
|
||||
|
||||
/**
|
||||
* reads file content in string with encoding using File.getText
|
||||
* @param filePath
|
||||
* @return
|
||||
*/
|
||||
String readFileStringWithCharset(String filePath) {
|
||||
File file = new File(filePath)
|
||||
String utf8Content = file.getText("UTF-8")
|
||||
return utf8Content
|
||||
}
|
||||
|
||||
/**
|
||||
* reads content of binary file and returns byte array
|
||||
* @param filePath
|
||||
* @return
|
||||
*/
|
||||
byte[] readBinaryFile(String filePath) {
|
||||
File file = new File(filePath)
|
||||
byte[] binaryContent = file.bytes
|
||||
return binaryContent
|
||||
}
|
||||
|
||||
/**
|
||||
* More Examples of reading a file
|
||||
* @return
|
||||
*/
|
||||
def moreExamples() {
|
||||
|
||||
//with reader with utf-8
|
||||
new File("src/main/resources/utf8Content.html").withReader('UTF-8') { reader ->
|
||||
def line
|
||||
while ((line = reader.readLine())!=null) {
|
||||
println "${line}"
|
||||
}
|
||||
}
|
||||
|
||||
//collect api
|
||||
def list = new File("src/main/resources/fileContent.txt").collect {it}
|
||||
|
||||
//as operator
|
||||
def array = new File("src/main/resources/fileContent.txt") as String[]
|
||||
|
||||
//eachline
|
||||
new File("src/main/resources/fileContent.txt").eachLine { line ->
|
||||
println line
|
||||
}
|
||||
|
||||
//newInputStream with eachLine
|
||||
def is = new File("src/main/resources/fileContent.txt").newInputStream()
|
||||
is.eachLine {
|
||||
println it
|
||||
}
|
||||
is.close()
|
||||
|
||||
//withInputStream
|
||||
new File("src/main/resources/fileContent.txt").withInputStream { stream ->
|
||||
stream.eachLine { line ->
|
||||
println line
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.io
|
||||
|
||||
class Task implements Serializable {
|
||||
String description
|
||||
Date startDate
|
||||
Date dueDate
|
||||
int status
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung.json
|
||||
|
||||
class Account {
|
||||
String id
|
||||
BigDecimal value
|
||||
Date createdAt
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.json
|
||||
|
||||
import groovy.json.JsonOutput
|
||||
import groovy.json.JsonParserType
|
||||
import groovy.json.JsonSlurper
|
||||
|
||||
class JsonParser {
|
||||
|
||||
Account toObject(String json) {
|
||||
JsonSlurper jsonSlurper = new JsonSlurper()
|
||||
jsonSlurper.parseText(json) as Account
|
||||
}
|
||||
|
||||
Account toObjectWithIndexOverlay(String json) {
|
||||
JsonSlurper jsonSlurper = new JsonSlurper(type: JsonParserType.INDEX_OVERLAY)
|
||||
jsonSlurper.parseText(json) as Account
|
||||
}
|
||||
|
||||
String toJson(Account account) {
|
||||
JsonOutput.toJson(account)
|
||||
}
|
||||
|
||||
String prettyfy(String json) {
|
||||
JsonOutput.prettyPrint(json)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.baeldung.scopes
|
||||
|
||||
import java.util.logging.Logger
|
||||
|
||||
x = 200
|
||||
logger = Logger.getLogger("Scopes.groovy")
|
||||
|
||||
def getGlobalResult() {
|
||||
logger.info(x.toString())
|
||||
return 1 + x
|
||||
}
|
||||
|
||||
def defineGlobalVariable() {
|
||||
z = 234
|
||||
logger = Logger.getLogger("Scopes.groovy")
|
||||
logger.info(z.toString())
|
||||
}
|
||||
|
||||
logger.info("- Global variable")
|
||||
logger.info(x.toString())
|
||||
logger.info("- Access global variable from inside function")
|
||||
logger.info(getGlobalResult().toString())
|
||||
logger.info("- function called to create variable")
|
||||
defineGlobalVariable()
|
||||
logger.info("- Variable created inside a function")
|
||||
logger.info(z.toString())
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.baeldung.scopes
|
||||
|
||||
import java.util.logging.Logger
|
||||
|
||||
logger = Logger.getLogger("ScopesFail.groovy")
|
||||
|
||||
y = 2
|
||||
|
||||
def fLocal() {
|
||||
def q = 333
|
||||
println(q)
|
||||
q
|
||||
}
|
||||
|
||||
fLocal()
|
||||
|
||||
logger.info("- Value of the created variable")
|
||||
logger.info(fLocal())
|
||||
logger.info("- Local variable doesn't exist outside")
|
||||
logger.info(q.toString())
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.scopes
|
||||
|
||||
import java.util.logging.Logger
|
||||
|
||||
logger = Logger.getLogger("ScopesFailNoPrint.groovy")
|
||||
|
||||
y = 2
|
||||
|
||||
def fLocal() {
|
||||
def q = 333
|
||||
println(q)
|
||||
q
|
||||
}
|
||||
|
||||
logger.info(y.toString())
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.baeldung.strings;
|
||||
|
||||
class Concatenate {
|
||||
String first = 'Hello'
|
||||
String last = 'Groovy'
|
||||
|
||||
String doSimpleConcat() {
|
||||
return 'My name is ' + first + ' ' + last
|
||||
}
|
||||
|
||||
String doConcatUsingGString() {
|
||||
return "My name is $first $last"
|
||||
}
|
||||
|
||||
String doConcatUsingGStringClosures() {
|
||||
return "My name is ${-> first} ${-> last}"
|
||||
}
|
||||
|
||||
String doConcatUsingStringConcatMethod() {
|
||||
return 'My name is '.concat(first).concat(' ').concat(last)
|
||||
}
|
||||
|
||||
String doConcatUsingLeftShiftOperator() {
|
||||
return 'My name is ' << first << ' ' << last
|
||||
}
|
||||
|
||||
String doConcatUsingArrayJoinMethod() {
|
||||
return ['My name is', first, last].join(' ')
|
||||
}
|
||||
|
||||
String doConcatUsingArrayInjectMethod() {
|
||||
return [first,' ', last]
|
||||
.inject(new StringBuffer('My name is '), { initial, name -> initial.append(name); return initial }).toString()
|
||||
}
|
||||
|
||||
String doConcatUsingStringBuilder() {
|
||||
return new StringBuilder().append('My name is ').append(first).append(' ').append(last)
|
||||
}
|
||||
|
||||
String doConcatUsingStringBuffer() {
|
||||
return new StringBuffer().append('My name is ').append(first).append(' ').append(last)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
trait AnimalTrait {
|
||||
|
||||
String basicBehavior() {
|
||||
return "Animalistic!!"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
package com.baeldung
|
||||
|
||||
class Car implements VehicleTrait {}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
class Dog implements WalkingTrait, SpeakingTrait {
|
||||
|
||||
String speakAndWalk() {
|
||||
WalkingTrait.super.speakAndWalk()
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
class Employee implements UserTrait {
|
||||
|
||||
String name() {
|
||||
return 'Bob'
|
||||
}
|
||||
|
||||
String lastName() {
|
||||
return "Marley"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
interface Human {
|
||||
|
||||
String lastName()
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
trait SpeakingTrait {
|
||||
|
||||
String basicAbility() {
|
||||
return "Speaking!!"
|
||||
}
|
||||
|
||||
String speakAndWalk() {
|
||||
return "Speak and walk!!"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
trait UserTrait implements Human {
|
||||
|
||||
String sayHello() {
|
||||
return "Hello!"
|
||||
}
|
||||
|
||||
abstract String name()
|
||||
|
||||
String showName() {
|
||||
return "Hello, ${name()}!"
|
||||
}
|
||||
|
||||
private String greetingMessage() {
|
||||
return 'Hello, from a private method!'
|
||||
}
|
||||
|
||||
String greet() {
|
||||
def msg = greetingMessage()
|
||||
println msg
|
||||
msg
|
||||
}
|
||||
|
||||
def self() {
|
||||
return this
|
||||
}
|
||||
|
||||
String showLastName() {
|
||||
return "Hello, ${lastName()}!"
|
||||
}
|
||||
|
||||
String email
|
||||
String address
|
||||
}
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.baeldung
|
||||
|
||||
trait VehicleTrait extends WheelTrait {
|
||||
|
||||
String showWheels() {
|
||||
return "Num of Wheels $noOfWheels"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
trait WalkingTrait {
|
||||
|
||||
String basicAbility() {
|
||||
return "Walking!!"
|
||||
}
|
||||
|
||||
String speakAndWalk() {
|
||||
return "Walk and speak!!"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.baeldung
|
||||
|
||||
trait WheelTrait {
|
||||
|
||||
int noOfWheels
|
||||
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,3 @@
|
||||
Line 1 : Hello World!!!
|
||||
Line 2 : This is a file content.
|
||||
Line 3 : String content
|
||||
BIN
core-groovy-modules/core-groovy/src/main/resources/ioData.txt
Normal file
BIN
core-groovy-modules/core-groovy/src/main/resources/ioData.txt
Normal file
Binary file not shown.
@@ -0,0 +1,4 @@
|
||||
First line of text
|
||||
Second line of text
|
||||
Third line of text
|
||||
Fourth line of text
|
||||
@@ -0,0 +1,3 @@
|
||||
Line one of output example
|
||||
Line two of output example
|
||||
Line three of output example
|
||||
@@ -0,0 +1,13 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
|
||||
</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT" />
|
||||
</root>
|
||||
</configuration>
|
||||
BIN
core-groovy-modules/core-groovy/src/main/resources/sample.png
Normal file
BIN
core-groovy-modules/core-groovy/src/main/resources/sample.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 329 B |
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
|
||||
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml">
|
||||
<meta charset="UTF-8">
|
||||
<body>
|
||||
<pre>
|
||||
ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ
|
||||
ᛋᚳᛖᚪᛚ᛫ᚦᛖᚪᚻ᛫ᛗᚪᚾᚾᚪ᛫ᚷᛖᚻᚹᛦᛚᚳ᛫ᛗᛁᚳᛚᚢᚾ᛫ᚻᛦᛏ᛫ᛞᚫᛚᚪᚾ
|
||||
ᚷᛁᚠ᛫ᚻᛖ᛫ᚹᛁᛚᛖ᛫ᚠᚩᚱ᛫ᛞᚱᛁᚻᛏᚾᛖ᛫ᛞᚩᛗᛖᛋ᛫ᚻᛚᛇᛏᚪᚾ
|
||||
</pre>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.closures
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
class ClosuresUnitTest extends GroovyTestCase {
|
||||
|
||||
Closures closures = new Closures()
|
||||
|
||||
void testDeclaration() {
|
||||
|
||||
closures.print("Hello! Closure")
|
||||
closures.formatToLowerCaseClosure("Hello! Closure")
|
||||
|
||||
closures.print.call("Hello! Closure")
|
||||
closures.formatToLowerCaseClosure.call("Hello! Closure")
|
||||
|
||||
}
|
||||
|
||||
void testClosureVsMethods() {
|
||||
assert closures.formatToLowerCase("TONY STARK") == closures.formatToLowerCaseClosure("Tony STark")
|
||||
}
|
||||
|
||||
void testParameters() {
|
||||
//implicit parameter
|
||||
assert closures.greet("Alex") == "Hello! Alex"
|
||||
|
||||
//multiple parameters
|
||||
assert closures.multiply(2, 4) == 8
|
||||
|
||||
assert closures.calculate(12, 4, "ADD") == 16
|
||||
assert closures.calculate(12, 4, "SUB") == 8
|
||||
assert closures.calculate(43, 8, "DIV") == 5.375
|
||||
|
||||
//varags
|
||||
assert closures.addAll(12, 10, 14) == 36
|
||||
|
||||
}
|
||||
|
||||
void testClosureAsAnArgument() {
|
||||
assert closures.volume({ l, b -> return l*b }, 12, 6, 10) == 720
|
||||
|
||||
assert closures.volume({ radius -> return Math.PI*radius*radius/3 }, 5, 10) == Math.PI * 250/3
|
||||
}
|
||||
|
||||
void testGStringsLazyEvaluation() {
|
||||
def name = "Samwell"
|
||||
def welcomeMsg = "Welcome! $name"
|
||||
|
||||
assert welcomeMsg == "Welcome! Samwell"
|
||||
|
||||
// changing the name does not affect original interpolated value
|
||||
name = "Tarly"
|
||||
assert welcomeMsg != "Welcome! Tarly"
|
||||
|
||||
def fullName = "Tarly Samson"
|
||||
def greetStr = "Hello! ${-> fullName}"
|
||||
|
||||
assert greetStr == "Hello! Tarly Samson"
|
||||
|
||||
// this time changing the variable affects the interpolated String's value
|
||||
fullName = "Jon Smith"
|
||||
assert greetStr == "Hello! Jon Smith"
|
||||
}
|
||||
|
||||
void testClosureInLists() {
|
||||
def list = [10, 11, 12, 13, 14, true, false, "BUNTHER"]
|
||||
list.each {
|
||||
println it
|
||||
}
|
||||
|
||||
assert [13, 14] == list.findAll{ it instanceof Integer && it >= 13}
|
||||
}
|
||||
|
||||
void testClosureInMaps() {
|
||||
def map = [1:10, 2:30, 4:5]
|
||||
|
||||
assert [10, 60, 20] == map.collect{it.key * it.value}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.baeldung.groovy.sql
|
||||
|
||||
import static org.junit.Assert.*
|
||||
import java.util.Calendar.*
|
||||
import java.time.LocalDate
|
||||
import java.text.SimpleDateFormat
|
||||
import org.junit.Test
|
||||
|
||||
|
||||
class DateTest {
|
||||
|
||||
def dateStr = "2019-02-28"
|
||||
def pattern = "yyyy-MM-dd"
|
||||
|
||||
@Test
|
||||
void whenGetStringRepresentation_thenCorrectlyConvertIntoDate() {
|
||||
def dateFormat = new SimpleDateFormat(pattern)
|
||||
def date = dateFormat.parse(dateStr)
|
||||
|
||||
println(" String to Date with DateFormatter : " + date)
|
||||
|
||||
def cal = new GregorianCalendar();
|
||||
cal.setTime(date);
|
||||
|
||||
assertEquals(cal.get(Calendar.YEAR),2019)
|
||||
assertEquals(cal.get(Calendar.DAY_OF_MONTH),28)
|
||||
assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenGetStringRepresentation_thenCorrectlyConvertWithDateUtilsExtension() {
|
||||
|
||||
def date = Date.parse(pattern, dateStr)
|
||||
|
||||
println(" String to Date with Date.parse : " + date)
|
||||
|
||||
def cal = new GregorianCalendar();
|
||||
cal.setTime(date);
|
||||
|
||||
assertEquals(cal.get(Calendar.YEAR),2019)
|
||||
assertEquals(cal.get(Calendar.DAY_OF_MONTH),28)
|
||||
assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenGetStringRepresentation_thenCorrectlyConvertIntoDateWithLocalDate() {
|
||||
def date = LocalDate.parse(dateStr, pattern)
|
||||
|
||||
println(" String to Date with LocalDate : " + date)
|
||||
|
||||
assertEquals(date.getYear(),2019)
|
||||
assertEquals(date.getMonth(),java.time.Month.FEBRUARY)
|
||||
assertEquals(date.getDayOfMonth(),28)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.baeldung.file
|
||||
|
||||
import spock.lang.Specification
|
||||
import spock.lang.Ignore
|
||||
|
||||
class ReadFileUnitTest extends Specification {
|
||||
|
||||
ReadFile readFile
|
||||
|
||||
void setup () {
|
||||
readFile = new ReadFile()
|
||||
}
|
||||
|
||||
def 'Should return number of lines in File using ReadFile.readFileLineByLine given filePath' () {
|
||||
given:
|
||||
def filePath = "src/main/resources/fileContent.txt"
|
||||
when:
|
||||
def noOfLines = readFile.readFileLineByLine(filePath)
|
||||
then:
|
||||
noOfLines
|
||||
noOfLines instanceof Integer
|
||||
assert noOfLines, 3
|
||||
}
|
||||
|
||||
def 'Should return File Content in list of lines using ReadFile.readFileInList given filePath' () {
|
||||
given:
|
||||
def filePath = "src/main/resources/fileContent.txt"
|
||||
when:
|
||||
def lines = readFile.readFileInList(filePath)
|
||||
then:
|
||||
lines
|
||||
lines instanceof List<String>
|
||||
assert lines.size(), 3
|
||||
}
|
||||
|
||||
def 'Should return file content in string using ReadFile.readFileString given filePath' () {
|
||||
given:
|
||||
def filePath = "src/main/resources/fileContent.txt"
|
||||
when:
|
||||
def fileContent = readFile.readFileString(filePath)
|
||||
then:
|
||||
fileContent
|
||||
fileContent instanceof String
|
||||
fileContent.contains("""Line 1 : Hello World!!!
|
||||
Line 2 : This is a file content.
|
||||
Line 3 : String content""")
|
||||
|
||||
}
|
||||
|
||||
def 'Should return UTF-8 encoded file content in string using ReadFile.readFileStringWithCharset given filePath' () {
|
||||
given:
|
||||
def filePath = "src/main/resources/utf8Content.html"
|
||||
when:
|
||||
def encodedContent = readFile.readFileStringWithCharset(filePath)
|
||||
then:
|
||||
encodedContent
|
||||
encodedContent instanceof String
|
||||
}
|
||||
|
||||
def 'Should return binary file content in byte array using ReadFile.readBinaryFile given filePath' () {
|
||||
given:
|
||||
def filePath = "src/main/resources/sample.png"
|
||||
when:
|
||||
def binaryContent = readFile.readBinaryFile(filePath)
|
||||
then:
|
||||
binaryContent
|
||||
binaryContent instanceof byte[]
|
||||
binaryContent.length == 329
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
package com.baeldung.groovy.sql
|
||||
|
||||
import groovy.sql.GroovyResultSet
|
||||
import groovy.sql.GroovyRowResult
|
||||
import groovy.sql.Sql
|
||||
import groovy.transform.CompileStatic
|
||||
import static org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class SqlTest {
|
||||
|
||||
final Map dbConnParams = [url: 'jdbc:hsqldb:mem:testDB', user: 'sa', password: '', driver: 'org.hsqldb.jdbc.JDBCDriver']
|
||||
|
||||
@Test
|
||||
void whenNewSqlInstance_thenDbIsAccessed() {
|
||||
def sql = Sql.newInstance(dbConnParams)
|
||||
sql.close()
|
||||
sql.close()
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTableDoesNotExist_thenSelectFails() {
|
||||
try {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.eachRow('select * from PROJECT') {}
|
||||
}
|
||||
|
||||
fail("An exception should have been thrown")
|
||||
} catch (ignored) {
|
||||
//Ok
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTableCreated_thenSelectIsPossible() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
def result = sql.execute 'create table PROJECT_1 (id integer not null, name varchar(50), url varchar(100))'
|
||||
|
||||
assertEquals(0, sql.updateCount)
|
||||
assertFalse(result)
|
||||
|
||||
result = sql.execute('select * from PROJECT_1')
|
||||
|
||||
assertTrue(result)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenIdentityColumn_thenInsertReturnsNewId() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_2 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
def ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
|
||||
assertEquals(0, ids[0][0])
|
||||
|
||||
ids = sql.executeInsert("INSERT INTO PROJECT_2 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
|
||||
assertEquals(1, ids[0][0])
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUpdate_thenNumberOfAffectedRows() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_3 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_3 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
def count = sql.executeUpdate("UPDATE PROJECT_3 SET URL = 'https://' + URL")
|
||||
|
||||
assertEquals(2, count)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenEachRow_thenResultSetHasProperties() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_4 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_4 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
|
||||
sql.eachRow("SELECT * FROM PROJECT_4") { GroovyResultSet rs ->
|
||||
assertNotNull(rs.name)
|
||||
assertNotNull(rs.url)
|
||||
assertNotNull(rs[0])
|
||||
assertNotNull(rs[1])
|
||||
assertNotNull(rs[2])
|
||||
assertEquals(rs.name, rs['name'])
|
||||
assertEquals(rs.url, rs['url'])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenPagination_thenSubsetIsReturned() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
def rows = sql.rows('SELECT * FROM PROJECT_5 ORDER BY NAME', 1, 1)
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
assertEquals('REST with Spring', rows[0].name)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenParameters_thenReplacement() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_6 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.execute('INSERT INTO PROJECT_6 (NAME, URL) VALUES (?, ?)', 'tutorials', 'github.com/eugenp/tutorials')
|
||||
sql.execute("INSERT INTO PROJECT_6 (NAME, URL) VALUES (:name, :url)", [name: 'REST with Spring', url: 'github.com/eugenp/REST-With-Spring'])
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'tutorials'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
|
||||
rows = sql.rows("SELECT * FROM PROJECT_6 WHERE NAME = 'REST with Spring'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenParametersInGString_thenReplacement() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_7 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${'tutorials'}, ${'github.com/eugenp/tutorials'})"
|
||||
def name = 'REST with Spring'
|
||||
def url = 'github.com/eugenp/REST-With-Spring'
|
||||
sql.execute "INSERT INTO PROJECT_7 (NAME, URL) VALUES (${name}, ${url})"
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_7 WHERE NAME = 'tutorials'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
|
||||
rows = sql.rows("SELECT * FROM PROJECT_7 WHERE NAME = 'REST with Spring'")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTransactionRollback_thenNoDataInserted() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.withTransaction {
|
||||
sql.execute 'create table PROJECT_8 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_8 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
sql.rollback()
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_8")
|
||||
|
||||
assertEquals(0, rows.size())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenTransactionRollbackThenCommit_thenOnlyLastInserted() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.withTransaction {
|
||||
sql.execute 'create table PROJECT_9 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.rollback()
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
sql.rollback()
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_9 (NAME, URL) VALUES ('REST with Spring', 'https://github.com/eugenp/REST-With-Spring')")
|
||||
}
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_9")
|
||||
|
||||
assertEquals(2, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenException_thenTransactionIsRolledBack() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
try {
|
||||
sql.withTransaction {
|
||||
sql.execute 'create table PROJECT_10 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_10 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
throw new Exception('rollback')
|
||||
}
|
||||
} catch (ignored) {}
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_10")
|
||||
|
||||
assertEquals(0, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenCachedConnection_whenException_thenDataIsPersisted() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
try {
|
||||
sql.cacheConnection {
|
||||
sql.execute 'create table PROJECT_11 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_11 (NAME, URL) VALUES ('tutorials', 'https://github.com/eugenp/tutorials')")
|
||||
throw new Exception('This does not rollback')
|
||||
}
|
||||
} catch (ignored) {}
|
||||
|
||||
def rows = sql.rows("SELECT * FROM PROJECT_11")
|
||||
|
||||
assertEquals(1, rows.size())
|
||||
}
|
||||
}
|
||||
|
||||
/*@Test
|
||||
void whenModifyResultSet_thenDataIsChanged() {
|
||||
Sql.withInstance(dbConnParams) { Sql sql ->
|
||||
sql.execute 'create table PROJECT_5 (ID IDENTITY, NAME VARCHAR (50), URL VARCHAR (100))'
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('tutorials', 'github.com/eugenp/tutorials')")
|
||||
sql.executeInsert("INSERT INTO PROJECT_5 (NAME, URL) VALUES ('REST with Spring', 'github.com/eugenp/REST-With-Spring')")
|
||||
|
||||
sql.eachRow("SELECT * FROM PROJECT_5 FOR UPDATE ") { GroovyResultSet rs ->
|
||||
rs['name'] = "The great ${rs.name}!" as String
|
||||
rs.updateRow()
|
||||
}
|
||||
|
||||
sql.eachRow("SELECT * FROM PROJECT_5") { GroovyResultSet rs ->
|
||||
assertTrue(rs.name.startsWith('The great '))
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.baeldung.io
|
||||
|
||||
import static org.junit.Assert.*
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
class DataAndObjectsUnitTest {
|
||||
@Test
|
||||
void whenUsingWithDataOutputStream_thenDataIsSerializedToAFile() {
|
||||
String message = 'This is a serialized string'
|
||||
int length = message.length()
|
||||
boolean valid = true
|
||||
new File('src/main/resources/ioData.txt').withDataOutputStream { out ->
|
||||
out.writeUTF(message)
|
||||
out.writeInt(length)
|
||||
out.writeBoolean(valid)
|
||||
}
|
||||
|
||||
String loadedMessage = ""
|
||||
int loadedLength
|
||||
boolean loadedValid
|
||||
|
||||
new File('src/main/resources/ioData.txt').withDataInputStream { is ->
|
||||
loadedMessage = is.readUTF()
|
||||
loadedLength = is.readInt()
|
||||
loadedValid = is.readBoolean()
|
||||
}
|
||||
|
||||
assertEquals(message, loadedMessage)
|
||||
assertEquals(length, loadedLength)
|
||||
assertEquals(valid, loadedValid)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingWithObjectOutputStream_thenObjectIsSerializedToFile() {
|
||||
Task task = new Task(description:'Take out the trash', startDate:new Date(), status:0)
|
||||
def serializedDataFile = new File('src/main/resources/ioSerializedObject.txt')
|
||||
serializedDataFile.createNewFile()
|
||||
serializedDataFile.withObjectOutputStream { out ->
|
||||
out.writeObject(task)
|
||||
}
|
||||
|
||||
Task taskRead
|
||||
|
||||
new File('src/main/resources/ioSerializedObject.txt').withObjectInputStream { is ->
|
||||
taskRead = is.readObject()
|
||||
}
|
||||
|
||||
assertEquals(task.description, taskRead.description)
|
||||
assertEquals(task.startDate, taskRead.startDate)
|
||||
assertEquals(task.status, taskRead.status)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
package com.baeldung.io
|
||||
|
||||
import static org.junit.Assert.*
|
||||
import org.junit.Test
|
||||
|
||||
class ReadExampleUnitTest {
|
||||
|
||||
@Test
|
||||
void whenUsingEachLine_thenCorrectLinesReturned() {
|
||||
def expectedList = [
|
||||
'First line of text',
|
||||
'Second line of text',
|
||||
'Third line of text',
|
||||
'Fourth line of text']
|
||||
|
||||
def lines = []
|
||||
|
||||
new File('src/main/resources/ioInput.txt').eachLine { line ->
|
||||
lines.add(line)
|
||||
}
|
||||
assertEquals(expectedList, lines)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingReadEachLineWithLineNumber_thenCorrectLinesReturned() {
|
||||
def expectedList = [
|
||||
'Second line of text',
|
||||
'Third line of text',
|
||||
'Fourth line of text']
|
||||
|
||||
def lineNoRange = 2..4
|
||||
def lines = []
|
||||
|
||||
new File('src/main/resources/ioInput.txt').eachLine { line, lineNo ->
|
||||
if (lineNoRange.contains(lineNo)) {
|
||||
lines.add(line)
|
||||
}
|
||||
}
|
||||
assertEquals(expectedList, lines)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingReadEachLineWithLineNumberStartAtZero_thenCorrectLinesReturned() {
|
||||
def expectedList = [
|
||||
'Second line of text',
|
||||
'Third line of text',
|
||||
'Fourth line of text']
|
||||
|
||||
def lineNoRange = 1..3
|
||||
def lines = []
|
||||
|
||||
new File('src/main/resources/ioInput.txt').eachLine(0, { line, lineNo ->
|
||||
if (lineNoRange.contains(lineNo)) {
|
||||
lines.add(line)
|
||||
}
|
||||
})
|
||||
assertEquals(expectedList, lines)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingWithReader_thenLineCountReturned() {
|
||||
def expectedCount = 4
|
||||
def actualCount = 0
|
||||
new File('src/main/resources/ioInput.txt').withReader { reader ->
|
||||
while(reader.readLine()) {
|
||||
actualCount++
|
||||
}
|
||||
}
|
||||
assertEquals(expectedCount, actualCount)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingNewReader_thenOutputFileCreated() {
|
||||
def outputPath = 'src/main/resources/ioOut.txt'
|
||||
def reader = new File('src/main/resources/ioInput.txt').newReader()
|
||||
new File(outputPath).append(reader)
|
||||
reader.close()
|
||||
def ioOut = new File(outputPath)
|
||||
assertTrue(ioOut.exists())
|
||||
ioOut.delete()
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingWithInputStream_thenCorrectBytesAreReturned() {
|
||||
def expectedLength = 1139
|
||||
byte[] data = []
|
||||
new File("src/main/resources/binaryExample.jpg").withInputStream { stream ->
|
||||
data = stream.getBytes()
|
||||
}
|
||||
assertEquals(expectedLength, data.length)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingNewInputStream_thenOutputFileCreated() {
|
||||
def outputPath = 'src/main/resources/binaryOut.jpg'
|
||||
def is = new File('src/main/resources/binaryExample.jpg').newInputStream()
|
||||
new File(outputPath).append(is)
|
||||
is.close()
|
||||
def ioOut = new File(outputPath)
|
||||
assertTrue(ioOut.exists())
|
||||
ioOut.delete()
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingCollect_thenCorrectListIsReturned() {
|
||||
def expectedList = ['First line of text', 'Second line of text', 'Third line of text', 'Fourth line of text']
|
||||
|
||||
def actualList = new File('src/main/resources/ioInput.txt').collect {it}
|
||||
assertEquals(expectedList, actualList)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingAsStringArray_thenCorrectArrayIsReturned() {
|
||||
String[] expectedArray = ['First line of text', 'Second line of text', 'Third line of text', 'Fourth line of text']
|
||||
|
||||
def actualArray = new File('src/main/resources/ioInput.txt') as String[]
|
||||
assertArrayEquals(expectedArray, actualArray)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingText_thenCorrectStringIsReturned() {
|
||||
def ln = System.getProperty('line.separator')
|
||||
def expectedString = "First line of text${ln}Second line of text${ln}Third line of text${ln}Fourth line of text"
|
||||
def actualString = new File('src/main/resources/ioInput.txt').text
|
||||
assertEquals(expectedString.toString(), actualString)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingBytes_thenByteArrayIsReturned() {
|
||||
def expectedLength = 1139
|
||||
def contents = new File('src/main/resources/binaryExample.jpg').bytes
|
||||
assertEquals(expectedLength, contents.length)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.baeldung.io
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import groovy.io.FileType
|
||||
import groovy.io.FileVisitResult
|
||||
|
||||
class TraverseFileTreeUnitTest {
|
||||
@Test
|
||||
void whenUsingEachFile_filesAreListed() {
|
||||
new File('src/main/resources').eachFile { file ->
|
||||
println file.name
|
||||
}
|
||||
}
|
||||
|
||||
@Test(expected = IllegalArgumentException)
|
||||
void whenUsingEachFileOnAFile_anErrorOccurs() {
|
||||
new File('src/main/resources/ioInput.txt').eachFile { file ->
|
||||
println file.name
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileMatch_filesAreListed() {
|
||||
new File('src/main/resources').eachFileMatch(~/io.*\.txt/) { file ->
|
||||
println file.name
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileRecurse_thenFilesInSubfoldersAreListed() {
|
||||
new File('src/main').eachFileRecurse(FileType.FILES) { file ->
|
||||
println "$file.parent $file.name"
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachFileRecurse_thenDirsInSubfoldersAreListed() {
|
||||
new File('src/main').eachFileRecurse(FileType.DIRECTORIES) { file ->
|
||||
println "$file.parent $file.name"
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingEachDirRecurse_thenDirsAndSubDirsAreListed() {
|
||||
new File('src/main').eachDirRecurse { dir ->
|
||||
println "$dir.parent $dir.name"
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingTraverse_thenDirectoryIsTraversed() {
|
||||
new File('src/main').traverse { file ->
|
||||
if (file.directory && file.name == 'groovy') {
|
||||
FileVisitResult.SKIP_SUBTREE
|
||||
} else {
|
||||
println "$file.parent - $file.name"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.io
|
||||
|
||||
import static org.junit.Assert.*
|
||||
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
class WriteExampleUnitTest {
|
||||
@Before
|
||||
void clearOutputFile() {
|
||||
new File('src/main/resources/ioOutput.txt').text = ''
|
||||
new File('src/main/resources/ioBinaryOutput.bin').delete()
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingWithWriter_thenFileCreated() {
|
||||
def outputLines = [
|
||||
'Line one of output example',
|
||||
'Line two of output example',
|
||||
'Line three of output example'
|
||||
]
|
||||
|
||||
def outputFileName = 'src/main/resources/ioOutput.txt'
|
||||
new File(outputFileName).withWriter { writer ->
|
||||
outputLines.each { line ->
|
||||
writer.writeLine line
|
||||
}
|
||||
}
|
||||
def writtenLines = new File(outputFileName).collect {it}
|
||||
assertEquals(outputLines, writtenLines)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingNewWriter_thenFileCreated() {
|
||||
def outputLines = [
|
||||
'Line one of output example',
|
||||
'Line two of output example',
|
||||
'Line three of output example'
|
||||
]
|
||||
|
||||
def outputFileName = 'src/main/resources/ioOutput.txt'
|
||||
def writer = new File(outputFileName).newWriter()
|
||||
outputLines.forEach {line ->
|
||||
writer.writeLine line
|
||||
}
|
||||
writer.flush()
|
||||
writer.close()
|
||||
|
||||
def writtenLines = new File(outputFileName).collect {it}
|
||||
assertEquals(outputLines, writtenLines)
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingDoubleLessThanOperator_thenFileCreated() {
|
||||
def outputLines = [
|
||||
'Line one of output example',
|
||||
'Line two of output example',
|
||||
'Line three of output example'
|
||||
]
|
||||
|
||||
def ln = System.getProperty('line.separator')
|
||||
def outputFileName = 'src/main/resources/ioOutput.txt'
|
||||
new File(outputFileName) << "Line one of output example${ln}Line two of output example${ln}Line three of output example"
|
||||
def writtenLines = new File(outputFileName).collect {it}
|
||||
assertEquals(outputLines.size(), writtenLines.size())
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingBytes_thenBinaryFileCreated() {
|
||||
def outputFileName = 'src/main/resources/ioBinaryOutput.bin'
|
||||
def outputFile = new File(outputFileName)
|
||||
byte[] outBytes = [44, 88, 22]
|
||||
outputFile.bytes = outBytes
|
||||
assertEquals(3, new File(outputFileName).size())
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingWithOutputStream_thenBinaryFileCreated() {
|
||||
def outputFileName = 'src/main/resources/ioBinaryOutput.bin'
|
||||
byte[] outBytes = [44, 88, 22]
|
||||
new File(outputFileName).withOutputStream { stream ->
|
||||
stream.write(outBytes)
|
||||
}
|
||||
assertEquals(3, new File(outputFileName).size())
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingNewOutputStream_thenBinaryFileCreated() {
|
||||
def outputFileName = 'src/main/resources/ioBinaryOutput.bin'
|
||||
byte[] outBytes = [44, 88, 22]
|
||||
def os = new File(outputFileName).newOutputStream()
|
||||
os.write(outBytes)
|
||||
os.close()
|
||||
assertEquals(3, new File(outputFileName).size())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
package com.baeldung.json
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
import java.text.SimpleDateFormat
|
||||
|
||||
class JsonParserTest extends Specification {
|
||||
|
||||
JsonParser jsonParser
|
||||
|
||||
void setup () {
|
||||
jsonParser = new JsonParser()
|
||||
}
|
||||
|
||||
def 'Should parse to Account given Json String' () {
|
||||
given:
|
||||
def json = '{"id":"1234","value":15.6}'
|
||||
when:
|
||||
def account = jsonParser.toObject(json)
|
||||
then:
|
||||
account
|
||||
account instanceof Account
|
||||
account.id == '1234'
|
||||
account.value == 15.6
|
||||
}
|
||||
|
||||
/*def 'Should parse to Account given Json String with date property' () {
|
||||
given:
|
||||
def json = '{"id":"1234","value":15.6,"createdAt":"2018-01-01T00:00:00+0000"}'
|
||||
when:
|
||||
def account = jsonParser.toObjectWithIndexOverlay(json)
|
||||
then:
|
||||
account
|
||||
account instanceof Account
|
||||
account.id == '1234'
|
||||
account.value == 15.6
|
||||
println account.createdAt
|
||||
account.createdAt == Date.parse('yyyy-MM-dd', '2018-01-01')
|
||||
}*/
|
||||
|
||||
/*def 'Should parse to Json given an Account object' () {
|
||||
given:
|
||||
Account account = new Account(
|
||||
id: '123',
|
||||
value: 15.6,
|
||||
createdAt: new SimpleDateFormat('MM/dd/yyyy').parse('01/01/2018')
|
||||
)
|
||||
when:
|
||||
def json = jsonParser.toJson(account)
|
||||
then:
|
||||
json
|
||||
json == '{"value":15.6,"createdAt":"2018-01-01T00:00:00+0000","id":"123"}'
|
||||
}*/
|
||||
|
||||
def 'Should prettify given a json string' () {
|
||||
given:
|
||||
String json = '{"value":15.6,"createdAt":"01/01/2018","id":"123456"}'
|
||||
when:
|
||||
def jsonPretty = jsonParser.prettyfy(json)
|
||||
then:
|
||||
jsonPretty
|
||||
jsonPretty == '{\n "value": 15.6,\n "createdAt": "01/01/2018",\n "id": "123456"\n}'
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import com.baeldung.strings.Concatenate;
|
||||
|
||||
class ConcatenateTest extends GroovyTestCase {
|
||||
|
||||
void testSimpleConcat() {
|
||||
def name = new Concatenate()
|
||||
name.first = 'Joe';
|
||||
name.last = 'Smith';
|
||||
def expected = 'My name is Joe Smith'
|
||||
assertToString(name.doSimpleConcat(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingGString() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingGString(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingGStringClosures() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingGStringClosures(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingStringConcatMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingStringConcatMethod(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingLeftShiftOperator() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingLeftShiftOperator(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingArrayJoinMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingArrayJoinMethod(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingArrayInjectMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingArrayInjectMethod(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingStringBuilder() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingStringBuilder(), expected)
|
||||
}
|
||||
|
||||
void testConcatUsingStringBuffer() {
|
||||
def name = new Concatenate()
|
||||
name.first = "Joe";
|
||||
name.last = "Smith";
|
||||
def expected = "My name is Joe Smith"
|
||||
assertToString(name.doConcatUsingStringBuffer(), expected)
|
||||
}
|
||||
|
||||
void testConcatMultilineUsingStringConcatMethod() {
|
||||
def name = new Concatenate()
|
||||
name.first = '''Joe
|
||||
Smith
|
||||
''';
|
||||
name.last = 'Junior';
|
||||
def expected = '''My name is Joe
|
||||
Smith
|
||||
Junior''';
|
||||
assertToString(name.doConcatUsingStringConcatMethod(), expected)
|
||||
}
|
||||
|
||||
void testGStringvsClosure(){
|
||||
def first = "Joe";
|
||||
def last = "Smith";
|
||||
def eagerGString = "My name is $first $last"
|
||||
def lazyGString = "My name is ${-> first} ${-> last}"
|
||||
|
||||
assert eagerGString == "My name is Joe Smith"
|
||||
assert lazyGString == "My name is Joe Smith"
|
||||
first = "David";
|
||||
assert eagerGString == "My name is Joe Smith"
|
||||
assert lazyGString == "My name is David Smith"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.baeldung.strings
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
import java.util.regex.Pattern
|
||||
|
||||
class StringMatchingSpec extends Specification {
|
||||
|
||||
def "pattern operator example"() {
|
||||
given: "a pattern"
|
||||
def p = ~'foo'
|
||||
|
||||
expect:
|
||||
p instanceof Pattern
|
||||
|
||||
and: "you can use slash strings to avoid escaping of blackslash"
|
||||
def digitPattern = ~/\d*/
|
||||
digitPattern.matcher('4711').matches()
|
||||
}
|
||||
|
||||
def "match operator example"() {
|
||||
expect:
|
||||
'foobar' ==~ /.*oba.*/
|
||||
|
||||
and: "matching is strict"
|
||||
!('foobar' ==~ /foo/)
|
||||
}
|
||||
|
||||
def "find operator example"() {
|
||||
when: "using the find operator"
|
||||
def matcher = 'foo and bar, baz and buz' =~ /(\w+) and (\w+)/
|
||||
|
||||
then: "will find groups"
|
||||
matcher.size() == 2
|
||||
|
||||
and: "can access groups using array"
|
||||
matcher[0][0] == 'foo and bar'
|
||||
matcher[1][2] == 'buz'
|
||||
|
||||
and: "you can use it as a predicate"
|
||||
'foobarbaz' =~ /bar/
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package com.baeldung.stringtoint
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
import java.text.DecimalFormat
|
||||
|
||||
import static org.junit.Assert.assertEquals
|
||||
import static org.junit.Assert.assertNull
|
||||
|
||||
class ConvertStringToInt {
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingAsInteger_thenConvertToInteger() {
|
||||
def stringNum = "123"
|
||||
def invalidString = "123a"
|
||||
Integer expectedInteger = 123
|
||||
Integer integerNum = stringNum as Integer
|
||||
def intNum = invalidString?.isInteger() ? invalidString as Integer : null
|
||||
|
||||
assertNull(null, intNum)
|
||||
assertEquals(integerNum, expectedInteger)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingAsInt_thenConvertToInt() {
|
||||
def stringNum = "123"
|
||||
int expectedInt = 123
|
||||
int intNum = stringNum as int
|
||||
|
||||
assertEquals(intNum, expectedInt)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingToInteger_thenConvertToInteger() {
|
||||
def stringNum = "123"
|
||||
int expectedInt = 123
|
||||
int intNum = stringNum.toInteger()
|
||||
|
||||
assertEquals(intNum, expectedInt)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingParseInt_thenConvertToInteger() {
|
||||
def stringNum = "123"
|
||||
int expectedInt = 123
|
||||
int intNum = Integer.parseInt(stringNum)
|
||||
|
||||
assertEquals(intNum, expectedInt)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingValueOf_thenConvertToInteger() {
|
||||
def stringNum = "123"
|
||||
int expectedInt = 123
|
||||
int intNum = Integer.valueOf(stringNum)
|
||||
|
||||
assertEquals(intNum, expectedInt)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingIntValue_thenConvertToInteger() {
|
||||
def stringNum = "123"
|
||||
int expectedInt = 123
|
||||
int intNum = new Integer(stringNum).intValue()
|
||||
|
||||
assertEquals(intNum, expectedInt)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingNewInteger_thenConvertToInteger() {
|
||||
def stringNum = "123"
|
||||
int expectedInt = 123
|
||||
int intNum = new Integer(stringNum)
|
||||
|
||||
assertEquals(intNum, expectedInt)
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingDecimalFormat_thenConvertToInteger() {
|
||||
def stringNum = "123"
|
||||
int expectedInt = 123
|
||||
DecimalFormat decimalFormat = new DecimalFormat("#")
|
||||
int intNum = decimalFormat.parse(stringNum).intValue()
|
||||
|
||||
assertEquals(intNum, expectedInt)
|
||||
}
|
||||
|
||||
@Test(expected = NumberFormatException.class)
|
||||
void givenInvalidString_whenUsingAs_thenThrowNumberFormatException() {
|
||||
def invalidString = "123a"
|
||||
invalidString as Integer
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
void givenNullString_whenUsingToInteger_thenThrowNullPointerException() {
|
||||
def invalidString = null
|
||||
invalidString.toInteger()
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenString_whenUsingIsInteger_thenCheckIfCorrectValue() {
|
||||
def invalidString = "123a"
|
||||
def validString = "123"
|
||||
def invalidNum = invalidString?.isInteger() ? invalidString as Integer : false
|
||||
def correctNum = validString?.isInteger() ? validString as Integer : false
|
||||
|
||||
assertEquals(false, invalidNum)
|
||||
assertEquals(123, correctNum)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class CharacterInGroovy {
|
||||
|
||||
@Test
|
||||
void 'character'() {
|
||||
char a = 'A' as char
|
||||
char b = 'B' as char
|
||||
char c = (char) 'C'
|
||||
|
||||
Assert.assertTrue(a instanceof Character)
|
||||
Assert.assertTrue(b instanceof Character)
|
||||
Assert.assertTrue(c instanceof Character)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
class DollarSlashyString {
|
||||
|
||||
@Test
|
||||
void 'dollar slashy string'() {
|
||||
def name = "John"
|
||||
|
||||
def dollarSlashy = $/
|
||||
Hello $name!,
|
||||
|
||||
I can show you $ sign or escaped dollar sign: $$
|
||||
Both slashes works: \ or /, but we can still escape it: $/
|
||||
|
||||
We have to escape opening and closing delimiter:
|
||||
- $$$/
|
||||
- $/$$
|
||||
/$
|
||||
|
||||
print(dollarSlashy)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class DoubleQuotedString {
|
||||
|
||||
@Test
|
||||
void 'escape double quoted string'() {
|
||||
def example = "Hello \"world\"!"
|
||||
|
||||
println(example)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'String ang GString'() {
|
||||
def string = "example"
|
||||
def stringWithExpression = "example${2}"
|
||||
|
||||
Assert.assertTrue(string instanceof String)
|
||||
Assert.assertTrue(stringWithExpression instanceof GString)
|
||||
Assert.assertTrue(stringWithExpression.toString() instanceof String)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'placeholder with variable'() {
|
||||
def name = "John"
|
||||
def helloName = "Hello $name!".toString()
|
||||
|
||||
Assert.assertEquals("Hello John!", helloName)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'placeholder with expression'() {
|
||||
def result = "result is ${2 * 2}".toString()
|
||||
|
||||
Assert.assertEquals("result is 4", result)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'placeholder with dotted access'() {
|
||||
def person = [name: 'John']
|
||||
|
||||
def myNameIs = "I'm $person.name, and you?".toString()
|
||||
|
||||
Assert.assertEquals("I'm John, and you?", myNameIs)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'placeholder with method call'() {
|
||||
def name = 'John'
|
||||
|
||||
def result = "Uppercase name: ${name.toUpperCase()}".toString()
|
||||
|
||||
Assert.assertEquals("Uppercase name: JOHN", result)
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
void 'GString and String hashcode'() {
|
||||
def string = "2+2 is 4"
|
||||
def gstring = "2+2 is ${4}"
|
||||
|
||||
Assert.assertTrue(string.hashCode() != gstring.hashCode())
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class SingleQuotedString {
|
||||
|
||||
@Test
|
||||
void 'single quoted string'() {
|
||||
def example = 'Hello world'
|
||||
|
||||
Assert.assertEquals('Hello world!', 'Hello' + ' world!')
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class SlashyString {
|
||||
|
||||
@Test
|
||||
void 'slashy string'() {
|
||||
def pattern = /.*foobar.*\/hello.*/
|
||||
|
||||
Assert.assertTrue("I'm matching foobar /hello regexp pattern".matches(pattern))
|
||||
}
|
||||
|
||||
void 'wont compile'() {
|
||||
// if ('' == //) {
|
||||
// println("I can't compile")
|
||||
// }
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'interpolate and multiline'() {
|
||||
def name = 'John'
|
||||
|
||||
def example = /
|
||||
Hello $name
|
||||
second line
|
||||
/
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class Strings {
|
||||
|
||||
@Test
|
||||
void 'string interpolation '() {
|
||||
def name = "Kacper"
|
||||
|
||||
def result = "Hello ${name}!"
|
||||
|
||||
Assert.assertEquals("Hello Kacper!", result.toString())
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'string concatenation'() {
|
||||
def first = "first"
|
||||
def second = "second"
|
||||
|
||||
def concatenation = first + second
|
||||
|
||||
Assert.assertEquals("firstsecond", concatenation)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Test
|
||||
|
||||
class TripleDoubleQuotedString {
|
||||
|
||||
@Test
|
||||
void 'triple-quoted strings with interpolation'() {
|
||||
def name = "John"
|
||||
|
||||
def multiLine = """
|
||||
I'm $name.
|
||||
"This is quotation"
|
||||
"""
|
||||
|
||||
println(multiLine)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package groovy.com.baeldung.stringtypes
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
|
||||
class TripleSingleQuotedString {
|
||||
|
||||
def 'formatted json'() {
|
||||
def jsonContent = '''
|
||||
{
|
||||
"name": "John",
|
||||
"age": 20,
|
||||
"birthDate": null
|
||||
}
|
||||
'''
|
||||
}
|
||||
|
||||
def 'triple single quoted'() {
|
||||
def triple = '''im triple single quoted string'''
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'triple single quoted with multiline string'() {
|
||||
def triple = '''
|
||||
firstline
|
||||
secondline
|
||||
'''
|
||||
|
||||
Assert.assertTrue(triple.startsWith("\n"))
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'triple single quoted with multiline string with stripIndent() and removing newline characters'() {
|
||||
def triple = '''\
|
||||
firstline
|
||||
secondline'''.stripIndent()
|
||||
|
||||
Assert.assertEquals("firstline\nsecondline", triple)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'triple single quoted with multiline string with last line with only whitespaces'() {
|
||||
def triple = '''\
|
||||
firstline
|
||||
secondline\
|
||||
'''.stripIndent()
|
||||
|
||||
println(triple)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'triple single quoted with multiline string with stripMargin(Character) and removing newline characters'() {
|
||||
def triple = '''\
|
||||
|firstline
|
||||
|secondline'''.stripMargin()
|
||||
|
||||
println(triple)
|
||||
}
|
||||
|
||||
@Test
|
||||
void 'striple single quoted with special characters'() {
|
||||
def specialCharacters = '''hello \'John\'. This is backslash - \\. \nSecond line starts here'''
|
||||
|
||||
println(specialCharacters)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package com.baeldung.traits
|
||||
|
||||
import spock.lang.Specification
|
||||
|
||||
class TraitsUnitTest extends Specification {
|
||||
|
||||
Employee employee
|
||||
Dog dog
|
||||
|
||||
void setup () {
|
||||
employee = new Employee()
|
||||
dog = new Dog()
|
||||
}
|
||||
|
||||
def 'Should return msg string when using Employee.sayHello method provided by UserTrait' () {
|
||||
when:
|
||||
def msg = employee.sayHello()
|
||||
then:
|
||||
msg
|
||||
msg instanceof String
|
||||
assert msg == "Hello!"
|
||||
}
|
||||
|
||||
def 'Should return displayMsg string when using Employee.showName method' () {
|
||||
when:
|
||||
def displayMsg = employee.showName()
|
||||
then:
|
||||
displayMsg
|
||||
displayMsg instanceof String
|
||||
assert displayMsg == "Hello, Bob!"
|
||||
}
|
||||
|
||||
def 'Should return greetMsg string when using Employee.greet method' () {
|
||||
when:
|
||||
def greetMsg = employee.greet()
|
||||
then:
|
||||
greetMsg
|
||||
greetMsg instanceof String
|
||||
assert greetMsg == "Hello, from a private method!"
|
||||
}
|
||||
|
||||
def 'Should return MissingMethodException when using Employee.greetingMessage method' () {
|
||||
when:
|
||||
def exception
|
||||
try {
|
||||
employee.greetingMessage()
|
||||
}catch(Exception e) {
|
||||
exception = e
|
||||
}
|
||||
|
||||
then:
|
||||
exception
|
||||
exception instanceof groovy.lang.MissingMethodException
|
||||
assert exception.message == "No signature of method: com.baeldung.traits.Employee.greetingMessage()"+
|
||||
" is applicable for argument types: () values: []"
|
||||
}
|
||||
|
||||
def 'Should return employee instance when using Employee.whoAmI method' () {
|
||||
when:
|
||||
def emp = employee.self()
|
||||
then:
|
||||
emp
|
||||
emp instanceof Employee
|
||||
assert emp.is(employee)
|
||||
}
|
||||
|
||||
def 'Should display lastName when using Employee.showLastName method' () {
|
||||
when:
|
||||
def lastNameMsg = employee.showLastName()
|
||||
then:
|
||||
lastNameMsg
|
||||
lastNameMsg instanceof String
|
||||
assert lastNameMsg == "Hello, Marley!"
|
||||
}
|
||||
|
||||
def 'Should be able to define properties of UserTrait in Employee instance' () {
|
||||
when:
|
||||
employee = new Employee(email: "a@e.com", address: "baeldung.com")
|
||||
then:
|
||||
employee
|
||||
employee instanceof Employee
|
||||
assert employee.email == "a@e.com"
|
||||
assert employee.address == "baeldung.com"
|
||||
}
|
||||
|
||||
def 'Should execute basicAbility method from SpeakingTrait and return msg string' () {
|
||||
when:
|
||||
def speakMsg = dog.basicAbility()
|
||||
then:
|
||||
speakMsg
|
||||
speakMsg instanceof String
|
||||
assert speakMsg == "Speaking!!"
|
||||
}
|
||||
|
||||
def 'Should verify multiple inheritance with traits and execute overridden traits method' () {
|
||||
when:
|
||||
def walkSpeakMsg = dog.speakAndWalk()
|
||||
println walkSpeakMsg
|
||||
then:
|
||||
walkSpeakMsg
|
||||
walkSpeakMsg instanceof String
|
||||
assert walkSpeakMsg == "Walk and speak!!"
|
||||
}
|
||||
|
||||
def 'Should implement AnimalTrait at runtime and access basicBehavior method' () {
|
||||
when:
|
||||
def dogInstance = new Dog() as AnimalTrait
|
||||
def basicBehaviorMsg = dogInstance.basicBehavior()
|
||||
then:
|
||||
basicBehaviorMsg
|
||||
basicBehaviorMsg instanceof String
|
||||
assert basicBehaviorMsg == "Animalistic!!"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user