diff --git a/mongodb-optimization-tips/.gitignore b/mongodb-optimization-tips/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/mongodb-optimization-tips/.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/mongodb-optimization-tips/build.gradle b/mongodb-optimization-tips/build.gradle new file mode 100644 index 0000000..ae1230d --- /dev/null +++ b/mongodb-optimization-tips/build.gradle @@ -0,0 +1,34 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.3' + id 'io.spring.dependency-management' version '1.1.4' +} + +group = 'com.stacktips' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '17' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-mongodb' + implementation 'org.springframework.boot:spring-boot-starter-web' + implementation 'org.projectlombok:lombok' + annotationProcessor('org.projectlombok:lombok') + + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testImplementation 'org.springframework.boot:spring-boot-testcontainers' + testImplementation 'org.testcontainers:junit-jupiter' + testImplementation 'org.testcontainers:mongodb' + implementation 'com.opencsv:opencsv:5.7.1' + +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/mongodb-optimization-tips/gradle/wrapper/gradle-wrapper.jar b/mongodb-optimization-tips/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/mongodb-optimization-tips/gradle/wrapper/gradle-wrapper.jar differ diff --git a/mongodb-optimization-tips/gradle/wrapper/gradle-wrapper.properties b/mongodb-optimization-tips/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..1af9e09 --- /dev/null +++ b/mongodb-optimization-tips/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/mongodb-optimization-tips/gradlew b/mongodb-optimization-tips/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/mongodb-optimization-tips/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/mongodb-optimization-tips/gradlew.bat b/mongodb-optimization-tips/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/mongodb-optimization-tips/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem 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, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/mongodb-optimization-tips/readme.md b/mongodb-optimization-tips/readme.md new file mode 100644 index 0000000..deafcbb --- /dev/null +++ b/mongodb-optimization-tips/readme.md @@ -0,0 +1,22 @@ +# Testing Spring Boot Repository Using MongoDB Testcontainers + +Testcontainers are lightweight, throwaway container instances, used for common test cases like testing against a database, ActiveMQ or anything else that can run in a Docker container. + +Testcontainers allows you to run your tests against a real instance of your application's dependencies, such as a real database, rather than against a mock or an in-memory database. We can configure the Testcontainers to closely mimic the production environment by using the specific versions of your dependencies and pre-loading with test data. + +It spins up a new container instance for each test, hence every test is completely isolated from each other. + +For running tests using the Testcontainers, we need to have the docker up and running, no other dependencies are required. + +Read [the full article here](https://stacktips.com/articles/testing-spring-boot-repository-using-mongodb-testcontainers) + +### Related topics: + +* [#spring-boot](https://stacktips.com/topics/spring-boot) +* [#android](https://stacktips.com/topics/android) +* [#java](https://stacktips.com/topics/java) +* [#python](https://stacktips.com/topics/python) +* [#spring](https://stacktips.com/topics/spring) +* [#design-pattern](https://stacktips.com/topics/design-pattern) +* [#git](https://stacktips.com/topics/git) +* [#maven](https://stacktips.com/topics/maven) diff --git a/mongodb-optimization-tips/settings.gradle b/mongodb-optimization-tips/settings.gradle new file mode 100644 index 0000000..5d549ef --- /dev/null +++ b/mongodb-optimization-tips/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'mongodb-optimization-tips' diff --git a/mongodb-optimization-tips/src/main/java/com/stacktips/movies/MoviesApiApplication.java b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/MoviesApiApplication.java new file mode 100644 index 0000000..92a624b --- /dev/null +++ b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/MoviesApiApplication.java @@ -0,0 +1,14 @@ +package com.stacktips.movies; + +import lombok.RequiredArgsConstructor; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +@RequiredArgsConstructor +public class MoviesApiApplication { + + public static void main(String[] args) { + SpringApplication.run(MoviesApiApplication.class, args); + } +} diff --git a/mongodb-optimization-tips/src/main/java/com/stacktips/movies/config/MongoConfiguration.java b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/config/MongoConfiguration.java new file mode 100644 index 0000000..ba92910 --- /dev/null +++ b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/config/MongoConfiguration.java @@ -0,0 +1,31 @@ +package com.stacktips.movies.config; + +import com.mongodb.ReadPreference; +import com.mongodb.WriteConcern; +import org.springframework.boot.autoconfigure.mongo.MongoClientSettingsBuilderCustomizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.mongodb.core.WriteConcernResolver; + +@Configuration +public class MongoConfiguration { + + @Bean + public WriteConcernResolver writeConcernResolver() { + return action -> { + String entityName = action.getEntityType().getSimpleName(); + if (entityName.contains("Product")) { + return WriteConcern.ACKNOWLEDGED; + } else if (entityName.contains("Metadata")) { + return WriteConcern.JOURNALED; + } + return action.getDefaultWriteConcern(); + + }; + } + + @Bean + public MongoClientSettingsBuilderCustomizer monoClientCustomizer() { + return builder -> builder.readPreference(ReadPreference.nearest()); + } +} \ No newline at end of file diff --git a/mongodb-optimization-tips/src/main/java/com/stacktips/movies/dto/TotalSales.java b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/dto/TotalSales.java new file mode 100644 index 0000000..67b5985 --- /dev/null +++ b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/dto/TotalSales.java @@ -0,0 +1,13 @@ +package com.stacktips.movies.dto; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +@Getter +@Setter +@ToString +public class TotalSales { + private String productName; + private double totalSales; +} diff --git a/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/LogEntry.java b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/LogEntry.java new file mode 100644 index 0000000..d63ead6 --- /dev/null +++ b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/LogEntry.java @@ -0,0 +1,17 @@ +package com.stacktips.movies.models; + +import lombok.*; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Getter +@Setter +@AllArgsConstructor +@RequiredArgsConstructor +@Document(collection = "logs") +public class LogEntry { + + @Id + private String id; + private final String log; +} diff --git a/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/Price.java b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/Price.java new file mode 100644 index 0000000..f121b93 --- /dev/null +++ b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/Price.java @@ -0,0 +1,19 @@ +package com.stacktips.movies.models; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Document(collection = "Price") +public class Price { + @Id + private String id; + private double price; +} diff --git a/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/Product.java b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/Product.java new file mode 100644 index 0000000..324f40e --- /dev/null +++ b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/Product.java @@ -0,0 +1,20 @@ +package com.stacktips.movies.models; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@Document(collection = "Product") +public class Product { + @Id + private String id; + private String name; + private String brand; +} diff --git a/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/Sales.java b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/Sales.java new file mode 100644 index 0000000..2b31808 --- /dev/null +++ b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/models/Sales.java @@ -0,0 +1,24 @@ +package com.stacktips.movies.models; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import org.bson.types.ObjectId; +import org.springframework.data.annotation.Id; +import org.springframework.data.mongodb.core.mapping.Document; + +import java.util.Date; + +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +@Document(collection = "Sales") +public class Sales { + @Id + private String id; + private String productId; + private int quantity; + private Date date; +} diff --git a/mongodb-optimization-tips/src/main/java/com/stacktips/movies/repository/ProductRepository.java b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/repository/ProductRepository.java new file mode 100644 index 0000000..6e1b2fc --- /dev/null +++ b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/repository/ProductRepository.java @@ -0,0 +1,26 @@ +package com.stacktips.movies.repository; + +import com.stacktips.movies.models.Product; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Repository; + +import java.util.List; + +@Repository +public class ProductRepository { + + private final MongoTemplate mongoTemplate; + + public ProductRepository(MongoTemplate mongoTemplate) { + this.mongoTemplate = mongoTemplate; + } + + public List getProducts(int page, int size) { + Pageable pageable = PageRequest.of(page, size); + Query query = new Query().with(pageable); + return mongoTemplate.find(query, Product.class); + } +} diff --git a/mongodb-optimization-tips/src/main/java/com/stacktips/movies/repository/SalesRepository.java b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/repository/SalesRepository.java new file mode 100644 index 0000000..18246af --- /dev/null +++ b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/repository/SalesRepository.java @@ -0,0 +1,64 @@ +package com.stacktips.movies.repository; + +import com.stacktips.movies.dto.TotalSales; +import lombok.RequiredArgsConstructor; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.aggregation.*; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.stereotype.Repository; + +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +@Repository +@RequiredArgsConstructor +public class SalesRepository { + + private final MongoTemplate mongoTemplate; + + public List calculateLastMonthSales() { + MatchOperation matchStage = Aggregation.match(Criteria.where("date") + .gte(getLastMonthStartDate()) + .lte(new Date())); + + LookupOperation lookupProduct = Aggregation.lookup( + "Product", "productId", "_id", "product"); + LookupOperation lookupPrice = Aggregation.lookup( + "Price", "productId", "_id", "price"); + UnwindOperation unwindProduct = Aggregation.unwind("product"); + UnwindOperation unwindPrice = Aggregation.unwind("price"); + + GroupOperation groupStage = Aggregation.group("product.name") + .sum(ArithmeticOperators.Multiply.valueOf("quantity") + .multiplyBy("price.price")) + .as("totalSales"); + + ProjectionOperation projectStage = Aggregation.project() + .andExpression("_id").as("productName") + .andExpression("totalSales").as("totalSales") + .andExclude("_id"); + + Aggregation aggregation = Aggregation.newAggregation(matchStage, + lookupProduct, + unwindProduct, + lookupPrice, + unwindPrice, + groupStage, + projectStage); + AggregationResults results = mongoTemplate.aggregate( + aggregation, "Sales", TotalSales.class); + return results.getMappedResults(); + } + + private Date getLastMonthStartDate() { + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, -1); + calendar.set(Calendar.DAY_OF_MONTH, 1); + calendar.set(Calendar.HOUR_OF_DAY, 0); + calendar.set(Calendar.MINUTE, 0); + calendar.set(Calendar.SECOND, 0); + calendar.set(Calendar.MILLISECOND, 0); + return calendar.getTime(); + } +} diff --git a/mongodb-optimization-tips/src/main/java/com/stacktips/movies/services/ApplicationLogger.java b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/services/ApplicationLogger.java new file mode 100644 index 0000000..34cb1a3 --- /dev/null +++ b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/services/ApplicationLogger.java @@ -0,0 +1,40 @@ +package com.stacktips.movies.services; + +import com.stacktips.movies.models.LogEntry; +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.CommandLineRunner; +import org.springframework.data.mongodb.core.CollectionOptions; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ApplicationLogger implements CommandLineRunner { + + private final MongoTemplate mongoTemplate; + + private static final long MAX_SIZE = 5 * 1024 * 1024; + private static final long MAX_DOCUMENTS = 100; + + @PostConstruct + public void init() { + if (!mongoTemplate.collectionExists(LogEntry.class)) { + mongoTemplate.createCollection(LogEntry.class, + CollectionOptions.empty().capped() + .size(MAX_SIZE) + .maxDocuments(MAX_DOCUMENTS)); + } + } + + @Override + public void run(String... args) throws Exception { + for (int i = 1; i <= 1500; i++) { + mongoTemplate.save(new LogEntry("Log entry " + i)); + } + log.info("Size: {0}", mongoTemplate.count(new Query(), LogEntry.class)); + } +} \ No newline at end of file diff --git a/mongodb-optimization-tips/src/main/java/com/stacktips/movies/services/DataLoader.java b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/services/DataLoader.java new file mode 100644 index 0000000..8c67f8d --- /dev/null +++ b/mongodb-optimization-tips/src/main/java/com/stacktips/movies/services/DataLoader.java @@ -0,0 +1,41 @@ +package com.stacktips.movies.services; + +import com.opencsv.bean.CsvToBeanBuilder; +import com.stacktips.movies.models.Product; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.CommandLineRunner; +import org.springframework.data.mongodb.core.BulkOperations; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.stereotype.Component; + +import java.io.FileReader; +import java.io.IOException; +import java.io.Reader; +import java.util.List; + +@Component +@RequiredArgsConstructor +public class DataLoader implements CommandLineRunner { + + private static final String FILE_PATH = "src/main/resources/products.csv"; + + private final MongoTemplate mongoTemplate; + + @Override + public void run(String... args) throws Exception { + List products = parseCsv(FILE_PATH, Product.class) + .stream() + .map(row -> new Product(row.getId(), row.getName(), row.getBrand())) + .toList(); + + mongoTemplate.bulkOps(BulkOperations.BulkMode.ORDERED, Product.class) + .insert(products) + .execute(); + } + + public static List parseCsv(String filePath, Class type) throws IOException { + try (Reader reader = new FileReader(filePath)) { + return new CsvToBeanBuilder(reader).withType(type).build().parse(); + } + } +} diff --git a/mongodb-optimization-tips/src/main/resources/application.yaml b/mongodb-optimization-tips/src/main/resources/application.yaml new file mode 100644 index 0000000..46528fa --- /dev/null +++ b/mongodb-optimization-tips/src/main/resources/application.yaml @@ -0,0 +1,15 @@ +spring: + data: + mongodb: + uri: mongodb://localhost:27017/mongodb_optimization_tips + authentication-database: admin + +logging: + level: + org: + springframework: + data: + mongodb: + core: + MongoTemplate: debug + root: warn \ No newline at end of file diff --git a/mongodb-optimization-tips/src/main/resources/products.csv b/mongodb-optimization-tips/src/main/resources/products.csv new file mode 100644 index 0000000..9a267c5 --- /dev/null +++ b/mongodb-optimization-tips/src/main/resources/products.csv @@ -0,0 +1,101 @@ +id,name,brand +productId1,Product 0,Brand A +productId2,Product 1,Brand C +productId3,Product 2,Brand E +productId4,Product 3,Brand C +productId5,Product 4,Brand E +productId6,Product 5,Brand D +productId7,Product 6,Brand A +productId8,Product 7,Brand B +productId9,Product 8,Brand A +productId10,Product 9,Brand A +productId11,Product 10,Brand A +productId12,Product 11,Brand E +productId13,Product 12,Brand B +productId14,Product 13,Brand E +productId15,Product 14,Brand B +productId16,Product 15,Brand E +productId17,Product 16,Brand E +productId18,Product 17,Brand B +productId19,Product 18,Brand A +productId20,Product 19,Brand E +productId21,Product 20,Brand D +productId22,Product 21,Brand E +productId23,Product 22,Brand B +productId24,Product 23,Brand A +productId25,Product 24,Brand D +productId26,Product 25,Brand C +productId27,Product 26,Brand E +productId28,Product 27,Brand E +productId29,Product 28,Brand B +productId30,Product 29,Brand A +productId31,Product 30,Brand E +productId32,Product 31,Brand C +productId33,Product 32,Brand D +productId34,Product 33,Brand B +productId35,Product 34,Brand E +productId36,Product 35,Brand E +productId37,Product 36,Brand B +productId38,Product 37,Brand B +productId39,Product 38,Brand D +productId40,Product 39,Brand D +productId41,Product 40,Brand D +productId42,Product 41,Brand A +productId43,Product 42,Brand B +productId44,Product 43,Brand C +productId45,Product 44,Brand D +productId46,Product 45,Brand D +productId47,Product 46,Brand E +productId48,Product 47,Brand D +productId49,Product 48,Brand D +productId50,Product 49,Brand D +productId51,Product 50,Brand D +productId52,Product 51,Brand B +productId53,Product 52,Brand C +productId54,Product 53,Brand B +productId55,Product 54,Brand A +productId56,Product 55,Brand C +productId57,Product 56,Brand B +productId58,Product 57,Brand C +productId59,Product 58,Brand C +productId60,Product 59,Brand E +productId61,Product 60,Brand D +productId62,Product 61,Brand D +productId63,Product 62,Brand E +productId64,Product 63,Brand E +productId65,Product 64,Brand D +productId66,Product 65,Brand E +productId67,Product 66,Brand C +productId68,Product 67,Brand B +productId69,Product 68,Brand D +productId70,Product 69,Brand D +productId71,Product 70,Brand C +productId72,Product 71,Brand C +productId73,Product 72,Brand A +productId74,Product 73,Brand D +productId75,Product 74,Brand B +productId76,Product 75,Brand C +productId77,Product 76,Brand C +productId78,Product 77,Brand C +productId79,Product 78,Brand A +productId80,Product 79,Brand A +productId81,Product 80,Brand B +productId82,Product 81,Brand C +productId83,Product 82,Brand E +productId84,Product 83,Brand D +productId85,Product 84,Brand B +productId86,Product 85,Brand D +productId87,Product 86,Brand C +productId88,Product 87,Brand D +productId89,Product 88,Brand D +productId90,Product 89,Brand D +productId91,Product 90,Brand D +productId92,Product 91,Brand B +productId93,Product 92,Brand C +productId94,Product 93,Brand C +productId95,Product 94,Brand D +productId96,Product 95,Brand E +productId97,Product 96,Brand A +productId98,Product 97,Brand B +productId99,Product 98,Brand D +productId100,Product 99,Brand B diff --git a/mongodb-optimization-tips/src/test/java/com/stacktips/movies/repository/SalesRepositoryTest.java b/mongodb-optimization-tips/src/test/java/com/stacktips/movies/repository/SalesRepositoryTest.java new file mode 100644 index 0000000..ae16cc7 --- /dev/null +++ b/mongodb-optimization-tips/src/test/java/com/stacktips/movies/repository/SalesRepositoryTest.java @@ -0,0 +1,113 @@ +package com.stacktips.movies.repository; + +import com.stacktips.movies.dto.TotalSales; +import com.stacktips.movies.models.Price; +import com.stacktips.movies.models.Product; +import com.stacktips.movies.models.Sales; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.stereotype.Repository; +import org.springframework.test.context.DynamicPropertyRegistry; +import org.springframework.test.context.DynamicPropertySource; +import org.testcontainers.containers.MongoDBContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +import java.util.Calendar; +import java.util.Date; +import java.util.List; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +@Testcontainers +@DataMongoTest(includeFilters = @ComponentScan.Filter(Repository.class)) +class SalesRepositoryTest { + + @Autowired + SalesRepository repository; + + @Autowired + MongoTemplate mongoTemplate; + + @Container + static final MongoDBContainer mongoDbContainer = new MongoDBContainer("mongo:latest") + .withExposedPorts(27017); + + @DynamicPropertySource + static void setProperties(DynamicPropertyRegistry registry) { + registry.add("spring.data.mongodb.host", mongoDbContainer::getHost); + registry.add("spring.data.mongodb.port", mongoDbContainer::getFirstMappedPort); + registry.add("spring.data.mongodb.username", () -> "test_user"); + registry.add("spring.data.mongodb.password", () -> "test_password"); + registry.add("spring.data.mongodb.database", () -> "movies_db"); + registry.add("spring.data.mongodb.uri", mongoDbContainer::getReplicaSetUrl); + } + + static { + mongoDbContainer.start(); + } + + @BeforeEach + public void setUp() { + mongoTemplate.dropCollection("Product"); + mongoTemplate.dropCollection("Price"); + mongoTemplate.dropCollection("Sales"); + List products = List.of( + new Product("productId1", "Product A", "Brand A"), + new Product("productId2", "Product B", "Brand B"), + new Product("productId3", "Product B", "Brand C") + ); + List prices = List.of( + new Price("productId1", 100), + new Price("productId2", 200), + new Price("productId3", 150) + ); + List sales = List.of( + new Sales("saleId1", "productId1", 3, getSaleDate(1)), + new Sales("saleId2", "productId1", 3, getSaleDate(3)), + new Sales("saleId3", "productId1", 5, getSaleDate(1)), + new Sales("saleId4", "productId2", 3, getSaleDate(1)) + ); + + mongoTemplate.insertAll(products); + mongoTemplate.insertAll(prices); + mongoTemplate.insertAll(sales); + } + + @Test + void testCalculateLastMonthSales() { + List totalSalesList = repository.calculateLastMonthSales(); + System.out.println(totalSalesList); + + assertThat(totalSalesList, is(notNullValue())); + assertThat(totalSalesList.size(), comparesEqualTo(2)); + + TotalSales productASales = totalSalesList.stream() + .filter(totalSales -> "Product A".equals(totalSales.getProductName())) + .findFirst() + .orElse(null); + + TotalSales productBSales = totalSalesList.stream() + .filter(totalSales -> "Product B".equals(totalSales.getProductName())) + .findFirst() + .orElse(null); + + assertThat(productASales, is(notNullValue())); + assertThat(productBSales, is(notNullValue())); + assertThat(productASales.getTotalSales(), is(800.0)); + + assertThat(productBSales, is(notNullValue())); + assertThat(productBSales.getTotalSales(), is(600.0)); + } + + Date getSaleDate(int monthsToGoBack) { + Calendar calendar = Calendar.getInstance(); + calendar.add(Calendar.MONTH, -monthsToGoBack); + return calendar.getTime(); + } +} \ No newline at end of file diff --git a/spring-boot-feature-toggle/.gitignore b/spring-boot-feature-toggle/.gitignore new file mode 100644 index 0000000..c2065bc --- /dev/null +++ b/spring-boot-feature-toggle/.gitignore @@ -0,0 +1,37 @@ +HELP.md +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ diff --git a/spring-boot-feature-toggle/build.gradle b/spring-boot-feature-toggle/build.gradle new file mode 100644 index 0000000..a9fe461 --- /dev/null +++ b/spring-boot-feature-toggle/build.gradle @@ -0,0 +1,28 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.3.0' + id 'io.spring.dependency-management' version '1.1.5' +} + +group = 'com.stacktips.app' +version = '0.0.1-SNAPSHOT' + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-web' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + useJUnitPlatform() +} diff --git a/spring-boot-feature-toggle/gradle/wrapper/gradle-wrapper.jar b/spring-boot-feature-toggle/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/spring-boot-feature-toggle/gradle/wrapper/gradle-wrapper.jar differ diff --git a/spring-boot-feature-toggle/gradle/wrapper/gradle-wrapper.properties b/spring-boot-feature-toggle/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a441313 --- /dev/null +++ b/spring-boot-feature-toggle/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/spring-boot-feature-toggle/gradlew b/spring-boot-feature-toggle/gradlew new file mode 100755 index 0000000..b740cf1 --- /dev/null +++ b/spring-boot-feature-toggle/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/spring-boot-feature-toggle/gradlew.bat b/spring-boot-feature-toggle/gradlew.bat new file mode 100644 index 0000000..7101f8e --- /dev/null +++ b/spring-boot-feature-toggle/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem 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, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/spring-boot-feature-toggle/settings.gradle b/spring-boot-feature-toggle/settings.gradle new file mode 100644 index 0000000..d8c35df --- /dev/null +++ b/spring-boot-feature-toggle/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'spring-boot-feature-toggle' diff --git a/spring-boot-feature-toggle/src/main/java/com/stacktips/app/MyApplication.java b/spring-boot-feature-toggle/src/main/java/com/stacktips/app/MyApplication.java new file mode 100644 index 0000000..69d8a40 --- /dev/null +++ b/spring-boot-feature-toggle/src/main/java/com/stacktips/app/MyApplication.java @@ -0,0 +1,13 @@ +package com.stacktips.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class MyApplication { + + public static void main(String[] args) { + SpringApplication.run(MyApplication.class, args); + } + +} diff --git a/spring-boot-feature-toggle/src/main/resources/application.properties b/spring-boot-feature-toggle/src/main/resources/application.properties new file mode 100644 index 0000000..ed79ec5 --- /dev/null +++ b/spring-boot-feature-toggle/src/main/resources/application.properties @@ -0,0 +1 @@ +spring.application.name=spring-boot-feature-toggle diff --git a/spring-boot-feature-toggle/src/test/java/com/stacktips/app/MyApplicationTests.java b/spring-boot-feature-toggle/src/test/java/com/stacktips/app/MyApplicationTests.java new file mode 100644 index 0000000..7782f23 --- /dev/null +++ b/spring-boot-feature-toggle/src/test/java/com/stacktips/app/MyApplicationTests.java @@ -0,0 +1,13 @@ +package com.stacktips.app; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class MyApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/spring-dependency-injection/spring-dependency-injection/build2.gradle b/spring-dependency-injection/spring-dependency-injection/build2.gradle new file mode 100644 index 0000000..d02cf27 --- /dev/null +++ b/spring-dependency-injection/spring-dependency-injection/build2.gradle @@ -0,0 +1,46 @@ +plugins { + id 'java' + id 'org.springframework.boot' version '3.2.5' + id 'io.spring.dependency-management' version '1.1.4' +} + +group = 'com.stacktps.app' +version = '0.0.1-SNAPSHOT' + +java { + sourceCompatibility = '21' +} + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.springframework.boot:spring-boot-starter-data-jpa' + implementation 'org.springframework.boot:spring-boot-starter-web' + testImplementation 'org.springframework.boot:spring-boot-starter-test' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +tasks.named('test') { + useJUnitPlatform() +} + + + + + + + + + + + + + + + + + + + diff --git a/spring-dependency-injection/spring-dependency-injection/pom.xml b/spring-dependency-injection/spring-dependency-injection/pom.xml new file mode 100644 index 0000000..aac245a --- /dev/null +++ b/spring-dependency-injection/spring-dependency-injection/pom.xml @@ -0,0 +1,44 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.2.5 + + + com.stacktps.app + movies-api + 0.0.1-SNAPSHOT + movies-api + Demo project for Spring Boot + + 21 + + + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + + + +