JAVA-12098: Moved core-groovy-2 inside core-groovy-modules
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
# Core Groovy 2
|
||||
|
||||
This module contains articles about core Groovy concepts
|
||||
|
||||
## Relevant articles:
|
||||
|
||||
- [Template Engines in Groovy](https://www.baeldung.com/groovy-template-engines)
|
||||
- [Groovy def Keyword](https://www.baeldung.com/groovy-def-keyword)
|
||||
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
|
||||
- [Working with XML in Groovy](https://www.baeldung.com/groovy-xml)
|
||||
- [Integrating Groovy into Java Applications](https://www.baeldung.com/groovy-java-applications)
|
||||
- [Concatenate Strings with Groovy](https://www.baeldung.com/groovy-concatenate-strings)
|
||||
- [Metaprogramming in Groovy](https://www.baeldung.com/groovy-metaprogramming)
|
||||
- [A Quick Guide to Working with Web Services in Groovy](https://www.baeldung.com/groovy-web-services)
|
||||
- [Categories in Groovy](https://www.baeldung.com/groovy-categories)
|
||||
- [How to Determine the Data Type in Groovy](https://www.baeldung.com/groovy-determine-data-type)
|
||||
- [[<-- Prev]](/core-groovy)
|
||||
@@ -0,0 +1,177 @@
|
||||
<?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-2</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy-2</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.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
<type>pom</type>
|
||||
</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>
|
||||
<scriptSourceDirectory>src/main/groovy</scriptSourceDirectory>
|
||||
<sourceDirectory>src/main/java</sourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.gmavenplus</groupId>
|
||||
<artifactId>gmavenplus-plugin</artifactId>
|
||||
<version>1.7.0</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<goals>
|
||||
<goal>execute</goal>
|
||||
<goal>addSources</goal>
|
||||
<goal>addTestSources</goal>
|
||||
<goal>generateStubs</goal>
|
||||
<goal>compile</goal>
|
||||
<goal>generateTestStubs</goal>
|
||||
<goal>compileTests</goal>
|
||||
<goal>removeStubs</goal>
|
||||
<goal>removeTestStubs</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<!-- any version of Groovy \>= 1.5.0 should work here -->
|
||||
<version>${groovy.version}</version>
|
||||
<scope>runtime</scope>
|
||||
<type>pom</type>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
</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>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>2.20.1</version>
|
||||
<configuration>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
<include>**/*Spec.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!-- Maven Assembly Plugin: needed to run the jar through command line -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
<configuration>
|
||||
<!-- get all project dependencies -->
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
<!-- MainClass in mainfest make a executable jar -->
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.MyJointCompilationApp</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id>
|
||||
<!-- bind to the packaging phase -->
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
<url>http://jcenter.bintray.com</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||
<commons-lang3.version>3.9</commons-lang3.version>
|
||||
<java.version>1.8</java.version>
|
||||
<logback.version>1.2.3</logback.version>
|
||||
<groovy.version>2.5.7</groovy.version>
|
||||
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
|
||||
</properties>
|
||||
</project>
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
<?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-2</artifactId>
|
||||
<version>1.0-SNAPSHOT</version>
|
||||
<name>core-groovy-2</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.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>ch.qos.logback</groupId>
|
||||
<artifactId>logback-classic</artifactId>
|
||||
<version>${logback.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-all</artifactId>
|
||||
<version>${groovy.version}</version>
|
||||
<type>pom</type>
|
||||
</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>
|
||||
<dependency>
|
||||
<groupId>com.github.groovy-wslite</groupId>
|
||||
<artifactId>groovy-wslite</artifactId>
|
||||
<version>${groovy-wslite.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<scriptSourceDirectory>src/main/groovy</scriptSourceDirectory>
|
||||
<sourceDirectory>src/main/java</sourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-eclipse-compiler</artifactId>
|
||||
<version>${groovy.compiler.version}</version>
|
||||
<extensions>true</extensions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${compiler.plugin.version}</version>
|
||||
<configuration>
|
||||
<compilerId>groovy-eclipse-compiler</compilerId>
|
||||
<source>${java.version}</source>
|
||||
<target>${java.version}</target>
|
||||
</configuration>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-eclipse-compiler</artifactId>
|
||||
<version>${groovy.compiler.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.groovy</groupId>
|
||||
<artifactId>groovy-eclipse-batch</artifactId>
|
||||
<version>${groovy.version}-01</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</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>
|
||||
<plugin>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<configuration>
|
||||
<useFile>false</useFile>
|
||||
<includes>
|
||||
<include>**/*Test.java</include>
|
||||
<include>**/*Spec.java</include>
|
||||
</includes>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<!-- Maven Assembly Plugin: needed to run the jar through command line -->
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>${assembly.plugin.version}</version>
|
||||
<configuration>
|
||||
<!-- get all project dependencies -->
|
||||
<descriptorRefs>
|
||||
<descriptorRef>jar-with-dependencies</descriptorRef>
|
||||
</descriptorRefs>
|
||||
<!-- MainClass in mainfest make a executable jar -->
|
||||
<archive>
|
||||
<manifest>
|
||||
<mainClass>com.baeldung.MyJointCompilationApp</mainClass>
|
||||
</manifest>
|
||||
</archive>
|
||||
|
||||
</configuration>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>make-assembly</id>
|
||||
<!-- bind to the packaging phase -->
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>single</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>central</id>
|
||||
<url>https://jcenter.bintray.com</url>
|
||||
</repository>
|
||||
</repositories>
|
||||
|
||||
<properties>
|
||||
<hsqldb.version>2.4.0</hsqldb.version>
|
||||
<spock-core.version>1.1-groovy-2.4</spock-core.version>
|
||||
<groovy-wslite.version>1.1.3</groovy-wslite.version>
|
||||
<groovy.version>2.5.7</groovy.version>
|
||||
<assembly.plugin.version>3.1.0</assembly.plugin.version>
|
||||
<compiler.plugin.version>3.8.0</compiler.plugin.version>
|
||||
<groovy.compiler.version>3.3.0-01</groovy.compiler.version>
|
||||
</properties>
|
||||
|
||||
</project>
|
||||
@@ -0,0 +1,25 @@
|
||||
package com.baeldung
|
||||
|
||||
import org.slf4j.LoggerFactory
|
||||
|
||||
class CalcMath {
|
||||
def log = LoggerFactory.getLogger(this.getClass())
|
||||
|
||||
def calcSum(x, y) {
|
||||
log.info "Executing $x + $y"
|
||||
x + y
|
||||
}
|
||||
|
||||
/**
|
||||
* example of method that in java would throw error at compile time
|
||||
* @param x
|
||||
* @param y
|
||||
* @return
|
||||
*/
|
||||
def calcSum2(x, y) {
|
||||
log.info "Executing $x + $y"
|
||||
// DANGER! This won't throw a compilation issue and fail only at runtime!!!
|
||||
calcSum3()
|
||||
log.info("Logging an undefined variable: $z")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.baeldung
|
||||
|
||||
def calcSum(x, y) {
|
||||
x + y
|
||||
}
|
||||
|
||||
def calcSum2(x, y) {
|
||||
// DANGER! The variable "log" may be undefined
|
||||
log.info "Executing $x + $y"
|
||||
// DANGER! This method doesn't exist!
|
||||
calcSum3()
|
||||
// DANGER! The logged variable "z" is undefined!
|
||||
log.info("Logging an undefined variable: $z")
|
||||
}
|
||||
|
||||
calcSum(1,5)
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.category;
|
||||
|
||||
class BaeldungCategory {
|
||||
|
||||
public static String capitalize(String self) {
|
||||
String capitalizedStr = self;
|
||||
if (self.size() > 0) {
|
||||
capitalizedStr = self.substring(0, 1).toUpperCase() + self.substring(1);
|
||||
}
|
||||
return capitalizedStr
|
||||
}
|
||||
|
||||
public static double toThePower(Number self, Number exponent) {
|
||||
return Math.pow(self, exponent);
|
||||
}
|
||||
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baeldung.category;
|
||||
|
||||
import groovy.lang.Category
|
||||
|
||||
@Category(Number)
|
||||
class NumberCategory {
|
||||
|
||||
public Number cube() {
|
||||
return this*this*this
|
||||
}
|
||||
|
||||
public int divideWithRoundUp(BigDecimal divisor, boolean isRoundUp) {
|
||||
def mathRound = isRoundUp ? BigDecimal.ROUND_UP : BigDecimal.ROUND_DOWN
|
||||
return (int)new BigDecimal(this).divide(divisor, 0, mathRound)
|
||||
}
|
||||
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
package com.baeldung.concatenate
|
||||
|
||||
class Wonder {
|
||||
|
||||
String numOfWonder = 'seven'
|
||||
|
||||
String operator_plus() {
|
||||
return 'The ' + numOfWonder + ' wonders of the world'
|
||||
}
|
||||
|
||||
String operator_left() {
|
||||
return 'The ' << numOfWonder << ' wonders of ' << 'the world'
|
||||
}
|
||||
|
||||
String interpolation_one() {
|
||||
return "The $numOfWonder wonders of the world"
|
||||
|
||||
}
|
||||
|
||||
String interpolation_two() {
|
||||
return "The ${numOfWonder} wonders of the world"
|
||||
}
|
||||
|
||||
String multilineString() {
|
||||
return """
|
||||
There are $numOfWonder wonders of the world.
|
||||
Can you name them all?
|
||||
1. The Great Pyramid of Giza
|
||||
2. Hanging Gardens of Babylon
|
||||
3. Colossus of Rhode
|
||||
4. Lighthouse of Alexendra
|
||||
5. Temple of Artemis
|
||||
6. Status of Zeus at Olympia
|
||||
7. Mausoleum at Halicarnassus
|
||||
"""
|
||||
}
|
||||
|
||||
String method_concat() {
|
||||
return 'The '.concat(numOfWonder).concat(' wonders of the world')
|
||||
|
||||
}
|
||||
|
||||
String method_builder() {
|
||||
return new StringBuilder()
|
||||
.append('The ').append(numOfWonder).append(' wonders of the world')
|
||||
}
|
||||
|
||||
String method_buffer() {
|
||||
return new StringBuffer()
|
||||
.append('The ').append(numOfWonder).append(' wonders of the world')
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package com.baeldung.determinedatatype
|
||||
|
||||
class Person {
|
||||
|
||||
private int ageAsInt
|
||||
private Double ageAsDouble
|
||||
private String ageAsString
|
||||
|
||||
Person() {}
|
||||
Person(int ageAsInt) { this.ageAsInt = ageAsInt}
|
||||
Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble}
|
||||
Person(String ageAsString) { this.ageAsString = ageAsString}
|
||||
}
|
||||
class Student extends Person {}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.baeldung.metaprogramming
|
||||
|
||||
import groovy.transform.AutoClone
|
||||
import groovy.transform.Canonical
|
||||
import groovy.transform.EqualsAndHashCode
|
||||
import groovy.transform.ToString
|
||||
import groovy.transform.TupleConstructor
|
||||
import groovy.util.logging.*
|
||||
|
||||
@Canonical
|
||||
@TupleConstructor
|
||||
@EqualsAndHashCode
|
||||
@ToString(includePackage=false, excludes=['id'])
|
||||
@Log
|
||||
@AutoClone
|
||||
class Employee {
|
||||
|
||||
long id
|
||||
String firstName
|
||||
String lastName
|
||||
int age
|
||||
|
||||
//method to catch missing property's getter
|
||||
def propertyMissing(String propertyName) {
|
||||
log.info "$propertyName is not available"
|
||||
"property '$propertyName' is not available"
|
||||
}
|
||||
|
||||
//method to catch missing property's setter
|
||||
def propertyMissing(String propertyName, propertyValue) {
|
||||
println "property '$propertyName' is not available"
|
||||
log.info "$propertyName is not available"
|
||||
"property '$propertyName' is not available"
|
||||
}
|
||||
|
||||
def methodMissing(String methodName, def methodArgs) {
|
||||
log.info "$methodName is not defined"
|
||||
"method '$methodName' is not defined"
|
||||
}
|
||||
|
||||
def logEmp() {
|
||||
log.info "Employee: $lastName, $firstName is of $age years age"
|
||||
}
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baeldung.metaprogramming.extension
|
||||
|
||||
import com.baeldung.metaprogramming.Employee
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.Year
|
||||
|
||||
class BasicExtensions {
|
||||
|
||||
static int getYearOfBirth(Employee self) {
|
||||
return Year.now().value - self.age
|
||||
}
|
||||
|
||||
static String capitalize(String self) {
|
||||
return self.substring(0, 1).toUpperCase() + self.substring(1)
|
||||
}
|
||||
|
||||
static void printCounter(Integer self) {
|
||||
while (self>0) {
|
||||
println self
|
||||
self--
|
||||
}
|
||||
}
|
||||
|
||||
static Long square(Long self) {
|
||||
return self*self
|
||||
}
|
||||
|
||||
static BigDecimal cube(BigDecimal self) {
|
||||
return self*self*self
|
||||
}
|
||||
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.baeldung.metaprogramming.extension
|
||||
|
||||
import com.baeldung.metaprogramming.Employee
|
||||
|
||||
class StaticEmployeeExtension {
|
||||
|
||||
static Employee getDefaultObj(Employee self) {
|
||||
return new Employee(firstName: "firstName", lastName: "lastName", age: 20)
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.baeldung;
|
||||
|
||||
import groovy.lang.*;
|
||||
import groovy.util.GroovyScriptEngine;
|
||||
import groovy.util.ResourceException;
|
||||
import groovy.util.ScriptException;
|
||||
import org.codehaus.groovy.jsr223.GroovyScriptEngineFactory;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import javax.script.ScriptEngine;
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileReader;
|
||||
import java.io.IOException;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* Hello world!
|
||||
*
|
||||
*/
|
||||
public class MyJointCompilationApp {
|
||||
private final static Logger LOG = LoggerFactory.getLogger(MyJointCompilationApp.class);
|
||||
private final GroovyClassLoader loader;
|
||||
private final GroovyShell shell;
|
||||
private final GroovyScriptEngine engine;
|
||||
private final ScriptEngine engineFromFactory;
|
||||
|
||||
public MyJointCompilationApp() {
|
||||
loader = new GroovyClassLoader(this.getClass().getClassLoader());
|
||||
shell = new GroovyShell(loader, new Binding());
|
||||
|
||||
URL url = null;
|
||||
try {
|
||||
url = new File("src/main/groovy/com/baeldung/").toURI().toURL();
|
||||
} catch (MalformedURLException e) {
|
||||
LOG.error("Exception while creating url", e);
|
||||
}
|
||||
engine = new GroovyScriptEngine(new URL[] {url}, this.getClass().getClassLoader());
|
||||
engineFromFactory = new GroovyScriptEngineFactory().getScriptEngine();
|
||||
}
|
||||
|
||||
private void addWithCompiledClasses(int x, int y) {
|
||||
LOG.info("Executing {} + {}", x, y);
|
||||
Object result1 = new CalcScript().calcSum(x, y);
|
||||
LOG.info("Result of CalcScript.calcSum() method is {}", result1);
|
||||
|
||||
Object result2 = new CalcMath().calcSum(x, y);
|
||||
LOG.info("Result of CalcMath.calcSum() method is {}", result2);
|
||||
}
|
||||
|
||||
private void addWithGroovyShell(int x, int y) throws IOException {
|
||||
Script script = shell.parse(new File("src/main/groovy/com/baeldung/", "CalcScript.groovy"));
|
||||
LOG.info("Executing {} + {}", x, y);
|
||||
Object result = script.invokeMethod("calcSum", new Object[] { x, y });
|
||||
LOG.info("Result of CalcScript.calcSum() method is {}", result);
|
||||
}
|
||||
|
||||
private void addWithGroovyShellRun() throws IOException {
|
||||
Script script = shell.parse(new File("src/main/groovy/com/baeldung/", "CalcScript.groovy"));
|
||||
LOG.info("Executing script run method");
|
||||
Object result = script.run();
|
||||
LOG.info("Result of CalcScript.run() method is {}", result);
|
||||
}
|
||||
|
||||
private void addWithGroovyClassLoader(int x, int y) throws IllegalAccessException, InstantiationException, IOException {
|
||||
Class calcClass = loader.parseClass(
|
||||
new File("src/main/groovy/com/baeldung/", "CalcMath.groovy"));
|
||||
GroovyObject calc = (GroovyObject) calcClass.newInstance();
|
||||
Object result = calc.invokeMethod("calcSum", new Object[] { x + 14, y + 14 });
|
||||
LOG.info("Result of CalcMath.calcSum() method is {}", result);
|
||||
}
|
||||
|
||||
private void addWithGroovyScriptEngine(int x, int y) throws IllegalAccessException,
|
||||
InstantiationException, ResourceException, ScriptException {
|
||||
Class<GroovyObject> calcClass = engine.loadScriptByName("CalcMath.groovy");
|
||||
GroovyObject calc = calcClass.newInstance();
|
||||
//WARNING the following will throw a ClassCastException
|
||||
//((CalcMath)calc).calcSum(1,2);
|
||||
Object result = calc.invokeMethod("calcSum", new Object[] { x, y });
|
||||
LOG.info("Result of CalcMath.calcSum() method is {}", result);
|
||||
}
|
||||
|
||||
private void addWithEngineFactory(int x, int y) throws IllegalAccessException,
|
||||
InstantiationException, javax.script.ScriptException, FileNotFoundException {
|
||||
Class calcClass = (Class) engineFromFactory.eval(
|
||||
new FileReader(new File("src/main/groovy/com/baeldung/", "CalcMath.groovy")));
|
||||
GroovyObject calc = (GroovyObject) calcClass.newInstance();
|
||||
Object result = calc.invokeMethod("calcSum", new Object[] { x, y });
|
||||
LOG.info("Result of CalcMath.calcSum() method is {}", result);
|
||||
}
|
||||
|
||||
private void addWithStaticCompiledClasses() {
|
||||
LOG.info("Running the Groovy classes compiled statically...");
|
||||
addWithCompiledClasses(5, 10);
|
||||
|
||||
}
|
||||
|
||||
private void addWithDynamicCompiledClasses() throws IOException, IllegalAccessException, InstantiationException,
|
||||
ResourceException, ScriptException, javax.script.ScriptException {
|
||||
LOG.info("Invocation of a dynamic groovy script...");
|
||||
addWithGroovyShell(5, 10);
|
||||
LOG.info("Invocation of the run method of a dynamic groovy script...");
|
||||
addWithGroovyShellRun();
|
||||
LOG.info("Invocation of a dynamic groovy class loaded with GroovyClassLoader...");
|
||||
addWithGroovyClassLoader(10, 30);
|
||||
LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine...");
|
||||
addWithGroovyScriptEngine(15, 0);
|
||||
LOG.info("Invocation of a dynamic groovy class loaded with GroovyScriptEngine JSR223...");
|
||||
addWithEngineFactory(5, 6);
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws InstantiationException, IllegalAccessException,
|
||||
ResourceException, ScriptException, IOException, javax.script.ScriptException {
|
||||
MyJointCompilationApp myJointCompilationApp = new MyJointCompilationApp();
|
||||
LOG.info("Example of addition operation via Groovy scripts integration with Java.");
|
||||
myJointCompilationApp.addWithStaticCompiledClasses();
|
||||
myJointCompilationApp.addWithDynamicCompiledClasses();
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
moduleName=core-groovy-2
|
||||
moduleVersion=1.0-SNAPSHOT
|
||||
extensionClasses=com.baeldung.metaprogramming.extension.BasicExtensions
|
||||
staticExtensionClasses=com.baeldung.metaprogramming.extension.StaticEmployeeExtension
|
||||
@@ -0,0 +1,5 @@
|
||||
Dear <% out << (user) %>,
|
||||
Please read the requested article below.
|
||||
<% out << (articleText) %>
|
||||
From,
|
||||
<% out << (signature) %>
|
||||
@@ -0,0 +1,3 @@
|
||||
Dear $user,
|
||||
Thanks for subscribing our services.
|
||||
${signature}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package com.baeldung.category
|
||||
|
||||
import groovy.time.*
|
||||
import java.text.SimpleDateFormat
|
||||
import groovy.xml.*
|
||||
import groovy.xml.dom.*
|
||||
import com.baeldung.category.BaeldungCategory
|
||||
import com.baeldung.category.NumberCategory
|
||||
|
||||
class CategoryUnitTest extends GroovyTestCase {
|
||||
|
||||
void test_whenUsingTimeCategory_thenOperationOnDate() {
|
||||
def jan_1_2019 = new Date("01/01/2019")
|
||||
use (TimeCategory) {
|
||||
assert jan_1_2019 + 10.seconds == new Date("01/01/2019 00:00:10")
|
||||
|
||||
assert jan_1_2019 + 20.minutes == new Date("01/01/2019 00:20:00")
|
||||
|
||||
assert jan_1_2019 + 2.hours == new Date("01/01/2019 02:00:00")
|
||||
|
||||
assert jan_1_2019 - 1.day == new Date("12/31/2018")
|
||||
|
||||
assert jan_1_2019 + 2.weeks == new Date("01/15/2019")
|
||||
|
||||
assert jan_1_2019 - 2.months == new Date("11/01/2018")
|
||||
|
||||
assert jan_1_2019 + 3.years == new Date("01/01/2022")
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenUsingTimeCategory_thenOperationOnNumber() {
|
||||
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy")
|
||||
use (TimeCategory) {
|
||||
assert sdf.format(5.days.from.now) == sdf.format(new Date() + 5.days)
|
||||
|
||||
sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss")
|
||||
assert sdf.format(10.minutes.from.now) == sdf.format(new Date() + 10.minutes)
|
||||
assert sdf.format(2.hours.ago) == sdf.format(new Date() - 2.hours)
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenUsingDOMCategory_thenOperationOnXML() {
|
||||
|
||||
def baeldungArticlesText = """
|
||||
<articles>
|
||||
<article core-java="true">
|
||||
<title>An Intro to the Java Debug Interface (JDI)</title>
|
||||
<desc>A quick and practical overview of Java Debug Interface.</desc>
|
||||
</article>
|
||||
<article core-java="false">
|
||||
<title>A Quick Guide to Working with Web Services in Groovy</title>
|
||||
<desc>Learn how to work with Web Services in Groovy.</desc>
|
||||
</article>
|
||||
</articles>
|
||||
"""
|
||||
def baeldungArticlesDom = DOMBuilder.newInstance().parseText(baeldungArticlesText)
|
||||
|
||||
def root = baeldungArticlesDom.documentElement
|
||||
|
||||
use (DOMCategory) {
|
||||
assert root.article.size() == 2
|
||||
|
||||
def articles = root.article
|
||||
|
||||
assert articles[0].title.text() == "An Intro to the Java Debug Interface (JDI)"
|
||||
assert articles[1].desc.text() == "Learn how to work with Web Services in Groovy."
|
||||
|
||||
def articleNode3 = root.appendNode(new QName("article"), ["core-java": "false"])
|
||||
|
||||
articleNode3.appendNode("title", "Metaprogramming in Groovy")
|
||||
articleNode3.appendNode("desc", "Explore the concept of runtime and compile-time metaprogramming in Groovy")
|
||||
|
||||
assert root.article.size() == 3
|
||||
|
||||
assert root.article[2].title.text() == "Metaprogramming in Groovy"
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenUsingBaeldungCategory_thenCapitalizeString() {
|
||||
use (BaeldungCategory) {
|
||||
assert "norman".capitalize() == "Norman"
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenUsingBaeldungCategory_thenOperationsOnNumber() {
|
||||
use (BaeldungCategory) {
|
||||
assert 50.toThePower(2) == 2500
|
||||
assert 2.4.toThePower(4) == 33.1776
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenUsingNumberCategory_thenOperationsOnNumber() {
|
||||
use (NumberCategory) {
|
||||
assert 3.cube() == 27
|
||||
assert 25.divideWithRoundUp(6, true) == 5
|
||||
assert 120.23.divideWithRoundUp(6.1, true) == 20
|
||||
assert 150.9.divideWithRoundUp(12.1, false) == 12
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.baeldung.concatenate
|
||||
|
||||
import org.junit.Before
|
||||
import org.junit.Test
|
||||
|
||||
import static org.junit.Assert.*
|
||||
|
||||
class WonderUnitTest {
|
||||
|
||||
static final String EXPECTED_SINGLE_LINE = "The seven wonders of the world"
|
||||
|
||||
Wonder wonder
|
||||
|
||||
@Before
|
||||
void before() {
|
||||
wonder = new Wonder()
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingOperatorPlus_thenConcatCorrectly() {
|
||||
assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_plus())
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingOperatorLeft_thenConcatCorrectly() {
|
||||
assertEquals(EXPECTED_SINGLE_LINE, wonder.operator_left())
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingInterpolationOne_thenConcatCorrectly() {
|
||||
assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_one())
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingInterpolationTwo_thenConcatCorrectly() {
|
||||
assertEquals(EXPECTED_SINGLE_LINE, wonder.interpolation_two())
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingMultiline_thenConcatCorrectly() {
|
||||
def expectedMultiline = """
|
||||
There are seven wonders of the world.
|
||||
Can you name them all?
|
||||
1. The Great Pyramid of Giza
|
||||
2. Hanging Gardens of Babylon
|
||||
3. Colossus of Rhode
|
||||
4. Lighthouse of Alexendra
|
||||
5. Temple of Artemis
|
||||
6. Status of Zeus at Olympia
|
||||
7. Mausoleum at Halicarnassus
|
||||
"""
|
||||
assertEquals(expectedMultiline, wonder.multilineString())
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingMethodConcat_thenConcatCorrectly() {
|
||||
assertEquals(EXPECTED_SINGLE_LINE, wonder.method_concat())
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingMethodBuilder_thenConcatCorrectly() {
|
||||
assertEquals(EXPECTED_SINGLE_LINE, wonder.method_builder())
|
||||
}
|
||||
|
||||
@Test
|
||||
void whenUsingMethodBuffer_thenConcatCorrectly() {
|
||||
assertEquals(EXPECTED_SINGLE_LINE, wonder.method_buffer())
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.baeldung.defkeyword
|
||||
|
||||
import org.codehaus.groovy.runtime.NullObject
|
||||
import org.codehaus.groovy.runtime.typehandling.GroovyCastException
|
||||
|
||||
import groovy.transform.TypeChecked
|
||||
import groovy.transform.TypeCheckingMode
|
||||
|
||||
@TypeChecked
|
||||
class DefUnitTest extends GroovyTestCase {
|
||||
|
||||
def id
|
||||
def firstName = "Samwell"
|
||||
def listOfCountries = ['USA', 'UK', 'FRANCE', 'INDIA']
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
def multiply(x, y) {
|
||||
return x*y
|
||||
}
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
void testDefVariableDeclaration() {
|
||||
|
||||
def list
|
||||
assert list.getClass() == org.codehaus.groovy.runtime.NullObject
|
||||
assert list.is(null)
|
||||
|
||||
list = [1,2,4]
|
||||
assert list instanceof ArrayList
|
||||
}
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
void testTypeVariables() {
|
||||
int rate = 200
|
||||
try {
|
||||
rate = [12] //GroovyCastException
|
||||
rate = "nill" //GroovyCastException
|
||||
} catch(GroovyCastException) {
|
||||
println "Cannot assign anything other than integer"
|
||||
}
|
||||
}
|
||||
|
||||
@TypeChecked(TypeCheckingMode.SKIP)
|
||||
void testDefVariableMultipleAssignment() {
|
||||
def rate
|
||||
assert rate == null
|
||||
assert rate.getClass() == org.codehaus.groovy.runtime.NullObject
|
||||
|
||||
rate = 12
|
||||
assert rate instanceof Integer
|
||||
|
||||
rate = "Not Available"
|
||||
assert rate instanceof String
|
||||
|
||||
rate = [1, 4]
|
||||
assert rate instanceof List
|
||||
|
||||
assert divide(12, 3) instanceof BigDecimal
|
||||
assert divide(1, 0) instanceof String
|
||||
|
||||
}
|
||||
|
||||
def divide(int x, int y) {
|
||||
if(y==0) {
|
||||
return "Should not divide by 0"
|
||||
} else {
|
||||
return x/y
|
||||
}
|
||||
}
|
||||
|
||||
def greetMsg() {
|
||||
println "Hello! I am Groovy"
|
||||
}
|
||||
|
||||
void testDefVsType() {
|
||||
def int count
|
||||
assert count instanceof Integer
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package com.baeldung.determinedatatype
|
||||
|
||||
import org.junit.Assert
|
||||
import org.junit.Test
|
||||
import com.baeldung.determinedatatype.Person
|
||||
|
||||
public class PersonTest {
|
||||
|
||||
@Test
|
||||
public void givenWhenParameterTypeIsInteger_thenReturnTrue() {
|
||||
Person personObj = new Person(10)
|
||||
Assert.assertTrue(personObj.ageAsInt instanceof Integer)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhenParameterTypeIsDouble_thenReturnTrue() {
|
||||
Person personObj = new Person(10.0)
|
||||
Assert.assertTrue((personObj.ageAsDouble).getClass() == Double)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhenParameterTypeIsString_thenReturnTrue() {
|
||||
Person personObj = new Person("10 years")
|
||||
Assert.assertTrue(personObj.ageAsString.class == String)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenClassName_WhenParameterIsInteger_thenReturnTrue() {
|
||||
Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhenObjectIsInstanceOfType_thenReturnTrue() {
|
||||
Person personObj = new Person()
|
||||
Assert.assertTrue(personObj instanceof Person)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenWhenInstanceIsOfSubtype_thenReturnTrue() {
|
||||
Student studentObj = new Student()
|
||||
Assert.assertTrue(studentObj in Person)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGroovyList_WhenFindClassName_thenReturnTrue() {
|
||||
def ageList = ['ageAsString','ageAsDouble', 10]
|
||||
Assert.assertTrue(ageList.class == ArrayList)
|
||||
Assert.assertTrue(ageList.getClass() == ArrayList)
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenGrooyMap_WhenFindClassName_thenReturnTrue() {
|
||||
def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0]
|
||||
Assert.assertFalse(ageMap.class == LinkedHashMap)
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
package com.baeldung.metaprogramming
|
||||
|
||||
|
||||
import java.time.LocalDate
|
||||
import java.time.Period
|
||||
import java.time.Year
|
||||
|
||||
class MetaprogrammingUnitTest extends GroovyTestCase {
|
||||
|
||||
Employee emp = new Employee(firstName: "Norman", lastName: "Lewis")
|
||||
|
||||
void testPropertyMissing() {
|
||||
assert emp.address == "property 'address' is not available"
|
||||
}
|
||||
|
||||
void testMethodMissing() {
|
||||
Employee emp = new Employee()
|
||||
try {
|
||||
emp.getFullName()
|
||||
} catch(MissingMethodException e) {
|
||||
println "method is not defined"
|
||||
}
|
||||
assert emp.getFullName() == "method 'getFullName' is not defined"
|
||||
}
|
||||
|
||||
void testMetaClassProperty() {
|
||||
Employee.metaClass.address = ""
|
||||
emp = new Employee(firstName: "Norman", lastName: "Lewis", address: "US")
|
||||
assert emp.address == "US"
|
||||
}
|
||||
|
||||
void testMetaClassMethod() {
|
||||
emp.metaClass.getFullName = {
|
||||
"$lastName, $firstName"
|
||||
}
|
||||
assert emp.getFullName() == "Lewis, Norman"
|
||||
}
|
||||
|
||||
void testMetaClassConstructor() {
|
||||
try {
|
||||
Employee emp = new Employee("Norman")
|
||||
} catch(GroovyRuntimeException e) {
|
||||
assert e.message == "Could not find matching constructor for: com.baeldung.metaprogramming.Employee(String)"
|
||||
}
|
||||
|
||||
Employee.metaClass.constructor = { String firstName ->
|
||||
new Employee(firstName: firstName)
|
||||
}
|
||||
|
||||
Employee norman = new Employee("Norman")
|
||||
assert norman.firstName == "Norman"
|
||||
assert norman.lastName == null
|
||||
}
|
||||
|
||||
void testJavaMetaClass() {
|
||||
String.metaClass.capitalize = { String str ->
|
||||
str.substring(0, 1).toUpperCase() + str.substring(1)
|
||||
}
|
||||
assert "norman".capitalize() == "Norman"
|
||||
}
|
||||
|
||||
void testEmployeeExtension() {
|
||||
def age = 28
|
||||
def expectedYearOfBirth = Year.now() - age
|
||||
Employee emp = new Employee(age: age)
|
||||
assert emp.getYearOfBirth() == expectedYearOfBirth.value
|
||||
}
|
||||
|
||||
void testJavaClassesExtensions() {
|
||||
5.printCounter()
|
||||
|
||||
assert 40l.square() == 1600l
|
||||
|
||||
assert (2.98).cube() == 26.463592
|
||||
}
|
||||
|
||||
void testStaticEmployeeExtension() {
|
||||
assert Employee.getDefaultObj().firstName == "firstName"
|
||||
assert Employee.getDefaultObj().lastName == "lastName"
|
||||
assert Employee.getDefaultObj().age == 20
|
||||
}
|
||||
|
||||
void testToStringAnnotation() {
|
||||
Employee employee = new Employee()
|
||||
employee.id = 1
|
||||
employee.firstName = "norman"
|
||||
employee.lastName = "lewis"
|
||||
employee.age = 28
|
||||
|
||||
assert employee.toString() == "Employee(norman, lewis, 28)"
|
||||
}
|
||||
|
||||
void testTupleConstructorAnnotation() {
|
||||
Employee norman = new Employee(1, "norman", "lewis", 28)
|
||||
assert norman.toString() == "Employee(norman, lewis, 28)"
|
||||
|
||||
Employee snape = new Employee(2, "snape")
|
||||
assert snape.toString() == "Employee(snape, null, 0)"
|
||||
|
||||
}
|
||||
|
||||
void testEqualsAndHashCodeAnnotation() {
|
||||
Employee norman = new Employee(1, "norman", "lewis", 28)
|
||||
Employee normanCopy = new Employee(1, "norman", "lewis", 28)
|
||||
assert norman.equals(normanCopy)
|
||||
assert norman.hashCode() == normanCopy.hashCode()
|
||||
}
|
||||
|
||||
void testAutoCloneAnnotation() {
|
||||
try {
|
||||
Employee norman = new Employee(1, "norman", "lewis", 28)
|
||||
def normanCopy = norman.clone()
|
||||
assert norman == normanCopy
|
||||
} catch(CloneNotSupportedException e) {
|
||||
e.printStackTrace()
|
||||
}
|
||||
}
|
||||
|
||||
void testLoggingAnnotation() {
|
||||
Employee employee = new Employee(1, "Norman", "Lewis", 28)
|
||||
employee.logEmp()
|
||||
}
|
||||
}
|
||||
+44
@@ -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/
|
||||
}
|
||||
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package com.baeldung.templateengine
|
||||
|
||||
import groovy.text.SimpleTemplateEngine
|
||||
import groovy.text.StreamingTemplateEngine
|
||||
import groovy.text.GStringTemplateEngine
|
||||
import groovy.text.XmlTemplateEngine
|
||||
import groovy.text.XmlTemplateEngine
|
||||
import groovy.text.markup.MarkupTemplateEngine
|
||||
import groovy.text.markup.TemplateConfiguration
|
||||
|
||||
class TemplateEnginesUnitTest extends GroovyTestCase {
|
||||
|
||||
def bindMap = [user: "Norman", signature: "Baeldung"]
|
||||
|
||||
void testSimpleTemplateEngine() {
|
||||
def smsTemplate = 'Dear <% print user %>, Thanks for reading our Article. ${signature}'
|
||||
def smsText = new SimpleTemplateEngine().createTemplate(smsTemplate).make(bindMap)
|
||||
|
||||
assert smsText.toString() == "Dear Norman, Thanks for reading our Article. Baeldung"
|
||||
}
|
||||
|
||||
void testStreamingTemplateEngine() {
|
||||
def articleEmailTemplate = new File('src/main/resources/articleEmail.template')
|
||||
bindMap.articleText = """1. Overview
|
||||
This is a tutorial article on Template Engines""" //can be a string larger than 64k
|
||||
|
||||
def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(bindMap)
|
||||
|
||||
assert articleEmailText.toString() == """Dear Norman,
|
||||
Please read the requested article below.
|
||||
1. Overview
|
||||
This is a tutorial article on Template Engines
|
||||
From,
|
||||
Baeldung"""
|
||||
|
||||
}
|
||||
|
||||
void testGStringTemplateEngine() {
|
||||
def emailTemplate = new File('src/main/resources/email.template')
|
||||
def emailText = new GStringTemplateEngine().createTemplate(emailTemplate).make(bindMap)
|
||||
|
||||
assert emailText.toString() == "Dear Norman,\nThanks for subscribing our services.\nBaeldung"
|
||||
}
|
||||
|
||||
void testXmlTemplateEngine() {
|
||||
def emailXmlTemplate = '''<xs xmlns:gsp='groovy-server-pages'>
|
||||
<gsp:scriptlet>def emailContent = "Thanks for subscribing our services."</gsp:scriptlet>
|
||||
<email>
|
||||
<greet>Dear ${user}</greet>
|
||||
<content><gsp:expression>emailContent</gsp:expression></content>
|
||||
<signature>${signature}</signature>
|
||||
</email>
|
||||
</xs>'''
|
||||
def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(bindMap)
|
||||
println emailXml.toString()
|
||||
}
|
||||
|
||||
void testMarkupTemplateEngineHtml() {
|
||||
def emailHtmlTemplate = """html {
|
||||
head {
|
||||
title('Service Subscription Email')
|
||||
}
|
||||
body {
|
||||
p('Dear Norman')
|
||||
p('Thanks for subscribing our services.')
|
||||
p('Baeldung')
|
||||
}
|
||||
}"""
|
||||
|
||||
|
||||
def emailHtml = new MarkupTemplateEngine().createTemplate(emailHtmlTemplate).make()
|
||||
println emailHtml.toString()
|
||||
|
||||
}
|
||||
|
||||
void testMarkupTemplateEngineXml() {
|
||||
def emailXmlTemplate = """xmlDeclaration()
|
||||
xs{
|
||||
email {
|
||||
greet('Dear Norman')
|
||||
content('Thanks for subscribing our services.')
|
||||
signature('Baeldung')
|
||||
}
|
||||
}
|
||||
"""
|
||||
TemplateConfiguration config = new TemplateConfiguration()
|
||||
config.autoIndent = true
|
||||
config.autoEscape = true
|
||||
config.autoNewLine = true
|
||||
|
||||
def emailXml = new MarkupTemplateEngine(config).createTemplate(emailXmlTemplate).make()
|
||||
|
||||
println emailXml.toString()
|
||||
}
|
||||
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package com.baeldung.webservice
|
||||
|
||||
import groovy.json.JsonSlurper
|
||||
import wslite.rest.ContentType
|
||||
import wslite.rest.RESTClient
|
||||
import wslite.rest.RESTClientException
|
||||
import wslite.soap.SOAPClient
|
||||
import wslite.soap.SOAPMessageBuilder
|
||||
import wslite.http.auth.HTTPBasicAuthorization
|
||||
import org.junit.Test
|
||||
|
||||
class WebserviceManualTest extends GroovyTestCase {
|
||||
|
||||
JsonSlurper jsonSlurper = new JsonSlurper()
|
||||
|
||||
static RESTClient client = new RESTClient("https://postman-echo.com")
|
||||
|
||||
static {
|
||||
client.defaultAcceptHeader = ContentType.JSON
|
||||
client.httpClient.sslTrustAllCerts = true
|
||||
}
|
||||
|
||||
void test_whenSendingGet_thenRespose200() {
|
||||
def postmanGet = new URL('https://postman-echo.com/get')
|
||||
def getConnection = postmanGet.openConnection()
|
||||
getConnection.requestMethod = 'GET'
|
||||
assert getConnection.responseCode == 200
|
||||
if (getConnection.responseCode == 200) {
|
||||
assert jsonSlurper.parseText(getConnection.content.text)?.headers?.host == "postman-echo.com"
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenSendingPost_thenRespose200() {
|
||||
def postmanPost = new URL('https://postman-echo.com/post')
|
||||
def query = "q=This is post request form parameter."
|
||||
def postConnection = postmanPost.openConnection()
|
||||
postConnection.requestMethod = 'POST'
|
||||
assert postConnection.responseCode == 200
|
||||
}
|
||||
|
||||
void test_whenSendingPostWithParams_thenRespose200() {
|
||||
def postmanPost = new URL('https://postman-echo.com/post')
|
||||
def form = "param1=This is request parameter."
|
||||
def postConnection = postmanPost.openConnection()
|
||||
postConnection.requestMethod = 'POST'
|
||||
postConnection.doOutput = true
|
||||
def text
|
||||
postConnection.with {
|
||||
outputStream.withWriter { outputStreamWriter ->
|
||||
outputStreamWriter << form
|
||||
}
|
||||
text = content.text
|
||||
}
|
||||
assert postConnection.responseCode == 200
|
||||
assert jsonSlurper.parseText(text)?.json.param1 == "This is request parameter."
|
||||
}
|
||||
|
||||
void test_whenReadingRSS_thenReceiveFeed() {
|
||||
def rssFeed = new XmlParser().parse("https://news.google.com/rss?hl=en-US&gl=US&ceid=US:en")
|
||||
def stories = []
|
||||
(0..4).each {
|
||||
def item = rssFeed.channel.item.get(it)
|
||||
stories << item.title.text()
|
||||
}
|
||||
assert stories.size() == 5
|
||||
}
|
||||
|
||||
void test_whenReadingAtom_thenReceiveFeed() {
|
||||
def atomFeed = new XmlParser().parse("https://news.google.com/atom?hl=en-US&gl=US&ceid=US:en")
|
||||
def stories = []
|
||||
(0..4).each {
|
||||
def entry = atomFeed.entry.get(it)
|
||||
stories << entry.title.text()
|
||||
}
|
||||
assert stories.size() == 5
|
||||
}
|
||||
|
||||
void test_whenConsumingSoap_thenReceiveResponse() {
|
||||
def url = "http://www.dataaccess.com/webservicesserver/numberconversion.wso"
|
||||
def soapClient = new SOAPClient(url)
|
||||
def message = new SOAPMessageBuilder().build({
|
||||
body {
|
||||
NumberToWords(xmlns: "http://www.dataaccess.com/webservicesserver/") {
|
||||
ubiNum(1234)
|
||||
}
|
||||
}
|
||||
})
|
||||
def response = soapClient.send(message.toString());
|
||||
def words = response.NumberToWordsResponse
|
||||
assert words == "one thousand two hundred and thirty four "
|
||||
}
|
||||
|
||||
void test_whenConsumingRestGet_thenReceiveResponse() {
|
||||
def path = "/get"
|
||||
def response
|
||||
try {
|
||||
response = client.get(path: path)
|
||||
assert response.statusCode == 200
|
||||
assert response.json?.headers?.host == "postman-echo.com"
|
||||
} catch (RESTClientException e) {
|
||||
assert e?.response?.statusCode != 200
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenConsumingRestPost_thenReceiveResponse() {
|
||||
def path = "/post"
|
||||
def params = ["foo":1,"bar":2]
|
||||
def response
|
||||
try {
|
||||
response = client.post(path: path) {
|
||||
type ContentType.JSON
|
||||
json params
|
||||
}
|
||||
assert response.json?.data == params
|
||||
} catch (RESTClientException e) {
|
||||
e.printStackTrace()
|
||||
assert e?.response?.statusCode != 200
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenBasicAuthentication_thenReceive200() {
|
||||
def path = "/basic-auth"
|
||||
def response
|
||||
try {
|
||||
client.authorization = new HTTPBasicAuthorization("postman", "password")
|
||||
response = client.get(path: path)
|
||||
assert response.statusCode == 200
|
||||
assert response.json?.authenticated == true
|
||||
} catch (RESTClientException e) {
|
||||
e.printStackTrace()
|
||||
assert e?.response?.statusCode != 200
|
||||
}
|
||||
}
|
||||
|
||||
void test_whenOAuth_thenReceive200() {
|
||||
RESTClient oAuthClient = new RESTClient("https://postman-echo.com")
|
||||
oAuthClient.defaultAcceptHeader = ContentType.JSON
|
||||
oAuthClient.httpClient.sslTrustAllCerts = true
|
||||
|
||||
def path = "/oauth1"
|
||||
def params = [oauth_consumer_key: "RKCGzna7bv9YD57c", oauth_signature_method: "HMAC-SHA1", oauth_timestamp:1567089944, oauth_nonce: "URT7v4", oauth_version: 1.0, oauth_signature: 'RGgR/ktDmclkM0ISWaFzebtlO0A=']
|
||||
def response
|
||||
try {
|
||||
response = oAuthClient.get(path: path, query: params)
|
||||
assert response.statusCode == 200
|
||||
assert response.statusMessage == "OK"
|
||||
assert response.json.status == "pass"
|
||||
} catch (RESTClientException e) {
|
||||
assert e?.response?.statusCode != 200
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.xml
|
||||
|
||||
import groovy.xml.MarkupBuilder
|
||||
import groovy.xml.XmlUtil
|
||||
import spock.lang.Specification
|
||||
|
||||
class MarkupBuilderUnitTest extends Specification {
|
||||
|
||||
def xmlFile = getClass().getResource("articles_short_formatted.xml")
|
||||
|
||||
def "Should create XML properly"() {
|
||||
given: "Node structures"
|
||||
|
||||
when: "Using MarkupBuilderUnitTest to create com.baeldung.xml structure"
|
||||
def writer = new StringWriter()
|
||||
new MarkupBuilder(writer).articles {
|
||||
article {
|
||||
title('First steps in Java')
|
||||
author(id: '1') {
|
||||
firstname('Siena')
|
||||
lastname('Kerr')
|
||||
}
|
||||
'release-date'('2018-12-01')
|
||||
}
|
||||
article {
|
||||
title('Dockerize your SpringBoot application')
|
||||
author(id: '2') {
|
||||
firstname('Jonas')
|
||||
lastname('Lugo')
|
||||
}
|
||||
'release-date'('2018-12-01')
|
||||
}
|
||||
}
|
||||
|
||||
then: "Xml is created properly"
|
||||
XmlUtil.serialize(writer.toString()) == XmlUtil.serialize(xmlFile.text)
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.baeldung.xml
|
||||
|
||||
|
||||
import spock.lang.Shared
|
||||
import spock.lang.Specification
|
||||
|
||||
class XmlParserUnitTest extends Specification {
|
||||
|
||||
def xmlFile = getClass().getResourceAsStream("articles.xml")
|
||||
|
||||
@Shared
|
||||
def parser = new XmlParser()
|
||||
|
||||
def "Should read XML file properly"() {
|
||||
given: "XML file"
|
||||
|
||||
when: "Using XmlParser to read file"
|
||||
def articles = parser.parse(xmlFile)
|
||||
|
||||
then: "Xml is loaded properly"
|
||||
articles.'*'.size() == 4
|
||||
articles.article[0].author.firstname.text() == "Siena"
|
||||
articles.article[2].'release-date'.text() == "2018-06-12"
|
||||
articles.article[3].title.text() == "Java 12 insights"
|
||||
articles.article.find { it.author.'@id'.text() == "3" }.author.firstname.text() == "Daniele"
|
||||
}
|
||||
|
||||
|
||||
def "Should add node to existing com.baeldung.xml using NodeBuilder"() {
|
||||
given: "XML object"
|
||||
def articles = parser.parse(xmlFile)
|
||||
|
||||
when: "Adding node to com.baeldung.xml"
|
||||
def articleNode = new NodeBuilder().article(id: '5') {
|
||||
title('Traversing XML in the nutshell')
|
||||
author {
|
||||
firstname('Martin')
|
||||
lastname('Schmidt')
|
||||
}
|
||||
'release-date'('2019-05-18')
|
||||
}
|
||||
articles.append(articleNode)
|
||||
|
||||
then: "Node is added to com.baeldung.xml properly"
|
||||
articles.'*'.size() == 5
|
||||
articles.article[4].title.text() == "Traversing XML in the nutshell"
|
||||
}
|
||||
|
||||
def "Should replace node"() {
|
||||
given: "XML object"
|
||||
def articles = parser.parse(xmlFile)
|
||||
|
||||
when: "Adding node to com.baeldung.xml"
|
||||
def articleNode = new NodeBuilder().article(id: '5') {
|
||||
title('Traversing XML in the nutshell')
|
||||
author {
|
||||
firstname('Martin')
|
||||
lastname('Schmidt')
|
||||
}
|
||||
'release-date'('2019-05-18')
|
||||
}
|
||||
articles.article[0].replaceNode(articleNode)
|
||||
|
||||
then: "Node is added to com.baeldung.xml properly"
|
||||
articles.'*'.size() == 4
|
||||
articles.article[0].title.text() == "Traversing XML in the nutshell"
|
||||
}
|
||||
|
||||
def "Should modify node"() {
|
||||
given: "XML object"
|
||||
def articles = parser.parse(xmlFile)
|
||||
|
||||
when: "Changing value of one of the nodes"
|
||||
articles.article.each { it.'release-date'[0].value = "2019-05-18" }
|
||||
|
||||
then: "XML is updated"
|
||||
articles.article.findAll { it.'release-date'.text() != "2019-05-18" }.isEmpty()
|
||||
}
|
||||
|
||||
def "Should remove article from com.baeldung.xml"() {
|
||||
given: "XML object"
|
||||
def articles = parser.parse(xmlFile)
|
||||
|
||||
when: "Removing all articles but with id==3"
|
||||
articles.article
|
||||
.findAll { it.author.'@id'.text() != "3" }
|
||||
.each { articles.remove(it) }
|
||||
|
||||
then: "There is only one article left"
|
||||
articles.children().size() == 1
|
||||
articles.article[0].author.'@id'.text() == "3"
|
||||
}
|
||||
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package com.baeldung.xml
|
||||
|
||||
|
||||
import groovy.xml.XmlUtil
|
||||
import spock.lang.Shared
|
||||
import spock.lang.Specification
|
||||
|
||||
class XmlSlurperUnitTest extends Specification {
|
||||
|
||||
def xmlFile = getClass().getResourceAsStream("articles.xml")
|
||||
|
||||
@Shared
|
||||
def parser = new XmlSlurper()
|
||||
|
||||
def "Should read XML file properly"() {
|
||||
given: "XML file"
|
||||
|
||||
when: "Using XmlSlurper to read file"
|
||||
def articles = parser.parse(xmlFile)
|
||||
|
||||
then: "Xml is loaded properly"
|
||||
articles.'*'.size() == 4
|
||||
articles.article[0].author.firstname == "Siena"
|
||||
articles.article[2].'release-date' == "2018-06-12"
|
||||
articles.article[3].title == "Java 12 insights"
|
||||
articles.article.find { it.author.'@id' == "3" }.author.firstname == "Daniele"
|
||||
}
|
||||
|
||||
def "Should add node to existing com.baeldung.xml"() {
|
||||
given: "XML object"
|
||||
def articles = parser.parse(xmlFile)
|
||||
|
||||
when: "Adding node to com.baeldung.xml"
|
||||
articles.appendNode {
|
||||
article(id: '5') {
|
||||
title('Traversing XML in the nutshell')
|
||||
author {
|
||||
firstname('Martin')
|
||||
lastname('Schmidt')
|
||||
}
|
||||
'release-date'('2019-05-18')
|
||||
}
|
||||
}
|
||||
|
||||
articles = parser.parseText(XmlUtil.serialize(articles))
|
||||
|
||||
then: "Node is added to com.baeldung.xml properly"
|
||||
articles.'*'.size() == 5
|
||||
articles.article[4].title == "Traversing XML in the nutshell"
|
||||
}
|
||||
|
||||
def "Should modify node"() {
|
||||
given: "XML object"
|
||||
def articles = parser.parse(xmlFile)
|
||||
|
||||
when: "Changing value of one of the nodes"
|
||||
articles.article.each { it.'release-date' = "2019-05-18" }
|
||||
|
||||
then: "XML is updated"
|
||||
articles.article.findAll { it.'release-date' != "2019-05-18" }.isEmpty()
|
||||
}
|
||||
|
||||
def "Should replace node"() {
|
||||
given: "XML object"
|
||||
def articles = parser.parse(xmlFile)
|
||||
|
||||
when: "Replacing node"
|
||||
articles.article[0].replaceNode {
|
||||
article(id: '5') {
|
||||
title('Traversing XML in the nutshell')
|
||||
author {
|
||||
firstname('Martin')
|
||||
lastname('Schmidt')
|
||||
}
|
||||
'release-date'('2019-05-18')
|
||||
}
|
||||
}
|
||||
|
||||
articles = parser.parseText(XmlUtil.serialize(articles))
|
||||
|
||||
then: "Node is replaced properly"
|
||||
articles.'*'.size() == 4
|
||||
articles.article[0].title == "Traversing XML in the nutshell"
|
||||
}
|
||||
|
||||
def "Should remove article from com.baeldung.xml"() {
|
||||
given: "XML object"
|
||||
def articles = parser.parse(xmlFile)
|
||||
|
||||
when: "Removing all articles but with id==3"
|
||||
articles.article
|
||||
.findAll { it.author.'@id' != "3" }
|
||||
.replaceNode {}
|
||||
|
||||
articles = parser.parseText(XmlUtil.serialize(articles))
|
||||
|
||||
then: "There is only one article left"
|
||||
articles.children().size() == 1
|
||||
articles.article[0].author.'@id' == "3"
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<articles>
|
||||
<article>
|
||||
<title>First steps in Java</title>
|
||||
<author id='1'>
|
||||
<firstname>Siena</firstname>
|
||||
<lastname>Kerr</lastname>
|
||||
</author>
|
||||
<release-date>2018-12-01</release-date>
|
||||
</article>
|
||||
<article>
|
||||
<title>Dockerize your SpringBoot application</title>
|
||||
<author id='2'>
|
||||
<firstname>Jonas</firstname>
|
||||
<lastname>Lugo</lastname>
|
||||
</author>
|
||||
<release-date>2018-12-01</release-date>
|
||||
</article>
|
||||
<article>
|
||||
<title>SpringBoot tutorial</title>
|
||||
<author id='3'>
|
||||
<firstname>Daniele</firstname>
|
||||
<lastname>Ferguson</lastname>
|
||||
</author>
|
||||
<release-date>2018-06-12</release-date>
|
||||
</article>
|
||||
<article>
|
||||
<title>Java 12 insights</title>
|
||||
<author id='1'>
|
||||
<firstname>Siena</firstname>
|
||||
<lastname>Kerr</lastname>
|
||||
</author>
|
||||
<release-date>2018-07-22</release-date>
|
||||
</article>
|
||||
</articles>
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
<articles>
|
||||
<article>
|
||||
<title>First steps in Java</title>
|
||||
<author id='1'>
|
||||
<firstname>Siena</firstname>
|
||||
<lastname>Kerr</lastname>
|
||||
</author>
|
||||
<release-date>2018-12-01</release-date>
|
||||
</article>
|
||||
<article>
|
||||
<title>Dockerize your SpringBoot application</title>
|
||||
<author id='2'>
|
||||
<firstname>Jonas</firstname>
|
||||
<lastname>Lugo</lastname>
|
||||
</author>
|
||||
<release-date>2018-12-01</release-date>
|
||||
</article>
|
||||
</articles>
|
||||
Reference in New Issue
Block a user