Merge pull request #3 from codehunter34/master

Merge from master to BAEL-2969 branch
This commit is contained in:
codehunter34
2019-06-09 23:16:29 -04:00
committed by GitHub
105 changed files with 2798 additions and 244 deletions
@@ -0,0 +1,51 @@
package com.baeldung.algorithms.graphcycledetection.domain;
import java.util.ArrayList;
import java.util.List;
public class Graph {
private List<Vertex> vertices;
public Graph() {
this.vertices = new ArrayList<>();
}
public Graph(List<Vertex> vertices) {
this.vertices = vertices;
}
public void addVertex(Vertex vertex) {
this.vertices.add(vertex);
}
public void addEdge(Vertex from, Vertex to) {
from.addNeighbour(to);
}
public boolean hasCycle() {
for (Vertex vertex : vertices) {
if (!vertex.isVisited() && hasCycle(vertex)) {
return true;
}
}
return false;
}
public boolean hasCycle(Vertex sourceVertex) {
sourceVertex.setBeingVisited(true);
for (Vertex neighbour : sourceVertex.getAdjacencyList()) {
if (neighbour.isBeingVisited()) {
// backward edge exists
return true;
} else if (!neighbour.isVisited() && hasCycle(neighbour)) {
return true;
}
}
sourceVertex.setBeingVisited(false);
sourceVertex.setVisited(true);
return false;
}
}
@@ -0,0 +1,56 @@
package com.baeldung.algorithms.graphcycledetection.domain;
import java.util.ArrayList;
import java.util.List;
public class Vertex {
private String label;
private boolean visited;
private boolean beingVisited;
private List<Vertex> adjacencyList;
public Vertex(String label) {
this.label = label;
this.adjacencyList = new ArrayList<>();
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public boolean isBeingVisited() {
return beingVisited;
}
public void setBeingVisited(boolean beingVisited) {
this.beingVisited = beingVisited;
}
public List<Vertex> getAdjacencyList() {
return adjacencyList;
}
public void setAdjacencyList(List<Vertex> adjacencyList) {
this.adjacencyList = adjacencyList;
}
public void addNeighbour(Vertex adjacent) {
this.adjacencyList.add(adjacent);
}
}
@@ -0,0 +1,56 @@
package com.baeldung.algorithms.graphcycledetection;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.baeldung.algorithms.graphcycledetection.domain.Graph;
import com.baeldung.algorithms.graphcycledetection.domain.Vertex;
public class GraphCycleDetectionUnitTest {
@Test
public void givenGraph_whenCycleExists_thenReturnTrue() {
Vertex vertexA = new Vertex("A");
Vertex vertexB = new Vertex("B");
Vertex vertexC = new Vertex("C");
Vertex vertexD = new Vertex("D");
Graph graph = new Graph();
graph.addVertex(vertexA);
graph.addVertex(vertexB);
graph.addVertex(vertexC);
graph.addVertex(vertexD);
graph.addEdge(vertexA, vertexB);
graph.addEdge(vertexB, vertexC);
graph.addEdge(vertexC, vertexA);
graph.addEdge(vertexD, vertexC);
assertTrue(graph.hasCycle());
}
@Test
public void givenGraph_whenNoCycleExists_thenReturnFalse() {
Vertex vertexA = new Vertex("A");
Vertex vertexB = new Vertex("B");
Vertex vertexC = new Vertex("C");
Vertex vertexD = new Vertex("D");
Graph graph = new Graph();
graph.addVertex(vertexA);
graph.addVertex(vertexB);
graph.addVertex(vertexC);
graph.addVertex(vertexD);
graph.addEdge(vertexA, vertexB);
graph.addEdge(vertexB, vertexC);
graph.addEdge(vertexA, vertexC);
graph.addEdge(vertexD, vertexC);
assertFalse(graph.hasCycle());
}
}
+2 -1
View File
@@ -3,5 +3,6 @@
## Relevant articles:
- [String Matching in Groovy](http://www.baeldung.com/)
- [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)
- [Pattern Matching in Strings in Groovy](https://www.baeldung.com/groovy-pattern-matching)
+178
View File
@@ -0,0 +1,178 @@
<?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>parent-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.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>
<junit.platform.version>1.0.0</junit.platform.version>
<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>
+93 -37
View File
@@ -1,6 +1,6 @@
<?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">
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>
@@ -15,25 +15,20 @@
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>${groovy.version}</version>
<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-all.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-dateutil</artifactId>
<version>${groovy.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-sql</artifactId>
<version>${groovy-sql.version}</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
@@ -56,21 +51,35 @@
</dependencies>
<build>
<scriptSourceDirectory>src/main/groovy</scriptSourceDirectory>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.codehaus.gmavenplus</groupId>
<artifactId>gmavenplus-plugin</artifactId>
<version>${gmavenplus-plugin.version}</version>
<executions>
<execution>
<goals>
<goal>addSources</goal>
<goal>addTestSources</goal>
<goal>compile</goal>
<goal>compileTests</goal>
</goals>
</execution>
</executions>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-compiler</artifactId>
<version>3.3.0-01</version>
<extensions>true</extensions>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</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>3.3.0-01</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>
@@ -101,13 +110,42 @@
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
<configuration>
<useFile>false</useFile>
<includes>
<include>**/*Test.java</include>
<include>**/*Spec.java</include>
</includes>
<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>
@@ -118,14 +156,32 @@
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>bintray</id>
<name>Groovy Bintray</name>
<url>https://dl.bintray.com/groovy/maven</url>
<releases>
<!-- avoid automatic updates -->
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
<properties>
<junit.platform.version>1.0.0</junit.platform.version>
<groovy.version>2.5.6</groovy.version>
<groovy-all.version>2.5.6</groovy-all.version>
<groovy-sql.version>2.5.6</groovy-sql.version>
<hsqldb.version>2.4.0</hsqldb.version>
<spock-core.version>1.1-groovy-2.4</spock-core.version>
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
<commons-lang3.version>3.9</commons-lang3.version>
<java.version>1.8</java.version>
<maven-compiler-plugin.version>3.8.1</maven-compiler-plugin.version>
<logback.version>1.2.3</logback.version>
<groovy.version>2.5.7</groovy.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</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)
@@ -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();
}
}
@@ -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)
}
}
@@ -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"
}
}
@@ -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>
@@ -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>
@@ -1,15 +0,0 @@
package com.baeldung.error;
public class ErrorGenerator {
public void throwException() throws Exception {
throw new Exception("checked");
}
public void throwRuntimeException() {
throw new RuntimeException("unchecked");
}
public void throwError() {
throw new Error("unchecked");
}
}
@@ -1,51 +0,0 @@
package com.baeldung.error;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ErrorGeneratorUnitTest {
private ErrorGenerator errorGenerator;
@Before
public void setUp() {
errorGenerator = new ErrorGenerator();
}
@Test
public void whenCheckedException_thenIsCaughtByCatchException() {
try {
errorGenerator.throwException();
} catch (Exception e) {
// caught! -> test pass
}
}
@Test
public void whenUncheckedException_thenIsCaughtByCatchException() {
try {
errorGenerator.throwRuntimeException();
} catch (Exception e) {
// caught! -> test pass
}
}
@Test(expected = Error.class)
public void whenError_thenIsNotCaughtByCatchException() {
try {
errorGenerator.throwError();
} catch (Exception e) {
Assert.fail(); // errors are not caught by catch exception
}
}
@Test
public void whenError_thenIsCaughtByCatchError() {
try {
errorGenerator.throwError();
} catch (Error e) {
// caught! -> test pass
}
}
}
+2
View File
@@ -1,3 +1,5 @@
## Relevant articles:
- [Multi-Module Maven Application with Java Modules](https://www.baeldung.com/maven-multi-module-project-java-jpms)
- [Guide to Java FileChannel](https://www.baeldung.com/java-filechannel)
- [Understanding the NumberFormatException in Java](https://www.baeldung.com/java-number-format-exception)
+1
View File
@@ -7,4 +7,5 @@
- [Exploring the New HTTP Client in Java 9 and 11](https://www.baeldung.com/java-9-http-client)
- [An Introduction to Epsilon GC: A No-Op Experimental Garbage Collector](https://www.baeldung.com/jvm-epsilon-gc-garbage-collector)
- [Guide to jlink](https://www.baeldung.com/jlink)
- [Negate a Predicate Method Reference with Java 11](https://www.baeldung.com/java-negate-predicate-method-reference)
- [Transforming an Empty String into an Empty Optional](https://www.baeldung.com/java-empty-string-to-empty-optional)
+2 -1
View File
@@ -3,5 +3,6 @@
## Core Java 8 Cookbooks and Examples (part 2)
### Relevant Articles:
- [Anonymous Classes in Java](https://www.baeldung.com/java-anonymous-classes)
- [Anonymous Classes in Java](http://www.baeldung.com/)
- [How to Delay Code Execution in Java](https://www.baeldung.com/java-delay-code-execution)
- [Run JAR Application With Command Line Arguments](https://www.baeldung.com/java-run-jar-with-arguments)
-1
View File
@@ -30,7 +30,6 @@
<artifactId>icu4j</artifactId>
<version>${icu.version}</version>
</dependency>
</dependencies>
<build>
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit
name="com.baeldung.optionalReturnType"
transaction-type="RESOURCE_LOCAL">
<description>Persist Optional Return Type Demo</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.optionalReturnType.User</class>
<class>com.baeldung.optionalReturnType.UserOptional</class>
<!--
<class>com.baeldung.optionalReturnType.UserOptionalField</class>
-->
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver"
value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:mem:test" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.H2Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true" />
<property name="hibernate.temp.use_jdbc_metadata_defaults"
value="false" />
</properties>
</persistence-unit>
</persistence>
@@ -15,3 +15,4 @@
- [Intersection Between two Integer Arrays](https://www.baeldung.com/java-array-intersection)
- [Sorting Arrays in Java](https://www.baeldung.com/java-sorting-arrays)
- [Convert a Float to a Byte Array in Java](https://www.baeldung.com/java-convert-float-to-byte-array)
- [Converting Between Stream and Array in Java](https://www.baeldung.com/java-stream-to-array)
@@ -0,0 +1,26 @@
package com.baeldung.error;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class ErrorGeneratorUnitTest {
@Test(expected = AssertionError.class)
public void whenError_thenIsNotCaughtByCatchException() {
try {
throw new AssertionError();
} catch (Exception e) {
Assert.fail(); // errors are not caught by catch exception
}
}
@Test
public void whenError_thenIsCaughtByCatchError() {
try {
throw new AssertionError();
} catch (Error e) {
// caught! -> test pass
}
}
}
@@ -0,0 +1,5 @@
=========
## Core Java Optional
### Relevant Articles:
@@ -0,0 +1,53 @@
<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>
<parent>
<groupId>com.baeldung.core-java-modules</groupId>
<artifactId>core-java-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>core-java-optional</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<hibernate.core.version>5.4.0.Final</hibernate.core.version>
<h2database.version>1.4.197</h2database.version>
<jackson.databind.version>2.9.8</jackson.databind.version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.core.version}</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${h2database.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,41 @@
package com.baeldung.optionalReturnType;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
public class HandleOptionalTypeExample {
static Map<String, User> usersByName = new HashMap();
static {
User user1 = new User();
user1.setUserId(1l);
user1.setFirstName("baeldung");
usersByName.put("baeldung", user1);
}
public static void main(String[] args) {
changeUserName("baeldung", "baeldung-new");
changeUserName("user", "user-new");
}
public static void changeUserName(String oldFirstName, String newFirstName) {
Optional<User> userOpt = findUserByName(oldFirstName);
if (userOpt.isPresent()) {
User user = userOpt.get();
user.setFirstName(newFirstName);
System.out.println("user with name " + oldFirstName + " is changed to " + user.getFirstName());
} else {
// user is missing
System.out.println("user with name " + oldFirstName + " is not found.");
}
}
public static Optional<User> findUserByName(String name) {
// look up the user in the database, the user object below could be null
User user = usersByName.get(name);
Optional<User> opt = Optional.ofNullable(user);
return opt;
}
}
@@ -0,0 +1,19 @@
package com.baeldung.optionalReturnType;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class OptionalToJsonExample {
public static void main(String[] args) {
UserOptional user = new UserOptional();
user.setUserId(1l);
user.setFirstName("Bael Dung");
ObjectMapper om = new ObjectMapper();
try {
System.out.print("user in json is:" + om.writeValueAsString(user));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,26 @@
package com.baeldung.optionalReturnType;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistOptionalTypeExample {
static String persistenceUnit = "com.baeldung.optionalReturnType";
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
static EntityManager entityManager = emf.createEntityManager();
// to run this app, uncomment the follow line in META-INF/persistence.xml
// <class>com.baeldung.optionalReturnType.UserOptionalField</class>
public static void main(String[] args) {
UserOptionalField user1 = new UserOptionalField();
user1.setUserId(1l);
user1.setFirstName(Optional.of("Bael Dung"));
entityManager.persist(user1);
UserOptional user2 = entityManager.find(UserOptional.class, 1l);
System.out.print("User2.firstName:" + user2.getFirstName());
}
}
@@ -0,0 +1,22 @@
package com.baeldung.optionalReturnType;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistOptionalTypeExample2 {
static String persistenceUnit = "com.baeldung.optionalReturnType";
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
static EntityManager em = emf.createEntityManager();
public static void main(String[] args) {
UserOptional user1 = new UserOptional();
user1.setUserId(1l);
user1.setFirstName("Bael Dung");
em.persist(user1);
UserOptional user2 = em.find(UserOptional.class, 1l);
System.out.print("User2.firstName:" + user2.getFirstName());
}
}
@@ -0,0 +1,22 @@
package com.baeldung.optionalReturnType;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistUserExample {
static String persistenceUnit = "com.baeldung.optionalReturnType";
static EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit);
static EntityManager em = emf.createEntityManager();
public static void main(String[] args) {
User user1 = new User();
user1.setUserId(1l);
user1.setFirstName("Bael Dung");
em.persist(user1);
User user2 = em.find(User.class, 1l);
System.out.print("User2.firstName:" + user2.getFirstName());
}
}

Some files were not shown because too many files have changed in this diff Show More