Unverified Commit aa6dd118 authored by Dhawal Kapil's avatar Dhawal Kapil Committed by GitHub
Browse files

Merged master (#13525)


* Bump to Groovy `3.0.8`

* SQL queries conventions

* Test `JsonGenerator`

* Align tests with `Spock` testing framework

* Reformat and single liner `read*` methods

* Minor fixes for Trait subject

* Align tests with `Spock` testing framework

* Minor fixes for Trait subject

* fix: Typos in Avro module

* Data Type in Groovy: align with `Spock` testing framework

* Metaprogramming: Align with groovy version `3.0.8` and use spock testing framework

* Categories: code reformat

* Maps in Groovy: convert to spock test framework

* Finding Elements in Collections in Groovy: refactor to use spock testing framework

* Lists in Groovy: refactor to use spock testing framework

* A Quick Guide to Iterating a Map in Groovy: refactor to use spock testing framework

* How to Remove a Prefix From Strings in Groovy: refactor to use spock testing framework

* added code of collections-vs-stream

* added setup and teardown method

* rename the package

* removed unwanted code

* removed transactional annotation

* renamed the Test class

* Feature/bael 6101 singleton (#13325)

* BAEL-6101: singleton bean and pattern example

* BAEL-6101: change package

* BAEL-6101: refactor

* BAEL-6101: refactor

* BAEL-6101: PR comment fix

* [BAEL-5788] Accessing Private Constructor

* BAEL-6097: Pitfalls on Testing with Spring Boot (#13441)

* BAEL-6097: Create project

* BAEL-6097: Implement sample code and tests with custom test slices

* BAEL-6097: Fix application-test.yml

* BAEL-6097: Rename tests to match BDD naming strategy, add test for Mapper Integration Test

* Difference Between Function(String… args) and Function(String[] args) (#13473)

* BAEL-6210: Examples for RethinkDB article (#13481)

* JAVA-17608 Restored AtomicInteger default increment method

* [JAVA-16376] Moved apache-poi, apache-velocity,di-modules,asciidoctor… (#13461)

* [JAVA-16376] Moved apache-poi, apache-velocity,di-modules,asciidoctor,aws-modules to jdk9-and-above profile

* [JAVA-16376] testing war plugin

* [JAVA-16376] Upgraded asciidoctor dependencies

* [JAVA-16376] Upgraded lombok version

* [JAVA-16376] Upgraded guice version

* [JAVA-16376] Clean up properties

* BAEL-6046 - MongoDB - Field Level Encryption (#13440)

* bael-6046 - first draft

* review 1

* review 2

* null checks and lambda

* BAEL-6162: Code examples from article (#13458)

* Code example from article

* BAEL-6162: Add unit tests

* Rename test class

* Updated Instancio version

* [JAVA-16376] Moved spring-reactive-modules to jdk9-and-above profile (#13470)

* [JAVA-16376] Moved spring-reactive-modules to jdk9-and-above profile

* [JAVA-16376] Upgraded geotools dependencies and moved module to jdk9-and-above profile

* [JAVA-16376] Replaced vividsolutions artifact with  locationtech

* [JAVA-16376] Moved data-structures to jdk9-and-above profile

* [JAVA-16376] Moved deeplearning4j module to jdk9-and-above profile

---------

Co-authored-by: default avatarDhawal Kapil <dhawalkapil@gmail.com>

* BAEL-5288 Code for the Map Date Types With openapi generator article (#13467)

Co-authored-by: default avatarthibault.faure <thibault.faure@mimacom.com>

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* Create README.md

[skip ci]

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* Update README.md

[skip ci]

* [2lists-to-map] Combining Two Lists into a Map in Java (#13484)

* [2lists-to-map] Combining Two Lists into a Map in Java

* [2lists-to-map] rename package

* JAVA-17429 Upgrade to latest spring-boot-2 (#13480)

* [BAEL-6027] Add example for Awaitility and Thread.sleep comparison (#13450)

* Add example for Awaitility and Thread.sleep comparison

* Fix unit test method name and indentation.

* Use property in pom.xml for awaitility dependency version.

---------

Co-authored-by: default avatarUhrin Attila <attila.uhrin@frontendart.com>

* BAEL-6100-Add-example-code-for-integer-array-to-strings-using-streams… (#13375)

* BAEL-6100-Add-example-code-for-integer-array-to-strings-using-streams-tutorial

* BAEL-6100 remove wrongly added README update

* BAEL-6100 Add interger array to single string example

* BAEL-6100 Correct typo in test class name

* BAEL-4487 remove padding that causes non-deterministic behaviour (#13425)

* BAEL-6046 - MongoDB - Field Level Encryption (#13494)

* [JAVA-6143] java copy from one hashmap to another (#13497)

Co-authored-by: default avatarBhaskar <bhaskar.dastidar@freshworks.com>

* Update README.md

[skip ci]

* Update README.md

* Update README.md

* Bael 5190: Verify Digital Signatures in Java article (#13439)

* #BAEL-5190: add keystore and certificate files

* #BAEL-5190: add keystore address

* #BAEL-5190: update hashing

* #BAEL-5190: delete main classes

* #BAEL-5190: move keystore files to test directory

* #BAEL-5190: rename to DigitalSignatureUtils

* #BAEL-5190: main source code

* #BAEL-5190: main test source

* #BAEL-5190: update for testing

* #BAEL-5190: update keystore type

* #BAEL-5190: remove p12 keystores

* #BAEL-5190: add jks keystores

---------

Co-authored-by: default avatarh_sharifi <h_sharifi@modernisc.com>

* BAEL-6154: Migrate from Java 8 to Java 17 + tests (#13474)

* BAEL-4971 - Object mapping with Cassandra (#13427)

* BAEL-4971 - Object mapping with Cassandra

* BAEL-4971 - Object mapping with Cassandra

* BAEL-4971 - Object mapping with Cassandra - changing test name

* BAEL-4971 - Object mapping with Cassandra - code formatting

* BAEL-4971 - Object mapping with Cassandra - review incorporation

* JAVA-17818 Split or move spring-cloud-openfeign module (conti-2) (#13485)

Co-authored-by: default avatartimis1 <noreplay@yahoo.com>

* JAVA-2420 Merge spring-apache-camel and spring-boot-camel modules (#13409)

* JAVA-2420 Merge spring-apache-camel and spring-boot-camel modules

* JAVA-2420 Migrate spring-boot-camel to spring-apache camel

* JAVA-2420 Update README.md file

* JAVA-2420 Remove spring-boot-camel

---------

Co-authored-by: default avatartimis1 <noreplay@yahoo.com>

* JAVA-14723 Convert spring-mvc-basics-4 to Spring Boot project and upd… (#13399)

* JAVA-14723 Convert spring-mvc-basics-4 to Spring Boot project and update articles

* JAVA-14723 Refactoring and remove unused files

* JAVA-14723 remove the WEB-INF and migrate jsp to html

* JAVA-14723 Add back the removed test and rename the test into: ArticleViewerControllerWithRequiredAttributeIntegrationTest

---------

Co-authored-by: default avatartimis1 <noreplay@yahoo.com>

* JAVA-18445 Cleanup un-committed or un-ignored artifacts - Week 6 - 2023 (conti-1) (moved-1) (#13510)

Co-authored-by: default avatartimis1 <noreplay@yahoo.com>

* JAVA-18132 Upgrade custom-pmd module to JDK 11 (#13500)

Co-authored-by: default avatartimis1 <noreplay@yahoo.com>

* BAEL-6069: Exclude dependency in a Maven plugin (#13508)

* BAEL-5549: feat: Hibernate Keywords - using keywords as table column names (#13355)

* BAEL-5549: feat: Hibernate Keywords - using keywords as table column names

* BAEL-5549: feat: Hibernate Keywords - using keywords as table column names

* BAEL-5549: feat: Hibernate Keywords - using keywords as table column names

* BAEL-5549: fix: Hibernate Keywords - alter the "where" value to make sure it is obvious that it is not the value but the @Column that is causing the error.

* BAEL-5549: doc: Hibernate Keywords - revert README changes

* [JAVA-18124] Moved apache-libraries module to jdk9-and-above profile (#13502)

* [JAVA-18124] Moved apache-libraries module to jdk9-and-above profile

* [JAVA-18124] Upgrade beam version

* BAEL-5912 Introduction to RoaringBitmap (#13326)

* Finding All Duplicates in a List in Java- BAEL-6075 (#13291)

* Deep & Shallow Copy

* Revert "Deep & Shallow Copy"

This reverts commit 62f75b00

.

* duplicates in a list in java

* Unit test changes

* unit test changes

* Tests change after review

* Code formatted

* code formatted

* new module core-java-lang-6

* entry in parent pom and test setup method name change

* module renamed

* parent pom entry added

* pom.xml changes reverted

* Bael 6069 (#13521)

* BAEL-6069: Exclude dependency in a Maven plugin

* BAEL-6069: rename project

* [JAVA-16376] Moved quarkus-modules to jdk9-and-above profile (#13487)

* [JAVA-16376] Moved quarkus-modules to jdk9-and-above profile

* [JAVA-18171] Moved reactive-systems module to jdk9-and-above profile

* [JAVA-18170] Moved rxjava-modules to jdk9-and-above profile

* [JAVA-18165] Moved patterns-modules to jdk9-and-above profile

* [JAVA-18168] Upgraded quarkus version

* [JAVA-16394] Moved groovy modules to jdk9-and-above profile

* [JAVA-18165] Reverted changes for pattern-modules

* [JAVA-16394] Upgraded dependencies to latest versions

* [JAVA-18134] Upgraded guava-modules to java 11 and moved to jdk9-and-above profile

* [JAVA-16394] Fixed groovy-eclipse-batch dependency version

---------

Co-authored-by: default avatarDhawal Kapil <dhawalkapil@gmail.com>

---------

Co-authored-by: default avatarAlex Golub <a12thu@gmail.com>
Co-authored-by: default avatargantoin <gantoin@pm.me>
Co-authored-by: default avatarAmit Kumatr <amit.kumar@fyndna.com>
Co-authored-by: default avatarDaniel Strmecki <daniel.strmecki@gmail.com>
Co-authored-by: default avatarStef Serban-Cristian <stef.serban.cristian@gmail.com>
Co-authored-by: default avatarRalf Ueberfuhr <40685729+ueberfuhr@users.noreply.github.com>
Co-authored-by: default avatardavidmartinezbarua <davmb5@gmail.com>
Co-authored-by: default avatarIniubong LA <arthurshur@gmail.com>
Co-authored-by: default avatarGraham Cox <graham@grahamcox.co.uk>
Co-authored-by: default avatarAnastasios Ioannidis <anastasios.ioannidisa@gmail.com>
Co-authored-by: default avatarLoredana Crusoveanu <lore.crusoveanu@gmail.com>
Co-authored-by: default avatarpanos-kakos <102670093+panos-kakos@users.noreply.github.com>
Co-authored-by: default avatarUlisses Lima <ulisseslima@users.noreply.github.com>
Co-authored-by: default avatarMichael Pratt <prattm@gmail.com>
Co-authored-by: default avatarArman Sharif <armandino@gmail.com>
Co-authored-by: default avatarthibaultfaure <thibault.faure.pro@gmail.com>
Co-authored-by: default avatarthibault.faure <thibault.faure@mimacom.com>
Co-authored-by: default avataredizor <113095366+edizor@users.noreply.github.com>
Co-authored-by: default avatarKai Yuan <kent.yuan@Gmail.com>
Co-authored-by: default avatarAnastasios Ioannidis <121166333+anastasiosioannidis@users.noreply.github.com>
Co-authored-by: default avatarAttilaUhrin <uhrin.attila1@gmail.com>
Co-authored-by: default avatarUhrin Attila <attila.uhrin@frontendart.com>
Co-authored-by: default avatarsam-gardner <53271849+sam-gardner@users.noreply.github.com>
Co-authored-by: default avatarShaun Phillips <61982125+ShaPhi7@users.noreply.github.com>
Co-authored-by: default avatarBhaskar Ghosh Dastidar <dastidar.bhaskar@gmail.com>
Co-authored-by: default avatarBhaskar <bhaskar.dastidar@freshworks.com>
Co-authored-by: default avatarHamid Reza Sharifi <hmdrzsharifi@gmail.com>
Co-authored-by: default avatarh_sharifi <h_sharifi@modernisc.com>
Co-authored-by: default avatarPalaniappan Arunachalam <palaniappan.ar@gmail.com>
Co-authored-by: default avatarAbhinav Pandey <abhinavpandey312@gmail.com>
Co-authored-by: default avatartimis1 <12120641+timis1@users.noreply.github.com>
Co-authored-by: default avatartimis1 <noreplay@yahoo.com>
Co-authored-by: default avatarACHRAF TAITAI <43656331+achraftt@users.noreply.github.com>
Co-authored-by: default avatarGrzegorz Musiał <grzegorz@musial.tk>
Co-authored-by: default avataralemoles <alemolerio@gmail.com>
Co-authored-by: default avatar2406ankita <41814570+2406ankita@users.noreply.github.com>
No related merge requests found
Showing with 336 additions and 262 deletions
+336 -262
......@@ -107,4 +107,7 @@ spring-boot-modules/spring-boot-properties-3/*.log
.sdkmanrc
# Localstack
**/.localstack
\ No newline at end of file
**/.localstack
#web-modules/ninja
devDb*.db
\ No newline at end of file
......@@ -31,7 +31,7 @@ The projects are broadly divided into 3 lists: first, second and heavy.
Next, they are segregated further on the basis of the tests that we want to execute.
Additionally, there are 2 profiles dedicated for JDK9 and above builds.
Additionally, there are 2 profiles dedicated for JDK9 and above builds - **which require JDK 17**.
We also have a parents profile to build only parent modules.
......
......@@ -118,11 +118,6 @@
<artifactId>curator-recipes</artifactId>
<version>${curator.version}</version>
</dependency>
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>${zookeeper.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
......@@ -191,10 +186,8 @@
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<avro.version>1.8.2</avro.version>
<beam.version>2.19.0</beam.version>
<beam.version>2.45.0</beam.version>
<bval.version>1.1.2</bval.version>
<javax.validation.validation-api.version>1.1.0.Final</javax.validation.validation-api.version>
<meecrowave-junit.version>1.2.0</meecrowave-junit.version>
......
package com.baeldung.avro.util.serealization;
package com.baeldung.avro.util.serialization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.DatumReader;
......@@ -10,11 +10,11 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
public class AvroDeSerealizer {
public class AvroDeSerializer {
private static Logger logger = LoggerFactory.getLogger(AvroDeSerealizer.class);
private static Logger logger = LoggerFactory.getLogger(AvroDeSerializer.class);
public AvroHttpRequest deSerealizeAvroHttpRequestJSON(byte[] data) {
public AvroHttpRequest deSerializeAvroHttpRequestJSON(byte[] data) {
DatumReader<AvroHttpRequest> reader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = null;
try {
......@@ -27,7 +27,7 @@ public class AvroDeSerealizer {
return null;
}
public AvroHttpRequest deSerealizeAvroHttpRequestBinary(byte[] data) {
public AvroHttpRequest deSerializeAvroHttpRequestBinary(byte[] data) {
DatumReader<AvroHttpRequest> employeeReader = new SpecificDatumReader<>(AvroHttpRequest.class);
Decoder decoder = DecoderFactory.get()
.binaryDecoder(data, null);
......
package com.baeldung.avro.util.serealization;
package com.baeldung.avro.util.serialization;
import com.baeldung.avro.util.model.AvroHttpRequest;
import org.apache.avro.io.*;
......@@ -9,11 +9,11 @@ import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class AvroSerealizer {
public class AvroSerializer {
private static final Logger logger = LoggerFactory.getLogger(AvroSerealizer.class);
private static final Logger logger = LoggerFactory.getLogger(AvroSerializer.class);
public byte[] serealizeAvroHttpRequestJSON(AvroHttpRequest request) {
public byte[] serializeAvroHttpRequestJSON(AvroHttpRequest request) {
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
......@@ -30,7 +30,7 @@ public class AvroSerealizer {
return data;
}
public byte[] serealizeAvroHttpRequestBinary(AvroHttpRequest request) {
public byte[] serializeAvroHttpRequestBinary(AvroHttpRequest request) {
DatumWriter<AvroHttpRequest> writer = new SpecificDatumWriter<>(AvroHttpRequest.class);
byte[] data = new byte[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
......
package com.baeldung.avro.util.serealization;
package com.baeldung.avro.util.serialization;
import com.baeldung.avro.util.model.Active;
import com.baeldung.avro.util.model.AvroHttpRequest;
......@@ -13,16 +13,16 @@ import java.util.Objects;
import static org.junit.Assert.*;
public class AvroSerealizerDeSerealizerIntegrationTest {
public class AvroSerializerDeSerializerIntegrationTest {
AvroSerealizer serealizer;
AvroDeSerealizer deSerealizer;
AvroSerializer serializer;
AvroDeSerializer deserializer;
AvroHttpRequest request;
@Before
public void setUp() throws Exception {
serealizer = new AvroSerealizer();
deSerealizer = new AvroDeSerealizer();
serializer = new AvroSerializer();
deserializer = new AvroDeSerializer();
ClientIdentifier clientIdentifier = ClientIdentifier.newBuilder()
.setHostName("localhost")
......@@ -49,22 +49,22 @@ public class AvroSerealizerDeSerealizerIntegrationTest {
@Test
public void WhenSerializedUsingJSONEncoder_thenObjectGetsSerialized() {
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
byte[] data = serializer.serializeAvroHttpRequestJSON(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenSerializedUsingBinaryEncoder_thenObjectGetsSerialized() {
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
byte[] data = serializer.serializeAvroHttpRequestBinary(request);
assertTrue(Objects.nonNull(data));
assertTrue(data.length > 0);
}
@Test
public void WhenDeserializeUsingJSONDecoder_thenActualAndExpectedObjectsAreEqual() {
byte[] data = serealizer.serealizeAvroHttpRequestJSON(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestJSON(data);
byte[] data = serializer.serializeAvroHttpRequestJSON(request);
AvroHttpRequest actualRequest = deserializer.deSerializeAvroHttpRequestJSON(data);
assertEquals(actualRequest, request);
assertTrue(actualRequest.getRequestTime()
.equals(request.getRequestTime()));
......@@ -72,12 +72,12 @@ public class AvroSerealizerDeSerealizerIntegrationTest {
@Test
public void WhenDeserializeUsingBinaryecoder_thenActualAndExpectedObjectsAreEqual() {
byte[] data = serealizer.serealizeAvroHttpRequestBinary(request);
AvroHttpRequest actualRequest = deSerealizer.deSerealizeAvroHttpRequestBinary(data);
byte[] data = serializer.serializeAvroHttpRequestBinary(request);
AvroHttpRequest actualRequest = deserializer.deSerializeAvroHttpRequestBinary(data);
assertEquals(actualRequest, request);
assertTrue(actualRequest.getRequestTime()
.equals(request.getRequestTime()));
}
}
......@@ -63,6 +63,7 @@
<org.apache.httpcomponents.version>4.5.2</org.apache.httpcomponents.version>
<velocity-version>1.7</velocity-version>
<velocity-tools-version>2.0</velocity-tools-version>
<maven-war-plugin.version>3.3.2</maven-war-plugin.version>
</properties>
</project>
\ No newline at end of file
......@@ -62,10 +62,10 @@
</build>
<properties>
<asciidoctor-maven-plugin.version>1.5.6</asciidoctor-maven-plugin.version>
<asciidoctorj.version>1.5.6</asciidoctorj.version>
<asciidoctorj-pdf.version>1.5.0-alpha.15</asciidoctorj-pdf.version>
<asciidoctorj-pdf.plugin.version>1.5.0-alpha.15</asciidoctorj-pdf.plugin.version>
<asciidoctor-maven-plugin.version>2.2.2</asciidoctor-maven-plugin.version>
<asciidoctorj.version>2.5.7</asciidoctorj.version>
<asciidoctorj-pdf.version>2.3.4</asciidoctorj-pdf.version>
<asciidoctorj-pdf.plugin.version>2.3.4</asciidoctorj-pdf.plugin.version>
</properties>
</project>
\ No newline at end of file
......@@ -77,6 +77,7 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
</dependencies>
......@@ -92,6 +93,7 @@
<properties>
<spring.version>2.2.1.RELEASE</spring.version>
<awssdk.version>2.17.283</awssdk.version>
<lombok.version>1.18.20</lombok.version>
</properties>
</project>
\ No newline at end of file
......@@ -36,8 +36,8 @@
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
......
......@@ -83,7 +83,7 @@
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-batch</artifactId>
<version>${groovy.version}-01</version>
<version>${groovy-eclipse-batch.version}</version>
</dependency>
</dependencies>
</plugin>
......@@ -155,16 +155,18 @@
<repositories>
<repository>
<id>central</id>
<url>https://jcenter.bintray.com</url>
<id>maven_central</id>
<name>Maven Central</name>
<url>https://repo.maven.apache.org/maven2/</url>
</repository>
</repositories>
<properties>
<groovy-wslite.version>1.1.3</groovy-wslite.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>
<assembly.plugin.version>3.4.2</assembly.plugin.version>
<compiler.plugin.version>3.8.1</compiler.plugin.version>
<groovy.compiler.version>3.7.0</groovy.compiler.version>
<groovy-eclipse-batch.version>3.0.8-01</groovy-eclipse-batch.version>
</properties>
</project>
\ No newline at end of file
</project>
package com.baeldung.category;
package com.baeldung.category
class BaeldungCategory {
public static String capitalize(String self) {
String capitalizedStr = self;
static String capitalize(String self) {
String capitalizedStr = self
if (self.size() > 0) {
capitalizedStr = self.substring(0, 1).toUpperCase() + self.substring(1);
capitalizedStr = self.substring(0, 1).toUpperCase() + self.substring(1)
}
return capitalizedStr
}
public static double toThePower(Number self, Number exponent) {
return Math.pow(self, exponent);
}
static double toThePower(Number self, Number exponent) {
return Math.pow(self, exponent)
}
}
package com.baeldung.category;
import groovy.lang.Category
package com.baeldung.category
@Category(Number)
class NumberCategory {
public Number cube() {
return this*this*this
Number cube() {
return this**3
}
public int divideWithRoundUp(BigDecimal divisor, boolean isRoundUp) {
int divideWithRoundUp(BigDecimal divisor, boolean isRoundUp) {
def mathRound = isRoundUp ? BigDecimal.ROUND_UP : BigDecimal.ROUND_DOWN
return (int)new BigDecimal(this).divide(divisor, 0, mathRound)
return (int) new BigDecimal(this).divide(divisor, 0, mathRound)
}
}
package com.baeldung.determinedatatype
class Person {
private int ageAsInt
private Double ageAsDouble
private String ageAsString
int ageAsInt
Double ageAsDouble
String ageAsString
Person() {}
Person(int ageAsInt) { this.ageAsInt = ageAsInt}
Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble}
Person(String ageAsString) { this.ageAsString = ageAsString}
Person(int ageAsInt) { this.ageAsInt = ageAsInt }
Person(Double ageAsDouble) { this.ageAsDouble = ageAsDouble }
Person(String ageAsString) { this.ageAsString = ageAsString }
}
class Student extends Person {
}
class Student extends Person {}
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.*
import groovy.transform.*
import groovy.util.logging.Log
@Canonical
@ToString(includePackage = false, excludes = ['id'])
@TupleConstructor
@EqualsAndHashCode
@ToString(includePackage=false, excludes=['id'])
@Log
@AutoClone
@Canonical
@AutoClone(style = AutoCloneStyle.SIMPLE)
@Log
class Employee {
long id
......@@ -30,16 +26,15 @@ class Employee {
def propertyMissing(String propertyName, propertyValue) {
println "property '$propertyName' is not available"
log.info "$propertyName is not available"
"property '$propertyName' is not available"
"property '$propertyName' with value '$propertyValue' is not available"
}
def methodMissing(String methodName, def methodArgs) {
def methodMissing(String methodName, Object methodArgs) {
log.info "$methodName is not defined"
"method '$methodName' is not defined"
}
def logEmp() {
log.info "Employee: $lastName, $firstName is of $age years age"
}
}
\ No newline at end of file
}
......@@ -2,32 +2,31 @@ 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) {
while (self > 0) {
println self
self--
}
}
static Long square(Long self) {
return self*self
return self * self
}
static BigDecimal cube(BigDecimal self) {
return self*self*self
return self * self * self
}
}
\ No newline at end of file
}
package com.baeldung.category
import groovy.time.*
import groovy.time.TimeCategory
import groovy.xml.DOMBuilder
import groovy.xml.QName
import groovy.xml.dom.DOMCategory
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) {
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")
......@@ -30,7 +30,7 @@ class CategoryUnitTest extends GroovyTestCase {
void test_whenUsingTimeCategory_thenOperationOnNumber() {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy")
use (TimeCategory) {
use(TimeCategory) {
assert sdf.format(5.days.from.now) == sdf.format(new Date() + 5.days)
sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss")
......@@ -57,7 +57,7 @@ class CategoryUnitTest extends GroovyTestCase {
def root = baeldungArticlesDom.documentElement
use (DOMCategory) {
use(DOMCategory) {
assert root.article.size() == 2
def articles = root.article
......@@ -75,27 +75,26 @@ class CategoryUnitTest extends GroovyTestCase {
assert root.article[2].title.text() == "Metaprogramming in Groovy"
}
}
void test_whenUsingBaeldungCategory_thenCapitalizeString() {
use (BaeldungCategory) {
use(BaeldungCategory) {
assert "norman".capitalize() == "Norman"
}
}
}
void test_whenUsingBaeldungCategory_thenOperationsOnNumber() {
use (BaeldungCategory) {
use(BaeldungCategory) {
assert 50.toThePower(2) == 2500
assert 2.4.toThePower(4) == 33.1776
}
}
void test_whenUsingNumberCategory_thenOperationsOnNumber() {
use (NumberCategory) {
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
}
}
}
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() {
import spock.lang.Specification
class PersonTest extends Specification {
def "givenWhenParameterTypeIsIntegerThenReturnTrue"() {
given:
Person personObj = new Person(10)
Assert.assertTrue(personObj.ageAsInt instanceof Integer)
expect:
personObj.ageAsInt.class == Integer
}
@Test
public void givenWhenParameterTypeIsDouble_thenReturnTrue() {
def "givenWhenParameterTypeIsDouble_thenReturnTrue"() {
given:
Person personObj = new Person(10.0)
Assert.assertTrue((personObj.ageAsDouble).getClass() == Double)
expect:
personObj.ageAsDouble.class == Double
}
@Test
public void givenWhenParameterTypeIsString_thenReturnTrue() {
def "givenWhenParameterTypeIsString_thenReturnTrue"() {
given:
Person personObj = new Person("10 years")
Assert.assertTrue(personObj.ageAsString.class == String)
expect:
personObj.ageAsString.class == String
}
@Test
public void givenClassName_WhenParameterIsInteger_thenReturnTrue() {
Assert.assertTrue(Person.class.getDeclaredField('ageAsInt').type == int.class)
def "givenClassName_WhenParameterIsInteger_thenReturnTrue"() {
expect:
Person.class.getDeclaredField('ageAsInt').type == int.class
}
@Test
public void givenWhenObjectIsInstanceOfType_thenReturnTrue() {
def "givenWhenObjectIsInstanceOfType_thenReturnTrue"() {
given:
Person personObj = new Person()
Assert.assertTrue(personObj instanceof Person)
expect:
personObj.class == Person
}
@Test
public void givenWhenInstanceIsOfSubtype_thenReturnTrue() {
def "givenWhenInstanceIsOfSubtype_thenReturnTrue"() {
given:
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)
}
}
\ No newline at end of file
expect:
studentObj.class.superclass == Person
}
def "givenGroovyList_WhenFindClassName_thenReturnTrue"() {
given:
def ageList = ['ageAsString', 'ageAsDouble', 10]
expect:
ageList.class == ArrayList
ageList.getClass() == ArrayList
}
def "givenGroovyMap_WhenFindClassName_thenReturnTrue"() {
given:
def ageMap = [ageAsString: '10 years', ageAsDouble: 10.0]
expect:
ageMap.getClass() == LinkedHashMap
}
}
package com.baeldung.metaprogramming
import spock.lang.Specification
import java.time.LocalDate
import java.time.Period
import java.time.Year
class MetaprogrammingUnitTest extends GroovyTestCase {
class MetaprogrammingUnitTest extends Specification {
Employee emp = new Employee(firstName: "Norman", lastName: "Lewis")
Employee emp
void testPropertyMissing() {
assert emp.address == "property 'address' is not available"
void setup() {
emp = new Employee(firstName: "Norman", lastName: "Lewis")
}
void testMethodMissing() {
def "testPropertyMissing"() {
expect:
emp.address == "property 'address' is not available"
}
def "testMethodMissing"() {
given:
Employee emp = new Employee()
try {
emp.getFullName()
} catch(MissingMethodException e) {
println "method is not defined"
}
assert emp.getFullName() == "method 'getFullName' is not defined"
expect:
emp.getFullName() == "method 'getFullName' is not defined"
}
void testMetaClassProperty() {
def "testMetaClassProperty"() {
when:
Employee.metaClass.address = ""
emp = new Employee(firstName: "Norman", lastName: "Lewis", address: "US")
assert emp.address == "US"
and:
emp = new Employee(firstName: "Norman",
lastName: "Lewis",
address: "US")
then:
emp.address == "US"
}
void testMetaClassMethod() {
def "testMetaClassMethod"() {
when:
emp.metaClass.getFullName = {
"$lastName, $firstName"
}
assert emp.getFullName() == "Lewis, Norman"
then:
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)"
}
def "testOnlyNameConstructor"() {
when:
new Employee("Norman")
then:
thrown(GroovyRuntimeException)
}
def "testMetaClassConstructor"() {
when:
Employee.metaClass.constructor = { String firstName ->
new Employee(firstName: firstName)
}
and:
Employee norman = new Employee("Norman")
assert norman.firstName == "Norman"
assert norman.lastName == null
then:
norman.firstName == "Norman"
norman.lastName == null
}
void testJavaMetaClass() {
def "testJavaMetaClass"() {
when:
String.metaClass.capitalize = { String str ->
str.substring(0, 1).toUpperCase() + str.substring(1)
}
assert "norman".capitalize() == "Norman"
and:
String.metaClass.static.joinWith = { String delimiter, String... args ->
String.join(delimiter, args)
}
then:
"norman".capitalize() == "Norman"
String.joinWith(" -> ", "a", "b", "c") == "a -> b -> c"
}
void testEmployeeExtension() {
def "testEmployeeExtension"() {
given:
def age = 28
def expectedYearOfBirth = Year.now() - age
Employee emp = new Employee(age: age)
assert emp.getYearOfBirth() == expectedYearOfBirth.value
expect:
emp.getYearOfBirth() == expectedYearOfBirth.value
}
void testJavaClassesExtensions() {
def "testJavaClassesExtensions"() {
when:
5.printCounter()
assert 40l.square() == 1600l
assert (2.98).cube() == 26.463592
then:
40L.square() == 1600L
(2.98).cube() == 26.463592
}
void testStaticEmployeeExtension() {
def "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
def "testToStringAnnotation"() {
when:
Employee employee = new Employee().tap {
id = 1
firstName = "norman"
lastName = "lewis"
age = 28
}
assert employee.toString() == "Employee(norman, lewis, 28)"
then:
employee.toString() == "Employee(norman, lewis, 28)"
}
void testTupleConstructorAnnotation() {
def "testTupleConstructorAnnotation"() {
when:
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)"
then:
norman.toString() == "Employee(norman, lewis, 28)"
snape.toString() == "Employee(snape, null, 0)"
}
void testEqualsAndHashCodeAnnotation() {
def "testEqualsAndHashCodeAnnotation"() {
when:
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()
}
then:
norman == normanCopy
norman.hashCode() == normanCopy.hashCode()
}
def "testAutoCloneAnnotation"() {
given:
Employee norman = new Employee(1, "norman", "lewis", 28)
when:
def normanCopy = norman.clone()
then:
norman == normanCopy
}
void testLoggingAnnotation() {
def "testLoggingAnnotation"() {
given:
Employee employee = new Employee(1, "Norman", "Lewis", 28)
employee.logEmp()
employee.logEmp() // INFO: Employee: Lewis, Norman is of 28 years age
}
}
package com.baeldung.templateengine
import groovy.text.GStringTemplateEngine
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
import spock.lang.Specification
class TemplateEnginesUnitTest extends GroovyTestCase {
def bindMap = [user: "Norman", signature: "Baeldung"]
void testSimpleTemplateEngine() {
class TemplateEnginesUnitTest extends Specification {
final Map BIND_MAP = [user: "Norman", signature: "Baeldung"]
def "testSimpleTemplateEngine"() {
given:
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"
when:
def smsText = new SimpleTemplateEngine().createTemplate(smsTemplate).make(BIND_MAP)
then:
smsText.toString() == "Dear Norman, Thanks for reading our Article. Baeldung"
}
void testStreamingTemplateEngine() {
def "testStreamingTemplateEngine"() {
given:
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"""
//can be a string larger than 64k
BIND_MAP.articleText = """|1. Overview
|This is a tutorial article on Template Engines""".stripMargin()
when:
def articleEmailText = new StreamingTemplateEngine().createTemplate(articleEmailTemplate).make(BIND_MAP)
then:
articleEmailText.toString() == """|Dear Norman,
|Please read the requested article below.
|1. Overview
|This is a tutorial article on Template Engines
|From,
|Baeldung""".stripMargin()
}
void testGStringTemplateEngine() {
def "testGStringTemplateEngine"() {
given:
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"
when:
def emailText = new GStringTemplateEngine().createTemplate(emailTemplate).make(BIND_MAP)
then:
emailText.toString() == """|Dear Norman,
|Thanks for subscribing our services.
|Baeldung""".stripMargin()
}
void testXmlTemplateEngine() {
def "testXmlTemplateEngine"() {
given:
def emailXmlTemplate = '''<xs xmlns:gsp='groovy-server-pages'>
<gsp:scriptlet>def emailContent = "Thanks for subscribing our services."</gsp:scriptlet>
<email>
......@@ -51,11 +65,16 @@ Baeldung"""
<signature>${signature}</signature>
</email>
</xs>'''
def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(bindMap)
when:
def emailXml = new XmlTemplateEngine().createTemplate(emailXmlTemplate).make(BIND_MAP)
then:
println emailXml.toString()
}
void testMarkupTemplateEngineHtml() {
def "testMarkupTemplateEngineHtml"() {
given:
def emailHtmlTemplate = """html {
head {
title('Service Subscription Email')
......@@ -66,14 +85,16 @@ Baeldung"""
p('Baeldung')
}
}"""
when:
def emailHtml = new MarkupTemplateEngine().createTemplate(emailHtmlTemplate).make()
then:
println emailHtml.toString()
}
void testMarkupTemplateEngineXml() {
def "testMarkupTemplateEngineXml"() {
given:
def emailXmlTemplate = """xmlDeclaration()
xs{
email {
......@@ -83,14 +104,18 @@ Baeldung"""
}
}
"""
TemplateConfiguration config = new TemplateConfiguration()
config.autoIndent = true
config.autoEscape = true
config.autoNewLine = true
TemplateConfiguration config = new TemplateConfiguration().with {
autoIndent = true
autoEscape = true
autoNewLine = true
return it
}
when:
def emailXml = new MarkupTemplateEngine(config).createTemplate(emailXmlTemplate).make()
then:
println emailXml.toString()
}
}
\ No newline at end of file
}
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment