diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..a45eb6b --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,118 @@ +/* + * 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 + * + * 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. + */ + +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(); + } + +} diff --git a/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..2cc7d4a Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..642d572 --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -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 diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..a16b543 --- /dev/null +++ b/mvnw @@ -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 "$@" diff --git a/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/mvnw.cmd @@ -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 https://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% diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..5fa7547 --- /dev/null +++ b/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.2 + + + com.tutorial + spring-data-mongodb-dynamic-queries + 0.0.1-SNAPSHOT + spring-data-mongodb-dynamic-queries + Demo project for Spring Boot + + 1.8 + + + + org.springframework.boot + spring-boot-starter-data-mongodb + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.projectlombok + lombok + true + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/SpringDataMongodbDynamicQueriesApplication.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/SpringDataMongodbDynamicQueriesApplication.java new file mode 100644 index 0000000..44a23e4 --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/SpringDataMongodbDynamicQueriesApplication.java @@ -0,0 +1,57 @@ +package com.tutorial.springdatamongodbdynamicqueries; + +import com.tutorial.springdatamongodbdynamicqueries.domain.Department; +import com.tutorial.springdatamongodbdynamicqueries.domain.Employee; +import com.tutorial.springdatamongodbdynamicqueries.repository.EmployeeRepository; +import com.tutorial.springdatamongodbdynamicqueries.repository.support.ResourceRepositoryImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; + +import java.util.Arrays; +import java.util.List; + +@SpringBootApplication +@EnableMongoRepositories(repositoryBaseClass = ResourceRepositoryImpl.class) +public class SpringDataMongodbDynamicQueriesApplication implements CommandLineRunner { + + @Autowired + private EmployeeRepository employeeRepository; + + public static void main(String[] args) { + SpringApplication.run(SpringDataMongodbDynamicQueriesApplication.class, args); + } + + @Override + public void run(String... args) throws Exception { + List departments = Arrays.asList( + new Department("IT", "IT department"), + new Department("RAD", "research and development team"), + new Department("MK", "marketing"), + new Department("TS", "technical support team"), + new Department("AG", "Accounting") + ); + + List employees = Arrays.asList( + new Employee("600f4997e3a11bc10091f786","Ferdinand","Wynne","Etiam.ligula.tortor@vestibulumMauris.com",departments.get(0)), + new Employee("600f49a1a5bd0e51ceb6c2d3","Grant","Quinlan","lobortis.ultrices.Vivamus@diamvelarcu.org",departments.get(0)), + new Employee("600f49b6ff49b4e466efb4c4","Brielle","Hanae","Cras.dictum.ultricies@Integeridmagna.edu",departments.get(0)), + + new Employee("600f49aee40e8fd42bbf3e8f","Morgan","Ivory","feugiat.metus@Duisa.edu",departments.get(1)), + new Employee("600f49c16c3c8f51ff49d30e","Alexa","Colorado","mus.Proin@mollisvitaeposuere.net",departments.get(1)), + new Employee("600f49cc2eabbc1a8b9b7ead","Mercedes","Zeph","eu.placerat.eget@lacuspedesagittis.net",departments.get(1)), + new Employee("600f49d3b5d8765523b9a17e","Chancellor","Myra","velit.dui.semper@magnaNam.org",departments.get(1)), + new Employee("600f49ddc441d3b63d2f3f15","Leroy","Dillon","risus.Donec.egestas@loremvitaeodio.edu",departments.get(1)), + new Employee("600f49e6687e2ce48b81831a","Cole","Xander","lacus.Nulla@quistristique.org",departments.get(1)), + + new Employee("600f49efecb77b12d517b519","Eleanor","Paul","metus.Aenean@urnaNullamlobortis.edu",departments.get(2)), + new Employee("600f49f9be0c3402ac8f7416","Katell","Sawyer","porttitor@non.org",departments.get(2)), + + new Employee("600f49f9be0c3402ac8f7416","TaShya","Stewart","fames.ac.turpis@dolor.edu",departments.get(3)) + ); + + employeeRepository.saveAll(employees); + } +} diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/controller/EmployeeController.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/controller/EmployeeController.java new file mode 100644 index 0000000..6b5211f --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/controller/EmployeeController.java @@ -0,0 +1,87 @@ +package com.tutorial.springdatamongodbdynamicqueries.controller; + +import com.tutorial.springdatamongodbdynamicqueries.controller.dto.FilterCondition; +import com.tutorial.springdatamongodbdynamicqueries.domain.Employee; +import com.tutorial.springdatamongodbdynamicqueries.repository.support.GenericFilterCriteriaBuilder; +import com.tutorial.springdatamongodbdynamicqueries.service.EmployeeService; +import com.tutorial.springdatamongodbdynamicqueries.service.FilterBuilderService; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import java.util.List; + +@RestController +@RequestMapping("/employee") +public class EmployeeController { + + private final EmployeeService employeeService; + private final FilterBuilderService filterBuilderService; + + public EmployeeController(EmployeeService employeeService, FilterBuilderService filterBuilderService) { + this.employeeService = employeeService; + this.filterBuilderService = filterBuilderService; + } + + + /** + * @param page page number + * @param size size count + * @param filterOr string filter or conditions + * @param filterAnd string filter and conditions + * @param orders string orders + * @return PageResponse + */ + @GetMapping(value = "/page") + public ResponseEntity> getSearchCriteriaPage( + @RequestParam(value = "page", defaultValue = "0") int page, + @RequestParam(value = "size", defaultValue = "20") int size, + @RequestParam(value = "filterOr", required = false) String filterOr, + @RequestParam(value = "filterAnd", required = false) String filterAnd, + @RequestParam(value = "orders", required = false) String orders) { + + PageResponse response = new PageResponse<>(); + + Pageable pageable = filterBuilderService.getPageable(size, page, orders); + GenericFilterCriteriaBuilder filterCriteriaBuilder = new GenericFilterCriteriaBuilder(); + + + List andConditions = filterBuilderService.createFilterCondition(filterAnd); + List orConditions = filterBuilderService.createFilterCondition(filterOr); + + Query query = filterCriteriaBuilder.addCondition(andConditions, orConditions); + Page pg = employeeService.getPage(query, pageable); + response.setPageStats(pg, pg.getContent()); + + return new ResponseEntity<>(response, HttpStatus.OK); + } + + /** + * @param filterOr string filter or conditions + * @param filterAnd string filter and conditions + * @return list of Employee + */ + @GetMapping() + public ResponseEntity> getAllSearchCriteria( + @RequestParam(value = "filterOr", required = false) String filterOr, + @RequestParam(value = "filterAnd", required = false) String filterAnd) { + + GenericFilterCriteriaBuilder filterCriteriaBuilder = new GenericFilterCriteriaBuilder(); + + List andConditions = filterBuilderService.createFilterCondition(filterAnd); + List orConditions = filterBuilderService.createFilterCondition(filterOr); + + Query query = filterCriteriaBuilder.addCondition(andConditions, orConditions); + List employees = employeeService.getAll(query); + + return new ResponseEntity<>(employees, HttpStatus.OK); + } + + +} \ No newline at end of file diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/controller/PageResponse.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/controller/PageResponse.java new file mode 100644 index 0000000..f4566ad --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/controller/PageResponse.java @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2019. @aek - (anicetkeric@gmail.com) + * 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. + * + */ + +package com.tutorial.springdatamongodbdynamicqueries.controller; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Sort; + +import java.util.List; + +@Setter +@Getter +@AllArgsConstructor +@NoArgsConstructor +public class PageResponse { + + private int totalPages; + private long totalItems; + private int currentPage; + private boolean first; + private boolean last; + private int itemsPerPage; + private int pageSize; + + private List items; + + public void setPageStats(Page pg, List elts) { + first = pg.isFirst(); + last = pg.isLast(); + currentPage = pg.getNumber() + 1; + pageSize = pg.getSize(); + totalPages = pg.getTotalPages(); + totalItems = pg.getTotalElements(); + itemsPerPage = pg.getNumberOfElements(); + items = elts; + } + + +} diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/controller/dto/FilterCondition.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/controller/dto/FilterCondition.java new file mode 100644 index 0000000..0a86f1f --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/controller/dto/FilterCondition.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2019. @aek - (anicetkeric@gmail.com) + * 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. + * + */ + +package com.tutorial.springdatamongodbdynamicqueries.controller.dto; + +import com.tutorial.springdatamongodbdynamicqueries.enums.FilterOperationEnum; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.RequiredArgsConstructor; +import lombok.Setter; + +/** + *

