Compare commits

...

28 Commits

Author SHA1 Message Date
dependabot[bot]
f96c17f012 Bump chart.js from 2.9.3 to 2.9.4 in /spring-boot/thymeleaf-vue/client
Bumps [chart.js](https://github.com/chartjs/Chart.js) from 2.9.3 to 2.9.4.
- [Release notes](https://github.com/chartjs/Chart.js/releases)
- [Commits](https://github.com/chartjs/Chart.js/compare/v2.9.3...v2.9.4)

Signed-off-by: dependabot[bot] <support@github.com>
2021-05-24 20:46:10 +00:00
Tom Hombergs
a359a8d3f2 Merge pull request #83 from pratikdas/aws-spring-cloud-rds
added code for spring cloud jdbc for aws rds
2021-05-25 06:45:04 +10:00
Pratik Das
273111b0c6 removed jdbc 2021-05-21 15:51:24 +04:00
Pratik Das
bcd975e02f added rds code 2021-05-13 16:08:18 +04:00
Pratik Das
7fd1bdc29f added rds code 2021-05-13 15:56:32 +04:00
Tom Hombergs
4b69588894 Merge pull request #82 from pratikdas/aws-spring-cloud-messaging
code example aws-spring-cloud-messaging
2021-05-10 07:04:59 +10:00
Tom Hombergs
88936def38 Merge pull request #79 from pratikdas/patch-1
Update README.md to correct spelling of AWS
2021-05-08 07:24:59 +10:00
Tom Hombergs
caf96dd931 Merge pull request #78 from pratikdas/thread-dump-analyzer
Thread dump analyzer
2021-05-05 06:56:13 +10:00
Pratik Das
6b13e04aea Merge branch 'master' into aws-spring-cloud-messaging 2021-05-01 20:47:18 +04:00
Pratik Das
a9795c3298 modified build-all 2021-05-01 20:31:49 +04:00
Pratik Das
ecb2634a77 modified pom 2021-05-01 18:48:25 +04:00
Pratik Das
237a5a6441 added readme 2021-05-01 18:30:59 +04:00
Pratik Das
674d4feb17 code example aws-spring-cloud-messaging 2021-05-01 18:26:28 +04:00
Tom Hombergs
610906f891 Merge pull request #80 from saajn/actuator2
Examples for the Actuator article
2021-04-30 07:16:36 +10:00
Tom Hombergs
258f7fb137 Merge branch 'master' into actuator2 2021-04-30 07:05:14 +10:00
Tom Hombergs
475ef47881 Merge pull request #77 from silenum/feature/clean-unit-tests-with-mockito
added code examples for clean unit tests with mockito
2021-04-25 10:35:17 +10:00
Saajan
39c28dddf0 Moved the counter 2021-04-24 20:24:25 +05:30
Saajan
2b8664e49e Added module to build-all 2021-04-24 19:56:12 +05:30
Saajan
d0c5706133 Initial check in 2021-04-24 19:43:07 +05:30
Pratik Das
cd45701470 Update README.md
Important::Correction in the spelling of AWS.
2021-04-22 05:24:29 +04:00
Tom Hombergs
070ad968e6 Merge pull request #76 from pratikdas/aws-terraform
updated git ignore to exclude DS-Store and uploaded Terraform aws source
2021-04-21 07:57:15 +10:00
Pratik Das
c29993b416 thread dump example 2021-04-20 18:17:31 +04:00
Pratik Das
a481a48992 thread dump example 2021-04-20 18:05:48 +04:00
Pratik Das
3be0e85a77 thread dumo example 2021-04-20 17:46:27 +04:00
Lukas Leuenberger
973cb7a081 updated build-all.sh for mockito 2021-04-20 00:02:06 +02:00
Lukas Leuenberger
33dacb36de added code examples for clean unit tests with mockito 2021-04-20 00:02:06 +02:00
Pratik Das
aaa07d4c70 added README 2021-04-16 16:24:21 +04:00
Pratik Das
23cd4e4da7 updated git ignore 2021-04-16 16:01:29 +04:00
149 changed files with 7601 additions and 7 deletions

2
.gitignore vendored
View File

@@ -1,3 +1,5 @@
**/.idea/
**/*.iml
**/.DS_Store
**/.terraform

View File

@@ -0,0 +1,11 @@
# Terraform for creating AWS Resources
Example code to create/update AWS resources with Terraform.
Examples include Terraform capabilities of using modules, input variables and using Terraform cloud.
## Blog posts
Blog posts about this topic:
* [Using Terraform to create AWS resources](https://reflectoring.io/terraform-aws/)

View File

@@ -0,0 +1,41 @@
terraform {
backend "remote" {
hostname = "app.terraform.io"
organization = "pratikorg"
token = "pj7p59JFwSC4jQ.atlasv1.qfmTxLjTfaM5zKyaQrcGzuTojv6oCyLIoIAO7DkA2ieQY7OyINjINGGMiTczt62p1bs"
workspaces {
name = "my-tf-workspace"
}
}
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.36"
}
}
}
provider "aws" {
profile = "default"
region = "us-west-2"
}
module "app_server" {
source = "./modules/application"
ec2_instance_type = "t2.micro"
ami = "ami-830c94e3"
tags = {
Name = "server for web"
Env = "dev"
}
}
module "app_storage" {
source = "./modules/storage/"
bucket_name = "io.pratik.tf-example-bucket"
env = "dev"
}

View File

@@ -0,0 +1,5 @@
resource "aws_instance" "vm-web" {
ami = var.ami
instance_type = var.ec2_instance_type
tags = var.tags
}

View File

@@ -0,0 +1,4 @@
output "instanceID" {
description = "ID of ec2 instance"
value = aws_instance.vm-web.id
}

View File

@@ -0,0 +1,16 @@
variable "ec2_instance_type" {
description = "Instance type"
type = string
}
variable "ami" {
description = "ami id"
type = string
}
variable "tags" {
description = "Tags to set on the bucket."
type = map(string)
default = {Name = "server for web"
Env = "dev"}
}

View File

@@ -0,0 +1,9 @@
resource "aws_s3_bucket" "s3_bucket" {
bucket = format("%s-%s",var.bucket_name,var.env)
acl = "private"
tags = {
Name = var.bucket_name
Environment = var.env
}
}

View File

@@ -0,0 +1,4 @@
output "arn" {
description = "ARN of the bucket"
value = aws_s3_bucket.s3_bucket.arn
}

View File

@@ -0,0 +1,13 @@
# Input variable definitions
variable "bucket_name" {
description = "Name of bucket"
type = string
}
variable "env" {
description = "Environment like dev, prod"
type = string
}

View File

@@ -0,0 +1,24 @@
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.27"
}
}
}
provider "aws" {
profile = "default"
region = "us-west-2"
}
resource "aws_instance" "vm-web" {
ami = "ami-830c94e3"
instance_type = var.ec2_instance_type
tags = {
Name = "server for web"
Env = "dev"
}
}

View File

@@ -0,0 +1 @@
ec2_instance_type = "t2.micro"

View File

@@ -0,0 +1,4 @@
variable "ec2_instance_type" {
description = "AWS EC2 instance type."
type = string
}

View File

@@ -0,0 +1,33 @@
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.36"
}
}
}
provider "aws" {
profile = "default"
region = "us-west-2"
}
module "app_server" {
source = "./modules/application"
ec2_instance_type = "t2.micro"
ami = "ami-830c94e3"
tags = {
Name = "server for web"
Env = "dev"
}
}
module "app_storage" {
source = "./modules/storage/"
bucket_name = "io.pratik.tf-example-bucket"
env = "dev"
}

View File

@@ -0,0 +1,5 @@
resource "aws_instance" "vm-web" {
ami = var.ami
instance_type = var.ec2_instance_type
tags = var.tags
}

View File

@@ -0,0 +1,4 @@
output "instanceID" {
description = "ID of ec2 instance"
value = aws_instance.vm-web.id
}

View File

@@ -0,0 +1,16 @@
variable "ec2_instance_type" {
description = "Instance type"
type = string
}
variable "ami" {
description = "ami id"
type = string
}
variable "tags" {
description = "Tags to set on the bucket."
type = map(string)
default = {Name = "server for web"
Env = "dev"}
}

View File

@@ -0,0 +1,9 @@
resource "aws_s3_bucket" "s3_bucket" {
bucket = format("%s-%s",var.bucket_name,var.env)
acl = "private"
tags = {
Name = var.bucket_name
Environment = var.env
}
}

View File

@@ -0,0 +1,4 @@
output "arn" {
description = "ARN of the bucket"
value = aws_s3_bucket.s3_bucket.arn
}

View File

@@ -0,0 +1,13 @@
# Input variable definitions
variable "bucket_name" {
description = "Name of bucket"
type = string
}
variable "env" {
description = "Environment like dev, prod"
type = string
}

View File

@@ -0,0 +1,24 @@
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.27"
}
}
}
provider "aws" {
profile = "default"
region = "us-west-2"
}
resource "aws_instance" "vm-web" {
ami = "ami-830c94e3"
instance_type = "t2.micro"
tags = {
Name = "server for web"
Env = "dev"
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

Binary file not shown.

View File

@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

View File

@@ -0,0 +1,10 @@
# Working with AWS RDS and Spring Cloud
Example code for using Spring Cloud AWS JDBC
## Blog posts
Blog posts about this topic:
* [Working with AWS RDS and Spring Cloud](https://reflectoring.io/spring-cloud-aws-rds/)

310
aws/springcloudrds/mvnw vendored Executable file
View File

@@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

182
aws/springcloudrds/mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@@ -0,0 +1,89 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>io.pratik</groupId>
<artifactId>springcloudrds</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springcloudrds</name>
<description>Demo project for Spring Cloud RDS</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-starter-aws-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-dependencies</artifactId>
<version>2.3.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,27 @@
/**
*
*/
package io.pratik.springcloudrds;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.awspring.cloud.jdbc.config.annotation.RdsInstanceConfigurer;
import io.awspring.cloud.jdbc.datasource.TomcatJdbcDataSourceFactory;
/**
* @author pratikdas
*
*/
@Configuration
public class ApplicationConfiguration {
@Bean
public RdsInstanceConfigurer instanceConfigurer() {
return ()-> {
TomcatJdbcDataSourceFactory dataSourceFactory = new TomcatJdbcDataSourceFactory();
dataSourceFactory.setInitialSize(10);
dataSourceFactory.setValidationQuery("SELECT 1 FROM DUAL");
return dataSourceFactory;
};
}
}

View File

@@ -0,0 +1,13 @@
package io.pratik.springcloudrds;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringcloudrdsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudrdsApplication.class, args);
}
}

View File

@@ -0,0 +1,58 @@
/**
*
*/
package io.pratik.springcloudrds;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* @author pratikdas
*
*/
@Service
public class SystemRepository {
private final JdbcTemplate jdbcTemplate;
@Autowired
public SystemRepository(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public String getCurrentDate() {
String result = jdbcTemplate.queryForObject("SELECT CURRENT_DATE FROM DUAL", new RowMapper<String>(){
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString(1);
}
});
return result;
}
@Transactional(readOnly = true)
public List<String> getUsers(){
List<String> result = jdbcTemplate.query("SELECT USER() FROM DUAL", new RowMapper<String>(){
@Override
public String mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString(1);
}
});
return result;
}
}

View File

@@ -0,0 +1,10 @@
cloud.aws.credentials.profile-name=pratikpoc
cloud.aws.region.auto=false
cloud.aws.region.static=us-east-1
cloud.aws.rds.instances[0].db-instance-identifier=testinstance
cloud.aws.rds.instances[0].username=pocadmin
cloud.aws.rds.instances[0].password=pocadmin
cloud.aws.rds.instances[0].databaseName=mysql
cloud.aws.rds.instances[0].readReplicaSupport=true

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/cloud/aws/jdbc"
xmlns:context="http://www.springframework.org/schema/cloud/aws/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cloud/aws/jdbc
http://www.springframework.org/schema/cloud/aws/jdbc/spring-cloud-aws-jdbc.xsd
http://www.springframework.org/schema/cloud/aws/context
http://www.springframework.org/schema/cloud/aws/context/spring-cloud-aws-context.xsd">
<jdbc:retry-interceptor
db-instance-identifier="testinstance"
id="interceptor"
max-number-of-retries="3"
amazon-rds="customRdsClient"/>
<bean id="customRdsClient" class="io.pratik.springcloudrds.SystemRepository" >
<constructor-arg value="com.amazonaws.services.rds.AmazonRDS"/>
</bean>
</beans>

View File

@@ -0,0 +1,19 @@
package io.pratik.springcloudrds;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringcloudrdsApplicationTests {
@Autowired
private SystemRepository systemRepository;
@Test
void testCurrentDate() {
String currentDate = systemRepository.getCurrentDate();
System.out.println("currentDate "+currentDate);
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

Binary file not shown.

View File

@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

View File

@@ -0,0 +1,10 @@
# Working with AWS SQS and Spring Cloud
Example code for using Spring Cloud AWS Messaging
## Blog posts
Blog posts about this topic:
* [Working with AWS SQS and Spring Cloud](https://reflectoring.io/spring-cloud-aws-sqs/)

310
aws/springcloudsqs/mvnw vendored Executable file
View File

@@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

182
aws/springcloudsqs/mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@@ -0,0 +1,67 @@
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>io.pratik</groupId>
<artifactId>springcloudsqs</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springcloudsqs</name>
<description>Demo project for Spring Cloud AWS SQS</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-starter-aws-messaging</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-dependencies</artifactId>
<version>2.3.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,53 @@
/**
*
*/
package io.pratik.springcloudsqs;
import java.util.Collections;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.converter.MessageConverter;
import org.springframework.messaging.handler.annotation.support.PayloadMethodArgumentResolver;
import com.amazonaws.services.sqs.AmazonSQSAsync;
import com.amazonaws.services.sqs.buffered.AmazonSQSBufferedAsyncClient;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.awspring.cloud.messaging.config.QueueMessageHandlerFactory;
import io.awspring.cloud.messaging.core.QueueMessagingTemplate;
/**
* @author pratikdas
*
*/
@Configuration
public class CustomSqsConfiguration {
@Bean
public QueueMessagingTemplate queueMessagingTemplate(AmazonSQSAsync amazonSQSAsync) {
return new QueueMessagingTemplate(amazonSQSAsync);
}
@Bean
public QueueMessageHandlerFactory queueMessageHandlerFactory(final ObjectMapper mapper,
final AmazonSQSAsync amazonSQSAsync) {
final QueueMessageHandlerFactory queueHandlerFactory = new QueueMessageHandlerFactory();
queueHandlerFactory.setAmazonSqs(amazonSQSAsync);
queueHandlerFactory.setArgumentResolvers(
Collections.singletonList(new PayloadMethodArgumentResolver(jackson2MessageConverter(mapper))));
return queueHandlerFactory;
}
private MessageConverter jackson2MessageConverter(final ObjectMapper mapper) {
final MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
// set strict content type match to false to enable the listener to handle AWS events
converter.setStrictContentTypeMatch(false);
converter.setObjectMapper(mapper);
return converter;
}
}

View File

@@ -0,0 +1,42 @@
/**
*
*/
package io.pratik.springcloudsqs;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;
import com.amazonaws.services.s3.event.S3EventNotification;
import io.awspring.cloud.messaging.listener.SqsMessageDeletionPolicy;
import io.awspring.cloud.messaging.listener.annotation.SqsListener;
import io.pratik.springcloudsqs.models.SignupEvent;
import lombok.extern.slf4j.Slf4j;
/**
* @author pratikdas
*
*/
@Slf4j
@Service
public class MessageReceiver {
@SqsListener(value = "testQueue", deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS )
public void receiveStringMessage(final String message,
@Header("SenderId") String senderId) {
log.info("message received {} {}",senderId,message);
}
@SqsListener(value = "testObjectQueue", deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS )
public void receiveObjectMessage(final SignupEvent message,
@Header("SenderId") String senderId) {
log.info("object message received {} {}",senderId,message);
}
@SqsListener(value = "testS3Queue", deletionPolicy = SqsMessageDeletionPolicy.ON_SUCCESS)
public void receiveS3Event(S3EventNotification s3EventNotificationRecord) {
S3EventNotification.S3Entity s3Entity = s3EventNotificationRecord.getRecords().get(0).getS3();
String objectKey = s3Entity.getObject().getKey();
log.info("s3 event::objectKey:: {}",objectKey);
}
}

View File

@@ -0,0 +1,52 @@
/**
*
*/
package io.pratik.springcloudsqs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.amazonaws.services.sqs.AmazonSQSAsync;
import io.awspring.cloud.messaging.core.QueueMessageChannel;
import io.awspring.cloud.messaging.core.QueueMessagingTemplate;
/**
* @author pratikdas
*
*/
@Service
public class MessageSender {
private static final Logger logger = LoggerFactory.getLogger(MessageSender.class);
private static final String QUEUE_NAME = "https://sqs.us-east-1.amazonaws.com/474715013863/testQueue";
@Autowired
private final AmazonSQSAsync amazonSqs;
@Autowired
public MessageSender(final AmazonSQSAsync amazonSQSAsync) {
this.amazonSqs = amazonSQSAsync;
}
public boolean send(final String messagePayload) {
MessageChannel messageChannel = new QueueMessageChannel(amazonSqs, QUEUE_NAME);
Message<String> msg = MessageBuilder.withPayload(messagePayload)
.setHeader("sender", "app1")
.setHeaderIfAbsent("country", "AE")
.build();
long waitTimeoutMillis = 5000;
boolean sentStatus = messageChannel.send(msg,waitTimeoutMillis);
logger.info("message sent");
return sentStatus;
}
}

View File

@@ -0,0 +1,45 @@
/**
*
*/
package io.pratik.springcloudsqs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import io.awspring.cloud.messaging.core.QueueMessagingTemplate;
import lombok.extern.slf4j.Slf4j;
/**
* @author pratikdas
*
*/
@Slf4j
@Service
public class MessageSenderWithTemplate {
private static final String TEST_QUEUE = "testQueue";
@Autowired
private QueueMessagingTemplate messagingTemplate;
public void send(final String messagePayload) {
Message<String> msg = MessageBuilder.withPayload(messagePayload)
.setHeader("sender", "app1")
.setHeaderIfAbsent("country", "AE")
.build();
messagingTemplate.convertAndSend(TEST_QUEUE, msg);
log.info("message sent");
}
public void sendToFifoQueue(final String messagePayload, final String messageGroupID, final String messageDedupID) {
Message<String> msg = MessageBuilder.withPayload(messagePayload)
.setHeader("message-group-id", messageGroupID)
.setHeader("message-deduplication-id", messageDedupID)
.build();
messagingTemplate.convertAndSend(TEST_QUEUE, msg);
log.info("message sent");
}
}

View File

@@ -0,0 +1,12 @@
package io.pratik.springcloudsqs;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringcloudsqsApplication {
public static void main(String[] args) {
SpringApplication.run(SpringcloudsqsApplication.class, args);
}
}

View File

@@ -0,0 +1,19 @@
/**
*
*/
package io.pratik.springcloudsqs.models;
import lombok.Data;
/**
* @author pratikdas
*
*/
@Data
public class SignupEvent {
private String signupTime;
private String userName;
private String email;
}

View File

@@ -0,0 +1,3 @@
cloud.aws.credentials.profile-name=default
cloud.aws.region.auto=false
cloud.aws.region.static=us-east-1

View File

@@ -0,0 +1,34 @@
package io.pratik.springcloudsqs;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringcloudsqsApplicationTests {
private static final Logger logger = LoggerFactory.getLogger(SpringcloudsqsApplicationTests.class.getName());
@Autowired
private MessageSender messageSender;
@Autowired
private MessageSenderWithTemplate messageSenderWithTemplate;
@Test
void contextLoads() {
}
void send_message_with_message_template() {
logger.info("test with message template.");
messageSenderWithTemplate.send("Test Message1");
}
@Test
void send_message_with_message_channel() {
logger.info("test with message channel.");
messageSender.send("Test msg");
}
}

View File

@@ -86,6 +86,10 @@ if [[ "$MODULE" == "module5" ]]
then
# ADD NEW MODULES HERE
# (add new modules above the rest so you get quicker feedback if it fails)
build_maven_module "aws/springcloudrds"
build_maven_module "aws/springcloudsqs"
build_maven_module "spring-boot/spring-boot-actuator"
build_maven_module "mockito"
build_maven_module "core-java/service-provider-interface"
build_gradle_module "spring-boot/hazelcast/hazelcast-embedded-cache"
build_gradle_module "spring-boot/hazelcast/hazelcast-client-server"
@@ -179,6 +183,7 @@ fi
if [[ "$MODULE" == "module4" ]]
then
build_maven_module "core-java/threaddump"
build_gradle_module "spring-boot/mocking"
build_gradle_module "spring-boot/modular"
build_gradle_module "spring-boot/paging"

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

Binary file not shown.

View File

@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

310
core-java/threaddump/mvnw vendored Executable file
View File

@@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

182
core-java/threaddump/mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@@ -0,0 +1,47 @@
<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>
<groupId>io.pratik.server</groupId>
<artifactId>ServerApp</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>ServerApp</name>
<url>http://maven.apache.org</url>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
</configuration>
</plugin>
<plugin>
<!-- Build an executable JAR -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<mainClass>io.pratik.server.App</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@@ -0,0 +1,21 @@
package io.pratik.server;
import java.net.ServerSocket;
import java.util.logging.Logger;
/**
* @author pratikdas
*
*/
public class App {
private static final Logger logger = Logger.getLogger(App.class.getName());
public static void main(String[] args) throws Exception {
ServerSocket ssock = new ServerSocket(8080);
logger.info("Server Started. Listening on port 8080");
while (true) {
new RequestProcessor(ssock).handleClientRequest();;
}
}
}

View File

@@ -0,0 +1,80 @@
/**
*
*/
package io.pratik.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* @author pratikdas
*
*/
public class RequestProcessor {
private static final Logger logger = Logger.getLogger(RequestProcessor.class.getName());
private ServerSocket serverSocket = null;
public RequestProcessor(final ServerSocket ssock) {
super();
this.serverSocket = ssock;
}
public void handleClientRequest() throws IOException {
try (Socket client = serverSocket.accept()) {
logger.info("Processing request from client " + client.getInetAddress().getHostAddress());
BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream()));
StringBuilder requestBuilder = new StringBuilder();
String line;
while (!(line = br.readLine()).isBlank()) {
requestBuilder.append(line + "\r\n");
}
String request = requestBuilder.toString();
String[] requestsLines = request.split("\r\n");
String[] requestLine = requestsLines[0].split(" ");
String method = requestLine[0];
String path = requestLine[1];
String version = requestLine[2];
String host = requestsLines[1].split(" ")[1];
List<String> headers = new ArrayList<>();
for (int h = 2; h < requestsLines.length; h++) {
String header = requestsLines[h];
headers.add(header);
}
String accessLog = String.format("Client %s, method %s, path %s, version %s, host %s, headers %s",
client.toString(), method, path, version, host, headers.toString());
System.out.println(accessLog);
String contentType = "application/json";
String dummyContent = "{\"message\":\"This is a dummy server. I am healthy\"}";
sendResponse(client, "200 OK", contentType, dummyContent.getBytes());
} catch (Exception e) {
logger.info("Error in processing "+e.getMessage());
}
}
private void sendResponse(Socket client, String status, String contentType, byte[] content) throws IOException {
OutputStream clientOutput = client.getOutputStream();
clientOutput.write(("HTTP/1.1 \r\n" + status).getBytes());
clientOutput.write(("ContentType: " + contentType + "\r\n").getBytes());
clientOutput.write("\r\n".getBytes());
clientOutput.write(content);
clientOutput.write("\r\n\r\n".getBytes());
clientOutput.flush();
client.close();
}
}

View File

@@ -0,0 +1,57 @@
/**
*
*/
package io.pratik.threadops;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.logging.Logger;
/**
* @author pratikdas
*
*/
public class ThreadMXBeanSample {
private static final Logger logger = Logger.getLogger(ThreadMXBeanSample.class.getName());
public static void main(String[] args) {
startThreads();
ThreadMXBean threadMxBean = ManagementFactory.getThreadMXBean();
for (ThreadInfo ti : threadMxBean.dumpAllThreads(true, true)) {
logger.info(ti.toString());
}
logger.info("\nGeneral Thread information");
logger.info(("Number of live threads :" + threadMxBean.getThreadCount()));
logger.info("Total CPU time for the current thread: " + threadMxBean.getCurrentThreadCpuTime());
logger.info("Current number of live daemon threads:" + threadMxBean.getDaemonThreadCount());
logger.info("Peak live thread count :" + threadMxBean.getPeakThreadCount());
logger.info("Total number of threads created and started : " + threadMxBean.getTotalStartedThreadCount());
}
/**
* Starts two threads thread1 and thread2 and calls their synchronized methods
* in the run method resulting in a deadlock.
*/
private static void startThreads() {
final ThreadSample thread1 = new ThreadSample();
final ThreadSample thread2 = new ThreadSample();
Thread t1 = new Thread("Thread1") {
public void run() {
thread1.executeMethod1(thread2);
}
};
Thread t2 = new Thread("Thread2") {
@Override
public void run() {
thread2.executeMethod2(thread1);
}
};
t1.start();
t2.start();
}
}

View File

@@ -0,0 +1,32 @@
/**
*
*/
package io.pratik.threadops;
import java.util.logging.Logger;
/**
* @author pratikdas
*
*/
public class ThreadSample {
private static final Logger logger = Logger.getLogger(ThreadSample.class.getName());
synchronized void executeMethod1(final ThreadSample thread) {
log("Thread " + Thread.currentThread().getName() + " is executing");
thread.executeMethod2(this);
log(Thread.currentThread().getName() + " has finished method execution");
}
synchronized void executeMethod2(final ThreadSample thread) {
log("Thread " + Thread.currentThread().getName() + " is executing");
thread.executeMethod1(this);
log(Thread.currentThread().getName() + " has finished method execution");
}
private void log(final String message) {
System.out.println(message);
//logger.info(message);
}
}

View File

@@ -0,0 +1,38 @@
package io.pratik;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}

