This commit is contained in:
Ahmed Tawila 2017-10-31 18:42:46 +02:00
commit c9889b0e2d
269 changed files with 1276 additions and 538 deletions

Binary file not shown.

View File

@ -1 +0,0 @@
distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.0/apache-maven-3.5.0-bin.zip

View File

@ -1 +0,0 @@
## Relevant articles:

225
cas-secured-app/mvnw vendored
View File

@ -1,225 +0,0 @@
#!/bin/sh
# ----------------------------------------------------------------------------
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
# ----------------------------------------------------------------------------
# ----------------------------------------------------------------------------
# Maven2 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 Migwn, 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)`"
# TODO classpath?
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
export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}
echo $MAVEN_PROJECTBASEDIR
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
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 "$@"

View File

@ -1,143 +0,0 @@
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM http://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven2 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 key stroke 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 enable echoing my 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
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%

View File

@ -21,4 +21,7 @@ build/
nbbuild/
dist/
nbdist/
.nb-gradle/
.nb-gradle/
/.mvn/
/mvnw
/mvnw.cmd

View File

@ -106,75 +106,5 @@
</pluginRepository>
</pluginRepositories>
<profiles>
<profile>
<id>integration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/AutoconfigurationTest.java</exclude>
</excludes>
<includes>
<include>**/*IntegrationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>autoconfiguration</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<excludes>
<exclude>**/*LiveTest.java</exclude>
<exclude>**/*IntegrationTest.java</exclude>
</excludes>
<includes>
<include>**/AutoconfigurationTest.java</include>
</includes>
</configuration>
</execution>
</executions>
<configuration>
<systemPropertyVariables>
<test.mime>json</test.mime>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -7,7 +7,7 @@ import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class CasSecuredAppApplicationIntegrationTest {
public class CasSecuredAppApplicationTests {
@Test
public void contextLoads() {

View File

@ -8,7 +8,9 @@ import java.util.concurrent.Future;
import org.apache.commons.lang3.RandomUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -18,22 +20,34 @@ public class RunnableVsThreadTest {
private static Logger log =
LoggerFactory.getLogger(RunnableVsThreadTest.class);
private static ExecutorService executorService;
@BeforeClass
public static void setup() {
executorService = Executors.newCachedThreadPool();
}
@Test
public void givenARunnable_whenRunIt_thenResult() throws Exception{
Thread thread = new Thread(new SimpleRunnable(
"SimpleRunnable executed using Thread"));
thread.start();
thread.join();
ExecutorService executorService =
Executors.newCachedThreadPool();
}
@Test
public void givenARunnable_whenSubmitToES_thenResult() throws Exception{
executorService.submit(new SimpleRunnable(
"SimpleRunnable executed using ExecutorService")).get();
}
@Test
public void givenARunnableLambda_whenSubmitToES_thenResult()
throws Exception{
executorService.submit(()->
log.info("Lambda runnable executed!!!")).get();
executorService.shutdown();
}
@Test
@ -42,26 +56,39 @@ public class RunnableVsThreadTest {
"SimpleThread executed using Thread");
thread.start();
thread.join();
}
@Test
public void givenAThread_whenSubmitToES_thenResult() throws Exception{
ExecutorService executorService =
Executors.newCachedThreadPool();
executorService.submit(new SimpleThread(
"SimpleThread executed using ExecutorService")).get();
}
@Test
public void givenACallable_whenRunIt_thenResult() throws Exception {
ExecutorService executorService =
Executors.newCachedThreadPool();
public void givenACallable_whenSubmitToES_thenResult() throws Exception {
Future<Integer> future = executorService.submit(new SimpleCallable());
Future<Integer> future = executorService.submit(
new SimpleCallable());
log.info("Result from callable: {}", future.get());
}
@Test
public void givenACallableAsLambda_whenSubmitToES_thenResult()
throws Exception {
future = executorService.submit(() -> {
Future<Integer> future = executorService.submit(() -> {
return RandomUtils.nextInt(0, 100);
});
});
log.info("Result from callable: {}", future.get());
}
@AfterClass
public static void tearDown() {
if ( executorService != null && !executorService.isShutdown()) {
executorService.shutdown();
}
}
}
@ -107,4 +134,5 @@ class SimpleCallable implements Callable<Integer> {
return RandomUtils.nextInt(0, 100);
}
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.datetime
import java.time.Duration
import java.time.LocalTime
class UseDuration {
fun modifyDates(localTime: LocalTime, duration: Duration): LocalTime {
return localTime.plus(duration)
}
fun getDifferenceBetweenDates(localTime1: LocalTime, localTime2: LocalTime): Duration {
return Duration.between(localTime1, localTime2)
}
}

View File

@ -0,0 +1,42 @@
package com.baeldung.datetime
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import java.time.temporal.TemporalAdjusters
class UseLocalDate {
fun getLocalDateUsingFactoryOfMethod(year: Int, month: Int, dayOfMonth: Int): LocalDate {
return LocalDate.of(year, month, dayOfMonth)
}
fun getLocalDateUsingParseMethod(representation: String): LocalDate {
return LocalDate.parse(representation)
}
fun getLocalDateFromClock(): LocalDate {
return LocalDate.now()
}
fun getNextDay(localDate: LocalDate): LocalDate {
return localDate.plusDays(1)
}
fun getPreviousDay(localDate: LocalDate): LocalDate {
return localDate.minus(1, ChronoUnit.DAYS)
}
fun getDayOfWeek(localDate: LocalDate): DayOfWeek {
return localDate.dayOfWeek
}
fun getFirstDayOfMonth(): LocalDate {
return LocalDate.now().with(TemporalAdjusters.firstDayOfMonth())
}
fun getStartOfDay(localDate: LocalDate): LocalDateTime {
return localDate.atStartOfDay()
}
}

View File

@ -0,0 +1,10 @@
package com.baeldung.datetime
import java.time.LocalDateTime
class UseLocalDateTime {
fun getLocalDateTimeUsingParseMethod(representation: String): LocalDateTime {
return LocalDateTime.parse(representation)
}
}

View File

@ -0,0 +1,32 @@
package com.baeldung.datetime
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.temporal.ChronoUnit
class UseLocalTime {
fun getLocalTimeUsingFactoryOfMethod(hour: Int, min: Int, seconds: Int): LocalTime {
return LocalTime.of(hour, min, seconds)
}
fun getLocalTimeUsingParseMethod(timeRepresentation: String): LocalTime {
return LocalTime.parse(timeRepresentation)
}
fun getLocalTimeFromClock(): LocalTime {
return LocalTime.now()
}
fun addAnHour(localTime: LocalTime): LocalTime {
return localTime.plus(1, ChronoUnit.HOURS)
}
fun getHourFromLocalTime(localTime: LocalTime): Int {
return localTime.hour
}
fun getLocalTimeWithMinuteSetToValue(localTime: LocalTime, minute: Int): LocalTime {
return localTime.withMinute(minute)
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.datetime
import java.time.LocalDate
import java.time.Period
class UsePeriod {
fun modifyDates(localDate: LocalDate, period: Period): LocalDate {
return localDate.plus(period)
}
fun getDifferenceBetweenDates(localDate1: LocalDate, localDate2: LocalDate): Period {
return Period.between(localDate1, localDate2)
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.datetime
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZonedDateTime
class UseZonedDateTime {
fun getZonedDateTime(localDateTime: LocalDateTime, zoneId: ZoneId): ZonedDateTime {
return ZonedDateTime.of(localDateTime, zoneId)
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.kotlin.datetime
import com.baeldung.datetime.UseLocalDateTime
import java.time.LocalDate
import java.time.LocalTime
import java.time.Month
import org.junit.Test
import org.junit.Assert.assertEquals
class UseLocalDateTimeUnitTest {
var useLocalDateTime = UseLocalDateTime()
@Test
fun givenString_whenUsingParse_thenLocalDateTime() {
assertEquals(LocalDate.of(2016, Month.MAY, 10), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
.toLocalDate())
assertEquals(LocalTime.of(6, 30), useLocalDateTime.getLocalDateTimeUsingParseMethod("2016-05-10T06:30")
.toLocalTime())
}
}

View File

@ -0,0 +1,59 @@
package com.baeldung.kotlin.datetime
import com.baeldung.datetime.UseLocalDate
import org.junit.Assert
import org.junit.Test
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
class UseLocalDateUnitTest {
var useLocalDate = UseLocalDate()
@Test
fun givenValues_whenUsingFactoryOf_thenLocalDate() {
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingFactoryOfMethod(2016, 5, 10)
.toString())
}
@Test
fun givenString_whenUsingParse_thenLocalDate() {
Assert.assertEquals("2016-05-10", useLocalDate.getLocalDateUsingParseMethod("2016-05-10")
.toString())
}
@Test
fun whenUsingClock_thenLocalDate() {
Assert.assertEquals(LocalDate.now(), useLocalDate.getLocalDateFromClock())
}
@Test
fun givenDate_whenUsingPlus_thenNextDay() {
Assert.assertEquals(LocalDate.now()
.plusDays(1), useLocalDate.getNextDay(LocalDate.now()))
}
@Test
fun givenDate_whenUsingMinus_thenPreviousDay() {
Assert.assertEquals(LocalDate.now()
.minusDays(1), useLocalDate.getPreviousDay(LocalDate.now()))
}
@Test
fun givenToday_whenUsingGetDayOfWeek_thenDayOfWeek() {
Assert.assertEquals(DayOfWeek.SUNDAY, useLocalDate.getDayOfWeek(LocalDate.parse("2016-05-22")))
}
@Test
fun givenToday_whenUsingWithTemporalAdjuster_thenFirstDayOfMonth() {
Assert.assertEquals(1, useLocalDate.getFirstDayOfMonth()
.dayOfMonth.toLong())
}
@Test
fun givenLocalDate_whenUsingAtStartOfDay_thenReturnMidnight() {
Assert.assertEquals(LocalDateTime.parse("2016-05-22T00:00:00"), useLocalDate.getStartOfDay(LocalDate.parse("2016-05-22")))
}
}

View File

@ -0,0 +1,37 @@
package com.baeldung.kotlin.datetime
import com.baeldung.datetime.UseLocalTime
import java.time.LocalTime
import org.junit.Assert
import org.junit.Test
class UseLocalTimeUnitTest {
internal var useLocalTime = UseLocalTime()
@Test
fun givenValues_whenUsingFactoryOf_thenLocalTime() {
Assert.assertEquals("07:07:07", useLocalTime.getLocalTimeUsingFactoryOfMethod(7, 7, 7).toString())
}
@Test
fun givenString_whenUsingParse_thenLocalTime() {
Assert.assertEquals("06:30", useLocalTime.getLocalTimeUsingParseMethod("06:30").toString())
}
@Test
fun givenTime_whenAddHour_thenLocalTime() {
Assert.assertEquals("07:30", useLocalTime.addAnHour(LocalTime.of(6, 30)).toString())
}
@Test
fun getHourFromLocalTime() {
Assert.assertEquals(1, useLocalTime.getHourFromLocalTime(LocalTime.of(1, 1)).toLong())
}
@Test
fun getLocalTimeWithMinuteSetToValue() {
Assert.assertEquals(LocalTime.of(10, 20), useLocalTime.getLocalTimeWithMinuteSetToValue(LocalTime.of(10, 10), 20))
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.kotlin.datetime
import com.baeldung.datetime.UsePeriod
import java.time.LocalDate
import java.time.Period
import org.junit.Assert
import org.junit.Test
class UsePeriodUnitTest {
var usingPeriod = UsePeriod()
@Test
fun givenPeriodAndLocalDate_thenCalculateModifiedDate() {
val period = Period.ofDays(1)
val localDate = LocalDate.parse("2007-05-10")
Assert.assertEquals(localDate.plusDays(1), usingPeriod.modifyDates(localDate, period))
}
@Test
fun givenDates_thenGetPeriod() {
val localDate1 = LocalDate.parse("2007-05-10")
val localDate2 = LocalDate.parse("2007-05-15")
Assert.assertEquals(Period.ofDays(5), usingPeriod.getDifferenceBetweenDates(localDate1, localDate2))
}
}

View File

@ -0,0 +1,19 @@
package com.baeldung.kotlin.datetime
import com.baeldung.datetime.UseZonedDateTime
import org.junit.Assert
import org.junit.Test
import java.time.LocalDateTime
import java.time.ZoneId
class UseZonedDateTimeUnitTest {
internal var zonedDateTime = UseZonedDateTime()
@Test
fun givenZoneId_thenZonedDateTime() {
val zoneId = ZoneId.of("Europe/Paris")
val zonedDatetime = zonedDateTime.getZonedDateTime(LocalDateTime.parse("2016-05-20T06:30"), zoneId)
Assert.assertEquals(zoneId, ZoneId.from(zonedDatetime))
}
}

View File

@ -3,7 +3,13 @@
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="wildfly-jpa" transaction-type="JTA">
<jta-data-source>java:/PostgresDS</jta-data-source>
<jta-data-source>java:/H2DS</jta-data-source>
<class>model.User</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.hbm2ddl.import_files" value="data.sql" />
</properties>
</persistence-unit>
</persistence>

View File

@ -0,0 +1 @@
INSERT INTO users (username, email, postal_number) VALUES ('user1', 'user1@baeldung.com', 1000), ('user2', 'user2@baeldung.com', 2);

View File

@ -22,13 +22,19 @@
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.9.Final</version>
<version>5.2.12.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.8.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>

View File

@ -68,7 +68,7 @@ public class HibernateMultiTenantUtil {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate.properties");
.getResource("hibernate-multitenancy.properties");
FileInputStream inputStream = new FileInputStream(propertiesURL.getFile());
properties.load(inputStream);
System.out.println("LOADED PROPERTIES FROM hibernate.properties");

View File

@ -1,24 +1,58 @@
package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.Employee;
import com.baeldung.hibernate.pojo.EntityDescription;
import com.baeldung.hibernate.pojo.Phone;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static final SessionFactory sessionFactory;
static {
try {
Configuration configuration = new Configuration().configure();
sessionFactory = configuration.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
public static SessionFactory getSessionFactory() throws IOException {
if (sessionFactory == null) {
ServiceRegistry serviceRegistry = configureServiceRegistry();
sessionFactory = makeSessionFactory(serviceRegistry);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
private static SessionFactory makeSessionFactory(ServiceRegistry serviceRegistry) {
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addPackage("com.baeldung.hibernate.pojo");
metadataSources.addAnnotatedClass(Employee.class);
metadataSources.addAnnotatedClass(Phone.class);
metadataSources.addAnnotatedClass(EntityDescription.class);
Metadata metadata = metadataSources.buildMetadata();
return metadata.getSessionFactoryBuilder()
.build();
}
private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getProperties();
return new StandardServiceRegistryBuilder().applySettings(properties)
.build();
}
private static Properties getProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread()
.getContextClassLoader()
.getResource("hibernate.properties");
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
}

View File

@ -0,0 +1,87 @@
package com.baeldung.hibernate.pojo;
import org.hibernate.annotations.*;
import javax.persistence.Entity;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Entity
@Where(clause = "deleted = false")
@FilterDef(name = "incomeLevelFilter", parameters = @ParamDef(name = "incomeLimit", type = "int"))
@Filter(name = "incomeLevelFilter", condition = "grossIncome > :incomeLimit")
public class Employee implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private long grossIncome;
private int taxInPercents;
private boolean deleted;
public long getTaxJavaWay() {
return grossIncome * taxInPercents / 100;
}
@Formula("grossIncome * taxInPercents / 100")
private long tax;
@OneToMany
@JoinColumn(name = "employee_id")
@Where(clause = "deleted = false")
private Set<Phone> phones = new HashSet<>(0);
public Employee() {
}
public Employee(long grossIncome, int taxInPercents) {
this.grossIncome = grossIncome;
this.taxInPercents = taxInPercents;
}
public Integer getId() {
return id;
}
public long getGrossIncome() {
return grossIncome;
}
public int getTaxInPercents() {
return taxInPercents;
}
public long getTax() {
return tax;
}
public void setId(Integer id) {
this.id = id;
}
public void setGrossIncome(long grossIncome) {
this.grossIncome = grossIncome;
}
public void setTaxInPercents(int taxInPercents) {
this.taxInPercents = taxInPercents;
}
public boolean getDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public Set<Phone> getPhones() {
return phones;
}
}

View File

@ -0,0 +1,55 @@
package com.baeldung.hibernate.pojo;
import org.hibernate.annotations.Any;
import javax.persistence.*;
import java.io.Serializable;
@Entity
public class EntityDescription implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String description;
@Any(
metaDef = "EntityDescriptionMetaDef",
metaColumn = @Column(name = "entity_type")
)
@JoinColumn(name = "entity_id")
private Serializable entity;
public EntityDescription() {
}
public EntityDescription(String description, Serializable entity) {
this.description = description;
this.entity = entity;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Serializable getEntity() {
return entity;
}
public void setEntity(Serializable entity) {
this.entity = entity;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.hibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.io.Serializable;
@Entity
public class Phone implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private boolean deleted;
private String number;
public Phone() {
}
public Phone(String number) {
this.number = number;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}

View File

@ -0,0 +1,9 @@
@AnyMetaDef(name = "EntityDescriptionMetaDef", metaType = "string", idType = "int",
metaValues = {
@MetaValue(value = "Employee", targetEntity = Employee.class),
@MetaValue(value = "Phone", targetEntity = Phone.class)
})
package com.baeldung.hibernate.pojo;
import org.hibernate.annotations.AnyMetaDef;
import org.hibernate.annotations.MetaValue;

View File

@ -0,0 +1,164 @@
package com.baeldung.hibernate;
import com.baeldung.hibernate.pojo.Employee;
import com.baeldung.hibernate.pojo.EntityDescription;
import com.baeldung.hibernate.pojo.Phone;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class DynamicMappingIntegrationTest {
private Session session;
private Transaction transaction;
@Before
public void setUp() throws IOException {
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.createNativeQuery("delete from phone").executeUpdate();
session.createNativeQuery("delete from employee").executeUpdate();
transaction.commit();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
session.close();
}
@Test
public void givenEntity_whenFieldMappedWithFormula_thenFieldIsCalculated() {
Employee employee = new Employee(10_000L, 25);
assertThat(employee.getTaxJavaWay()).isEqualTo(2_500L);
session.save(employee);
session.flush();
session.clear();
employee = session.get(Employee.class, employee.getId());
assertThat(employee.getTax()).isEqualTo(2_500L);
}
@Test
public void givenEntityMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() {
Employee employee = new Employee();
session.save(employee);
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee).isNotNull();
employee.setDeleted(true);
session.flush();
employee = session.find(Employee.class, employee.getId());
assertThat(employee).isNotNull();
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee).isNull();
}
@Test
public void givenCollectionMappedWithWhere_whenDeletedIsTrue_thenEntityNotFetched() {
Employee employee = new Employee();
Phone phone1 = new Phone("555-45-67");
Phone phone2 = new Phone("555-89-01");
employee.getPhones().add(phone1);
employee.getPhones().add(phone2);
session.save(phone1);
session.save(phone2);
session.save(employee);
session.flush();
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee.getPhones()).hasSize(2);
employee.getPhones().iterator().next().setDeleted(true);
session.flush();
session.clear();
employee = session.find(Employee.class, employee.getId());
assertThat(employee.getPhones()).hasSize(1);
List<Phone> fullPhoneList = session.createQuery("from Phone").getResultList();
assertThat(fullPhoneList).hasSize(2);
}
@Test
public void givenFilterByIncome_whenIncomeLimitSet_thenFilterIsApplied() throws IOException {
session.save(new Employee(10_000, 25));
session.save(new Employee(12_000, 25));
session.save(new Employee(15_000, 25));
session.flush();
session.clear();
session.enableFilter("incomeLevelFilter")
.setParameter("incomeLimit", 11_000);
List<Employee> employees = session.createQuery("from Employee").getResultList();
assertThat(employees).hasSize(2);
Employee employee = session.get(Employee.class, 1);
assertThat(employee.getGrossIncome()).isEqualTo(10_000);
session.close();
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
employees = session.createQuery("from Employee").getResultList();
assertThat(employees).hasSize(3);
}
@Test
public void givenMappingWithAny_whenDescriptionAddedToEntity_thenDescriptionCanReferAnyEntity() {
Employee employee = new Employee();
Phone phone1 = new Phone("555-45-67");
Phone phone2 = new Phone("555-89-01");
employee.getPhones().add(phone1);
employee.getPhones().add(phone2);
EntityDescription employeeDescription = new EntityDescription("Send to conference next year", employee);
EntityDescription phone1Description = new EntityDescription("Home phone (do not call after 10PM)", phone1);
EntityDescription phone2Description = new EntityDescription("Work phone", phone1);
session.save(phone1);
session.save(phone2);
session.save(employee);
session.save(employeeDescription);
session.save(phone1Description);
session.save(phone2Description);
session.flush();
session.clear();
List<EntityDescription> descriptions = session.createQuery("from EntityDescription").getResultList();
assertThat(Employee.class.isAssignableFrom(descriptions.get(0).getEntity().getClass())).isTrue();
assertThat(Phone.class.isAssignableFrom(descriptions.get(1).getEntity().getClass())).isTrue();
assertThat(Phone.class.isAssignableFrom(descriptions.get(2).getEntity().getClass())).isTrue();
}
}

View File

@ -0,0 +1,9 @@
hibernate.connection.driver_class=org.h2.Driver
hibernate.connection.url=jdbc:h2:mem:mydb1;DB_CLOSE_DELAY=-1
hibernate.connection.username=sa
hibernate.connection.autocommit=true
jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.multiTenancy=DATABASE

View File

@ -6,4 +6,4 @@ jdbc.password=
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.show_sql=true
hibernate.multiTenancy=DATABASE
hibernate.hbm2ddl.auto=create-drop

View File

@ -6,4 +6,4 @@
- [Guide to Dynamic Tests in Junit 5](http://www.baeldung.com/junit5-dynamic-tests)
- [A Guied to JUnit 5 Extensions](http://www.baeldung.com/junit-5-extensions)
- [Inject Parameters into JUnit Jupiter Unit Tests](http://www.baeldung.com/junit-5-parameters)
- [Mockito and JUnit 5 Using ExtendWith](http://www.baeldung.com/mockito-junit-5-extension)

View File

@ -11,6 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -11,6 +11,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>

View File

@ -6,6 +6,7 @@
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -15,6 +15,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<properties>

View File

@ -15,6 +15,7 @@
<groupId>com.baeldung</groupId>
<artifactId>parent-modules</artifactId>
<version>1.0.0-SNAPSHOT</version>
<relativePath>../</relativePath>
</parent>
<dependencies>

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