FilterCondition

+ * + * @author aek + *

+ * Description: Filter Condition Class + */ +@Setter +@Getter +@AllArgsConstructor +@RequiredArgsConstructor +public class FilterCondition { + + private String field; + private FilterOperationEnum operator; + private Object value; + +} diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/domain/Department.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/domain/Department.java new file mode 100644 index 0000000..e6756b5 --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/domain/Department.java @@ -0,0 +1,17 @@ +package com.tutorial.springdatamongodbdynamicqueries.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class Department { + + @NonNull + private String code; + + private String name; +} diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/domain/Employee.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/domain/Employee.java new file mode 100644 index 0000000..833fa56 --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/domain/Employee.java @@ -0,0 +1,27 @@ +package com.tutorial.springdatamongodbdynamicqueries.domain; + +import lombok.*; +import lombok.experimental.Accessors; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Builder +@Data +@AllArgsConstructor +@NoArgsConstructor +@Accessors(chain = true) +@Document(collection = "employee") +public class Employee { + + @Id + private String id; + + private String firstName; + + private String lastName; + + private String email; + + @NonNull + private Department department; +} \ No newline at end of file diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/enums/FilterOperationEnum.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/enums/FilterOperationEnum.java new file mode 100644 index 0000000..bba142a --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/enums/FilterOperationEnum.java @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2019. @aek - (anicetkeric@gmail.com) + * 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. + * + */ + +package com.tutorial.springdatamongodbdynamicqueries.enums; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + *

FilterOperation

+ * + * @author aek + *

+ * Description: + */ +public enum FilterOperationEnum { + + EQUAL("eq"), + NOT_EQUAL("neq"), + GREATER_THAN("gt"), + GREATER_THAN_OR_EQUAL_TO("gte"), + LESS_THAN("lt"), + LESSTHAN_OR_EQUAL_TO("lte"), + IN("in"), + NOT_IN("nin"), + BETWEEN("btn"), + CONTAINS("like"), + NOT_CONTAINS("notLike"), + IS_NULL("isnull"), + IS_NOT_NULL("isnotnull"), + START_WITH("startwith"), + END_WITH("endwith"), + IS_EMPTY("isempty"), + IS_NOT_EMPTY("isnotempty"), + JOIN("jn"), + IS("is"); + + + private final String value; + + FilterOperationEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + public static FilterOperationEnum fromValue(String value) { + for (FilterOperationEnum op : FilterOperationEnum.values()) { + + //Case insensitive operation name + if (String.valueOf(op.value).equalsIgnoreCase(value)) { + return op; + } + } + return null; + } + +} diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/EmployeeRepository.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/EmployeeRepository.java new file mode 100644 index 0000000..1546d07 --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/EmployeeRepository.java @@ -0,0 +1,8 @@ +package com.tutorial.springdatamongodbdynamicqueries.repository; + +import com.tutorial.springdatamongodbdynamicqueries.domain.Employee; +import org.springframework.stereotype.Repository; + +@Repository +public interface EmployeeRepository extends ResourceRepository { +} diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/ResourceRepository.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/ResourceRepository.java new file mode 100644 index 0000000..0075036 --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/ResourceRepository.java @@ -0,0 +1,18 @@ +package com.tutorial.springdatamongodbdynamicqueries.repository; + +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.data.repository.NoRepositoryBean; + +import java.io.Serializable; +import java.util.List; + +@NoRepositoryBean +public interface ResourceRepository extends MongoRepository { + + Page findAll(Query query, Pageable pageable); + + List findAll(Query query); +} \ No newline at end of file diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/support/GenericFilterCriteriaBuilder.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/support/GenericFilterCriteriaBuilder.java new file mode 100644 index 0000000..3e81ca3 --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/support/GenericFilterCriteriaBuilder.java @@ -0,0 +1,94 @@ +package com.tutorial.springdatamongodbdynamicqueries.repository.support; + +import com.tutorial.springdatamongodbdynamicqueries.controller.dto.FilterCondition; +import org.bson.types.ObjectId; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * This class is used to build all the queries passed as parameters. + * filterAndConditions (filter list for the AND operator) + * filterOrConditions (filter list for the OR operator) + */ +public class GenericFilterCriteriaBuilder { + + private final List filterAndConditions; + private final List filterOrConditions; + + private static final Map> + FILTER_CRITERIA = new HashMap<>(); + + // Create map of filter + static { + FILTER_CRITERIA.put("EQUAL", condition -> Criteria.where(condition.getField()).is(condition.getValue())); + FILTER_CRITERIA.put("NOT_EQUAL", condition -> Criteria.where(condition.getField()).ne(condition.getValue())); + FILTER_CRITERIA.put("GREATER_THAN", condition -> Criteria.where(condition.getField()).gt(condition.getValue())); + FILTER_CRITERIA.put("GREATER_THAN_OR_EQUAL_TO", condition -> Criteria.where(condition.getField()).gte(condition.getValue())); + FILTER_CRITERIA.put("LESS_THAN", condition -> Criteria.where(condition.getField()).lt(condition.getValue())); + FILTER_CRITERIA.put("LESSTHAN_OR_EQUAL_TO", condition -> Criteria.where(condition.getField()).lte(condition.getValue())); + FILTER_CRITERIA.put("CONTAINS", condition -> Criteria.where(condition.getField()).regex((String) condition.getValue())); + FILTER_CRITERIA.put("JOIN", condition -> Criteria.where(condition.getField()).is(new ObjectId((String) condition.getValue()))); + } + + + public GenericFilterCriteriaBuilder() { + filterOrConditions = new ArrayList<>(); + filterAndConditions = new ArrayList<>(); + } + + public Query addCondition(List andConditions, List orConditions) { + + if (andConditions != null && !andConditions.isEmpty()) { + filterAndConditions.addAll(andConditions); + } + if (orConditions != null && !orConditions.isEmpty()) { + filterOrConditions.addAll(orConditions); + } + + List criteriaAndClause = new ArrayList<>(); + List criteriaOrClause = new ArrayList<>(); + Criteria criteria = new Criteria(); + + // build criteria + filterAndConditions.stream().map(condition -> criteriaAndClause.add(buildCriteria(condition))).collect(Collectors.toList()); + filterOrConditions.stream().map(condition -> criteriaOrClause.add(buildCriteria(condition))).collect(Collectors.toList()); + + + if (!criteriaAndClause.isEmpty() && !criteriaOrClause.isEmpty()) { + return new Query(criteria.andOperator(criteriaAndClause.toArray(new Criteria[0])).orOperator(criteriaOrClause.toArray(new Criteria[0]))); + } else if (!criteriaAndClause.isEmpty()) { + return new Query(criteria.andOperator(criteriaAndClause.toArray(new Criteria[0]))); + } else if (!criteriaOrClause.isEmpty()) { + return new Query(criteria.orOperator(criteriaOrClause.toArray(new Criteria[0]))); + } else { + return new Query(); + } + + } + + + /** + * Build the predicate according to the request + * + * @param condition The condition of the filter requested by the query + * @return {{@link Criteria}} + */ + private Criteria buildCriteria(FilterCondition condition) { + Function + function = FILTER_CRITERIA.get(condition.getOperator().name()); + + if (function == null) { + throw new IllegalArgumentException("Invalid function param type: "); + } + + return function.apply(condition); + } + +} diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/support/ResourceRepositoryImpl.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/support/ResourceRepositoryImpl.java new file mode 100644 index 0000000..e78fe2e --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/repository/support/ResourceRepositoryImpl.java @@ -0,0 +1,43 @@ +package com.tutorial.springdatamongodbdynamicqueries.repository.support; + +import com.tutorial.springdatamongodbdynamicqueries.repository.ResourceRepository; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; +import org.springframework.data.mongodb.core.MongoOperations; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.repository.query.MongoEntityInformation; +import org.springframework.data.mongodb.repository.support.SimpleMongoRepository; +import org.springframework.util.Assert; + +import java.io.Serializable; +import java.util.List; + +public class ResourceRepositoryImpl extends SimpleMongoRepository implements ResourceRepository { + + private MongoOperations mongoOperations; + private MongoEntityInformation entityInformation; + + public ResourceRepositoryImpl(final MongoEntityInformation entityInformation, final MongoOperations mongoOperations) { + super(entityInformation, mongoOperations); + + this.entityInformation = entityInformation; + this.mongoOperations = mongoOperations; + } + + @Override + public Page findAll(final Query query, final Pageable pageable) { + Assert.notNull(query, "Query must not be null!"); + + long total = mongoOperations.count(query, entityInformation.getJavaType(), entityInformation.getCollectionName()); + List content = mongoOperations.find(query.with(pageable), entityInformation.getJavaType(), entityInformation.getCollectionName()); + + return new PageImpl(content, pageable, total); + } + + @Override + public List findAll(Query query) { + Assert.notNull(query, "Query must not be null!"); + return mongoOperations.find(query, entityInformation.getJavaType(), entityInformation.getCollectionName()); + } +} \ No newline at end of file diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/service/EmployeeService.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/service/EmployeeService.java new file mode 100644 index 0000000..5978438 --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/service/EmployeeService.java @@ -0,0 +1,28 @@ +package com.tutorial.springdatamongodbdynamicqueries.service; + + +import com.tutorial.springdatamongodbdynamicqueries.domain.Employee; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.mongodb.core.query.Query; + +import java.util.List; + +public interface EmployeeService { + + + /** + * @param query custom query + * @return list of Employee + */ + List getAll(Query query); + + /** + * Get all custom paginate data for entity Employee + * + * @param query custom query + * @param pageable pageable param + * @return Page of entity Employee + */ + Page getPage(Query query, Pageable pageable); +} \ No newline at end of file diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/service/EmployeeServiceImpl.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/service/EmployeeServiceImpl.java new file mode 100644 index 0000000..bd33999 --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/service/EmployeeServiceImpl.java @@ -0,0 +1,37 @@ +package com.tutorial.springdatamongodbdynamicqueries.service; + +import com.tutorial.springdatamongodbdynamicqueries.domain.Employee; +import com.tutorial.springdatamongodbdynamicqueries.repository.EmployeeRepository; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class EmployeeServiceImpl implements EmployeeService { + + private final EmployeeRepository employeeRepository; + + public EmployeeServiceImpl(EmployeeRepository employeeRepository) { + this.employeeRepository = employeeRepository; + } + + /** + * {@inheritDoc} + */ + @Override + public List getAll(Query query) { + return employeeRepository.findAll(query); + } + + /** + * {@inheritDoc} + */ + @Override + public Page getPage(Query query, Pageable pageable) { + return employeeRepository.findAll(query, pageable); + } + +} \ No newline at end of file diff --git a/src/main/java/com/tutorial/springdatamongodbdynamicqueries/service/FilterBuilderService.java b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/service/FilterBuilderService.java new file mode 100644 index 0000000..c6c70d0 --- /dev/null +++ b/src/main/java/com/tutorial/springdatamongodbdynamicqueries/service/FilterBuilderService.java @@ -0,0 +1,100 @@ +package com.tutorial.springdatamongodbdynamicqueries.service; + +import com.tutorial.springdatamongodbdynamicqueries.controller.dto.FilterCondition; +import com.tutorial.springdatamongodbdynamicqueries.enums.FilterOperationEnum; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Service for Filtering Page + * This class is used to extract any filters requested by the client. + */ +@Service +public class FilterBuilderService { + + private static final int DEFAULT_SIZE_PAGE = 20; + + + /** + * Prepare filter condition. extract the different filters used in the controller via @RequestParam + * + * @param criteria search Criteria. + * @return a list of {@link FilterCondition} + */ + public List createFilterCondition(String criteria) { + // TODO ajouter try catch + + + List filters = new ArrayList<>(); + + if (criteria != null && !criteria.isEmpty()) { + + final String FILTER_SHEARCH_DELIMITER = "&"; + final String FILTER_CONDITION_DELIMITER = "\\|"; + + List values = split(criteria, FILTER_SHEARCH_DELIMITER); + if (!values.isEmpty()) { + values.forEach(x -> { + List filter = split(x, FILTER_CONDITION_DELIMITER); + if (FilterOperationEnum.fromValue(filter.get(1)) != null) { + filters.add(new FilterCondition(filter.get(0), FilterOperationEnum.fromValue(filter.get(1)), filter.get(2))); + } + }); + } + } + + return filters; + } + + + private static List split(String search, String delimiter) { + return Stream.of(search.split(delimiter)) + .collect(Collectors.toList()); + } + + + /** + * Get request pageable. Page Request Builder. custom pageable + * + * @param size the number of items to collect + * @param page page number + * @param order search order filter (eg: field|ASC) + * @return PageRequest + */ + public PageRequest getPageable(int size, int page, String order) { + // TODO ajouter try catch + + int pageSize = (size <= 0) ? DEFAULT_SIZE_PAGE : size; + int currentPage = (page <= 0) ? 1 : page; + + if (order != null && !order.isEmpty()) { + + final String FILTER_CONDITION_DELIMITER = "\\|"; + + List values = split(order, FILTER_CONDITION_DELIMITER); + String column = values.get(0); + String sortDirection = values.get(1); + + if (sortDirection.equalsIgnoreCase("ASC")) { + return PageRequest.of((currentPage - 1), pageSize, Sort.by(Sort.Direction.ASC, column)); + } else if (sortDirection.equalsIgnoreCase("DESC")) { + return PageRequest.of((currentPage - 1), pageSize, Sort.by(Sort.Direction.DESC, column)); + } else { + throw new IllegalArgumentException(String.format("Value for param 'order' is not valid : %s , must be 'asc' or 'desc'", sortDirection)); + } + + }else { + return PageRequest.of((currentPage - 1), pageSize); + } + } + + + + +} diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..db10723 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,8 @@ +spring: + data: + mongodb: + host: localhost + port: 27017 + database: mongo_dynamic_search + username: admin + password: 7MlG8f&H \ No newline at end of file diff --git a/src/test/java/com/tutorial/springdatamongodbdynamicqueries/SpringDataMongodbDynamicQueriesApplicationTests.java b/src/test/java/com/tutorial/springdatamongodbdynamicqueries/SpringDataMongodbDynamicQueriesApplicationTests.java new file mode 100644 index 0000000..db46bda --- /dev/null +++ b/src/test/java/com/tutorial/springdatamongodbdynamicqueries/SpringDataMongodbDynamicQueriesApplicationTests.java @@ -0,0 +1,13 @@ +package com.tutorial.springdatamongodbdynamicqueries; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class SpringDataMongodbDynamicQueriesApplicationTests { + + @Test + void contextLoads() { + } + +}