Browse Source

Add Spring Data AOT Sample

Closes gh-317
Josh Cummings 11 tháng trước cách đây
mục cha
commit
56033d76f8
24 tập tin đã thay đổi với 1008 bổ sung0 xóa
  1. 1 0
      servlet/spring-boot/java/aot/data/.sdkmanrc
  2. 74 0
      servlet/spring-boot/java/aot/data/README.adoc
  3. 39 0
      servlet/spring-boot/java/aot/data/build.gradle
  4. 4 0
      servlet/spring-boot/java/aot/data/gradle.properties
  5. 1 0
      servlet/spring-boot/java/aot/data/gradle/libs.versions.toml
  6. BIN
      servlet/spring-boot/java/aot/data/gradle/wrapper/gradle-wrapper.jar
  7. 6 0
      servlet/spring-boot/java/aot/data/gradle/wrapper/gradle-wrapper.properties
  8. 244 0
      servlet/spring-boot/java/aot/data/gradlew
  9. 92 0
      servlet/spring-boot/java/aot/data/gradlew.bat
  10. 8 0
      servlet/spring-boot/java/aot/data/settings.gradle
  11. 35 0
      servlet/spring-boot/java/aot/data/src/main/java/example/AuthorizeRead.java
  12. 16 0
      servlet/spring-boot/java/aot/data/src/main/java/example/CsrfAdvice.java
  13. 59 0
      servlet/spring-boot/java/aot/data/src/main/java/example/DataApplication.java
  14. 13 0
      servlet/spring-boot/java/aot/data/src/main/java/example/DataRuntimeHintsRegistrar.java
  15. 88 0
      servlet/spring-boot/java/aot/data/src/main/java/example/Message.java
  16. 60 0
      servlet/spring-boot/java/aot/data/src/main/java/example/MessageController.java
  17. 38 0
      servlet/spring-boot/java/aot/data/src/main/java/example/MessageRepository.java
  18. 33 0
      servlet/spring-boot/java/aot/data/src/main/java/example/Null.java
  19. 83 0
      servlet/spring-boot/java/aot/data/src/main/java/example/User.java
  20. 2 0
      servlet/spring-boot/java/aot/data/src/main/resources/META-INF/spring/aot.factories
  21. 17 0
      servlet/spring-boot/java/aot/data/src/main/resources/application.properties
  22. 10 0
      servlet/spring-boot/java/aot/data/src/main/resources/import.sql
  23. 84 0
      servlet/spring-boot/java/aot/data/src/test/java/example/DataApplicationTests.java
  24. 1 0
      settings.gradle

+ 1 - 0
servlet/spring-boot/java/aot/data/.sdkmanrc

@@ -0,0 +1 @@
+java=23.0.5.r17-nik

+ 74 - 0
servlet/spring-boot/java/aot/data/README.adoc

@@ -0,0 +1,74 @@
+= Spring Data AOT Sample
+
+To compile this project, you will need to use a special Java compiler.
+If you are using SDKMan!, then the version will be correctly selected for you.
+Or, you can do the following:
+
+```bash
+sdk use java 23.0.5.r17-nik
+```
+
+After that, you can compile like so:
+
+```bash
+./gradlew nativeCompile
+```
+
+Once compiled, you can run like so:
+
+```bash
+./build/native/nativeCompile/data
+```
+
+Then you can query for messages using `luke/password` and `rob/password`.
+
+Because the domain objects are secured, you will see a subset of fields with `luke`.
+
+For example, querying `/` with `luke`, you'll see:
+
+```json
+  ...
+    {
+        "created": "2014-07-12T16:00:00Z",
+        "id": 112,
+        "summary": "Is this secure?",
+        "text": "This message is for Luke",
+        "to": {
+            "email": "luke@example.com",
+            "id": "luke",
+            "password": "password"
+        }
+    }
+  ...
+```
+
+However, with `rob`, you'll also see `firstName` and `lastName` like so:
+
+```json
+  ...
+    {
+        "created": "2014-07-12T04:00:00Z",
+        "id": 102,
+        "summary": "Is this secure?",
+        "text": "This message is for Rob",
+        "to": {
+            "email": "rob@example.com",
+            "firstName": "Rob",
+            "id": "rob",
+            "lastName": "Winch",
+            "password": "password"
+        }
+    }
+  ...
+```
+
+You can also change the message text.
+To do this, copy and paste the `X-CSRF-TOKEN` and `Cookie: JSESSION` headers and include them in a `PUT :8080/102` request.
+
+An example of this request using HTTPie can be seen below:
+
+```bash
+echo -n "updated message" | http -a rob:password PUT :8080/102 "X-CSRF-TOKEN: {copied from GET request}" "Cookie: JSESSIONID={copied from GET request}"
+```
+
+Read more about the https://docs.spring.io/spring-security/reference/servlet/authorization/method-security.html#authorize-object[`@AuthorizeReturnObject`] and https://docs.spring.io/spring-security/reference/servlet/authorization/method-security.html#fallback-values-authorization-denied[]`@DeniedHandler`] in the Spring Security Reference.