View File

@@ -0,0 +1,117 @@
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}

View File

@@ -0,0 +1,2 @@
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.3/apache-maven-3.6.3-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar

4
mockito/README.md Normal file
View File

@@ -0,0 +1,4 @@
# Examples for [Clean Unit Tests With Mockito on reflectoring.io](https://reflectoring.io/clean-unit-tests-with-mockito)
This repository contains the source code of the article's examples.
It's based on Spring Boot and follows the Clean Architecture (aka Onion Architecture).

310
mockito/mvnw vendored Executable file
View File

@@ -0,0 +1,310 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven Start Up Batch script
#
# Required ENV vars:
# ------------------
# JAVA_HOME - location of a JDK home dir
#
# Optional ENV vars
# -----------------
# M2_HOME - location of maven2's installed home dir
# MAVEN_OPTS - parameters passed to the Java VM when running Maven
# e.g. to debug Maven itself, use
# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
# MAVEN_SKIP_RC - flag to disable loading of mavenrc files
# ----------------------------------------------------------------------------
if [ -z "$MAVEN_SKIP_RC" ] ; then
if [ -f /etc/mavenrc ] ; then
. /etc/mavenrc
fi
if [ -f "$HOME/.mavenrc" ] ; then
. "$HOME/.mavenrc"
fi
fi
# OS specific support. $var _must_ be set to either true or false.
cygwin=false;
darwin=false;
mingw=false
case "`uname`" in
CYGWIN*) cygwin=true ;;
MINGW*) mingw=true;;
Darwin*) darwin=true
# Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home
# See https://developer.apple.com/library/mac/qa/qa1170/_index.html
if [ -z "$JAVA_HOME" ]; then
if [ -x "/usr/libexec/java_home" ]; then
export JAVA_HOME="`/usr/libexec/java_home`"
else
export JAVA_HOME="/Library/Java/Home"
fi
fi
;;
esac
if [ -z "$JAVA_HOME" ] ; then
if [ -r /etc/gentoo-release ] ; then
JAVA_HOME=`java-config --jre-home`
fi
fi
if [ -z "$M2_HOME" ] ; then
## resolve links - $0 may be a link to maven's home
PRG="$0"
# need this for relative symlinks
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG="`dirname "$PRG"`/$link"
fi
done
saveddir=`pwd`
M2_HOME=`dirname "$PRG"`/..
# make it fully qualified
M2_HOME=`cd "$M2_HOME" && pwd`
cd "$saveddir"
# echo Using m2 at $M2_HOME
fi
# For Cygwin, ensure paths are in UNIX format before anything is touched
if $cygwin ; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --unix "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --unix "$CLASSPATH"`
fi
# For Mingw, ensure paths are in UNIX format before anything is touched
if $mingw ; then
[ -n "$M2_HOME" ] &&
M2_HOME="`(cd "$M2_HOME"; pwd)`"
[ -n "$JAVA_HOME" ] &&
JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`"
fi
if [ -z "$JAVA_HOME" ]; then
javaExecutable="`which javac`"
if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then
# readlink(1) is not available as standard on Solaris 10.
readLink=`which readlink`
if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then
if $darwin ; then
javaHome="`dirname \"$javaExecutable\"`"
javaExecutable="`cd \"$javaHome\" && pwd -P`/javac"
else
javaExecutable="`readlink -f \"$javaExecutable\"`"
fi
javaHome="`dirname \"$javaExecutable\"`"
javaHome=`expr "$javaHome" : '\(.*\)/bin'`
JAVA_HOME="$javaHome"
export JAVA_HOME
fi
fi
fi
if [ -z "$JAVACMD" ] ; then
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
else
JAVACMD="`which java`"
fi
fi
if [ ! -x "$JAVACMD" ] ; then
echo "Error: JAVA_HOME is not defined correctly." >&2
echo " We cannot execute $JAVACMD" >&2
exit 1
fi
if [ -z "$JAVA_HOME" ] ; then
echo "Warning: JAVA_HOME environment variable is not set."
fi
CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher
# traverses directory structure from process work directory to filesystem root
# first directory with .mvn subdirectory is considered project base directory
find_maven_basedir() {
if [ -z "$1" ]
then
echo "Path not specified to find_maven_basedir"
return 1
fi
basedir="$1"
wdir="$1"
while [ "$wdir" != '/' ] ; do
if [ -d "$wdir"/.mvn ] ; then
basedir=$wdir
break
fi
# workaround for JBEAP-8937 (on Solaris 10/Sparc)
if [ -d "${wdir}" ]; then
wdir=`cd "$wdir/.."; pwd`
fi
# end of workaround
done
echo "${basedir}"
}
# concatenates all lines of a file
concat_lines() {
if [ -f "$1" ]; then
echo "$(tr -s '\n' ' ' < "$1")"
fi
}
BASE_DIR=`find_maven_basedir "$(pwd)"`
if [ -z "$BASE_DIR" ]; then
exit 1;
fi
##########################################################################################
# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
# This allows using the maven wrapper in projects that prohibit checking in binary data.
##########################################################################################
if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found .mvn/wrapper/maven-wrapper.jar"
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..."
fi
if [ -n "$MVNW_REPOURL" ]; then
jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
else
jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
fi
while IFS="=" read key value; do
case "$key" in (wrapperUrl) jarUrl="$value"; break ;;
esac
done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties"
if [ "$MVNW_VERBOSE" = true ]; then
echo "Downloading from: $jarUrl"
fi
wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar"
if $cygwin; then
wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"`
fi
if command -v wget > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found wget ... using wget"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
wget "$jarUrl" -O "$wrapperJarPath"
else
wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath"
fi
elif command -v curl > /dev/null; then
if [ "$MVNW_VERBOSE" = true ]; then
echo "Found curl ... using curl"
fi
if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then
curl -o "$wrapperJarPath" "$jarUrl" -f
else
curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f
fi
else
if [ "$MVNW_VERBOSE" = true ]; then
echo "Falling back to using Java to download"
fi
javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java"
# For Cygwin, switch paths to Windows format before running javac
if $cygwin; then
javaClass=`cygpath --path --windows "$javaClass"`
fi
if [ -e "$javaClass" ]; then
if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Compiling MavenWrapperDownloader.java ..."
fi
# Compiling the Java class
("$JAVA_HOME/bin/javac" "$javaClass")
fi
if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then
# Running the downloader
if [ "$MVNW_VERBOSE" = true ]; then
echo " - Running MavenWrapperDownloader.java ..."
fi
("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR")
fi
fi
fi
fi
##########################################################################################
# End of extension
##########################################################################################
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
if [ "$MVNW_VERBOSE" = true ]; then
echo $MAVEN_PROJECTBASEDIR
fi
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
# For Cygwin, switch paths to Windows format before running java
if $cygwin; then
[ -n "$M2_HOME" ] &&
M2_HOME=`cygpath --path --windows "$M2_HOME"`
[ -n "$JAVA_HOME" ] &&
JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"`
[ -n "$CLASSPATH" ] &&
CLASSPATH=`cygpath --path --windows "$CLASSPATH"`
[ -n "$MAVEN_PROJECTBASEDIR" ] &&
MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"`
fi
# Provide a "standardized" way to retrieve the CLI args that will
# work with both Windows and non-Windows executions.
MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@"
export MAVEN_CMD_LINE_ARGS
WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
exec "$JAVACMD" \
$MAVEN_OPTS \
-classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \
"-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \
${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@"

182
mockito/mvnw.cmd vendored Normal file
View File

@@ -0,0 +1,182 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

73
mockito/pom.xml Normal file
View File

@@ -0,0 +1,73 @@
<?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>
<groupId>org.example.silenum.mockito</groupId>
<artifactId>mockito-examples</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<!-- Project Properties -->
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<!-- Project Dependency Versions -->
<spring-boot.version>2.4.4</spring-boot.version>
<unitils-core.version>3.4.6</unitils-core.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- Spring Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.unitils</groupId>
<artifactId>unitils-core</artifactId>
<version>${unitils-core.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,13 @@
package org.example.silenum.mockito.business.exception;
public class ElementNotFoundException extends Exception {
public ElementNotFoundException(String message) {
super(message);
}
public ElementNotFoundException(String message, Throwable cause) {
super(message, cause);
}
}

View File

@@ -0,0 +1,17 @@
package org.example.silenum.mockito.business.service;
import java.util.function.Supplier;
import org.example.silenum.mockito.domain.entity.BaseDomain;
public interface BaseService<D extends BaseDomain, E extends Exception> {
D save(D domain) throws E;
D find(Long id) throws E;
void delete(D domain) throws E;
Supplier<E> createSupplierOnElementNotFound(String message);
}

View File

@@ -0,0 +1,29 @@
package org.example.silenum.mockito.business.service;
import java.util.Set;
import org.example.silenum.mockito.business.exception.ElementNotFoundException;
import org.example.silenum.mockito.domain.entity.Canton;
import org.example.silenum.mockito.domain.entity.Country;
public interface CantonService extends BaseService<Canton, ElementNotFoundException> {
Canton findByAbbreviation(String abbreviation, boolean loadCities) throws ElementNotFoundException;
default Canton findByAbbreviation(String abbreviation) throws ElementNotFoundException {
return findByAbbreviation(abbreviation, false);
}
Canton findByName(String name, boolean loadCities) throws ElementNotFoundException;
default Canton findByName(String name) throws ElementNotFoundException {
return findByName(name, false);
}
Set<Canton> findAllByCountry(Country country, boolean loadCities);
default Set<Canton> findAllByCountry(Country country) {
return findAllByCountry(country, false);
}
}

View File

@@ -0,0 +1,88 @@
package org.example.silenum.mockito.business.service;
import java.util.Collections;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.example.silenum.mockito.business.exception.ElementNotFoundException;
import org.example.silenum.mockito.domain.entity.Canton;
import org.example.silenum.mockito.domain.entity.City;
import org.example.silenum.mockito.domain.entity.Country;
import org.example.silenum.mockito.domain.repository.CantonRepository;
public class CantonServiceImpl implements CantonService {
private static final String EXCEPTION_MESSAGE_TEMPLATE = "Canton with %s does not exist.";
private final CantonRepository cantonRepository;
private final CityService cityService;
public CantonServiceImpl(
CantonRepository cantonRepository,
CityService cityService) {
this.cantonRepository = cantonRepository;
this.cityService = cityService;
}
@Override
public Canton save(Canton canton) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + canton.getId());
return cantonRepository.save(canton)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
}
@Override
public Canton find(Long id) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "id " + id);
return cantonRepository.find(id)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
}
@Override
public void delete(Canton domain) {
cantonRepository.delete(domain);
}
@Override
public Supplier<ElementNotFoundException> createSupplierOnElementNotFound(String message) {
return () -> new ElementNotFoundException(message);
}
@Override
public Canton findByAbbreviation(String abbreviation, boolean loadCities) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "abbreviation " + abbreviation);
Canton canton = cantonRepository.findByAbbreviation(abbreviation)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
return buildCanton(canton, loadCities);
}
@Override
public Canton findByName(String name, boolean loadCities) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "name " + name);
Canton canton = cantonRepository.findByName(name)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
return buildCanton(canton, loadCities);
}
@Override
public Set<Canton> findAllByCountry(Country country, boolean loadCities) {
Set<Canton> cantons = cantonRepository.findAllByCountry(country);
return cantons.stream()
.map(canton -> Canton.builder().of(canton)
.setCities(!loadCities ?
Collections.emptySet() :
cityService.findAllByCanton(canton))
.setCountry(country)
.build())
.collect(Collectors.toSet());
}
private Canton buildCanton(Canton canton, boolean loadCities) {
Set<City> cities = !loadCities ? Collections.emptySet() : cityService.findAllByCanton(canton);
return Canton.builder().of(canton)
.setCities(cities)
.build();
}
}

View File

@@ -0,0 +1,18 @@
package org.example.silenum.mockito.business.service;
import java.util.Set;
import org.example.silenum.mockito.business.exception.ElementNotFoundException;
import org.example.silenum.mockito.domain.entity.Canton;
import org.example.silenum.mockito.domain.entity.City;
import org.example.silenum.mockito.domain.entity.Country;
public interface CityService extends BaseService<City, ElementNotFoundException> {
City findByName(String name) throws ElementNotFoundException;
Set<City> findAllByCanton(Canton canton);
Set<City> findAllByCountry(Country country);
}

View File

@@ -0,0 +1,69 @@
package org.example.silenum.mockito.business.service;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.example.silenum.mockito.business.exception.ElementNotFoundException;
import org.example.silenum.mockito.domain.entity.Canton;
import org.example.silenum.mockito.domain.entity.City;
import org.example.silenum.mockito.domain.entity.Country;
import org.example.silenum.mockito.domain.repository.CityRepository;
public class CityServiceImpl implements CityService {
private static final String EXCEPTION_MESSAGE_TEMPLATE = "City with %s does not exist.";
private final CityRepository cityRepository;
public CityServiceImpl(CityRepository cityRepository) {
this.cityRepository = cityRepository;
}
@Override
public City save(City city) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + city.getId());
return cityRepository.save(city)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
}
@Override
public City find(Long id) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + id);
return cityRepository.find(id)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
}
@Override
public void delete(City domain) {
cityRepository.delete(domain);
}
@Override
public Supplier<ElementNotFoundException> createSupplierOnElementNotFound(String message) {
return () -> new ElementNotFoundException(message);
}
@Override
public City findByName(String name) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "name " + name);
return cityRepository.findByName(name)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
}
@Override
public Set<City> findAllByCanton(Canton canton) {
return cityRepository.findAllByCanton(canton).stream()
.map(city -> City.builder()
.of(city)
.setCanton(canton)
.build())
.collect(Collectors.toSet());
}
@Override
public Set<City> findAllByCountry(Country country) {
return cityRepository.findAllByCountry(country);
}
}

View File

@@ -0,0 +1,38 @@
package org.example.silenum.mockito.business.service;
import org.example.silenum.mockito.business.exception.ElementNotFoundException;
import org.example.silenum.mockito.domain.entity.Country;
public interface CountryService extends BaseService<Country, ElementNotFoundException> {
Country findById(Long id, boolean loadCantons, boolean loadCities) throws ElementNotFoundException;
default Country findById(Long id, boolean loadCantons) throws ElementNotFoundException {
return findById(id, loadCantons, false);
}
default Country findById(Long id) throws ElementNotFoundException {
return findById(id, false, false);
}
Country findByName(String name, boolean loadCantons, boolean loadCities) throws ElementNotFoundException;
default Country findByName(String name, boolean loadCantons) throws ElementNotFoundException {
return findByName(name, loadCantons, false);
}
default Country findByName(String name) throws ElementNotFoundException {
return findByName(name, false, false);
}
Country findByCode(String code, boolean loadCantons, boolean loadCities) throws ElementNotFoundException;
default Country findByCode(String code, boolean loadCantons) throws ElementNotFoundException {
return findByCode(code, loadCantons, false);
}
default Country findByCode(String code) throws ElementNotFoundException {
return findByCode(code, false, false);
}
}

View File

@@ -0,0 +1,82 @@
package org.example.silenum.mockito.business.service;
import java.util.Collections;
import java.util.Set;
import java.util.function.Supplier;
import org.example.silenum.mockito.business.exception.ElementNotFoundException;
import org.example.silenum.mockito.domain.entity.Canton;
import org.example.silenum.mockito.domain.entity.Country;
import org.example.silenum.mockito.domain.repository.CountryRepository;
public class CountryServiceImpl implements CountryService {
private static final String EXCEPTION_MESSAGE_TEMPLATE = "Country with %s does not exist.";
private final CountryRepository countryRepository;
private final CantonService cantonService;
public CountryServiceImpl(
CountryRepository countryRepository,
CantonService cantonService) {
this.countryRepository = countryRepository;
this.cantonService = cantonService;
}
@Override
public Country save(Country country) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + country.getId());
return countryRepository.save(country)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
}
@Override
public Country find(Long id) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + id);
return countryRepository.find(id)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
}
@Override
public void delete(Country domain) {
countryRepository.delete(domain);
}
@Override
public Supplier<ElementNotFoundException> createSupplierOnElementNotFound(String message) {
return () -> new ElementNotFoundException(message);
}
@Override
public Country findById(Long id, boolean loadCantons, boolean loadCities) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "ID " + id);
Country country = countryRepository.find(id).orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
return buildCountry(country, loadCantons, loadCities);
}
@Override
public Country findByName(String name, boolean loadCantons, boolean loadCities) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "name " + name);
Country country = countryRepository.findByName(name)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
return buildCountry(country, loadCantons, loadCities);
}
@Override
public Country findByCode(String code, boolean loadCantons, boolean loadCities) throws ElementNotFoundException {
String exceptionMessage = String.format(EXCEPTION_MESSAGE_TEMPLATE, "code " + code);
Country country = countryRepository.findByCode(code)
.orElseThrow(createSupplierOnElementNotFound(exceptionMessage));
return buildCountry(country, loadCantons, loadCities);
}
private Country buildCountry(Country country, boolean loadCantons, boolean loadCities) {
Set<Canton> cantons = !loadCantons ?
Collections.emptySet() :
cantonService.findAllByCountry(country, loadCities);
return Country.builder().of(country)
.setCantons(cantons)
.build();
}
}

