Merge branch 'master' of https://github.com/Maiklins/tutorials into BAEL-2217

This commit is contained in:
mikr 2019-03-09 17:15:37 +01:00
commit 8893730201
1117 changed files with 34789 additions and 3451 deletions

7
.gitignore vendored
View File

@ -66,3 +66,10 @@ jmeter/src/main/resources/*-JMeter.csv
**/nb-configuration.xml
core-scala/.cache-main
core-scala/.cache-tests
persistence-modules/hibernate5/transaction.log
apache-avro/src/main/java/com/baeldung/avro/model/
jta/transaction-logs/
software-security/sql-injection-samples/derby.log
spring-soap/src/main/java/com/baeldung/springsoap/gen/

View File

@ -5,9 +5,9 @@
<groupId>com.baeldung</groupId>
<artifactId>JGit</artifactId>
<version>1.0-SNAPSHOT</version>
<name>JGit</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<name>JGit</name>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -2,8 +2,8 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>Twitter4J</artifactId>
<packaging>jar</packaging>
<name>Twitter4J</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -23,7 +23,7 @@
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-stream_2.12</artifactId>
<version>2.5.11</version>
<version>${akka.stream.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
@ -41,7 +41,6 @@
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<akka.http.version>10.0.11</akka.http.version>
<akka.stream.version>2.5.11</akka.stream.version>
</properties>

View File

@ -54,7 +54,6 @@
</build>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<io.jenetics.version>3.7.0</io.jenetics.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>

View File

@ -15,3 +15,5 @@
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)
- [Find the Longest Substring without Repeating Characters](https://www.baeldung.com/java-longest-substring-without-repeated-characters)
- [Java Two Pointer Technique](https://www.baeldung.com/java-two-pointer-technique)
- [Permutations of an Array in Java](https://www.baeldung.com/java-array-permutations)
- [Implementing Simple State Machines with Java Enums](https://www.baeldung.com/java-enum-simple-state-machine)

View File

@ -39,6 +39,11 @@
<version>${org.assertj.core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.dpaukov</groupId>
<artifactId>combinatoricslib3</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
<build>
@ -74,11 +79,10 @@
</reporting>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
<guava.version>25.1-jre</guava.version>
<guava.version>27.0.1-jre</guava.version>
</properties>
</project>

View File

@ -0,0 +1,29 @@
package com.baeldung.algorithms.combination;
import java.util.Arrays;
import java.util.Iterator;
import org.apache.commons.math3.util.CombinatoricsUtils;
public class ApacheCommonsCombinationGenerator {
private static final int N = 6;
private static final int R = 3;
/**
* Print all combinations of r elements from a set
* @param n - number of elements in set
* @param r - number of elements in selection
*/
public static void generate(int n, int r) {
Iterator<int[]> iterator = CombinatoricsUtils.combinationsIterator(n, r);
while (iterator.hasNext()) {
final int[] combination = iterator.next();
System.out.println(Arrays.toString(combination));
}
}
public static void main(String[] args) {
generate(N, R);
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.algorithms.combination;
import org.paukov.combinatorics3.Generator;
public class CombinatoricsLibCombinationGenerator {
public static void main(String[] args) {
Generator.combination(0, 1, 2, 3, 4, 5)
.simple(3)
.stream()
.forEach(System.out::println);
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.algorithms.combination;
import java.util.Arrays;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
public class GuavaCombinationsGenerator {
public static void main(String[] args) {
Set<Set<Integer>> combinations = Sets.combinations(ImmutableSet.of(0, 1, 2, 3, 4, 5), 3);
System.out.println(combinations.size());
System.out.println(Arrays.toString(combinations.toArray()));
}
}

View File

@ -0,0 +1,52 @@
package com.baeldung.algorithms.combination;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class IterativeCombinationGenerator {
private static final int N = 5;
private static final int R = 2;
/**
* Generate all combinations of r elements from a set
* @param n the number of elements in input set
* @param r the number of elements in a combination
* @return the list containing all combinations
*/
public List<int[]> generate(int n, int r) {
List<int[]> combinations = new ArrayList<>();
int[] combination = new int[r];
// initialize with lowest lexicographic combination
for (int i = 0; i < r; i++) {
combination[i] = i;
}
while (combination[r - 1] < n) {
combinations.add(combination.clone());
// generate next combination in lexicographic order
int t = r - 1;
while (t != 0 && combination[t] == n - r + t) {
t--;
}
combination[t]++;
for (int i = t + 1; i < r; i++) {
combination[i] = combination[i - 1] + 1;
}
}
return combinations;
}
public static void main(String[] args) {
IterativeCombinationGenerator generator = new IterativeCombinationGenerator();
List<int[]> combinations = generator.generate(N, R);
System.out.println(combinations.size());
for (int[] combination : combinations) {
System.out.println(Arrays.toString(combination));
}
}
}

View File

@ -0,0 +1,53 @@
package com.baeldung.algorithms.combination;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SelectionRecursiveCombinationGenerator {
private static final int N = 6;
private static final int R = 3;
/**
* Generate all combinations of r elements from a set
* @param n - number of elements in input set
* @param r - number of elements to be chosen
* @return the list containing all combinations
*/
public List<int[]> generate(int n, int r) {
List<int[]> combinations = new ArrayList<>();
helper(combinations, new int[r], 0, n - 1, 0);
return combinations;
}
/**
* Choose elements from set by recursing over elements selected
* @param combinations - List to store generated combinations
* @param data - current combination
* @param start - starting element of remaining set
* @param end - last element of remaining set
* @param index - number of elements chosen so far.
*/
private void helper(List<int[]> combinations, int data[], int start, int end, int index) {
if (index == data.length) {
int[] combination = data.clone();
combinations.add(combination);
} else {
int max = Math.min(end, end + 1 - data.length + index);
for (int i = start; i <= max; i++) {
data[index] = i;
helper(combinations, data, i + 1, end, index + 1);
}
}
}
public static void main(String[] args) {
SelectionRecursiveCombinationGenerator generator = new SelectionRecursiveCombinationGenerator();
List<int[]> combinations = generator.generate(N, R);
for (int[] combination : combinations) {
System.out.println(Arrays.toString(combination));
}
System.out.printf("generated %d combinations of %d items from %d ", combinations.size(), R, N);
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.algorithms.combination;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SetRecursiveCombinationGenerator {
private static final int N = 5;
private static final int R = 2;
/**
* Generate all combinations of r elements from a set
* @param n - number of elements in set
* @param r - number of elements in selection
* @return the list containing all combinations
*/
public List<int[]> generate(int n, int r) {
List<int[]> combinations = new ArrayList<>();
helper(combinations, new int[r], 0, n-1, 0);
return combinations;
}
/**
* @param combinations - List to contain the generated combinations
* @param data - List of elements in the selection
* @param start - index of the starting element in the remaining set
* @param end - index of the last element in the set
* @param index - number of elements selected so far
*/
private void helper(List<int[]> combinations, int data[], int start, int end, int index) {
if (index == data.length) {
int[] combination = data.clone();
combinations.add(combination);
} else if (start <= end) {
data[index] = start;
helper(combinations, data, start + 1, end, index + 1);
helper(combinations, data, start + 1, end, index);
}
}
public static void main(String[] args) {
SetRecursiveCombinationGenerator generator = new SetRecursiveCombinationGenerator();
List<int[]> combinations = generator.generate(N, R);
for (int[] combination : combinations) {
System.out.println(Arrays.toString(combination));
}
System.out.printf("generated %d combinations of %d items from %d ", combinations.size(), R, N);
}
}

View File

@ -0,0 +1,46 @@
package com.baeldung.algorithms.enumstatemachine;
public enum LeaveRequestState {
Submitted {
@Override
public LeaveRequestState nextState() {
System.out.println("Starting the Leave Request and sending to Team Leader for approval.");
return Escalated;
}
@Override
public String responsiblePerson() {
return "Employee";
}
},
Escalated {
@Override
public LeaveRequestState nextState() {
System.out.println("Reviewing the Leave Request and escalating to Department Manager.");
return Approved;
}
@Override
public String responsiblePerson() {
return "Team Leader";
}
},
Approved {
@Override
public LeaveRequestState nextState() {
System.out.println("Approving the Leave Request.");
return this;
}
@Override
public String responsiblePerson() {
return "Department Manager";
}
};
public abstract String responsiblePerson();
public abstract LeaveRequestState nextState();
}

View File

@ -0,0 +1,35 @@
package com.baeldung.algorithms.combination;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import org.junit.Test;
public class CombinationUnitTest {
private static final int N = 5;
private static final int R = 3;
private static final int nCr = 10;
@Test
public void givenSetAndSelectionSize_whenCalculatedUsingSetRecursiveAlgorithm_thenExpectedCount() {
SetRecursiveCombinationGenerator generator = new SetRecursiveCombinationGenerator();
List<int[]> selection = generator.generate(N, R);
assertEquals(nCr, selection.size());
}
@Test
public void givenSetAndSelectionSize_whenCalculatedUsingSelectionRecursiveAlgorithm_thenExpectedCount() {
SelectionRecursiveCombinationGenerator generator = new SelectionRecursiveCombinationGenerator();
List<int[]> selection = generator.generate(N, R);
assertEquals(nCr, selection.size());
}
@Test
public void givenSetAndSelectionSize_whenCalculatedUsingIterativeAlgorithm_thenExpectedCount() {
IterativeCombinationGenerator generator = new IterativeCombinationGenerator();
List<int[]> selection = generator.generate(N, R);
assertEquals(nCr, selection.size());
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.algorithms.enumstatemachine;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class LeaveRequestStateUnitTest {
@Test
public void givenLeaveRequest_whenStateEscalated_thenResponsibleIsTeamLeader() {
LeaveRequestState state = LeaveRequestState.Escalated;
assertEquals(state.responsiblePerson(), "Team Leader");
}
@Test
public void givenLeaveRequest_whenStateApproved_thenResponsibleIsDepartmentManager() {
LeaveRequestState state = LeaveRequestState.Approved;
assertEquals(state.responsiblePerson(), "Department Manager");
}
@Test
public void givenLeaveRequest_whenNextStateIsCalled_thenStateIsChanged() {
LeaveRequestState state = LeaveRequestState.Submitted;
state = state.nextState();
assertEquals(state, LeaveRequestState.Escalated);
state = state.nextState();
assertEquals(state, LeaveRequestState.Approved);
state = state.nextState();
assertEquals(state, LeaveRequestState.Approved);
}
}

View File

@ -68,7 +68,7 @@
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.7</version>
<version>${cobertura-maven-plugin.version}</version>
<configuration>
<instrumentation>
<ignores>
@ -84,13 +84,13 @@
</reporting>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<tradukisto.version>1.0.1</tradukisto.version>
<org.jgrapht.core.version>1.0.1</org.jgrapht.core.version>
<org.jgrapht.ext.version>1.0.1</org.jgrapht.ext.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>
<cobertura-maven-plugin.version>2.7</cobertura-maven-plugin.version>
</properties>
</project>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 KiB

After

Width:  |  Height:  |  Size: 9.4 KiB

View File

@ -49,7 +49,6 @@
</build>
<properties>
<lombok.version>1.16.12</lombok.version>
<commons-math3.version>3.6.1</commons-math3.version>
<org.assertj.core.version>3.9.0</org.assertj.core.version>
<commons-codec.version>1.11</commons-codec.version>

View File

@ -3,9 +3,9 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>animal-sniffer-mvn-plugin</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>animal-sniffer-mvn-plugin</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>

View File

@ -3,8 +3,8 @@
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>annotations</artifactId>
<packaging>pom</packaging>
<name>annotations</name>
<packaging>pom</packaging>
<parent>
<artifactId>parent-modules</artifactId>

View File

@ -7,14 +7,6 @@
<version>0.0.1-SNAPSHOT</version>
<name>apache-avro</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler-plugin.version>3.5</compiler-plugin.version>
<avro.version>1.8.2</avro.version>
<java.version>1.8</java.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
@ -85,4 +77,12 @@
</plugin>
</plugins>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<compiler-plugin.version>3.5</compiler-plugin.version>
<avro.version>1.8.2</avro.version>
<slf4j.version>1.7.25</slf4j.version>
</properties>
</project>

View File

@ -3,8 +3,8 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>apache-curator</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>apache-curator</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>
@ -39,7 +39,7 @@
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind.version}</version>
<version>${jackson.version}</version>
</dependency>
<!-- test scoped -->
<dependency>
@ -59,7 +59,6 @@
<properties>
<curator.version>4.0.1</curator.version>
<zookeeper.version>3.4.11</zookeeper.version>
<jackson-databind.version>2.9.7</jackson-databind.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>

View File

@ -12,22 +12,6 @@
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<properties>
<geode.core>1.6.0</geode.core>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
@ -38,8 +22,24 @@
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>RELEASE</version>
<version>${junit.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<geode.core>1.6.0</geode.core>
</properties>
</project>

View File

@ -7,51 +7,58 @@
<name>apache-meecrowave</name>
<description>A sample REST API application with Meecrowave</description>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-core -->
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-core</artifactId>
<version>1.2.1</version>
<version>${meecrowave-core.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.meecrowave/meecrowave-jpa -->
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-jpa</artifactId>
<version>1.2.1</version>
<version>${meecrowave-jpa.version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.10.0</version>
<version>${okhttp.version}</version>
</dependency>
<dependency>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-junit</artifactId>
<version>1.2.0</version>
<version>${meecrowave-junit.version}</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.meecrowave</groupId>
<artifactId>meecrowave-maven-plugin</artifactId>
<version>1.2.1</version>
<version>${meecrowave-maven-plugin.version}</version>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>4.10</junit.version>
<meecrowave-junit.version>1.2.0</meecrowave-junit.version>
<okhttp.version>3.10.0</okhttp.version>
<meecrowave-jpa.version>1.2.1</meecrowave-jpa.version>
<meecrowave-core.version>1.2.1</meecrowave-core.version>
<meecrowave-maven-plugin.version>1.2.1</meecrowave-maven-plugin.version>
</properties>
</project>

View File

@ -11,12 +11,14 @@
<dependency>
<groupId>org.apache.pulsar</groupId>
<artifactId>pulsar-client</artifactId>
<version>2.1.1-incubating</version>
<version>${pulsar-client.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<pulsar-client.version>2.1.1-incubating</pulsar-client.version>
</properties>
</project>

View File

@ -4,8 +4,8 @@
<groupId>com.baeldung</groupId>
<artifactId>apache-solrj</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>apache-solrj</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -1,3 +1,4 @@
### Relevant articles
- [Introduction to Apache Spark](http://www.baeldung.com/apache-spark)
- [Building a Data Pipeline with Kafka, Spark Streaming and Cassandra](https://www.baeldung.com/kafka-spark-data-pipeline)

View File

@ -4,8 +4,8 @@
<groupId>com.baeldung</groupId>
<artifactId>apache-spark</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>apache-spark</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>
@ -54,10 +54,10 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
@ -85,6 +85,7 @@
<org.apache.spark.spark-streaming-kafka.version>2.3.0</org.apache.spark.spark-streaming-kafka.version>
<com.datastax.spark.spark-cassandra-connector.version>2.3.0</com.datastax.spark.spark-cassandra-connector.version>
<com.datastax.spark.spark-cassandra-connector-java.version>1.5.2</com.datastax.spark.spark-cassandra-connector-java.version>
<maven-compiler-plugin.version>3.2</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -4,8 +4,8 @@
<groupId>com.baeldung</groupId>
<version>0.1-SNAPSHOT</version>
<artifactId>apache-velocity</artifactId>
<packaging>war</packaging>
<name>apache-velocity</name>
<packaging>war</packaging>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -5,8 +5,8 @@
<groupId>com.baeldung</groupId>
<artifactId>aws-lambda</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>aws-lambda</name>
<packaging>jar</packaging>
<parent>
<artifactId>parent-modules</artifactId>

View File

@ -4,7 +4,6 @@
- [AWS S3 with Java](http://www.baeldung.com/aws-s3-java)
- [AWS Lambda With Java](http://www.baeldung.com/java-aws-lambda)
- [Managing EC2 Instances in Java](http://www.baeldung.com/ec2-java)
- [http://www.baeldung.com/aws-s3-multipart-upload](https://github.com/eugenp/tutorials/tree/master/aws)
- [Multipart Uploads in Amazon S3 with Java](http://www.baeldung.com/aws-s3-multipart-upload)
- [Integration Testing with a Local DynamoDB Instance](http://www.baeldung.com/dynamodb-local-integration-tests)
- [Using the JetS3t Java Client With Amazon S3](http://www.baeldung.com/jets3t-amazon-s3)

View File

@ -4,8 +4,8 @@
<groupId>com.baeldung</groupId>
<artifactId>aws</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>aws</name>
<packaging>jar</packaging>
<parent>
<groupId>com.baeldung</groupId>

View File

@ -36,7 +36,7 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.1.1.RELEASE</version>
<version>${spring-boot.version}</version>
<scope>compile</scope>
</dependency>

View File

@ -5,9 +5,9 @@
<groupId>com.baeldung</groupId>
<artifactId>azure</artifactId>
<version>0.1</version>
<packaging>war</packaging>
<name>azure</name>
<description>Demo project for Spring Boot on Azure</description>
<packaging>war</packaging>
<parent>
<artifactId>parent-boot-2</artifactId>
@ -127,7 +127,6 @@
<docker.image.prefix>${azure.containerRegistry}.azurecr.io</docker.image.prefix>
<docker-maven-plugin.version>1.1.0</docker-maven-plugin.version>
<azure-webapp-maven-plugin.version>1.1.0</azure-webapp-maven-plugin.version>
<java.version>1.8</java.version>
</properties>
</project>

5
blade/README.md Normal file
View File

@ -0,0 +1,5 @@
### Relevant Articles:
- [Blade - A Complete GuideBook](http://www.baeldung.com/blade)
Run Integration Tests with `mvn integration-test`

205
blade/pom.xml Normal file
View File

@ -0,0 +1,205 @@
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- WITH THIS mvn integration-test DOES WORK -->
<groupId>com.baeldung</groupId>
<artifactId>blade</artifactId>
<version>1.0.0-SNAPSHOT</version>
<name>blade</name>
<!-- WITH THIS mvn integration-test DOESN'T WORK -->
<!-- <parent> -->
<!-- <groupId>com.baeldung</groupId> -->
<!-- <artifactId>parent-modules</artifactId> -->
<!-- <version>1.0.0-SNAPSHOT</version> -->
<!-- </parent> -->
<dependencies>
<dependency>
<groupId>com.bladejava</groupId>
<artifactId>blade-mvc</artifactId>
<version>${blade-mvc.version}</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>${bootstrap.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<!-- PROVIDED -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!-- TEST -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>${httpclient.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>${httpmime.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>${httpcore.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>sample-blade-app</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>${maven-surefire-plugin.version}</version>
<configuration>
<forkCount>3</forkCount>
<reuseForks>true</reuseForks>
<excludes>
<exclude>**/*LiveTest.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven-failsafe-plugin.version}</version>
<configuration>
<includes>
<include>**/*LiveTest.java</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>com.bazaarvoice.maven.plugins</groupId>
<artifactId>process-exec-maven-plugin</artifactId>
<version>${process-exec-maven-plugin.version}</version>
<executions>
<!--Start Blade -->
<execution>
<id>blade-process</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
<configuration>
<name>Blade</name>
<waitForInterrupt>false</waitForInterrupt>
<arguments>
<argument>java</argument>
<argument>-jar</argument>
<argument>sample-blade-app.jar</argument>
</arguments>
</configuration>
</execution>
<!--Stop all processes in reverse order -->
<execution>
<id>stop-all</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop-all</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<finalName>${project.build.finalName}</finalName>
<appendAssemblyId>false</appendAssemblyId>
<archive>
<manifest>
<mainClass>com.baeldung.blade.sample.App</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
<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>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<blade-mvc.version>2.0.14.RELEASE</blade-mvc.version>
<bootstrap.version>4.2.1</bootstrap.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<lombok.version>1.18.4</lombok.version>
<junit.version>4.12</junit.version>
<httpclient.version>4.5.6</httpclient.version>
<httpmime.version>4.5.6</httpmime.version>
<httpcore.version>4.4.10</httpcore.version>
<assertj-core.version>3.11.1</assertj-core.version>
<maven-failsafe-plugin.version>3.0.0-M3</maven-failsafe-plugin.version>
<process-exec-maven-plugin.version>0.7</process-exec-maven-plugin.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
</properties>
</project>

View File

@ -0,0 +1,38 @@
package com.baeldung.blade.sample;
import com.baeldung.blade.sample.interceptors.BaeldungMiddleware;
import com.blade.Blade;
import com.blade.event.EventType;
import com.blade.mvc.WebContext;
import com.blade.mvc.http.Session;
public class App {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(App.class);
public static void main(String[] args) {
Blade.of()
.get("/", ctx -> ctx.render("index.html"))
.get("/basic-route-example", ctx -> ctx.text("GET called"))
.post("/basic-route-example", ctx -> ctx.text("POST called"))
.put("/basic-route-example", ctx -> ctx.text("PUT called"))
.delete("/basic-route-example", ctx -> ctx.text("DELETE called"))
.addStatics("/custom-static")
// .showFileList(true)
.enableCors(true)
.before("/user/*", ctx -> log.info("[NarrowedHook] Before '/user/*', URL called: " + ctx.uri()))
.on(EventType.SERVER_STARTED, e -> {
String version = WebContext.blade()
.env("app.version")
.orElse("N/D");
log.info("[Event::serverStarted] Loading 'app.version' from configuration, value: " + version);
})
.on(EventType.SESSION_CREATED, e -> {
Session session = (Session) e.attribute("session");
session.attribute("mySessionValue", "Baeldung");
})
.use(new BaeldungMiddleware())
.start(App.class, args);
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.blade.sample;
import com.blade.mvc.annotation.GetRoute;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.blade.mvc.http.Session;
@Path
public class AttributesExampleController {
public final static String REQUEST_VALUE = "Some Request value";
public final static String SESSION_VALUE = "1337";
public final static String HEADER = "Some Header";
@GetRoute("/request-attribute-example")
public void getRequestAttribute(Request request, Response response) {
request.attribute("request-val", REQUEST_VALUE);
String requestVal = request.attribute("request-val");
response.text(requestVal);
}
@GetRoute("/session-attribute-example")
public void getSessionAttribute(Request request, Response response) {
Session session = request.session();
session.attribute("session-val", SESSION_VALUE);
String sessionVal = session.attribute("session-val");
response.text(sessionVal);
}
@GetRoute("/header-example")
public void getHeader(Request request, Response response) {
String headerVal = request.header("a-header", HEADER);
response.header("a-header", headerVal);
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.blade.sample;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.Route;
import com.blade.mvc.http.Response;
@Path
public class LogExampleController {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleController.class);
@Route(value = "/test-logs")
public void testLogs(Response response) {
log.trace("This is a TRACE Message");
log.debug("This is a DEBUG Message");
log.info("This is an INFO Message");
log.warn("This is a WARN Message");
log.error("This is an ERROR Message");
response.text("Check in ./logs");
}
}

View File

@ -0,0 +1,71 @@
package com.baeldung.blade.sample;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import com.baeldung.blade.sample.vo.User;
import com.blade.mvc.annotation.CookieParam;
import com.blade.mvc.annotation.GetRoute;
import com.blade.mvc.annotation.HeaderParam;
import com.blade.mvc.annotation.JSON;
import com.blade.mvc.annotation.MultipartParam;
import com.blade.mvc.annotation.Param;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.PathParam;
import com.blade.mvc.annotation.PostRoute;
import com.blade.mvc.http.Response;
import com.blade.mvc.multipart.FileItem;
import com.blade.mvc.ui.RestResponse;
@Path
public class ParameterInjectionExampleController {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ParameterInjectionExampleController.class);
@GetRoute("/params/form")
public void formParam(@Param String name, Response response) {
log.info("name: " + name);
response.text(name);
}
@GetRoute("/params/path/:uid")
public void restfulParam(@PathParam Integer uid, Response response) {
log.info("uid: " + uid);
response.text(String.valueOf(uid));
}
@PostRoute("/params-file") // DO NOT USE A SLASH WITHIN THE ROUTE OR IT WILL BREAK (?)
@JSON
public RestResponse<?> fileParam(@MultipartParam FileItem fileItem) throws Exception {
try {
byte[] fileContent = fileItem.getData();
log.debug("Saving the uploaded file");
java.nio.file.Path tempFile = Files.createTempFile("baeldung_tempfiles", ".tmp");
Files.write(tempFile, fileContent, StandardOpenOption.WRITE);
return RestResponse.ok();
} catch (Exception e) {
log.error(e.getMessage(), e);
return RestResponse.fail(e.getMessage());
}
}
@GetRoute("/params/header")
public void headerParam(@HeaderParam String customheader, Response response) {
log.info("Custom header: " + customheader);
response.text(customheader);
}
@GetRoute("/params/cookie")
public void cookieParam(@CookieParam(defaultValue = "default value") String myCookie, Response response) {
log.info("myCookie: " + myCookie);
response.text(myCookie);
}
@PostRoute("/params/vo")
public void voParam(@Param User user, Response response) {
log.info("user as voParam: " + user.toString());
response.html(user.toString() + "<br/><br/><a href='/'>Back</a>");
}
}

View File

@ -0,0 +1,78 @@
package com.baeldung.blade.sample;
import com.baeldung.blade.sample.configuration.BaeldungException;
import com.blade.mvc.WebContext;
import com.blade.mvc.annotation.DeleteRoute;
import com.blade.mvc.annotation.GetRoute;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.PostRoute;
import com.blade.mvc.annotation.PutRoute;
import com.blade.mvc.annotation.Route;
import com.blade.mvc.http.HttpMethod;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
@Path
public class RouteExampleController {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(RouteExampleController.class);
@GetRoute("/route-example")
public String get() {
return "get.html";
}
@PostRoute("/route-example")
public String post() {
return "post.html";
}
@PutRoute("/route-example")
public String put() {
return "put.html";
}
@DeleteRoute("/route-example")
public String delete() {
return "delete.html";
}
@Route(value = "/another-route-example", method = HttpMethod.GET)
public String anotherGet() {
return "get.html";
}
@Route(value = "/allmatch-route-example")
public String allmatch() {
return "allmatch.html";
}
@Route(value = "/triggerInternalServerError")
public void triggerInternalServerError() {
int x = 1 / 0;
}
@Route(value = "/triggerBaeldungException")
public void triggerBaeldungException() throws BaeldungException {
throw new BaeldungException("Foobar Exception to threat differently");
}
@Route(value = "/user/foo")
public void urlCoveredByNarrowedWebhook(Response response) {
response.text("Check out for the WebHook covering '/user/*' in the logs");
}
@GetRoute("/load-configuration-in-a-route")
public void loadConfigurationInARoute(Response response) {
String authors = WebContext.blade()
.env("app.authors", "Unknown authors");
log.info("[/load-configuration-in-a-route] Loading 'app.authors' from configuration, value: " + authors);
response.render("index.html");
}
@GetRoute("/template-output-test")
public void templateOutputTest(Request request, Response response) {
request.attribute("name", "Blade");
response.render("template-output-test.html");
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.blade.sample.configuration;
public class BaeldungException extends RuntimeException {
public BaeldungException(String message) {
super(message);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.blade.sample.configuration;
import com.blade.ioc.annotation.Bean;
import com.blade.mvc.WebContext;
import com.blade.mvc.handler.DefaultExceptionHandler;
@Bean
public class GlobalExceptionHandler extends DefaultExceptionHandler {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(GlobalExceptionHandler.class);
@Override
public void handle(Exception e) {
if (e instanceof BaeldungException) {
Exception baeldungException = (BaeldungException) e;
String msg = baeldungException.getMessage();
log.error("[GlobalExceptionHandler] Intercepted an exception to threat with additional logic. Error message: " + msg);
WebContext.response()
.render("index.html");
} else {
super.handle(e);
}
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.blade.sample.configuration;
import com.blade.Blade;
import com.blade.ioc.annotation.Bean;
import com.blade.loader.BladeLoader;
import com.blade.mvc.WebContext;
@Bean
public class LoadConfig implements BladeLoader {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LoadConfig.class);
@Override
public void load(Blade blade) {
String version = WebContext.blade()
.env("app.version")
.orElse("N/D");
String authors = WebContext.blade()
.env("app.authors", "Unknown authors");
log.info("[LoadConfig] loaded 'app.version' (" + version + ") and 'app.authors' (" + authors + ") in a configuration bean");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.blade.sample.configuration;
import com.blade.ioc.annotation.Bean;
import com.blade.task.annotation.Schedule;
@Bean
public class ScheduleExample {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ScheduleExample.class);
@Schedule(name = "baeldungTask", cron = "0 */1 * * * ?")
public void runScheduledTask() {
log.info("[ScheduleExample] This is a scheduled Task running once per minute.");
}
}

View File

@ -0,0 +1,17 @@
package com.baeldung.blade.sample.interceptors;
import com.blade.ioc.annotation.Bean;
import com.blade.mvc.RouteContext;
import com.blade.mvc.hook.WebHook;
@Bean
public class BaeldungHook implements WebHook {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BaeldungHook.class);
@Override
public boolean before(RouteContext ctx) {
log.info("[BaeldungHook] called before Route method");
return true;
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.blade.sample.interceptors;
import com.blade.mvc.RouteContext;
import com.blade.mvc.hook.WebHook;
public class BaeldungMiddleware implements WebHook {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(BaeldungMiddleware.class);
@Override
public boolean before(RouteContext context) {
log.info("[BaeldungMiddleware] called before Route method and other WebHooks");
return true;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.blade.sample.vo;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import lombok.Getter;
import lombok.Setter;
public class User {
@Getter @Setter private String name;
@Getter @Setter private String site;
@Override
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}

View File

@ -0,0 +1,5 @@
mvc.statics.show-list=true
mvc.view.404=my-404.html
mvc.view.500=my-500.html
app.version=0.0.1
app.authors=Andrea Ligios

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 650 B

View File

@ -0,0 +1 @@
/* App CSS */

View File

@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1>File Upload and download test</h1>
<form id="uploadForm" enctype="multipart/form-data">
<input id="file" type="file" name="file" />
<button id="upload" type="button">Upload</button>
</form>
<br />
<a href="/">Back</a>
<script>
var data = new FormData();
$('#upload').click(function() {
$.ajax({
url : '/params-file',
type : 'POST',
cache : false,
data : new FormData($('#uploadForm')[0]),
processData : false,
contentType : false
}).done(function(res) {
console.log(res);
if (res.success) {
alert('Ok');
} else {
alert(res.msg || 'Error');
}
}).fail(function(res) {
});
});
</script>
</body>
</html>

View File

@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h1>User POJO post test</h1>
<form id="uploadForm" action="/params/vo" method="post">
<span>Person POJO:</span>
<input type="text" name="name" placeholder="name"/>
<input type="text" name="site" placeholder="site"/>
<button id="upload" type="submit">Send user object</button>
</form>
<br />
<a href="/">Back</a>
</body>
</html>

View File

@ -0,0 +1 @@
ALLMATCH called

View File

@ -0,0 +1 @@
DELETE called

View File

@ -0,0 +1 @@
GET called

View File

@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Baeldung Blade App • Written by Andrea Ligios</title>
<link href="/static/app.css" rel="stylesheet" />
</head>
<body>
<h1>Baeldung Blade App - Showcase</h1>
<h3>Manual tests</h3>
<p>The following are tests which are not covered by integration tests, but that can be run manually in order to check the functionality, either in the browser or in the logs, depending on the case.</p>
<ul>
<li><a href="/static/file-upload.html">File Upload</a></li>
<li><a href="/static/user-post.html">User POJO Post</a></li>
<li><a href="/user/foo">Webhook narrowed to the '/user/*' URL</a></li>
<li><a href="/load-configuration-in-a-route">Load Configuration in a Route</a></li>
<li><a href="/triggerInternalServerError">Trigger internal server error (and test the custom error 500 page)</a></li>
<li><a href="/triggerBaeldungException">Trigger BaeldungException (and test the Global Exception Handler)</a></li>
</ul>
<h3>Session value created in App.java</h3>
<p>mySessionValue = ${mySessionValue}</p>
<script src="/static/app.js"></script>
</body>
</html>

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>404 Not found</title>
</head>
<body>
Custom Error 404 Page
</body>
</html>

View File

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>500 Internal Server Error</title>
</head>
<body>
<h1> Custom Error 500 Page </h1>
<p> The following error occurred "<strong>${message}</strong>"</p>
<pre> ${stackTrace} </pre>
</body>
</html>

View File

@ -0,0 +1 @@
POST called

View File

@ -0,0 +1 @@
PUT called

View File

@ -0,0 +1 @@
<h1>Hello, ${name}!</h1>

View File

@ -0,0 +1,56 @@
package com.baeldung.blade.sample;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class AppLiveTest {
@Test
public void givenBasicRoute_whenGet_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/basic-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("GET called");
}
}
@Test
public void givenBasicRoute_whenPost_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPost("http://localhost:9000/basic-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("POST called");
}
}
@Test
public void givenBasicRoute_whenPut_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPut("http://localhost:9000/basic-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("PUT called");
}
}
@Test
public void givenBasicRoute_whenDelete_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpDelete("http://localhost:9000/basic-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("DELETE called");
}
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.blade.sample;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class AttributesExampleControllerLiveTest {
@Test
public void givenRequestAttribute_whenSet_thenRetrieveWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/request-attribute-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo(AttributesExampleController.REQUEST_VALUE);
}
}
@Test
public void givenSessionAttribute_whenSet_thenRetrieveWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/session-attribute-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo(AttributesExampleController.SESSION_VALUE);
}
}
@Test
public void givenHeader_whenSet_thenRetrieveWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/header-example");
request.addHeader("a-header","foobar");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(httpResponse.getHeaders("a-header")[0].getValue()).isEqualTo("foobar");
}
}
@Test
public void givenNoHeader_whenSet_thenRetrieveDefaultValueWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/header-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(httpResponse.getHeaders("a-header")[0].getValue()).isEqualTo(AttributesExampleController.HEADER);
}
}
}

View File

@ -0,0 +1,82 @@
package com.baeldung.blade.sample;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class ParameterInjectionExampleControllerLiveTest {
@Test
public void givenFormParam_whenSet_thenRetrieveWithGet() throws Exception {
URIBuilder builder = new URIBuilder("http://localhost:9000/params/form");
builder.setParameter("name", "Andrea Ligios");
final HttpUriRequest request = new HttpGet(builder.build());
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("Andrea Ligios");
}
}
@Test
public void givenPathParam_whenSet_thenRetrieveWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/params/path/1337");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("1337");
}
}
// @Test
// public void givenFileParam_whenSet_thenRetrieveWithGet() throws Exception {
//
// byte[] data = "this is some temp file content".getBytes("UTF-8");
// java.nio.file.Path tempFile = Files.createTempFile("baeldung_test_tempfiles", ".tmp");
// Files.write(tempFile, data, StandardOpenOption.WRITE);
//
// //HttpEntity entity = MultipartEntityBuilder.create().addPart("file", new FileBody(tempFile.toFile())).build();
// HttpEntity entity = MultipartEntityBuilder.create().addTextBody("field1", "value1")
// .addBinaryBody("fileItem", tempFile.toFile(), ContentType.create("application/octet-stream"), "file1.txt").build();
//
// final HttpPost post = new HttpPost("http://localhost:9000/params-file");
// post.setEntity(entity);
//
// try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create().build().execute(post);) {
// assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("file1.txt");
// }
// }
@Test
public void givenHeader_whenSet_thenRetrieveWithGet() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/params/header");
request.addHeader("customheader", "foobar");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("foobar");
}
}
@Test
public void givenNoCookie_whenCalled_thenReadDefaultValue() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/params/cookie");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("default value");
}
}
}

View File

@ -0,0 +1,117 @@
package com.baeldung.blade.sample;
import static org.assertj.core.api.Assertions.assertThat;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
public class RouteExampleControllerLiveTest {
@Test
public void givenRoute_whenGet_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("GET called");
}
}
@Test
public void givenRoute_whenPost_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPost("http://localhost:9000/route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("POST called");
}
}
@Test
public void givenRoute_whenPut_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPut("http://localhost:9000/route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("PUT called");
}
}
@Test
public void givenRoute_whenDelete_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpDelete("http://localhost:9000/route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("DELETE called");
}
}
@Test
public void givenAnotherRoute_whenGet_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/another-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("GET called");
}
}
@Test
public void givenAllMatchRoute_whenGet_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/allmatch-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
}
}
@Test
public void givenAllMatchRoute_whenPost_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPost("http://localhost:9000/allmatch-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
}
}
@Test
public void givenAllMatchRoute_whenPut_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpPut("http://localhost:9000/allmatch-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
}
}
@Test
public void givenAllMatchRoute_whenDelete_thenCorrectOutput() throws Exception {
final HttpUriRequest request = new HttpDelete("http://localhost:9000/allmatch-route-example");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("ALLMATCH called");
}
}
@Test
public void givenRequestAttribute_whenRenderedWithTemplate_thenCorrectlyEvaluateIt() throws Exception {
final HttpUriRequest request = new HttpGet("http://localhost:9000/template-output-test");
try (final CloseableHttpResponse httpResponse = HttpClientBuilder.create()
.build()
.execute(request);) {
assertThat(EntityUtils.toString(httpResponse.getEntity())).isEqualTo("<h1>Hello, Blade!</h1>");
}
}
}

View File

@ -3,9 +3,9 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung.bootique</groupId>
<artifactId>bootique</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>bootique</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>

View File

@ -3,9 +3,9 @@
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>cas-secured-app</artifactId>
<packaging>jar</packaging>
<name>cas-secured-app</name>
<description>Demo project for CAS</description>
<packaging>jar</packaging>
<parent>
<artifactId>parent-boot-1</artifactId>

21
cas/pom.xml Normal file
View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
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>cas</artifactId>
<name>cas</name>
<packaging>pom</packaging>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>..</relativePath>
</parent>
<modules>
<module>cas-secured-app</module>
<module>cas-server</module>
</modules>
</project>

View File

@ -59,13 +59,13 @@
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<cdi-api.version>2.0.SP1</cdi-api.version>
<weld-se-core.version>3.0.5.Final</weld-se-core.version>
<aspectjweaver.version>1.9.2</aspectjweaver.version>
<hamcrest-core.version>1.3</hamcrest-core.version>
<assertj-core.version>3.10.0</assertj-core.version>
<junit.version>4.12</junit.version>
<spring.version>5.1.2.RELEASE</spring.version>
</properties>
</project>

View File

@ -3,9 +3,9 @@
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>checker-plugin</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>checker-plugin</name>
<packaging>jar</packaging>
<url>http://maven.apache.org</url>
<parent>

View File

@ -4,3 +4,7 @@
- [JDBC with Groovy](http://www.baeldung.com/jdbc-groovy)
- [Working with JSON in Groovy](http://www.baeldung.com/groovy-json)
- [Reading a File in Groovy](https://www.baeldung.com/groovy-file-read)
- [Types of Strings in Groovy](https://www.baeldung.com/groovy-strings)
- [A Quick Guide to Iterating a Map in Groovy](https://www.baeldung.com/groovy-map-iterating)
- [An Introduction to Traits in Groovy](https://www.baeldung.com/groovy-traits)

View File

@ -23,6 +23,12 @@
<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>
@ -103,9 +109,12 @@
<properties>
<junit.platform.version>1.0.0</junit.platform.version>
<groovy.version>2.4.13</groovy.version>
<groovy-all.version>2.4.13</groovy-all.version>
<groovy-sql.version>2.4.13</groovy-sql.version>
<!-- <groovy.version>2.4.13</groovy.version> -->
<!-- <groovy-all.version>2.4.13</groovy-all.version> -->
<!-- <groovy-sql.version>2.4.13</groovy-sql.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>

View File

@ -0,0 +1,107 @@
package com.baeldung.file
class ReadFile {
/**
* reads file content line by line using withReader and reader.readLine
* @param filePath
* @return
*/
int readFileLineByLine(String filePath) {
File file = new File(filePath)
def line, noOfLines = 0;
file.withReader { reader ->
while ((line = reader.readLine())!=null)
{
println "${line}"
noOfLines++
}
}
return noOfLines
}
/**
* reads file content in list of lines
* @param filePath
* @return
*/
List<String> readFileInList(String filePath) {
File file = new File(filePath)
def lines = file.readLines()
return lines
}
/**
* reads file content in string using File.text
* @param filePath
* @return
*/
String readFileString(String filePath) {
File file = new File(filePath)
String fileContent = file.text
return fileContent
}
/**
* reads file content in string with encoding using File.getText
* @param filePath
* @return
*/
String readFileStringWithCharset(String filePath) {
File file = new File(filePath)
String utf8Content = file.getText("UTF-8")
return utf8Content
}
/**
* reads content of binary file and returns byte array
* @param filePath
* @return
*/
byte[] readBinaryFile(String filePath) {
File file = new File(filePath)
byte[] binaryContent = file.bytes
return binaryContent
}
/**
* More Examples of reading a file
* @return
*/
def moreExamples() {
//with reader with utf-8
new File("src/main/resources/utf8Content.html").withReader('UTF-8') { reader ->
def line
while ((line = reader.readLine())!=null) {
println "${line}"
}
}
//collect api
def list = new File("src/main/resources/fileContent.txt").collect {it}
//as operator
def array = new File("src/main/resources/fileContent.txt") as String[]
//eachline
new File("src/main/resources/fileContent.txt").eachLine { line ->
println line
}
//newInputStream with eachLine
def is = new File("src/main/resources/fileContent.txt").newInputStream()
is.eachLine {
println it
}
is.close()
//withInputStream
new File("src/main/resources/fileContent.txt").withInputStream { stream ->
stream.eachLine { line ->
println line
}
}
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.io
class Task implements Serializable {
String description
Date startDate
Date dueDate
int status
}

View File

@ -0,0 +1,43 @@
package com.baeldung.strings;
class Concatenate {
String first = 'Hello'
String last = 'Groovy'
String doSimpleConcat() {
return 'My name is ' + first + ' ' + last
}
String doConcatUsingGString() {
return "My name is $first $last"
}
String doConcatUsingGStringClosures() {
return "My name is ${-> first} ${-> last}"
}
String doConcatUsingStringConcatMethod() {
return 'My name is '.concat(first).concat(' ').concat(last)
}
String doConcatUsingLeftShiftOperator() {
return 'My name is ' << first << ' ' << last
}
String doConcatUsingArrayJoinMethod() {
return ['My name is', first, last].join(' ')
}
String doConcatUsingArrayInjectMethod() {
return [first,' ', last]
.inject(new StringBuffer('My name is '), { initial, name -> initial.append(name); return initial }).toString()
}
String doConcatUsingStringBuilder() {
return new StringBuilder().append('My name is ').append(first).append(' ').append(last)
}
String doConcatUsingStringBuffer() {
return new StringBuffer().append('My name is ').append(first).append(' ').append(last)
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.traits
trait AnimalTrait {
String basicBehavior() {
return "Animalistic!!"
}
}

View File

@ -0,0 +1,3 @@
package com.baeldung
class Car implements VehicleTrait {}

View File

@ -0,0 +1,9 @@
package com.baeldung.traits
class Dog implements WalkingTrait, SpeakingTrait {
String speakAndWalk() {
WalkingTrait.super.speakAndWalk()
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.traits
class Employee implements UserTrait {
String name() {
return 'Bob'
}
String lastName() {
return "Marley"
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.traits
interface Human {
String lastName()
}

View File

@ -0,0 +1,13 @@
package com.baeldung.traits
trait SpeakingTrait {
String basicAbility() {
return "Speaking!!"
}
String speakAndWalk() {
return "Speak and walk!!"
}
}

View File

@ -0,0 +1,36 @@
package com.baeldung.traits
trait UserTrait implements Human {
String sayHello() {
return "Hello!"
}
abstract String name()
String showName() {
return "Hello, ${name()}!"
}
private String greetingMessage() {
return 'Hello, from a private method!'
}
String greet() {
def msg = greetingMessage()
println msg
msg
}
def self() {
return this
}
String showLastName() {
return "Hello, ${lastName()}!"
}
String email
String address
}

View File

@ -0,0 +1,9 @@
package com.baeldung
trait VehicleTrait extends WheelTrait {
String showWheels() {
return "Num of Wheels $noOfWheels"
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.traits
trait WalkingTrait {
String basicAbility() {
return "Walking!!"
}
String speakAndWalk() {
return "Walk and speak!!"
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung
trait WheelTrait {
int noOfWheels
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View File

@ -0,0 +1,3 @@
Line 1 : Hello World!!!
Line 2 : This is a file content.
Line 3 : String content

Binary file not shown.

View File

@ -0,0 +1,4 @@
First line of text
Second line of text
Third line of text
Fourth line of text

View File

@ -0,0 +1,3 @@
Line one of output example
Line two of output example
Line three of output example

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 329 B

View File

@ -0,0 +1,12 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta charset="UTF-8">
<body>
<pre>
ᚠᛇᚻ᛫ᛒᛦᚦ᛫ᚠᚱᚩᚠᚢᚱ᛫ᚠᛁᚱᚪ᛫ᚷᛖᚻᚹᛦᛚᚳᚢᛗ
ᛋᚳᛖᚪᛚ᛫ᚦᛖᚪᚻ᛫ᛗᚪᚾᚾᚪ᛫ᚷᛖᚻᚹᛦᛚᚳ᛫ᛗᛁᚳᛚᚢᚾ᛫ᚻᛦᛏ᛫ᛞᚫᛚᚪᚾ
ᚷᛁᚠ᛫ᚻᛖ᛫ᚹᛁᛚᛖ᛫ᚠᚩᚱ᛫ᛞᚱᛁᚻᛏᚾᛖ᛫ᛞᚩᛗᛖᛋ᛫ᚻᛚᛇᛏᚪᚾ
</pre>
</body>
</html>

View File

@ -0,0 +1,57 @@
package com.baeldung.groovy.sql
import static org.junit.Assert.*
import java.util.Calendar.*
import java.time.LocalDate
import java.text.SimpleDateFormat
import org.junit.Test
class DateTest {
def dateStr = "2019-02-28"
def pattern = "yyyy-MM-dd"
@Test
void whenGetStringRepresentation_thenCorrectlyConvertIntoDate() {
def dateFormat = new SimpleDateFormat(pattern)
def date = dateFormat.parse(dateStr)
println(" String to Date with DateFormatter : " + date)
def cal = new GregorianCalendar();
cal.setTime(date);
assertEquals(cal.get(Calendar.YEAR),2019)
assertEquals(cal.get(Calendar.DAY_OF_MONTH),28)
assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY)
}
@Test
void whenGetStringRepresentation_thenCorrectlyConvertWithDateUtilsExtension() {
def date = Date.parse(pattern, dateStr)
println(" String to Date with Date.parse : " + date)
def cal = new GregorianCalendar();
cal.setTime(date);
assertEquals(cal.get(Calendar.YEAR),2019)
assertEquals(cal.get(Calendar.DAY_OF_MONTH),28)
assertEquals(cal.get(Calendar.MONTH),java.util.Calendar.FEBRUARY)
}
@Test
void whenGetStringRepresentation_thenCorrectlyConvertIntoDateWithLocalDate() {
def date = LocalDate.parse(dateStr, pattern)
println(" String to Date with LocalDate : " + date)
assertEquals(date.getYear(),2019)
assertEquals(date.getMonth(),java.time.Month.FEBRUARY)
assertEquals(date.getDayOfMonth(),28)
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.file
import spock.lang.Specification
class ReadFileUnitTest extends Specification {
ReadFile readFile
void setup () {
readFile = new ReadFile()
}
def 'Should return number of lines in File using ReadFile.readFileLineByLine given filePath' () {
given:
def filePath = "src/main/resources/fileContent.txt"
when:
def noOfLines = readFile.readFileLineByLine(filePath)
then:
noOfLines
noOfLines instanceof Integer
assert noOfLines, 3
}
def 'Should return File Content in list of lines using ReadFile.readFileInList given filePath' () {
given:
def filePath = "src/main/resources/fileContent.txt"
when:
def lines = readFile.readFileInList(filePath)
then:
lines
lines instanceof List<String>
assert lines.size(), 3
}
def 'Should return file content in string using ReadFile.readFileString given filePath' () {
given:
def filePath = "src/main/resources/fileContent.txt"
when:
def fileContent = readFile.readFileString(filePath)
then:
fileContent
fileContent instanceof String
fileContent.contains("""Line 1 : Hello World!!!
Line 2 : This is a file content.
Line 3 : String content""")
}
def 'Should return UTF-8 encoded file content in string using ReadFile.readFileStringWithCharset given filePath' () {
given:
def filePath = "src/main/resources/utf8Content.html"
when:
def encodedContent = readFile.readFileStringWithCharset(filePath)
then:
encodedContent
encodedContent instanceof String
}
def 'Should return binary file content in byte array using ReadFile.readBinaryFile given filePath' () {
given:
def filePath = "src/main/resources/sample.png"
when:
def binaryContent = readFile.readBinaryFile(filePath)
then:
binaryContent
binaryContent instanceof byte[]
binaryContent.length == 329
}
}

View File

@ -0,0 +1,51 @@
package com.baeldung.io
import static org.junit.Assert.*
import org.junit.Test
class DataAndObjectsUnitTest {
@Test
void whenUsingWithDataOutputStream_thenDataIsSerializedToAFile() {
String message = 'This is a serialized string'
int length = message.length()
boolean valid = true
new File('src/main/resources/ioData.txt').withDataOutputStream { out ->
out.writeUTF(message)
out.writeInt(length)
out.writeBoolean(valid)
}
String loadedMessage = ""
int loadedLength
boolean loadedValid
new File('src/main/resources/ioData.txt').withDataInputStream { is ->
loadedMessage = is.readUTF()
loadedLength = is.readInt()
loadedValid = is.readBoolean()
}
assertEquals(message, loadedMessage)
assertEquals(length, loadedLength)
assertEquals(valid, loadedValid)
}
@Test
void whenUsingWithObjectOutputStream_thenObjectIsSerializedToFile() {
Task task = new Task(description:'Take out the trash', startDate:new Date(), status:0)
new File('src/main/resources/ioSerializedObject.txt').withObjectOutputStream { out ->
out.writeObject(task)
}
Task taskRead
new File('src/main/resources/ioSerializedObject.txt').withObjectInputStream { is ->
taskRead = is.readObject()
}
assertEquals(task.description, taskRead.description)
assertEquals(task.startDate, taskRead.startDate)
assertEquals(task.status, taskRead.status)
}
}

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