+ 39 - 0
servlet/spring-boot/java/aot/data/build.gradle

@@ -0,0 +1,39 @@
+plugins {
+	alias(libs.plugins.org.springframework.boot)
+	alias(libs.plugins.io.spring.dependency.management)
+	id "nebula.integtest" version "8.2.0"
+	id 'java'
+	id 'org.hibernate.orm' version '6.5.2.Final'
+	id "org.graalvm.buildtools.native" version "0.10.2"
+}
+
+repositories {
+	mavenCentral()
+	maven { url "https://repo.spring.io/milestone" }
+	maven { url "https://repo.spring.io/snapshot" }
+}
+
+dependencies {
+	implementation platform(libs.org.springframework.spring.framework.bom)
+	implementation platform(libs.org.springframework.security.spring.security.bom)
+	implementation platform(libs.org.springframework.data.spring.data.bom)
+	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
+	implementation 'org.springframework.boot:spring-boot-starter-security'
+	implementation 'org.springframework.boot:spring-boot-starter-web'
+	implementation 'org.springframework.security:spring-security-data'
+	implementation 'com.h2database:h2'
+
+	testImplementation 'org.springframework.boot:spring-boot-starter-test'
+	testImplementation 'org.springframework.security:spring-security-test'
+}
+
+hibernate {
+  enhancement {
+    enableAssociationManagement = true
+  }
+}
+
+tasks.withType(Test).configureEach {
+	useJUnitPlatform()
+	outputs.upToDateWhen { false }
+}

+ 4 - 0
servlet/spring-boot/java/aot/data/gradle.properties

@@ -0,0 +1,4 @@
+version=6.1.1
+spring-security.version=6.4.0-SNAPSHOT
+org.gradle.jvmargs=-Xmx6g -XX:+HeapDumpOnOutOfMemoryError
+org.gradle.caching=true

+ 1 - 0
servlet/spring-boot/java/aot/data/gradle/libs.versions.toml

@@ -0,0 +1 @@
+../../../../../../gradle/libs.versions.toml

BIN
servlet/spring-boot/java/aot/data/gradle/wrapper/gradle-wrapper.jar


+ 6 - 0
servlet/spring-boot/java/aot/data/gradle/wrapper/gradle-wrapper.properties

@@ -0,0 +1,6 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-bin.zip
+networkTimeout=10000
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists

+ 244 - 0
servlet/spring-boot/java/aot/data/gradlew

@@ -0,0 +1,244 @@
+#!/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##*/}
+APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+
+# 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"'
+
+# 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
+    which java >/dev/null 2>&1 || 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
+
+# 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=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=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
+
+# Collect all arguments for the java command;
+#   * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
+#     shell script including quotes and variable substitutions, so put them in
+#     double quotes to make sure that they get re-expanded; and
+#   * put everything else in single quotes, so that it's not re-expanded.
+
+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" "$@"

+ 92 - 0
servlet/spring-boot/java/aot/data/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

+ 8 - 0
servlet/spring-boot/java/aot/data/settings.gradle

@@ -0,0 +1,8 @@
+pluginManagement {
+    repositories {
+        mavenCentral()
+        gradlePluginPortal()
+        maven { url 'https://repo.spring.io/milestone' }
+        maven { url "https://repo.spring.io/snapshot" }
+    }
+}

+ 35 - 0
servlet/spring-boot/java/aot/data/src/main/java/example/AuthorizeRead.java

@@ -0,0 +1,35 @@
+/*
+ * Copyright 2024 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.
+ */
+
+package example;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+import org.springframework.security.access.prepost.PreAuthorize;
+import org.springframework.security.authorization.method.HandleAuthorizationDenied;
+
+@Target(ElementType.METHOD)
+@Retention(RetentionPolicy.RUNTIME)
+@PreAuthorize("hasAuthority('{value}:read')")
+@HandleAuthorizationDenied(handlerClass = Null.class)
+public @interface AuthorizeRead {
+
+	String value();
+
+}

+ 16 - 0
servlet/spring-boot/java/aot/data/src/main/java/example/CsrfAdvice.java

@@ -0,0 +1,16 @@
+package example;
+
+import jakarta.servlet.http.HttpServletResponse;
+
+import org.springframework.security.web.csrf.CsrfToken;
+import org.springframework.web.bind.annotation.ControllerAdvice;
+import org.springframework.web.bind.annotation.ModelAttribute;
+
+
+@ControllerAdvice
+public class CsrfAdvice {
+	@ModelAttribute
+	public void writeHeader(CsrfToken token, HttpServletResponse response) {
+		response.addHeader(token.getHeaderName(), token.getToken());
+	}
+}

+ 59 - 0
servlet/spring-boot/java/aot/data/src/main/java/example/DataApplication.java

@@ -0,0 +1,59 @@
+/*
+ * Copyright 2023 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.
+ */
+
+package example;
+
+import org.springframework.beans.factory.config.BeanDefinition;
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Role;
+import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
+import org.springframework.security.core.annotation.AnnotationTemplateExpressionDefaults;
+import org.springframework.security.core.userdetails.User;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.security.provisioning.InMemoryUserDetailsManager;
+
+@SpringBootApplication
+@EnableMethodSecurity
+public class DataApplication {
+
+	@Bean
+	@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
+	static AnnotationTemplateExpressionDefaults templateDefaults() {
+		return new AnnotationTemplateExpressionDefaults();
+	}
+
+	@Bean
+	public UserDetailsService userDetailsService() {
+		return new InMemoryUserDetailsManager(
+				User.withDefaultPasswordEncoder()
+					.username("rob")
+					.password("password")
+					.authorities("message:read", "user:read")
+					.build(),
+				User.withDefaultPasswordEncoder()
+					.username("luke")
+					.password("password")
+					.authorities("message:read")
+					.build());
+	}
+
+	public static void main(String[] args) {
+		SpringApplication.run(DataApplication.class, args);
+	}
+
+}

+ 13 - 0
servlet/spring-boot/java/aot/data/src/main/java/example/DataRuntimeHintsRegistrar.java

@@ -0,0 +1,13 @@
+package example;
+
+import org.springframework.aot.hint.RuntimeHints;
+import org.springframework.aot.hint.RuntimeHintsRegistrar;
+
+public class DataRuntimeHintsRegistrar implements RuntimeHintsRegistrar {
+
+	@Override
+	public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
+		hints.resources().registerPattern("import.sql");
+	}
+	
+}

+ 88 - 0
servlet/spring-boot/java/aot/data/src/main/java/example/Message.java

@@ -0,0 +1,88 @@
+/*
+ * Copyright 2020 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.
+ */
+
+package example;
+
+import java.time.Instant;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.GeneratedValue;
+import jakarta.persistence.GenerationType;
+import jakarta.persistence.Id;
+import jakarta.persistence.ManyToOne;
+
+import org.springframework.security.authorization.method.AuthorizeReturnObject;
+
+@Entity
+public class Message {
+
+	@Id
+	@GeneratedValue(strategy = GenerationType.AUTO)
+	private Long id;
+
+	private String text;
+
+	private String summary;
+
+	private Instant created = Instant.now();
+
+	@ManyToOne
+	private User to;
+
+	@AuthorizeReturnObject
+	public User getTo() {
+		return this.to;
+	}
+
+	public void setTo(User to) {
+		this.to = to;
+	}
+
+	public Long getId() {
+		return this.id;
+	}
+
+	public void setId(Long id) {
+		this.id = id;
+	}
+
+	public Instant getCreated() {
+		return this.created;
+	}
+
+	public void setCreated(Instant created) {
+		this.created = created;
+	}
+
+	@AuthorizeRead("message")
+	public String getText() {
+		return this.text;
+	}
+
+	public void setText(String text) {
+		this.text = text;
+	}
+
+	@AuthorizeRead("message")
+	public String getSummary() {
+		return this.summary;
+	}
+
+	public void setSummary(String summary) {
+		this.summary = summary;
+	}
+
+}

+ 60 - 0
servlet/spring-boot/java/aot/data/src/main/java/example/MessageController.java

@@ -0,0 +1,60 @@
+/*
+ * Copyright 2024 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.
+ */
+
+package example;
+
+import java.util.List;
+import java.util.Optional;
+
+import org.springframework.security.authorization.method.AuthorizationProxy;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.PutMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+public class MessageController {
+
+	private final MessageRepository messages;
+
+	public MessageController(MessageRepository messages) {
+		this.messages = messages;
+	}
+
+	@GetMapping
+	List<Message> getMessages() {
+		return this.messages.findAll();
+	}
+
+	@GetMapping("/{id}")
+	Optional<Message> getMessages(Long id) {
+		return this.messages.findById(id);
+	}
+
+	@PutMapping("/{id}")
+	Optional<Message> updateMessage(@PathVariable("id") Long id, @RequestBody String text) {
+		return this.messages.findById(id)
+			.map((message) -> {
+				message.setText(text);
+				// unwrap authorization proxy so Spring Data can persist
+				if (message instanceof AuthorizationProxy proxy) {
+					message = (Message) proxy.toAuthorizedTarget();
+				}
+				return this.messages.save(message);
+			});
+	}
+}

+ 38 - 0
servlet/spring-boot/java/aot/data/src/main/java/example/MessageRepository.java

@@ -0,0 +1,38 @@
+/*
+ * Copyright 2020 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.
+ */
+
+package example;
+
+import java.util.List;
+
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.CrudRepository;
+import org.springframework.security.authorization.method.AuthorizeReturnObject;
+import org.springframework.stereotype.Repository;
+
+/**
+ * A repository for accessing {@link Message}s.
+ *
+ * @author Rob Winch
+ */
+@Repository
+@AuthorizeReturnObject
+public interface MessageRepository extends CrudRepository<Message, Long> {
+
+	@Query("select m from Message m where m.to.id = ?#{ authentication.name }")
+	List<Message> findAll();
+
+}

+ 33 - 0
servlet/spring-boot/java/aot/data/src/main/java/example/Null.java

@@ -0,0 +1,33 @@
+/*
+ * Copyright 2024 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.
+ */
+
+package example;
+
+import org.aopalliance.intercept.MethodInvocation;
+
+import org.springframework.security.authorization.AuthorizationResult;
+import org.springframework.security.authorization.method.MethodAuthorizationDeniedHandler;
+import org.springframework.stereotype.Component;
+
+@Component
+public class Null implements MethodAuthorizationDeniedHandler {
+
+	@Override
+	public Object handleDeniedInvocation(MethodInvocation methodInvocation, AuthorizationResult authorizationResult) {
+		return null;
+	}
+
+}

+ 83 - 0
servlet/spring-boot/java/aot/data/src/main/java/example/User.java

@@ -0,0 +1,83 @@
+/*
+ * Copyright 2020 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.
+ */
+
+package example;
+
+import jakarta.persistence.Entity;
+import jakarta.persistence.Id;
+
+/**
+ * A user.
+ *
+ * @author Rob Winch
+ */
+@Entity(name = "users")
+public class User {
+
+	@Id
+	private String id;
+
+	private String firstName;
+
+	private String lastName;
+
+	private String email;
+
+	private String password;
+
+	public String getId() {
+		return this.id;
+	}
+
+	public void setId(String id) {
+		this.id = id;
+	}
+
+	@AuthorizeRead("user")
+	public String getFirstName() {
+		return this.firstName;
+	}
+
+	public void setFirstName(String firstName) {
+		this.firstName = firstName;
+	}
+
+	@AuthorizeRead("user")
+	public String getLastName() {
+		return this.lastName;
+	}
+
+	public void setLastName(String lastName) {
+		this.lastName = lastName;
+	}
+
+	public String getEmail() {
+		return this.email;
+	}
+
+	public void setEmail(String email) {
+		this.email = email;
+	}
+
+	public String getPassword() {
+		return this.password;
+	}
+
+	public void setPassword(String password) {
+		this.password = password;
+	}
+
+}

+ 2 - 0
servlet/spring-boot/java/aot/data/src/main/resources/META-INF/spring/aot.factories

@@ -0,0 +1,2 @@
+org.springframework.aot.hint.RuntimeHintsRegistrar=\
+example.DataRuntimeHintsRegistrar

+ 17 - 0
servlet/spring-boot/java/aot/data/src/main/resources/application.properties

@@ -0,0 +1,17 @@
+#
+# Copyright 2024 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.
+#
+
+spring.jackson.default-property-inclusion=non_null

+ 10 - 0
servlet/spring-boot/java/aot/data/src/main/resources/import.sql

@@ -0,0 +1,10 @@
+insert into users (id,email,password,first_name,last_name) values ('rob','rob@example.com','password','Rob','Winch');
+insert into users (id,email,password,first_name,last_name) values ('luke','luke@example.com','password','Luke','Taylor');
+
+insert into message (id,created,to_id,summary,text) values (100,'2014-07-10 10:00:00','rob','Hello Rob','This message is for Rob');
+insert into message (id,created,to_id,summary,text) values (101,'2014-07-10 14:00:00','rob','How are you Rob?','This message is for Rob');
+insert into message (id,created,to_id,summary,text) values (102,'2014-07-11 22:00:00','rob','Is this secure?','This message is for Rob');
+
+insert into message (id,created,to_id,summary,text) values (110,'2014-07-12 10:00:00','luke','Hello Luke','This message is for Luke');
+insert into message (id,created,to_id,summary,text) values (111,'2014-07-12 10:00:00','luke','Greetings Luke','This message is for Luke');
+insert into message (id,created,to_id,summary,text) values (112,'2014-07-12 10:00:00','luke','Is this secure?','This message is for Luke');

+ 84 - 0
servlet/spring-boot/java/aot/data/src/test/java/example/DataApplicationTests.java

@@ -0,0 +1,84 @@
+/*
+ * Copyright 2020 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.
+ */
+
+package example;
+
+import java.util.List;
+
+import org.junit.jupiter.api.Test;
+
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.security.test.context.support.WithMockUser;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * @author Rob Winch
+ */
+@SpringBootTest
+public class DataApplicationTests {
+
+	@Autowired
+	MessageRepository repository;
+
+	@Test
+	@WithMockUser("rob")
+	void findAllOnlyToCurrentUserCantReadMessage() {
+		List<Message> messages = this.repository.findAll();
+		assertThat(messages).hasSize(3);
+		for (Message message : messages) {
+			assertThat(message.getSummary()).isNull();
+			assertThat(message.getText()).isNull();
+		}
+	}
+
+	@Test
+	@WithMockUser(username = "rob", authorities = "message:read")
+	void findAllOnlyToCurrentUserCanReadMessage() {
+		List<Message> messages = this.repository.findAll();
+		assertThat(messages).hasSize(3);
+		for (Message message : messages) {
+			assertThat(message.getSummary()).isNotNull();
+			assertThat(message.getText()).isNotNull();
+		}
+	}
+
+	@Test
+	@WithMockUser(username = "rob", authorities = "message:read")
+	void findAllOnlyToCurrentUserCantReadUserDetails() {
+		List<Message> messages = this.repository.findAll();
+		assertThat(messages).hasSize(3);
+		for (Message message : messages) {
+			User user = message.getTo();
+			assertThat(user.getFirstName()).isNull();
+			assertThat(user.getLastName()).isNull();
+		}
+	}
+
+	@Test
+	@WithMockUser(username = "rob", authorities = { "message:read", "user:read" })
+	void findAllOnlyToCurrentUserCanReadUserDetails() {
+		List<Message> messages = this.repository.findAll();
+		assertThat(messages).hasSize(3);
+		for (Message message : messages) {
+			User user = message.getTo();
+			assertThat(user.getFirstName()).isNotNull();
+			assertThat(user.getLastName()).isNotNull();
+		}
+	}
+
+}

+ 1 - 0
settings.gradle

@@ -47,6 +47,7 @@ include ":servlet:java-configuration:hello-security"
 include ":servlet:java-configuration:hello-security-explicit"
 include ":servlet:java-configuration:max-sessions"
 include ":servlet:java-configuration:saml2:login"
+include ":servlet:spring-boot:java:aot:data"
 include ":servlet:spring-boot:java:authentication:username-password:user-details-service:custom-user"
 include ":servlet:spring-boot:java:authentication:username-password:mfa"
 include ":servlet:spring-boot:java:authentication:username-password:compromised-password-checker"