View File

@@ -0,0 +1,83 @@
package org.example.silenum.mockito.domain.entity;
import java.time.ZonedDateTime;
/**
* This {@link BaseDomain} defines the common fields of all domain objects.
* Every domain object must extends this {@link BaseDomain} for further processing.
*/
public abstract class BaseDomain {
private final Long id;
private final Integer version;
private final ZonedDateTime created;
private final ZonedDateTime updated;
protected BaseDomain(Builder<?> builder) {
id = builder.id;
version = builder.version;
created = builder.created;
updated = builder.updated;
}
public Long getId() {
return id;
}
public Integer getVersion() {
return version;
}
public ZonedDateTime getCreated() {
return created;
}
public ZonedDateTime getUpdated() {
return updated;
}
/**
* Abstract Builder Pattern for Inheritance
*
* @param <T> Builder from Subtype
*/
public abstract static class Builder<T extends Builder<T>> {
private Long id;
private Integer version;
private ZonedDateTime created;
private ZonedDateTime updated;
protected Builder() {
}
public T id(Long id) {
this.id = id;
return getThis();
}
public T version(Integer version) {
this.version = version;
return getThis();
}
public T created(ZonedDateTime created) {
this.created = created;
return getThis();
}
public T updated(ZonedDateTime updated) {
this.updated = updated;
return getThis();
}
/**
* Returns the this-object of the subtype.
*
* @return this-object of subtype
*/
protected abstract T getThis();
}
}

View File

@@ -0,0 +1,93 @@
package org.example.silenum.mockito.domain.entity;
import java.util.Set;
public class Canton extends BaseDomain {
private final String name;
private final String abbreviation;
private final Country country;
private final Set<City> cities;
private Canton(Builder builder) {
super(builder);
this.name = builder.name;
this.abbreviation = builder.abbreviation;
this.country = builder.country;
this.cities = builder.cities;
}
public static Builder builder() {
return new Builder();
}
public String getName() {
return name;
}
public String getAbbreviation() {
return abbreviation;
}
public Country getCountry() {
return country;
}
public Set<City> getCities() {
return cities;
}
public static class Builder extends BaseDomain.Builder<Builder> {
private String name;
private String abbreviation;
private Country country;
private Set<City> cities;
private Builder() {
}
@Override
protected Builder getThis() {
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setAbbreviation(String abbreviation) {
this.abbreviation = abbreviation;
return this;
}
public Builder setCountry(Country country) {
this.country = country;
return this;
}
public Builder setCities(Set<City> cities) {
this.cities = cities;
return this;
}
public Builder of(Canton canton) {
this.id(canton.getId());
this.version(canton.getVersion());
this.created(canton.getCreated());
this.updated(canton.getUpdated());
this.name = canton.name;
this.abbreviation = canton.abbreviation;
this.country = canton.country;
this.cities = canton.cities;
return this;
}
public Canton build() {
return new Canton(this);
}
}
}

View File

@@ -0,0 +1,65 @@
package org.example.silenum.mockito.domain.entity;
public class City extends BaseDomain {
private final String name;
private final Canton canton;
private City(Builder builder) {
super(builder);
this.name = builder.name;
this.canton = builder.canton;
}
public static Builder builder() {
return new Builder();
}
public String getName() {
return name;
}
public Canton getCanton() {
return canton;
}
public static class Builder extends BaseDomain.Builder<Builder> {
private String name;
private Canton canton;
private Builder() {
}
@Override
protected Builder getThis() {
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setCanton(Canton canton) {
this.canton = canton;
return this;
}
public Builder of(City city) {
this.id(city.getId());
this.version(city.getVersion());
this.created(city.getCreated());
this.updated(city.getUpdated());
this.name = city.name;
this.canton = city.canton;
return this;
}
public City build() {
return new City(this);
}
}
}

View File

@@ -0,0 +1,80 @@
package org.example.silenum.mockito.domain.entity;
import java.util.Set;
public class Country extends BaseDomain {
private final String name;
private final String code;
private final Set<Canton> cantons;
private Country(Builder builder) {
super(builder);
this.name = builder.name;
this.code = builder.code;
this.cantons = builder.cantons;
}
public static Builder builder() {
return new Builder();
}
public String getName() {
return name;
}
public String getCode() {
return code;
}
public Set<Canton> getCantons() {
return cantons;
}
public static class Builder extends BaseDomain.Builder<Builder> {
private String name;
private String code;
private Set<Canton> cantons;
private Builder() {
}
@Override
protected Builder getThis() {
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setCode(String code) {
this.code = code;
return this;
}
public Builder setCantons(Set<Canton> cantons) {
this.cantons = cantons;
return this;
}
public Builder of(Country country) {
this.id(country.getId());
this.version(country.getVersion());
this.created(country.getCreated());
this.updated(country.getUpdated());
this.name = country.name;
this.code = country.code;
this.cantons = country.cantons;
return this;
}
public Country build() {
return new Country(this);
}
}
}

View File

@@ -0,0 +1,15 @@
package org.example.silenum.mockito.domain.repository;
import java.util.Optional;
import org.example.silenum.mockito.domain.entity.BaseDomain;
public interface BaseDomainRepository<D extends BaseDomain> {
Optional<D> save(D domain);
Optional<D> find(Long id);
void delete(D domain);
}

View File

@@ -0,0 +1,17 @@
package org.example.silenum.mockito.domain.repository;
import java.util.Optional;
import java.util.Set;
import org.example.silenum.mockito.domain.entity.Canton;
import org.example.silenum.mockito.domain.entity.Country;
public interface CantonRepository extends BaseDomainRepository<Canton> {
Optional<Canton> findByAbbreviation(String abbreviation);
Optional<Canton> findByName(String name);
Set<Canton> findAllByCountry(Country country);
}

View File

@@ -0,0 +1,18 @@
package org.example.silenum.mockito.domain.repository;
import java.util.Optional;
import java.util.Set;
import org.example.silenum.mockito.domain.entity.Canton;
import org.example.silenum.mockito.domain.entity.City;
import org.example.silenum.mockito.domain.entity.Country;
public interface CityRepository extends BaseDomainRepository<City> {
Optional<City> findByName(String name);
Set<City> findAllByCanton(Canton canton);
Set<City> findAllByCountry(Country country);
}

View File

@@ -0,0 +1,13 @@
package org.example.silenum.mockito.domain.repository;
import java.util.Optional;
import org.example.silenum.mockito.domain.entity.Country;
public interface CountryRepository extends BaseDomainRepository<Country> {
Optional<Country> findByName(String name);
Optional<Country> findByCode(String code);
}

View File

@@ -0,0 +1,13 @@
package org.example.silenum.mockito.infrastructure;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

View File

@@ -0,0 +1,37 @@
package org.example.silenum.mockito.infrastructure.configuration.business;
import org.example.silenum.mockito.business.service.CantonService;
import org.example.silenum.mockito.business.service.CantonServiceImpl;
import org.example.silenum.mockito.business.service.CityService;
import org.example.silenum.mockito.business.service.CityServiceImpl;
import org.example.silenum.mockito.business.service.CountryService;
import org.example.silenum.mockito.business.service.CountryServiceImpl;
import org.example.silenum.mockito.domain.repository.CantonRepository;
import org.example.silenum.mockito.domain.repository.CityRepository;
import org.example.silenum.mockito.domain.repository.CountryRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServiceConfiguration {
@Bean
public CityService cityService(CityRepository cityRepository) {
return new CityServiceImpl(cityRepository);
}
@Bean
public CantonService cantonService(
CantonRepository cantonRepository,
CityService cityService) {
return new CantonServiceImpl(cantonRepository, cityService);
}
@Bean
public CountryService countryService(
CountryRepository countryRepository,
CantonService cantonService) {
return new CountryServiceImpl(countryRepository, cantonService);
}
}

View File

@@ -0,0 +1,27 @@
package org.example.silenum.mockito.infrastructure.configuration.mapper;
import org.example.silenum.mockito.infrastructure.mapper.CantonMapper;
import org.example.silenum.mockito.infrastructure.mapper.CityMapper;
import org.example.silenum.mockito.infrastructure.mapper.CountryMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MapperConfiguration {
@Bean
public CityMapper cityMapper(CantonMapper cantonMapper) {
return new CityMapper(cantonMapper);
}
@Bean
public CantonMapper cantonMapper(CountryMapper countryMapper) {
return new CantonMapper(countryMapper);
}
@Bean
public CountryMapper countryMapper() {
return new CountryMapper();
}
}

View File

@@ -0,0 +1,24 @@
package org.example.silenum.mockito.infrastructure.configuration.persistence;
import java.time.ZonedDateTime;
import java.util.Optional;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.auditing.DateTimeProvider;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaAuditing(dateTimeProviderRef = "zonedDateTimeProvider")
@EntityScan(basePackages = "org.example.silenum.mockito.infrastructure.database.entity")
@EnableJpaRepositories(basePackages = "org.example.silenum.mockito.infrastructure.database.repository")
public class PersistenceConfiguration {
@Bean(name = "zonedDateTimeProvider")
public DateTimeProvider dateTimeProvider() {
return () -> Optional.of(ZonedDateTime.now());
}
}

View File

@@ -0,0 +1,42 @@
package org.example.silenum.mockito.infrastructure.configuration.repository;
import org.example.silenum.mockito.domain.repository.CantonRepository;
import org.example.silenum.mockito.domain.repository.CityRepository;
import org.example.silenum.mockito.domain.repository.CountryRepository;
import org.example.silenum.mockito.infrastructure.database.repository.CantonEntityRepository;
import org.example.silenum.mockito.infrastructure.database.repository.CityEntityRepository;
import org.example.silenum.mockito.infrastructure.database.repository.CountryEntityRepository;
import org.example.silenum.mockito.infrastructure.mapper.CantonMapper;
import org.example.silenum.mockito.infrastructure.mapper.CityMapper;
import org.example.silenum.mockito.infrastructure.mapper.CountryMapper;
import org.example.silenum.mockito.infrastructure.repository.CantonRepositoryImpl;
import org.example.silenum.mockito.infrastructure.repository.CityRepositoryImpl;
import org.example.silenum.mockito.infrastructure.repository.CountryRepositoryImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RepositoryConfiguration {
@Bean
public CityRepository cityRepository(
CityEntityRepository cityEntityRepository,
CityMapper cityMapper) {
return new CityRepositoryImpl(cityEntityRepository, cityMapper);
}
@Bean
public CantonRepository cantonRepository(
CantonEntityRepository cantonEntityRepository,
CantonMapper cantonMapper) {
return new CantonRepositoryImpl(cantonEntityRepository, cantonMapper);
}
@Bean
public CountryRepository countryRepository(
CountryEntityRepository countryEntityRepository,
CountryMapper countryMapper) {
return new CountryRepositoryImpl(countryEntityRepository, countryMapper);
}
}

View File

@@ -0,0 +1,90 @@
package org.example.silenum.mockito.infrastructure.database.entity;
import java.time.ZonedDateTime;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
/**
* This class defines the common fields for each entity to be persisted.
*/
@MappedSuperclass
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@Version
private Integer version;
@CreatedDate
private ZonedDateTime created;
@LastModifiedDate
private ZonedDateTime updated;
protected BaseEntity() {
}
protected BaseEntity(Builder<?> builder) {
this.id = builder.id;
this.version = builder.version;
this.created = builder.created;
this.updated = builder.updated;
}
public Long getId() {
return id;
}
public Integer getVersion() {
return version;
}
public ZonedDateTime getCreated() {
return created;
}
public ZonedDateTime getUpdated() {
return updated;
}
public abstract static class Builder<T extends Builder<T>> {
private Long id;
private Integer version;
private ZonedDateTime created;
private ZonedDateTime updated;
public T id(Long id) {
this.id = id;
return this.getThis();
}
public T version(Integer version) {
this.version = version;
return this.getThis();
}
public T created(ZonedDateTime created) {
this.created = created;
return this.getThis();
}
public T updated(ZonedDateTime updated) {
this.updated = updated;
return this.getThis();
}
protected abstract T getThis();
}
}

View File

@@ -0,0 +1,122 @@
package org.example.silenum.mockito.infrastructure.database.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@Entity
@Table(name = "canton")
@EntityListeners(AuditingEntityListener.class)
public class CantonEntity extends BaseEntity {
@Column(nullable = false, unique = true)
private String name;
@Column(nullable = false, unique = true)
private String abbreviation;
@OneToMany(mappedBy = "canton", cascade = CascadeType.REMOVE)
private Set<CityEntity> cities = new HashSet<>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "countryId")
private CountryEntity country;
public CantonEntity() {
// Default constructor is required for JPA.
}
private CantonEntity(Builder builder) {
super(builder);
name = builder.name;
abbreviation = builder.abbreviation;
cities = builder.cities;
country = builder.country;
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(CantonEntity copy) {
Builder builder = new Builder();
builder.id(copy.getId());
builder.version(copy.getVersion());
builder.created(copy.getCreated());
builder.updated(copy.getUpdated());
builder.name = copy.getName();
builder.abbreviation = copy.getAbbreviation();
builder.cities = copy.getCities();
builder.country = copy.getCountry();
return builder;
}
public String getName() {
return name;
}
public String getAbbreviation() {
return abbreviation;
}
public Set<CityEntity> getCities() {
return cities;
}
public CountryEntity getCountry() {
return country;
}
public static final class Builder extends BaseEntity.Builder<Builder> {
private String name;
private String abbreviation;
private Set<CityEntity> cities;
private CountryEntity country;
private Builder() {
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder abbreviation(String abbreviation) {
this.abbreviation = abbreviation;
return this;
}
public Builder cities(Set<CityEntity> cities) {
this.cities = cities;
return this;
}
public Builder country(CountryEntity country) {
this.country = country;
return this;
}
public CantonEntity build() {
return new CantonEntity(this);
}
@Override
protected Builder getThis() {
return this;
}
}
}

View File

@@ -0,0 +1,88 @@
package org.example.silenum.mockito.infrastructure.database.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@Entity
@Table(name = "city")
@EntityListeners(AuditingEntityListener.class)
public class CityEntity extends BaseEntity {
@Column(nullable = false)
private String name;
// Note: This is the owning site (child) of the relation canton-city
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cantonId")
private CantonEntity canton;
public CityEntity() {
// Default constructor is required for JPA.
}
private CityEntity(Builder builder) {
super(builder);
name = builder.name;
canton = builder.canton;
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(CityEntity copy) {
Builder builder = new Builder();
builder.id(copy.getId());
builder.version(copy.getVersion());
builder.created(copy.getCreated());
builder.updated(copy.getUpdated());
builder.name = copy.getName();
builder.canton = copy.getCanton();
return builder;
}
public String getName() {
return name;
}
public CantonEntity getCanton() {
return canton;
}
public static final class Builder extends BaseEntity.Builder<Builder> {
private String name;
private CantonEntity canton;
private Builder() {
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder canton(CantonEntity canton) {
this.canton = canton;
return this;
}
public CityEntity build() {
return new CityEntity(this);
}
@Override
protected Builder getThis() {
return this;
}
}
}

View File

@@ -0,0 +1,104 @@
package org.example.silenum.mockito.infrastructure.database.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
@Entity
@Table(name = "country")
@EntityListeners(AuditingEntityListener.class)
public class CountryEntity extends BaseEntity {
@Column(nullable = false, unique = true)
private String name;
@Column(nullable = false, unique = true)
private String code;
// Note: This is the inverse site (parent) of the relation country-canton
@OneToMany(mappedBy = "country", cascade = CascadeType.REMOVE)
private Set<CantonEntity> cantons = new HashSet<>();
public CountryEntity() {
// Default constructor is required for JPA.
}
private CountryEntity(Builder builder) {
super(builder);
name = builder.name;
code = builder.code;
cantons = builder.cantons;
}
public static Builder builder() {
return new Builder();
}
public static Builder builder(CountryEntity copy) {
Builder builder = new Builder();
builder.id(copy.getId());
builder.version(copy.getVersion());
builder.created(copy.getCreated());
builder.updated(copy.getUpdated());
builder.name = copy.getName();
builder.code = copy.getCode();
builder.cantons = copy.getCantons();
return builder;
}
public String getName() {
return name;
}
public String getCode() {
return code;
}
public Set<CantonEntity> getCantons() {
return cantons;
}
public static final class Builder extends BaseEntity.Builder<Builder> {
private String name;
private String code;
private Set<CantonEntity> cantons;
private Builder() {
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder code(String code) {
this.code = code;
return this;
}
public Builder cantons(Set<CantonEntity> cantons) {
this.cantons = cantons;
return this;
}
public CountryEntity build() {
return new CountryEntity(this);
}
@Override
protected Builder getThis() {
return this;
}
}
}

View File

@@ -0,0 +1,12 @@
package org.example.silenum.mockito.infrastructure.database.repository;
import org.example.silenum.mockito.infrastructure.database.entity.BaseEntity;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Intermediate repository for {@link BaseEntity}
* It defines {@link Long} as default type for the ID of the {@link BaseEntity}
*/
public interface BaseEntityRepository<T extends BaseEntity> extends JpaRepository<T, Long> {
}

View File

@@ -0,0 +1,18 @@
package org.example.silenum.mockito.infrastructure.database.repository;
import java.util.List;
import java.util.Optional;
import org.example.silenum.mockito.infrastructure.database.entity.CantonEntity;
public interface CantonEntityRepository extends BaseEntityRepository<CantonEntity> {
Optional<CantonEntity> findByNameIgnoreCase(String name);
Optional<CantonEntity> findByAbbreviationIgnoreCase(String abbreviation);
List<CantonEntity> findAllByCountryNameIgnoreCase(String countryName);
List<CantonEntity> findAllByCountryId(Long countryId);
}

View File

@@ -0,0 +1,16 @@
package org.example.silenum.mockito.infrastructure.database.repository;
import java.util.List;
import java.util.Optional;
import org.example.silenum.mockito.infrastructure.database.entity.CityEntity;
public interface CityEntityRepository extends BaseEntityRepository<CityEntity> {
Optional<CityEntity> findByNameIgnoreCase(String name);
List<CityEntity> findAllByCantonId(Long cantonId);
List<CityEntity> findAllByCanton_Country_Id(Long countryId);
}

View File

@@ -0,0 +1,13 @@
package org.example.silenum.mockito.infrastructure.database.repository;
import java.util.Optional;
import org.example.silenum.mockito.infrastructure.database.entity.CountryEntity;
public interface CountryEntityRepository extends BaseEntityRepository<CountryEntity> {
Optional<CountryEntity> findByNameIgnoreCase(String name);
Optional<CountryEntity> findByCodeIgnoreCase(String code);
}

View File

@@ -0,0 +1,41 @@
package org.example.silenum.mockito.infrastructure.mapper;
import java.util.Optional;
import org.example.silenum.mockito.domain.entity.Canton;
import org.example.silenum.mockito.infrastructure.database.entity.CantonEntity;
public final class CantonMapper implements Mapper<Canton, CantonEntity> {
private final CountryMapper countryMapper;
public CantonMapper(CountryMapper countryMapper) {
this.countryMapper = countryMapper;
}
@Override
public Optional<Canton> toDomain(CantonEntity entity) {
return entity == null ? Optional.empty() : Optional.of(Canton.builder()
.id(entity.getId())
.version(entity.getVersion())
.created(entity.getCreated())
.updated(entity.getUpdated())
.setName(entity.getName())
.setAbbreviation(entity.getAbbreviation())
.build());
}
@Override
public CantonEntity toEntity(Canton canton) {
return canton == null ? null : CantonEntity.builder()
.id(canton.getId())
.version(canton.getVersion())
.created(canton.getCreated())
.updated(canton.getUpdated())
.name(canton.getName())
.abbreviation(canton.getAbbreviation())
.country(countryMapper.toEntity(canton.getCountry()))
.build();
}
}

View File

@@ -0,0 +1,39 @@
package org.example.silenum.mockito.infrastructure.mapper;
import java.util.Optional;
import org.example.silenum.mockito.domain.entity.City;
import org.example.silenum.mockito.infrastructure.database.entity.CityEntity;
public final class CityMapper implements Mapper<City, CityEntity> {
private final CantonMapper cantonMapper;
public CityMapper(CantonMapper cantonMapper) {
this.cantonMapper = cantonMapper;
}
@Override
public Optional<City> toDomain(CityEntity entity) {
return entity == null ? Optional.empty() : Optional.of(City.builder()
.id(entity.getId())
.version(entity.getVersion())
.created(entity.getCreated())
.updated(entity.getUpdated())
.setName(entity.getName())
.build());
}
@Override
public CityEntity toEntity(City city) {
return city == null ? null : CityEntity.builder()
.id(city.getId())
.version(city.getVersion())
.created(city.getCreated())
.updated(city.getUpdated())
.name(city.getName())
.canton(cantonMapper.toEntity(city.getCanton()))
.build();
}
}

View File

@@ -0,0 +1,34 @@
package org.example.silenum.mockito.infrastructure.mapper;
import java.util.Optional;
import org.example.silenum.mockito.domain.entity.Country;
import org.example.silenum.mockito.infrastructure.database.entity.CountryEntity;
public final class CountryMapper implements Mapper<Country, CountryEntity> {
@Override
public Optional<Country> toDomain(CountryEntity entity) {
return entity == null ? Optional.empty() : Optional.of(Country.builder()
.id(entity.getId())
.version(entity.getVersion())
.created(entity.getCreated())
.updated(entity.getUpdated())
.setName(entity.getName())
.setCode(entity.getCode())
.build());
}
@Override
public CountryEntity toEntity(Country domain) {
return domain == null ? null : CountryEntity.builder()
.id(domain.getId())
.version(domain.getVersion())
.created(domain.getCreated())
.updated(domain.getUpdated())
.name(domain.getName())
.code(domain.getCode())
.build();
}
}

View File

@@ -0,0 +1,36 @@
package org.example.silenum.mockito.infrastructure.mapper;
import java.util.Collection;
import java.util.Collections;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.example.silenum.mockito.domain.entity.BaseDomain;
import org.example.silenum.mockito.infrastructure.database.entity.BaseEntity;
public interface Mapper<D extends BaseDomain, E extends BaseEntity> {
default Optional<D> toDomain(Optional<E> entity) {
return entity.isEmpty() ? Optional.empty() : toDomain(entity.get());
}
Optional<D> toDomain(E entity);
default Set<D> toDomain(Collection<E> entities) {
return entities == null ? Collections.emptySet() : entities.stream()
.map(this::toDomain)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
}
E toEntity(D domain);
default Set<E> toEntity(Collection<D> domains) {
return domains == null ? Collections.emptySet() : domains.stream()
.map(this::toEntity)
.collect(Collectors.toSet());
}
}

View File

@@ -0,0 +1,63 @@
package org.example.silenum.mockito.infrastructure.repository;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.example.silenum.mockito.domain.entity.Canton;
import org.example.silenum.mockito.domain.entity.Country;
import org.example.silenum.mockito.domain.repository.CantonRepository;
import org.example.silenum.mockito.infrastructure.database.entity.CantonEntity;
import org.example.silenum.mockito.infrastructure.database.repository.CantonEntityRepository;
import org.example.silenum.mockito.infrastructure.mapper.CantonMapper;
public class CantonRepositoryImpl implements CantonRepository {
private final CantonEntityRepository cantonEntityRepository;
private final CantonMapper cantonMapper;
public CantonRepositoryImpl(
CantonEntityRepository cantonEntityRepository,
CantonMapper cantonMapper) {
this.cantonEntityRepository = cantonEntityRepository;
this.cantonMapper = cantonMapper;
}
@Override
public Optional<Canton> save(Canton domain) {
CantonEntity cantonEntity = cantonMapper.toEntity(domain);
cantonEntity = cantonEntityRepository.save(cantonEntity);
return cantonMapper.toDomain(cantonEntity);
}
@Override
public Optional<Canton> find(Long id) {
Optional<CantonEntity> cantonEntity = cantonEntityRepository.findById(id);
return cantonMapper.toDomain(cantonEntity);
}
@Override
public void delete(Canton domain) {
Optional<CantonEntity> cantonEntity = cantonEntityRepository.findById(domain.getId());
cantonEntity.ifPresent(cantonEntityRepository::delete);
}
@Override
public Optional<Canton> findByAbbreviation(String abbreviation) {
Optional<CantonEntity> cantonEntity = cantonEntityRepository.findByAbbreviationIgnoreCase(abbreviation);
return cantonMapper.toDomain(cantonEntity);
}
@Override
public Optional<Canton> findByName(String name) {
Optional<CantonEntity> cantonEntity = cantonEntityRepository.findByNameIgnoreCase(name);
return cantonMapper.toDomain(cantonEntity);
}
@Override
public Set<Canton> findAllByCountry(Country country) {
List<CantonEntity> cantonEntities = cantonEntityRepository.findAllByCountryNameIgnoreCase(country.getName());
return cantonMapper.toDomain(cantonEntities);
}
}

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