From 4f1e08ec34b019b8d8abeed1517b4794c5332582 Mon Sep 17 00:00:00 2001 From: azerr Date: Thu, 11 Jul 2024 11:17:01 +0200 Subject: [PATCH] feat: Qute: add support for template records See https://github.com/redhat-developer/quarkus-ls/issues/956 Signed-off-by: azerr --- .../projects/maven/qute-record/.classpath | 40 + .../projects/maven/qute-record/.dockerignore | 5 + .../projects/maven/qute-record/.gitignore | 43 + .../maven/qute-record/.mvn/wrapper/.gitignore | 1 + .../.mvn/wrapper/MavenWrapperDownloader.java | 98 ++ .../.mvn/wrapper/maven-wrapper.properties | 18 + .../qute/projects/maven/qute-record/.project | 23 + .../qute/projects/maven/qute-record/README.md | 66 ++ projects/qute/projects/maven/qute-record/mvnw | 308 ++++++ .../qute/projects/maven/qute-record/mvnw.cmd | 205 ++++ .../qute/projects/maven/qute-record/pom.xml | 121 +++ .../java/org/acme/sample/HelloResource.java | 22 + .../main/java/org/acme/sample/SomePage.java | 29 + .../src/main/resources/application.properties | 0 .../src/main/resources/templates/Hello.html | 11 + .../src/main/resources/templates/Hello2.html | 0 .../main/resources/templates/page.qute.html | 30 + .../qute/psi/QuteSupportForTemplate.java | 888 +++++++++--------- .../qute/psi/internal/QuteJavaConstants.java | 2 + .../AbstractQuteTemplateLinkCollector.java | 45 +- .../datamodel/TemplateRecordsSupport.java | 108 +++ .../datamodel/AbstractDataModelProvider.java | 21 + ...erfaceImplementationDataModelProvider.java | 85 ++ src/main/resources/META-INF/plugin.xml | 2 + .../qute/psi/QuteMavenProjectName.java | 3 +- .../TemplateGetDataModelProjectTest.java | 717 +++++++------- 26 files changed, 2108 insertions(+), 783 deletions(-) create mode 100644 projects/qute/projects/maven/qute-record/.classpath create mode 100644 projects/qute/projects/maven/qute-record/.dockerignore create mode 100644 projects/qute/projects/maven/qute-record/.gitignore create mode 100644 projects/qute/projects/maven/qute-record/.mvn/wrapper/.gitignore create mode 100644 projects/qute/projects/maven/qute-record/.mvn/wrapper/MavenWrapperDownloader.java create mode 100644 projects/qute/projects/maven/qute-record/.mvn/wrapper/maven-wrapper.properties create mode 100644 projects/qute/projects/maven/qute-record/.project create mode 100644 projects/qute/projects/maven/qute-record/README.md create mode 100644 projects/qute/projects/maven/qute-record/mvnw create mode 100644 projects/qute/projects/maven/qute-record/mvnw.cmd create mode 100644 projects/qute/projects/maven/qute-record/pom.xml create mode 100644 projects/qute/projects/maven/qute-record/src/main/java/org/acme/sample/HelloResource.java create mode 100644 projects/qute/projects/maven/qute-record/src/main/java/org/acme/sample/SomePage.java create mode 100644 projects/qute/projects/maven/qute-record/src/main/resources/application.properties create mode 100644 projects/qute/projects/maven/qute-record/src/main/resources/templates/Hello.html create mode 100644 projects/qute/projects/maven/qute-record/src/main/resources/templates/Hello2.html create mode 100644 projects/qute/projects/maven/qute-record/src/main/resources/templates/page.qute.html create mode 100644 src/main/java/com/redhat/devtools/intellij/qute/psi/internal/template/datamodel/TemplateRecordsSupport.java create mode 100644 src/main/java/com/redhat/devtools/intellij/qute/psi/template/datamodel/AbstractInterfaceImplementationDataModelProvider.java diff --git a/projects/qute/projects/maven/qute-record/.classpath b/projects/qute/projects/maven/qute-record/.classpath new file mode 100644 index 000000000..d2a08ebbb --- /dev/null +++ b/projects/qute/projects/maven/qute-record/.classpath @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/projects/qute/projects/maven/qute-record/.dockerignore b/projects/qute/projects/maven/qute-record/.dockerignore new file mode 100644 index 000000000..94810d006 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/.dockerignore @@ -0,0 +1,5 @@ +* +!target/*-runner +!target/*-runner.jar +!target/lib/* +!target/quarkus-app/* \ No newline at end of file diff --git a/projects/qute/projects/maven/qute-record/.gitignore b/projects/qute/projects/maven/qute-record/.gitignore new file mode 100644 index 000000000..726d8ae39 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/.gitignore @@ -0,0 +1,43 @@ +#Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +release.properties +.flattened-pom.xml + +# Eclipse +#.project +#.classpath +.settings/ +bin/ + +# IntelliJ +.idea +*.ipr +*.iml +*.iws + +# NetBeans +nb-configuration.xml + +# Visual Studio Code +.vscode +.factorypath + +# OSX +.DS_Store + +# Vim +*.swp +*.swo + +# patch +*.orig +*.rej + +# Local environment +.env + +# Plugin directory +/.quarkus/cli/plugins/ diff --git a/projects/qute/projects/maven/qute-record/.mvn/wrapper/.gitignore b/projects/qute/projects/maven/qute-record/.mvn/wrapper/.gitignore new file mode 100644 index 000000000..e72f5e8b7 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/.mvn/wrapper/.gitignore @@ -0,0 +1 @@ +maven-wrapper.jar diff --git a/projects/qute/projects/maven/qute-record/.mvn/wrapper/MavenWrapperDownloader.java b/projects/qute/projects/maven/qute-record/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 000000000..84d1e60d8 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,98 @@ +/* + * 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. + */ + +import java.io.IOException; +import java.io.InputStream; +import java.net.Authenticator; +import java.net.PasswordAuthentication; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; + +public final class MavenWrapperDownloader +{ + private static final String WRAPPER_VERSION = "3.2.0"; + + private static final boolean VERBOSE = Boolean.parseBoolean( System.getenv( "MVNW_VERBOSE" ) ); + + public static void main( String[] args ) + { + log( "Apache Maven Wrapper Downloader " + WRAPPER_VERSION ); + + if ( args.length != 2 ) + { + System.err.println( " - ERROR wrapperUrl or wrapperJarPath parameter missing" ); + System.exit( 1 ); + } + + try + { + log( " - Downloader started" ); + final URL wrapperUrl = new URL( args[0] ); + final String jarPath = args[1].replace( "..", "" ); // Sanitize path + final Path wrapperJarPath = Paths.get( jarPath ).toAbsolutePath().normalize(); + downloadFileFromURL( wrapperUrl, wrapperJarPath ); + log( "Done" ); + } + catch ( IOException e ) + { + System.err.println( "- Error downloading: " + e.getMessage() ); + if ( VERBOSE ) + { + e.printStackTrace(); + } + System.exit( 1 ); + } + } + + private static void downloadFileFromURL( URL wrapperUrl, Path wrapperJarPath ) + throws IOException + { + log( " - Downloading to: " + wrapperJarPath ); + if ( System.getenv( "MVNW_USERNAME" ) != null && System.getenv( "MVNW_PASSWORD" ) != null ) + { + final String username = System.getenv( "MVNW_USERNAME" ); + final char[] password = System.getenv( "MVNW_PASSWORD" ).toCharArray(); + Authenticator.setDefault( new Authenticator() + { + @Override + protected PasswordAuthentication getPasswordAuthentication() + { + return new PasswordAuthentication( username, password ); + } + } ); + } + try ( InputStream inStream = wrapperUrl.openStream() ) + { + Files.copy( inStream, wrapperJarPath, StandardCopyOption.REPLACE_EXISTING ); + } + log( " - Downloader complete" ); + } + + private static void log( String msg ) + { + if ( VERBOSE ) + { + System.out.println( msg ); + } + } + +} diff --git a/projects/qute/projects/maven/qute-record/.mvn/wrapper/maven-wrapper.properties b/projects/qute/projects/maven/qute-record/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..11f586804 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# 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. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.7/apache-maven-3.9.7-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/projects/qute/projects/maven/qute-record/.project b/projects/qute/projects/maven/qute-record/.project new file mode 100644 index 000000000..8a16b06e1 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/.project @@ -0,0 +1,23 @@ + + + qute-record + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/projects/qute/projects/maven/qute-record/README.md b/projects/qute/projects/maven/qute-record/README.md new file mode 100644 index 000000000..08a658eb0 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/README.md @@ -0,0 +1,66 @@ +# qute-record + +This project uses Quarkus, the Supersonic Subatomic Java Framework. + +If you want to learn more about Quarkus, please visit its website: . + +## Running the application in dev mode + +You can run your application in dev mode that enables live coding using: + +```shell script +./mvnw compile quarkus:dev +``` + +> **_NOTE:_** Quarkus now ships with a Dev UI, which is available in dev mode only at . + +## Packaging and running the application + +The application can be packaged using: + +```shell script +./mvnw package +``` + +It produces the `quarkus-run.jar` file in the `target/quarkus-app/` directory. +Be aware that it’s not an _über-jar_ as the dependencies are copied into the `target/quarkus-app/lib/` directory. + +The application is now runnable using `java -jar target/quarkus-app/quarkus-run.jar`. + +If you want to build an _über-jar_, execute the following command: + +```shell script +./mvnw package -Dquarkus.package.jar.type=uber-jar +``` + +The application, packaged as an _über-jar_, is now runnable using `java -jar target/*-runner.jar`. + +## Creating a native executable + +You can create a native executable using: + +```shell script +./mvnw package -Dnative +``` + +Or, if you don't have GraalVM installed, you can run the native executable build in a container using: + +```shell script +./mvnw package -Dnative -Dquarkus.native.container-build=true +``` + +You can then execute your native executable with: `./target/qute-record-1.0.0-SNAPSHOT-runner` + +If you want to learn more about building native executables, please consult . + +## Related Guides + +- REST Qute ([guide](https://quarkus.io/guides/qute-reference#rest_integration)): Qute integration for Quarkus REST. This extension is not compatible with the quarkus-resteasy extension, or any of the extensions that depend on it. + +## Provided Code + +### REST Qute + +Create your web page using Quarkus REST and Qute + +[Related guide section...](https://quarkus.io/guides/qute#type-safe-templates) diff --git a/projects/qute/projects/maven/qute-record/mvnw b/projects/qute/projects/maven/qute-record/mvnw new file mode 100644 index 000000000..8d937f4c1 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/mvnw @@ -0,0 +1,308 @@ +#!/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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.2.0 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# 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 /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + 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 + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=$(java-config --jre-home) + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --unix "$CLASSPATH") +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="$(which javac)" + if [ -n "$javaExecutable" ] && ! [ "$(expr "\"$javaExecutable\"" : '\([^ ]*\)')" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=$(which readlink) + if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then + if $darwin ; then + javaHome="$(dirname "\"$javaExecutable\"")" + javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" + else + javaExecutable="$(readlink -f "\"$javaExecutable\"")" + fi + javaHome="$(dirname "\"$javaExecutable\"")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="$(\unset -f command 2>/dev/null; \command -v 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 + +# 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/.." || exit 1; pwd) + fi + # end of workaround + done + printf '%s' "$(cd "$basedir" || exit 1; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" +else + log "Couldn't find $wrapperJarPath, downloading it ..." + + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + fi + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; + esac + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + + if $cygwin; then + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") + fi + + if command -v wget > /dev/null; then + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" + fi + else + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi +fi + +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") + [ -n "$CLASSPATH" ] && + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +# shellcheck disable=SC2086 # safe args +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/projects/qute/projects/maven/qute-record/mvnw.cmd b/projects/qute/projects/maven/qute-record/mvnw.cmd new file mode 100644 index 000000000..c4586b564 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/mvnw.cmd @@ -0,0 +1,205 @@ +@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 Apache Maven Wrapper startup batch script, version 3.2.0 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\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% + +cmd /C exit /B %ERROR_CODE% diff --git a/projects/qute/projects/maven/qute-record/pom.xml b/projects/qute/projects/maven/qute-record/pom.xml new file mode 100644 index 000000000..a25ff9fd5 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/pom.xml @@ -0,0 +1,121 @@ + + + 4.0.0 + org.acme.sample + qute-record + 1.0.0-SNAPSHOT + + + 3.13.0 + 21 + UTF-8 + UTF-8 + quarkus-bom + io.quarkus.platform + 3.12.1 + true + 3.2.5 + + + + + + ${quarkus.platform.group-id} + ${quarkus.platform.artifact-id} + ${quarkus.platform.version} + pom + import + + + + + + + io.quarkus + quarkus-rest-qute + + + io.quarkus + quarkus-arc + + + io.quarkus + quarkus-junit5 + test + + + + + + + ${quarkus.platform.group-id} + quarkus-maven-plugin + ${quarkus.platform.version} + true + + + + build + generate-code + generate-code-tests + native-image-agent + + + + + + maven-compiler-plugin + ${compiler-plugin.version} + + + -parameters + + + + + maven-surefire-plugin + ${surefire-plugin.version} + + + org.jboss.logmanager.LogManager + ${maven.home} + + + + + maven-failsafe-plugin + ${surefire-plugin.version} + + + + integration-test + verify + + + + + + ${project.build.directory}/${project.build.finalName}-runner + org.jboss.logmanager.LogManager + ${maven.home} + + + + + + + + + native + + + native + + + + false + true + + + + diff --git a/projects/qute/projects/maven/qute-record/src/main/java/org/acme/sample/HelloResource.java b/projects/qute/projects/maven/qute-record/src/main/java/org/acme/sample/HelloResource.java new file mode 100644 index 000000000..6d97383ef --- /dev/null +++ b/projects/qute/projects/maven/qute-record/src/main/java/org/acme/sample/HelloResource.java @@ -0,0 +1,22 @@ +package org.acme.sample; + +import jakarta.inject.Inject; +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.core.MediaType; + +import io.quarkus.qute.TemplateInstance; + +@Path("hello") +public class HelloResource { + + record Hello(String name) implements TemplateInstance {} + + @GET + @Produces(MediaType.TEXT_PLAIN) + public TemplateInstance get(@QueryParam("name") String name) { + return new Hello(name).data("foo", 100); + } +} diff --git a/projects/qute/projects/maven/qute-record/src/main/java/org/acme/sample/SomePage.java b/projects/qute/projects/maven/qute-record/src/main/java/org/acme/sample/SomePage.java new file mode 100644 index 000000000..691fd7f46 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/src/main/java/org/acme/sample/SomePage.java @@ -0,0 +1,29 @@ +package org.acme.sample; + +import io.quarkus.qute.Template; +import io.quarkus.qute.TemplateInstance; + +import jakarta.ws.rs.GET; +import jakarta.ws.rs.Path; +import jakarta.ws.rs.Produces; +import jakarta.ws.rs.QueryParam; +import jakarta.ws.rs.core.MediaType; + +import static java.util.Objects.requireNonNull; + +@Path("/some-page") +public class SomePage { + + private final Template page; + + public SomePage(Template page) { + this.page = requireNonNull(page, "page is required"); + } + + @GET + @Produces(MediaType.TEXT_HTML) + public TemplateInstance get(@QueryParam("name") String name) { + return page.data("name", name); + } + +} diff --git a/projects/qute/projects/maven/qute-record/src/main/resources/application.properties b/projects/qute/projects/maven/qute-record/src/main/resources/application.properties new file mode 100644 index 000000000..e69de29bb diff --git a/projects/qute/projects/maven/qute-record/src/main/resources/templates/Hello.html b/projects/qute/projects/maven/qute-record/src/main/resources/templates/Hello.html new file mode 100644 index 000000000..e74b9aef1 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/src/main/resources/templates/Hello.html @@ -0,0 +1,11 @@ +{name} +{foo} + + + + + + + + + diff --git a/projects/qute/projects/maven/qute-record/src/main/resources/templates/Hello2.html b/projects/qute/projects/maven/qute-record/src/main/resources/templates/Hello2.html new file mode 100644 index 000000000..e69de29bb diff --git a/projects/qute/projects/maven/qute-record/src/main/resources/templates/page.qute.html b/projects/qute/projects/maven/qute-record/src/main/resources/templates/page.qute.html new file mode 100644 index 000000000..203bd4b37 --- /dev/null +++ b/projects/qute/projects/maven/qute-record/src/main/resources/templates/page.qute.html @@ -0,0 +1,30 @@ + + + + + Hello {name ?: "Qute"} + + + +

Hello {name ?: "Qute"}

+ +

Create your web page using Quarkus RESTEasy & Qute

+ + diff --git a/src/main/java/com/redhat/devtools/intellij/qute/psi/QuteSupportForTemplate.java b/src/main/java/com/redhat/devtools/intellij/qute/psi/QuteSupportForTemplate.java index fd4f3a4ac..5e557f22c 100644 --- a/src/main/java/com/redhat/devtools/intellij/qute/psi/QuteSupportForTemplate.java +++ b/src/main/java/com/redhat/devtools/intellij/qute/psi/QuteSupportForTemplate.java @@ -1,14 +1,14 @@ /******************************************************************************* -* Copyright (c) 2021 Red Hat Inc. and others. -* All rights reserved. This program and the accompanying materials -* which accompanies this distribution, and is available at -* http://www.eclipse.org/legal/epl-v20.html -* -* SPDX-License-Identifier: EPL-2.0 -* -* Contributors: -* Red Hat Inc. - initial API and implementation -*******************************************************************************/ + * Copyright (c) 2021 Red Hat Inc. and others. + * All rights reserved. This program and the accompanying materials + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat Inc. - initial API and implementation + *******************************************************************************/ package com.redhat.devtools.intellij.qute.psi; import com.intellij.openapi.application.ApplicationManager; @@ -53,440 +53,450 @@ * Qute support for Template file. * * @author Angelo ZERR - * */ public class QuteSupportForTemplate { - private static final Logger LOGGER = Logger.getLogger(QuteSupportForTemplate.class.getName()); - - private static final String JAVA_LANG_OBJECT = "java.lang.Object"; - - private static final QuteSupportForTemplate INSTANCE = new QuteSupportForTemplate(); - - public static QuteSupportForTemplate getInstance() { - return INSTANCE; - } - - /** - * Returns the list of Qute projects from the workspace. - * - * @param utils the JDT LS utility. - * @param monitor the progress monitor. - * - * @return the list of Qute projects from the workspace. - */ - public List getProjects(Project project, IPsiUtils utils, ProgressIndicator monitor) { - List quteProjects = new ArrayList<>(); - // Loop for module from the given project - Module[] modules = ModuleManager.getInstance(project).getModules(); - for (Module javaProject: modules) { - if (PsiQuteProjectUtils.hasQuteSupport(javaProject)) { - // It is a Qute project - quteProjects.add(PsiQuteProjectUtils.getProjectInfo(javaProject)); - } - } - return quteProjects; - } - - /** - * Returns the project information for the given project Uri. - * - * @param params the project information parameters. - * @param utils the JDT LS utility. - * @param monitor the progress monitor. - * - * @return the project information for the given project Uri and null otherwise. - */ - public ProjectInfo getProjectInfo(QuteProjectParams params, IPsiUtils utils, ProgressIndicator monitor) { - Module javaProject = getJavaProjectFromTemplateFile(params.getTemplateFileUri(), utils); - if (javaProject == null) { - return null; - } - return PsiQuteProjectUtils.getProjectInfo(javaProject); - } - - /** - * Collect data model templates from the given project Uri. A data model - * template can be declared with: - * - *
    - *
  • @CheckedTemplate support: collect parameters for Qute Template by - * searching @CheckedTemplate annotation.
  • - *
  • Template field support: collect parameters for Qute Template by searching - * Template instance declared as field in Java class.
  • - *
  • Template extension support: see - * https://quarkus.io/guides/qute-reference#template_extension_methods
  • - *
- * - * @param params the project uri. - * @param utils JDT LS utilities - * @param monitor the progress monitor - * - * @return data model templates from the given project Uri. - */ - public DataModelProject> getDataModelProject( - QuteDataModelProjectParams params, IPsiUtils utils, ProgressIndicator monitor) { - String projectUri = params.getProjectUri(); - Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); - if (javaProject == null) { - return null; - } - - utils = utils.refine(javaProject); - - return QuarkusIntegrationForQute.getDataModelProject(javaProject, utils, monitor); - } - - /** - * Collect user tags from the given project Uri. - * - * @param params the project uri. - * @param utils JDT LS utilities - * @param monitor the progress monitor - * - * @return user tags from the given project Uri. - */ - public List getUserTags(QuteUserTagParams params, IPsiUtils utils, ProgressIndicator monitor) - { - String projectUri = params.getProjectUri(); - Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); - if (javaProject == null) { - return null; - } - return QuarkusIntegrationForQute.getUserTags(javaProject, monitor); - } - - /** - * Returns Java types for the given pattern which belong to the given project - * Uri. - * - * @param params the java types parameters. - * @param utils the JDT LS utility. - * @param monitor the progress monitor. - * - * @return list of Java types. - */ - public List getJavaTypes(QuteJavaTypesParams params, IPsiUtils utils, ProgressIndicator monitor) { - String projectUri = params.getProjectUri(); - Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); - if (javaProject == null) { - return null; - } - - utils = utils.refine(javaProject); - - return new JavaTypesSearch(params.getPattern(), javaProject).search(monitor); - } - - /** - * Returns the Java definition of the given Java type, method, field, method - * parameter, method invocation parameter and null otherwise. - * - * @param params the Java element information. - * @param utils the JDT LS utility. - * @param monitor the progress monitor. - * - * @return the Java definition of the given Java type, method, field, method - * parameter, method invocation parameter and null otherwise. - */ - public Location getJavaDefinition(QuteJavaDefinitionParams params, IPsiUtils utils, ProgressIndicator monitor) { - String projectUri = params.getProjectUri(); - Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); - if (javaProject == null) { - return null; - } - - utils = utils.refine(javaProject); - - PsiClass type = getTypeFromParams(params.getSourceType(), params.getProjectUri(), javaProject, monitor); - if (type == null) { - return null; - } - - String parameterName = params.getSourceParameter(); - boolean dataMethodInvocation = parameterName != null && params.isDataMethodInvocation(); - - String fieldName = params.getSourceField(); - if (fieldName != null) { - PsiField field = type.findFieldByName(fieldName, true); - if (field == null || !field.isValid()) { - // The field doesn't exist - return null; - } - - if (dataMethodInvocation) { - // returns the location of "data" method invocation with the given parameter - // name - return TemplateDataSupport.getDataMethodInvocationLocation(field, parameterName, utils, monitor); - } - // returns field location - return utils.toLocation(field); - } - - String sourceMethod = params.getSourceMethod(); - if (sourceMethod != null) { - PsiMethod method = findMethod(type, sourceMethod); - if (method == null || !method.isValid()) { - // The method doesn't exist - return null; - } - - if (parameterName != null) { - if (dataMethodInvocation) { - // returns the location of "data" method invocation with the given parameter - // name - return TemplateDataSupport.getDataMethodInvocationLocation(method, parameterName, utils, monitor); - } - PsiParameter[] parameters = method.getParameterList().getParameters(); - for (PsiParameter parameter : parameters) { - if (parameterName.equals(parameter.getName())) { - // returns the method parameter location - return utils.toLocation(parameter); - } - } - return null; - } - // returns method location - return utils.toLocation(method); - } - // returns Java type location - return utils.toLocation(type); - } - - private PsiMethod findMethod(PsiClass type, String sourceMethod) { - // For the moment we search method only by name - // FIXME:use method signature to retrieve the proper method (see findMethodOLD) - PsiMethod[] methods = type.getMethods(); - for (PsiMethod method : methods) { - if (sourceMethod.equals(method.getName())) { - return method; - } - } - return null; - } - - /** - * Returns the resolved type (fields and methods) for the given Java type. - * - * @param params the Java type to resolve. - * @param utils the JDT LS utility. - * @param monitor the progress monitor. - * - * @return the resolved type (fields and methods) for the given Java type. - */ - public ResolvedJavaTypeInfo getResolvedJavaType(QuteResolvedJavaTypeParams params, IPsiUtils utils, - ProgressIndicator monitor) { - if (monitor.isCanceled()) { - throw new ProcessCanceledException(); - } - String projectUri = params.getProjectUri(); - Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); - if (javaProject == null) { - return null; - } - - utils = utils.refine(javaProject); - - String typeName = params.getClassName(); - - // ex : org.acme.Item, java.util.List, ... - PsiClass type = findType(typeName, javaProject, monitor); - if (type == null) { - return null; - } - - ValueResolverKind kind = params.getKind(); - return ResolvedJavaTypeFactoryRegistry.getInstance().create(type, kind,javaProject); - } - - private static boolean isValidField(PsiField field, PsiClass type) { - if (type.isEnum()) { - return true; - } - return field.getModifierList().hasExplicitModifier(PsiModifier.PUBLIC); - } - - private static Module getJavaProjectFromProjectUri(String projectName, IPsiUtils utils) { - if (projectName == null) { - return null; - } - return ModuleManager.getInstance(utils.getProject()).findModuleByName(projectName); - } - - public static Module getJavaProjectFromTemplateFile(String templateFileUri, IPsiUtils utils) { - try { - templateFileUri = templateFileUri.replace("vscode-notebook-cell", "file"); - VirtualFile file = utils.findFile(templateFileUri); - return utils.getModule(file); - } catch (IOException e) { - return null; - } - } - - private static PsiClass[] findImplementedInterfaces(PsiClass type, ProgressIndicator progressMonitor) { - return type.getInterfaces(); - } - - - public static ITypeResolver createTypeResolver(PsiMember member, Module javaProject) { + private static final Logger LOGGER = Logger.getLogger(QuteSupportForTemplate.class.getName()); + + private static final String JAVA_LANG_OBJECT = "java.lang.Object"; + + private static final QuteSupportForTemplate INSTANCE = new QuteSupportForTemplate(); + + public static QuteSupportForTemplate getInstance() { + return INSTANCE; + } + + /** + * Returns the list of Qute projects from the workspace. + * + * @param utils the JDT LS utility. + * @param monitor the progress monitor. + * @return the list of Qute projects from the workspace. + */ + public List getProjects(Project project, IPsiUtils utils, ProgressIndicator monitor) { + List quteProjects = new ArrayList<>(); + // Loop for module from the given project + Module[] modules = ModuleManager.getInstance(project).getModules(); + for (Module javaProject : modules) { + if (PsiQuteProjectUtils.hasQuteSupport(javaProject)) { + // It is a Qute project + quteProjects.add(PsiQuteProjectUtils.getProjectInfo(javaProject)); + } + } + return quteProjects; + } + + /** + * Returns the project information for the given project Uri. + * + * @param params the project information parameters. + * @param utils the JDT LS utility. + * @param monitor the progress monitor. + * @return the project information for the given project Uri and null otherwise. + */ + public ProjectInfo getProjectInfo(QuteProjectParams params, IPsiUtils utils, ProgressIndicator monitor) { + Module javaProject = getJavaProjectFromTemplateFile(params.getTemplateFileUri(), utils); + if (javaProject == null) { + return null; + } + return PsiQuteProjectUtils.getProjectInfo(javaProject); + } + + /** + * Collect data model templates from the given project Uri. A data model + * template can be declared with: + * + *
    + *
  • @CheckedTemplate support: collect parameters for Qute Template by + * searching @CheckedTemplate annotation.
  • + *
  • Template field support: collect parameters for Qute Template by searching + * Template instance declared as field in Java class.
  • + *
  • Template extension support: see + * https://quarkus.io/guides/qute-reference#template_extension_methods
  • + *
+ * + * @param params the project uri. + * @param utils JDT LS utilities + * @param monitor the progress monitor + * @return data model templates from the given project Uri. + */ + public DataModelProject> getDataModelProject( + QuteDataModelProjectParams params, IPsiUtils utils, ProgressIndicator monitor) { + String projectUri = params.getProjectUri(); + Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); + if (javaProject == null) { + return null; + } + + utils = utils.refine(javaProject); + + return QuarkusIntegrationForQute.getDataModelProject(javaProject, utils, monitor); + } + + /** + * Collect user tags from the given project Uri. + * + * @param params the project uri. + * @param utils JDT LS utilities + * @param monitor the progress monitor + * @return user tags from the given project Uri. + */ + public List getUserTags(QuteUserTagParams params, IPsiUtils utils, ProgressIndicator monitor) { + String projectUri = params.getProjectUri(); + Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); + if (javaProject == null) { + return null; + } + return QuarkusIntegrationForQute.getUserTags(javaProject, monitor); + } + + /** + * Returns Java types for the given pattern which belong to the given project + * Uri. + * + * @param params the java types parameters. + * @param utils the JDT LS utility. + * @param monitor the progress monitor. + * @return list of Java types. + */ + public List getJavaTypes(QuteJavaTypesParams params, IPsiUtils utils, ProgressIndicator monitor) { + String projectUri = params.getProjectUri(); + Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); + if (javaProject == null) { + return null; + } + + utils = utils.refine(javaProject); + + return new JavaTypesSearch(params.getPattern(), javaProject).search(monitor); + } + + /** + * Returns the Java definition of the given Java type, method, field, method + * parameter, method invocation parameter and null otherwise. + * + * @param params the Java element information. + * @param utils the JDT LS utility. + * @param monitor the progress monitor. + * @return the Java definition of the given Java type, method, field, method + * parameter, method invocation parameter and null otherwise. + */ + public Location getJavaDefinition(QuteJavaDefinitionParams params, IPsiUtils utils, ProgressIndicator monitor) { + String projectUri = params.getProjectUri(); + Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); + if (javaProject == null) { + return null; + } + + utils = utils.refine(javaProject); + + PsiClass type = getTypeFromParams(params.getSourceType(), params.getProjectUri(), javaProject, monitor); + if (type == null) { + return null; + } + + String parameterName = params.getSourceParameter(); + boolean dataMethodInvocation = parameterName != null && params.isDataMethodInvocation(); + + if (type.isRecord()) { + // The source type is a record + if (dataMethodInvocation) { + // returns the location of "data" method invocation with the given parameter + // name + return TemplateDataSupport.getDataMethodInvocationLocation(type, parameterName, utils, + monitor); + } else { + // Search field of the record + for (var recordField : type.getRecordComponents()) { + if (parameterName.equals(recordField.getName())) { + // returns the record field location + return utils.toLocation(recordField); + } + } + } + } else { + // The source type is a class + String fieldName = params.getSourceField(); + if (fieldName != null) { + PsiField field = type.findFieldByName(fieldName, true); + if (field == null || !field.isValid()) { + // The field doesn't exist + return null; + } + + if (dataMethodInvocation) { + // returns the location of "data" method invocation with the given parameter + // name + return TemplateDataSupport.getDataMethodInvocationLocation(field, parameterName, utils, monitor); + } + // returns field location + return utils.toLocation(field); + } + + String sourceMethod = params.getSourceMethod(); + if (sourceMethod != null) { + PsiMethod method = findMethod(type, sourceMethod); + if (method == null || !method.isValid()) { + // The method doesn't exist + return null; + } + + if (parameterName != null) { + if (dataMethodInvocation) { + // returns the location of "data" method invocation with the given parameter + // name + return TemplateDataSupport.getDataMethodInvocationLocation(method, parameterName, utils, monitor); + } + PsiParameter[] parameters = method.getParameterList().getParameters(); + for (PsiParameter parameter : parameters) { + if (parameterName.equals(parameter.getName())) { + // returns the method parameter location + return utils.toLocation(parameter); + } + } + return null; + } + // returns method location + return utils.toLocation(method); + } + } + // returns Java type location + return utils.toLocation(type); + } + + private PsiMethod findMethod(PsiClass type, String sourceMethod) { + // For the moment we search method only by name + // FIXME:use method signature to retrieve the proper method (see findMethodOLD) + PsiMethod[] methods = type.getMethods(); + for (PsiMethod method : methods) { + if (sourceMethod.equals(method.getName())) { + return method; + } + } + return null; + } + + /** + * Returns the resolved type (fields and methods) for the given Java type. + * + * @param params the Java type to resolve. + * @param utils the JDT LS utility. + * @param monitor the progress monitor. + * @return the resolved type (fields and methods) for the given Java type. + */ + public ResolvedJavaTypeInfo getResolvedJavaType(QuteResolvedJavaTypeParams params, IPsiUtils utils, + ProgressIndicator monitor) { + if (monitor.isCanceled()) { + throw new ProcessCanceledException(); + } + String projectUri = params.getProjectUri(); + Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); + if (javaProject == null) { + return null; + } + + utils = utils.refine(javaProject); + + String typeName = params.getClassName(); + + // ex : org.acme.Item, java.util.List, ... + PsiClass type = findType(typeName, javaProject, monitor); + if (type == null) { + return null; + } + + ValueResolverKind kind = params.getKind(); + return ResolvedJavaTypeFactoryRegistry.getInstance().create(type, kind, javaProject); + } + + private static boolean isValidField(PsiField field, PsiClass type) { + if (type.isEnum()) { + return true; + } + return field.getModifierList().hasExplicitModifier(PsiModifier.PUBLIC); + } + + private static Module getJavaProjectFromProjectUri(String projectName, IPsiUtils utils) { + if (projectName == null) { + return null; + } + return ModuleManager.getInstance(utils.getProject()).findModuleByName(projectName); + } + + public static Module getJavaProjectFromTemplateFile(String templateFileUri, IPsiUtils utils) { + try { + templateFileUri = templateFileUri.replace("vscode-notebook-cell", "file"); + VirtualFile file = utils.findFile(templateFileUri); + return utils.getModule(file); + } catch (IOException e) { + return null; + } + } + + private static PsiClass[] findImplementedInterfaces(PsiClass type, ProgressIndicator progressMonitor) { + return type.getInterfaces(); + } + + + public static ITypeResolver createTypeResolver(PsiMember member, Module javaProject) { /*ITypeResolver typeResolver = !member.isBinary() ? new CompilationUnitTypeResolver((ICompilationUnit) member.getAncestor(IJavaElement.COMPILATION_UNIT)) : new ClassFileTypeResolver((IClassFile) member.getAncestor(IJavaElement.CLASS_FILE));*/ - ITypeResolver typeResolver = new ClassFileTypeResolver(member instanceof PsiClass ? - (PsiClass) member : member.getContainingClass(), javaProject); - return typeResolver; - } - - /** - * Returns the workspace edit to generate the given java member for the given - * type. - * - * @param params the parameters needed to resolve the workspace edit - * @param utils the jdt utils - * @param monitor the progress monitor - * @return the workspace edit to generate the given java member for the given - * type - */ - public WorkspaceEdit generateMissingJavaMember(GenerateMissingJavaMemberParams params, IPsiUtils utils, - ProgressIndicator monitor) { - return QuteSupportForTemplateGenerateMissingJavaMemberHandler.handleGenerateMissingJavaMember(params, utils, - monitor); - } - - /** - * Returns the formatted Javadoc for the member specified in the parameters. - * - * @param params the parameters used to specify the member whose documentation - * should be found - * @param utils the JDT utils - * @param monitor the progress monitor - * @return the formatted Javadoc for the member specified in the parameters - */ - public String getJavadoc(QuteJavadocParams params, IPsiUtils utils, ProgressIndicator monitor) { - try { - String projectUri = params.getProjectUri(); - Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); - if (javaProject == null) { - return null; - } - - final var refinedUtils = utils.refine(javaProject); - - PsiClass type = getTypeFromParams(params.getSourceType(), params.getProjectUri(), javaProject, monitor); - if (type == null) { - return null; - } - return getJavadoc(type, params.getDocumentFormat(), params.getMemberName(), params.getSignature(), refinedUtils, - monitor, new HashSet<>()); - } catch (ProcessCanceledException e) { - //Since 2024.2 ProcessCanceledException extends CancellationException so we can't use multicatch to keep backward compatibility - //TODO delete block when minimum required version is 2024.2 - throw e; - } catch (IndexNotReadyException | CancellationException e) { - throw e; - } catch (Exception e) { - LOGGER.log(Level.WARNING, - "Error while collecting Javadoc for " + params.getSourceType() + "#" + params.getMemberName(), e); - return null; - } - } - - private String getJavadoc(PsiClass type, DocumentFormat documentFormat, String memberName, String signature, - IPsiUtils utils, ProgressIndicator monitor, Set visited) { - if (visited.contains(type)) { - return null; - } - visited.add(type); - if (monitor.isCanceled()) { - throw new ProcessCanceledException(); - } - - ITypeResolver typeResolver = createTypeResolver(type, utils.getModule()); - - // 1) Check the fields for the member - - // Standard fields - PsiField[] fields = type.getFields(); - for (PsiField field : fields) { - if (isValidField(field, type) - && memberName.equals(field.getName()) - && signature.equals(typeResolver.resolveFieldSignature(field))) { - String javadoc = utils.getJavadoc(field, documentFormat); - if (javadoc != null) { - return javadoc; - } - } - } - - // Record fields - if (type.isRecord()) { - for (PsiRecordComponent field : type.getRecordComponents()) { - // All record components are valid - if (memberName.equals(field.getName()) - && signature.equals(typeResolver.resolveFieldSignature(field))) { - String javadoc = utils.getJavadoc(field, documentFormat); - if (javadoc != null) { - return javadoc; - } - } - } - } - - // 2) Check the methods for the member - PsiMethod[] methods = type.getMethods(); - for (PsiMethod method : methods) { - if (!method.isConstructor()) { - try { - if (signature.equals(typeResolver.resolveMethodSignature(method))) { - String javadoc = utils.getJavadoc(method, documentFormat); - if (javadoc != null) { - return javadoc; - } - } - } catch (ProcessCanceledException e) { - //Since 2024.2 ProcessCanceledException extends CancellationException so we can't use multicatch to keep backward compatibility - //TODO delete block when minimum required version is 2024.2 - throw e; - } catch (IndexNotReadyException | CancellationException e) { - throw e; - } catch (Exception e) { - LOGGER.log(Level.SEVERE, "Error while getting method signature of '" + method.getName() + "'.", - e); - } - } - } - - // 3) Check the superclasses for the member - - // Collect type extensions - List extendedTypes = null; - if (type.isInterface()) { - PsiClass[] interfaces = findImplementedInterfaces(type, monitor); - if (interfaces != null && interfaces.length > 0) { - extendedTypes = Arrays.asList(interfaces); - } - } else { - // ex : String implements CharSequence, .... - PsiClass[] allSuperTypes = type.getSupers(); - extendedTypes = Arrays.asList(allSuperTypes); - } - - if (extendedTypes != null) { - for (PsiClass extendedType : extendedTypes) { - String javadoc = getJavadoc(extendedType, documentFormat, memberName, signature, utils, monitor, visited); - if (javadoc != null) { - return javadoc; - } - } - } - - return null; - - } - - private PsiClass getTypeFromParams(String typeName, String projectUri,Module javaProject, ProgressIndicator monitor) { - PsiClass type = findType(typeName, javaProject, monitor); - return type; - } + ITypeResolver typeResolver = new ClassFileTypeResolver(member instanceof PsiClass ? + (PsiClass) member : member.getContainingClass(), javaProject); + return typeResolver; + } + + /** + * Returns the workspace edit to generate the given java member for the given + * type. + * + * @param params the parameters needed to resolve the workspace edit + * @param utils the jdt utils + * @param monitor the progress monitor + * @return the workspace edit to generate the given java member for the given + * type + */ + public WorkspaceEdit generateMissingJavaMember(GenerateMissingJavaMemberParams params, IPsiUtils utils, + ProgressIndicator monitor) { + return QuteSupportForTemplateGenerateMissingJavaMemberHandler.handleGenerateMissingJavaMember(params, utils, + monitor); + } + + /** + * Returns the formatted Javadoc for the member specified in the parameters. + * + * @param params the parameters used to specify the member whose documentation + * should be found + * @param utils the JDT utils + * @param monitor the progress monitor + * @return the formatted Javadoc for the member specified in the parameters + */ + public String getJavadoc(QuteJavadocParams params, IPsiUtils utils, ProgressIndicator monitor) { + try { + String projectUri = params.getProjectUri(); + Module javaProject = getJavaProjectFromProjectUri(projectUri, utils); + if (javaProject == null) { + return null; + } + + final var refinedUtils = utils.refine(javaProject); + + PsiClass type = getTypeFromParams(params.getSourceType(), params.getProjectUri(), javaProject, monitor); + if (type == null) { + return null; + } + return getJavadoc(type, params.getDocumentFormat(), params.getMemberName(), params.getSignature(), refinedUtils, + monitor, new HashSet<>()); + } catch (ProcessCanceledException e) { + //Since 2024.2 ProcessCanceledException extends CancellationException so we can't use multicatch to keep backward compatibility + //TODO delete block when minimum required version is 2024.2 + throw e; + } catch (IndexNotReadyException | CancellationException e) { + throw e; + } catch (Exception e) { + LOGGER.log(Level.WARNING, + "Error while collecting Javadoc for " + params.getSourceType() + "#" + params.getMemberName(), e); + return null; + } + } + + private String getJavadoc(PsiClass type, DocumentFormat documentFormat, String memberName, String signature, + IPsiUtils utils, ProgressIndicator monitor, Set visited) { + if (visited.contains(type)) { + return null; + } + visited.add(type); + if (monitor.isCanceled()) { + throw new ProcessCanceledException(); + } + + ITypeResolver typeResolver = createTypeResolver(type, utils.getModule()); + + // 1) Check the fields for the member + + // Standard fields + PsiField[] fields = type.getFields(); + for (PsiField field : fields) { + if (isValidField(field, type) + && memberName.equals(field.getName()) + && signature.equals(typeResolver.resolveFieldSignature(field))) { + String javadoc = utils.getJavadoc(field, documentFormat); + if (javadoc != null) { + return javadoc; + } + } + } + + // Record fields + if (type.isRecord()) { + for (PsiRecordComponent field : type.getRecordComponents()) { + // All record components are valid + if (memberName.equals(field.getName()) + && signature.equals(typeResolver.resolveFieldSignature(field))) { + String javadoc = utils.getJavadoc(field, documentFormat); + if (javadoc != null) { + return javadoc; + } + } + } + } + + // 2) Check the methods for the member + PsiMethod[] methods = type.getMethods(); + for (PsiMethod method : methods) { + if (!method.isConstructor()) { + try { + if (signature.equals(typeResolver.resolveMethodSignature(method))) { + String javadoc = utils.getJavadoc(method, documentFormat); + if (javadoc != null) { + return javadoc; + } + } + } catch (ProcessCanceledException e) { + //Since 2024.2 ProcessCanceledException extends CancellationException so we can't use multicatch to keep backward compatibility + //TODO delete block when minimum required version is 2024.2 + throw e; + } catch (IndexNotReadyException | CancellationException e) { + throw e; + } catch (Exception e) { + LOGGER.log(Level.SEVERE, "Error while getting method signature of '" + method.getName() + "'.", + e); + } + } + } + + // 3) Check the superclasses for the member + + // Collect type extensions + List extendedTypes = null; + if (type.isInterface()) { + PsiClass[] interfaces = findImplementedInterfaces(type, monitor); + if (interfaces != null && interfaces.length > 0) { + extendedTypes = Arrays.asList(interfaces); + } + } else { + // ex : String implements CharSequence, .... + PsiClass[] allSuperTypes = type.getSupers(); + extendedTypes = Arrays.asList(allSuperTypes); + } + + if (extendedTypes != null) { + for (PsiClass extendedType : extendedTypes) { + String javadoc = getJavadoc(extendedType, documentFormat, memberName, signature, utils, monitor, visited); + if (javadoc != null) { + return javadoc; + } + } + } + + return null; + + } + + private PsiClass getTypeFromParams(String typeName, String projectUri, Module javaProject, ProgressIndicator monitor) { + PsiClass type = findType(typeName, javaProject, monitor); + return type; + } } diff --git a/src/main/java/com/redhat/devtools/intellij/qute/psi/internal/QuteJavaConstants.java b/src/main/java/com/redhat/devtools/intellij/qute/psi/internal/QuteJavaConstants.java index 942982870..e2a8d5626 100644 --- a/src/main/java/com/redhat/devtools/intellij/qute/psi/internal/QuteJavaConstants.java +++ b/src/main/java/com/redhat/devtools/intellij/qute/psi/internal/QuteJavaConstants.java @@ -28,6 +28,8 @@ public class QuteJavaConstants { public static final String TEMPLATE_CLASS = "io.quarkus.qute.Template"; + public static final String TEMPLATE_INSTANCE_INTERFACE = "io.quarkus.qute.TemplateInstance"; + public static final String ENGINE_BUILDER_CLASS = "io.quarkus.qute.EngineBuilder"; public static final String VALUE_ANNOTATION_NAME = "value"; diff --git a/src/main/java/com/redhat/devtools/intellij/qute/psi/internal/java/AbstractQuteTemplateLinkCollector.java b/src/main/java/com/redhat/devtools/intellij/qute/psi/internal/java/AbstractQuteTemplateLinkCollector.java index 28e291e19..8a139c6ab 100644 --- a/src/main/java/com/redhat/devtools/intellij/qute/psi/internal/java/AbstractQuteTemplateLinkCollector.java +++ b/src/main/java/com/redhat/devtools/intellij/qute/psi/internal/java/AbstractQuteTemplateLinkCollector.java @@ -84,6 +84,17 @@ public AbstractQuteTemplateLinkCollector(PsiFile typeRoot, IPsiUtils utils, Prog this.relativeTemplatesBaseDir = PsiQuteProjectUtils.getRelativeTemplateBaseDir(utils.getModule(), resourcesDir); } + /** + * Support for "Template Fields" + * + *

+ * private Template items; + *

+ * + * @see Quarkus + * Integration + */ @Override public void visitField(PsiField node) { PsiType type = node.getType(); @@ -130,6 +141,27 @@ private AnnotationLocationSupport getAnnotationLocationSupport() { @Override public void visitClass(PsiClass node) { + if (node.isRecord()) { + visitRecordType(node); + } else { + visitClassType(node); + } + } + + /** + * Support for "TypeSafe Templates" + * + *

+ * + * @CheckedTemplate public static class Templates { public static native + * TemplateInstance book(Book book); + *

+ * + * @see TypeSafe + * Templates + */ + private void visitClassType(PsiClass node) { levelTypeDecl++; for (PsiAnnotation annotation : node.getAnnotations()) { if (AnnotationUtils.isMatchAnnotation(annotation, CHECKED_TEMPLATE_ANNOTATION) @@ -148,11 +180,22 @@ public void visitClass(PsiClass node) { levelTypeDecl--; } + /** + * Support for "Template Records" + * + * @see Template + * Records + */ + private void visitRecordType(PsiClass node) { + String recordName = node.getName(); + collectTemplateLink(null, node, null, node.getContainingClass(), null, recordName, false); + } + private static PsiClass getTypeDeclaration(PsiElement node) { return PsiTreeUtil.getParentOfType(node, PsiClass.class); } - private void collectTemplateLink(String basePath, PsiMethod methodDeclaration, PsiClass type, boolean ignoreFragments) { String className = null; boolean innerClass = levelTypeDecl > 1; diff --git a/src/main/java/com/redhat/devtools/intellij/qute/psi/internal/template/datamodel/TemplateRecordsSupport.java b/src/main/java/com/redhat/devtools/intellij/qute/psi/internal/template/datamodel/TemplateRecordsSupport.java new file mode 100644 index 000000000..5c405511b --- /dev/null +++ b/src/main/java/com/redhat/devtools/intellij/qute/psi/internal/template/datamodel/TemplateRecordsSupport.java @@ -0,0 +1,108 @@ +/******************************************************************************* + * Copyright (c) 2024 Red Hat Inc. and others. + * All rights reserved. This program and the accompanying materials + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v20.html + * + * SPDX-License-Identifier: EPL-2.0 + * + * Contributors: + * Red Hat Inc. - initial API and implementation + *******************************************************************************/ +package com.redhat.devtools.intellij.qute.psi.internal.template.datamodel; + +import com.intellij.openapi.progress.ProgressIndicator; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiRecordComponent; +import com.redhat.devtools.intellij.qute.psi.internal.template.TemplateDataSupport; +import com.redhat.devtools.intellij.qute.psi.template.datamodel.AbstractInterfaceImplementationDataModelProvider; +import com.redhat.devtools.intellij.qute.psi.template.datamodel.SearchContext; +import com.redhat.devtools.intellij.qute.psi.utils.PsiTypeUtils; +import com.redhat.qute.commons.datamodel.DataModelParameter; +import com.redhat.qute.commons.datamodel.DataModelTemplate; + +import java.util.ArrayList; +import java.util.List; + +import static com.redhat.devtools.intellij.qute.psi.internal.QuteJavaConstants.TEMPLATE_INSTANCE_INTERFACE; +import static com.redhat.devtools.intellij.qute.psi.utils.PsiQuteProjectUtils.getTemplatePath; + +/** + * Template Records support for template files: + * + * + * public class HelloResource { + *

+ * record Hello(String name) implements TemplateInstance {} + *

+ * ... + *

+ *

+ * @GET + * @Produces(MediaType.TEXT_PLAIN) + * public TemplateInstance get(@QueryParam("name") String name) { + * return new Hello(name).data("bar", 100); + * } + * + * + * @author Angelo ZERR + * @see Template + * Records + */ +public class TemplateRecordsSupport extends AbstractInterfaceImplementationDataModelProvider { + + private static final String[] INTERFACE_NAMES = {TEMPLATE_INSTANCE_INTERFACE}; + + @Override + protected String[] getInterfaceNames() { + return INTERFACE_NAMES; + } + + @Override + protected void processType(PsiClass type, SearchContext context, ProgressIndicator monitor) { + if (!type.isRecord()) { + return; + } + collectDataModelTemplateForTemplateRecord(type, context.getRelativeTemplateBaseDir(), context.getDataModelProject().getTemplates(), + monitor); + } + + private static void collectDataModelTemplateForTemplateRecord(PsiClass type, + String relativeTemplateBaseDir, + List> templates, ProgressIndicator monitor) { + DataModelTemplate template = createTemplateDataModel(type, relativeTemplateBaseDir, monitor); + templates.add(template); + } + + private static DataModelTemplate createTemplateDataModel(PsiClass type, + String relativeTemplateBaseDir, + ProgressIndicator monitor) { + + String recordName = type.getName(); + // src/main/resources/templates/${recordName}.qute.html + String templateUri = getTemplatePath(relativeTemplateBaseDir, null, null, recordName, true).getTemplateUri(); + + // Create template data model with: + // - template uri : Qute template file which must be bind with data model. + // - source type : the record class which defines Templates + // - + DataModelTemplate template = new DataModelTemplate(); + template.setParameters(new ArrayList<>()); + template.setTemplateUri(templateUri); + template.setSourceType(type.getQualifiedName()); + + // Collect data parameters from the record fields + for (PsiRecordComponent field : type.getRecordComponents()) { + DataModelParameter parameter = new DataModelParameter(); + parameter.setKey(field.getName()); + parameter.setSourceType(PsiTypeUtils.resolveSignature(field.getType(), field.isVarArgs())); + template.getParameters().add(parameter); + } + + // Collect data parameters for the given template + TemplateDataSupport.collectParametersFromDataMethodInvocation(type, template, monitor); + return template; + } + +} diff --git a/src/main/java/com/redhat/devtools/intellij/qute/psi/template/datamodel/AbstractDataModelProvider.java b/src/main/java/com/redhat/devtools/intellij/qute/psi/template/datamodel/AbstractDataModelProvider.java index b5d973d5e..d2f7f50cd 100644 --- a/src/main/java/com/redhat/devtools/intellij/qute/psi/template/datamodel/AbstractDataModelProvider.java +++ b/src/main/java/com/redhat/devtools/intellij/qute/psi/template/datamodel/AbstractDataModelProvider.java @@ -21,6 +21,7 @@ import com.intellij.psi.PsiModifierListOwner; import com.intellij.psi.PsiReference; import com.intellij.psi.search.searches.AnnotatedElementsSearch; +import com.intellij.psi.search.searches.DefinitionsScopedSearch; import com.intellij.psi.search.searches.ReferencesSearch; import com.intellij.util.EmptyQuery; import com.intellij.util.MergeQuery; @@ -125,6 +126,26 @@ protected static Query createFieldDeclarationTypeReferenceSearchPa } } + /** + * Create a search pattern to retrieve IType which implement the given + * interfaceNameinterfaceName createInterfaceImplementationSearchPattern(SearchContext context, + String interfaceName) { + PsiClass interfaceClass = context.getUtils().findClass(context.getJavaProject(), interfaceName); + if (interfaceClass != null) { + return DefinitionsScopedSearch.search(interfaceClass, context.getJavaProject().getModuleWithDependenciesAndLibrariesScope(false), false); + } else { + return new EmptyQuery<>(); + } + } + @Override public void endSearch(SearchContext context, ProgressIndicator monitor) { NamespaceResolverInfo info = getNamespaceResolverInfo(); diff --git a/src/main/java/com/redhat/devtools/intellij/qute/psi/template/datamodel/AbstractInterfaceImplementationDataModelProvider.java b/src/main/java/com/redhat/devtools/intellij/qute/psi/template/datamodel/AbstractInterfaceImplementationDataModelProvider.java new file mode 100644 index 000000000..6357ef373 --- /dev/null +++ b/src/main/java/com/redhat/devtools/intellij/qute/psi/template/datamodel/AbstractInterfaceImplementationDataModelProvider.java @@ -0,0 +1,85 @@ +/******************************************************************************* +* Copyright (c) 2024 Red Hat Inc. and others. +* All rights reserved. This program and the accompanying materials +* which accompanies this distribution, and is available at +* http://www.eclipse.org/legal/epl-v20.html +* +* SPDX-License-Identifier: EPL-2.0 +* +* Contributors: +* Red Hat Inc. - initial API and implementation +*******************************************************************************/ +package com.redhat.devtools.intellij.qute.psi.template.datamodel; + +import java.util.logging.Level; +import java.util.logging.Logger; + +import com.intellij.openapi.progress.ProgressIndicator; +import com.intellij.psi.PsiClass; +import com.intellij.util.Query; +import org.jetbrains.annotations.NotNull; + +/** + * Abstract class for data model provider based on class type search which + * implements some interfaces. + * + * @author Angelo ZERR + * + */ +public abstract class AbstractInterfaceImplementationDataModelProvider extends AbstractDataModelProvider { + + private static final Logger LOGGER = Logger + .getLogger(AbstractInterfaceImplementationDataModelProvider.class.getName()); + + @Override + protected String[] getPatterns() { + return getInterfaceNames(); + } + + /** + * Returns the interface names to search. + * + * @return the interface names to search. + */ + protected abstract String[] getInterfaceNames(); + + @Override + protected Query createSearchPattern(SearchContext context, String interfaceName) { + return createInterfaceImplementationSearchPattern(context, interfaceName); + } + + @Override + public void collectDataModel(Object match, SearchContext context, ProgressIndicator monitor) { + Object element = match; + if (element instanceof PsiClass type) { + try { + if (isApplicable(type)) { + processType(type, context, monitor); + } + } catch (Exception e) { + if (LOGGER.isLoggable(Level.SEVERE)) { + LOGGER.log(Level.SEVERE, + "Cannot collect Qute data model for the type '" + type.getQualifiedName() + "'.", e); + } + } + } + } + + private boolean isApplicable(PsiClass type) { + PsiClass @NotNull [] superInterfaceNames = type.getInterfaces(); + if (superInterfaceNames == null || superInterfaceNames.length == 0) { + return false; + } + for (String interfaceName : getInterfaceNames()) { + for (PsiClass superInterfaceName : superInterfaceNames) { + if (interfaceName.equals(superInterfaceName.getQualifiedName())) { + return true; + } + } + } + return false; + } + + protected abstract void processType(PsiClass recordElement, SearchContext context, ProgressIndicator monitor); + +} diff --git a/src/main/resources/META-INF/plugin.xml b/src/main/resources/META-INF/plugin.xml index 33d86a1b2..a3facf244 100644 --- a/src/main/resources/META-INF/plugin.xml +++ b/src/main/resources/META-INF/plugin.xml @@ -633,6 +633,8 @@ implementation="com.redhat.devtools.intellij.lsp4mp4ij.psi.internal.reactivemessaging.java.MicroProfileReactiveMessagingASTValidator"/> + > project = QuteSupportForTemplate.getInstance() - .getDataModelProject(params, PsiUtilsLSImpl.getInstance(myProject), new EmptyProgressIndicator()); - Assert.assertNotNull(project); + @Test + public void testQuteQuickStart() throws Exception { + + loadMavenProject(QuteMavenProjectName.qute_quickstart); + + QuteDataModelProjectParams params = new QuteDataModelProjectParams(QuteMavenProjectName.qute_quickstart); + DataModelProject> project = QuteSupportForTemplate.getInstance() + .getDataModelProject(params, PsiUtilsLSImpl.getInstance(myProject), new EmptyProgressIndicator()); + Assert.assertNotNull(project); + + // Test templates + testTemplates(project); + // Test value resolvers + + List resolvers = project.getValueResolvers(); + Assert.assertNotNull(resolvers); + Assert.assertFalse(resolvers.isEmpty()); - // Test templates - testTemplates(project); - // Test value resolvers + testValueResolversFromTemplateExtension(resolvers); + testValueResolversFromInject(resolvers); + testValueResolversFromTemplateData(resolvers); + testValueResolversFromTemplateEnum(resolvers); + testValueResolversFromTemplateGlobal(resolvers); + } + + private static void testTemplates(DataModelProject> project) { + List> templates = project.getTemplates(); + Assert.assertNotNull(templates); + Assert.assertFalse(templates.isEmpty()); + + templateField(project); + checkedTemplateInnerClass(project); + checkedTemplate(project); + } + + private static void templateField(DataModelProject> project) { + // Template hello; + + DataModelTemplate helloTemplate = project + .findDataModelTemplate("src/main/resources/templates/hello"); + Assert.assertNotNull(helloTemplate); + Assert.assertEquals("src/main/resources/templates/hello", helloTemplate.getTemplateUri()); + Assert.assertEquals("org.acme.qute.HelloResource", helloTemplate.getSourceType()); + Assert.assertEquals("hello", helloTemplate.getSourceField()); + + List parameters = helloTemplate.getParameters(); + Assert.assertNotNull(parameters); + + // hello.data("height", 1.50, "weight", 50L) + // .data("age", 12) + // .data("name", name); + + Assert.assertEquals(4, parameters.size()); + assertParameter("height", "double", true, parameters, 0); + assertParameter("weight", "long", true, parameters, 1); + assertParameter("age", "int", true, parameters, 2); + assertParameter("name", "java.lang.String", true, parameters, 3); + + // Template goodbye; + + DataModelTemplate goodbyeTemplate = project + .findDataModelTemplate("src/main/resources/templates/goodbye"); + Assert.assertNotNull(goodbyeTemplate); + Assert.assertEquals("src/main/resources/templates/goodbye", goodbyeTemplate.getTemplateUri()); + Assert.assertEquals("org.acme.qute.HelloResource", goodbyeTemplate.getSourceType()); + Assert.assertEquals("goodbye", goodbyeTemplate.getSourceField()); + + List parameters2 = goodbyeTemplate.getParameters(); + Assert.assertNotNull(parameters2); + + // goodbye.data("age2", 12); + // return goodbye.data("name2", name); + + Assert.assertEquals(2, parameters2.size()); + assertParameter("age2", "int", true, goodbyeTemplate); + assertParameter("name2", "java.lang.String", true, goodbyeTemplate); + + // Template hallo; + + DataModelTemplate halloTemplate = project + .findDataModelTemplate("src/main/resources/templates/detail/items2_v1.html"); + Assert.assertNotNull(halloTemplate); + Assert.assertEquals("src/main/resources/templates/detail/items2_v1.html", halloTemplate.getTemplateUri()); + Assert.assertEquals("org.acme.qute.HelloResource", halloTemplate.getSourceType()); + Assert.assertEquals("hallo", halloTemplate.getSourceField()); + + List parameters3 = halloTemplate.getParameters(); + Assert.assertNotNull(parameters3); + + // hallo.data("age3", 12); + // return hallo.data("name3", name); + + Assert.assertEquals(2, parameters3.size()); + assertParameter("age3", "int", true, halloTemplate); + assertParameter("name3", "java.lang.String", true, halloTemplate); + + } + + private static void checkedTemplateInnerClass(DataModelProject> project) { + // static native TemplateInstance items(List items); + DataModelTemplate items = project + .findDataModelTemplate("src/main/resources/templates/ItemResource/items"); + Assert.assertNotNull(items); + Assert.assertEquals("src/main/resources/templates/ItemResource/items", items.getTemplateUri()); + Assert.assertEquals("org.acme.qute.ItemResource$Templates", items.getSourceType()); + Assert.assertEquals("items", items.getSourceMethod()); + + List parameters = items.getParameters(); + Assert.assertNotNull(parameters); + + Assert.assertEquals(1, parameters.size()); + assertParameter("items", "java.util.List", false, items); + + // static native TemplateInstance map(Map> items, + // Map.Entry entry); + + DataModelTemplate map = project + .findDataModelTemplate("src/main/resources/templates/ItemResource/map"); + Assert.assertNotNull(map); + Assert.assertEquals("src/main/resources/templates/ItemResource/map", map.getTemplateUri()); + Assert.assertEquals("org.acme.qute.ItemResource$Templates", map.getSourceType()); + Assert.assertEquals("map", map.getSourceMethod()); + + parameters = map.getParameters(); + Assert.assertNotNull(parameters); + + Assert.assertEquals(2, parameters.size()); + assertParameter("items", "java.util.Map>", false, + map); + assertParameter("entry", "java.util.Map$Entry", false, map); + } + + private static void checkedTemplate(DataModelProject> project) { + // hello2 + DataModelTemplate hello2Template = project + .findDataModelTemplate("src/main/resources/templates/hello2"); + Assert.assertNotNull(hello2Template); + Assert.assertEquals("src/main/resources/templates/hello2", hello2Template.getTemplateUri()); + Assert.assertEquals("org.acme.qute.Templates", hello2Template.getSourceType()); + Assert.assertEquals("hello2", hello2Template.getSourceMethod()); + + List hello2Parameters = hello2Template.getParameters(); + Assert.assertNotNull(hello2Parameters); + + // public static native TemplateInstance hello2(String name); + + Assert.assertEquals(1, hello2Parameters.size()); + assertParameter("name", "java.lang.String", false, hello2Template); + + // hello3 + DataModelTemplate hello3Template = project + .findDataModelTemplate("src/main/resources/templates/hello3"); + Assert.assertNotNull(hello3Template); + Assert.assertEquals("src/main/resources/templates/hello3", hello3Template.getTemplateUri()); + Assert.assertEquals("org.acme.qute.Templates", hello3Template.getSourceType()); + Assert.assertEquals("hello3", hello3Template.getSourceMethod()); + + List hello3Parameters = hello3Template.getParameters(); + Assert.assertNotNull(hello3Parameters); + + // public static native TemplateInstance hello3(String name); + + Assert.assertEquals(1, hello3Parameters.size()); + assertParameter("name", "java.lang.String", false, hello3Template); + } + + private static void testValueResolversFromTemplateExtension(List resolvers) { + + // Resolver from Java sources + assertValueResolver(null, "discountedPrice(item : org.acme.qute.Item) : java.math.BigDecimal", + "org.acme.qute.ItemResource", resolvers); + // Resolver from Java binaries + // from io.quarkus.qute.runtime.extensions.CollectionTemplateExtensions + assertValueResolver(null, "get(list : java.util.List, index : int) : T", + "io.quarkus.qute.runtime.extensions.CollectionTemplateExtensions", resolvers); + assertValueResolver(null, "getByIndex(list : java.util.List, index : java.lang.String) : T", + "io.quarkus.qute.runtime.extensions.CollectionTemplateExtensions", resolvers); + + // from io.quarkus.qute.runtime.extensions.ConfigTemplateExtensions + assertValueResolver("config", "getConfigProperty(propertyName : java.lang.String) : java.lang.Object", + "io.quarkus.qute.runtime.extensions.ConfigTemplateExtensions", resolvers); + + // from io.quarkus.qute.runtime.extensions.MapTemplateExtensions + assertValueResolver(null, "map(map : java.util.Map, name : java.lang.String) : java.lang.Object", + "io.quarkus.qute.runtime.extensions.MapTemplateExtensions", resolvers); + assertValueResolver(null, "get(map : java.util.Map, key : java.lang.Object) : V", + "io.quarkus.qute.runtime.extensions.MapTemplateExtensions", resolvers); + + // from io.quarkus.qute.runtime.extensions.StringTemplateExtensions + assertValueResolver(null, "mod(number : java.lang.Integer, mod : java.lang.Integer) : java.lang.Integer", + "io.quarkus.qute.runtime.extensions.NumberTemplateExtensions", resolvers); + + // from io.quarkus.qute.runtime.extensions.StringTemplateExtensions + assertValueResolver(null, + "fmtInstance(format : java.lang.String, ignoredPropertyName : java.lang.String, args : java.lang.Object...) : java.lang.String", + "io.quarkus.qute.runtime.extensions.StringTemplateExtensions", resolvers); + assertValueResolver("str", + "fmt(ignoredPropertyName : java.lang.String, format : java.lang.String, args : java.lang.Object...) : java.lang.String", + "io.quarkus.qute.runtime.extensions.StringTemplateExtensions", resolvers); + + // from io.quarkus.qute.runtime.extensions.TimeTemplateExtensions + assertValueResolver(null, + "format(temporal : java.time.temporal.TemporalAccessor, pattern : java.lang.String) : java.lang.String", + "io.quarkus.qute.runtime.extensions.TimeTemplateExtensions", resolvers); + assertValueResolver("time", + "format(dateTimeObject : java.lang.Object, pattern : java.lang.String) : java.lang.String", + "io.quarkus.qute.runtime.extensions.TimeTemplateExtensions", resolvers); + + } + + private void testValueResolversFromInject(List resolvers) { + Assert.assertNotNull(resolvers); + Assert.assertFalse(resolvers.isEmpty()); + + // from org.acme.qute.InjectedData source + + // @Named + // public class InjectedData; + assertValueResolver("inject", "org.acme.qute.InjectedData", "org.acme.qute.InjectedData", // + "injectedData", resolvers); + + // @Named + // private String foo; + assertValueResolver("inject", "foo : java.lang.String", "org.acme.qute.InjectedData", // + "foo", resolvers); + + // @Named("bar") + // private String aBar; + assertValueResolver("inject", "aBar : java.lang.String", "org.acme.qute.InjectedData", // + "bar", resolvers); + + // @Named("user") + // private String getUser() {... + assertValueResolver("inject", "getUser() : java.lang.String", "org.acme.qute.InjectedData", // + "user", resolvers); + + // @Named + // private String getSystemUser() {... + assertValueResolver("inject", "getSystemUser() : java.lang.String", "org.acme.qute.InjectedData", // + "systemUser", resolvers); + + // from io.quarkus.vertx.http.runtime.CurrentRequestProducer + assertValueResolver("inject", + "getCurrentRequest(rc : io.vertx.ext.web.RoutingContext) : io.vertx.core.http.HttpServerRequest", + "io.quarkus.vertx.http.runtime.CurrentRequestProducer", // + "vertxRequest", resolvers); + + // @Named + // public @interface IgnoreInjectAnnotation + assertNotValueResolver("inject", "org.acme.qute.IgnoreInjectAnnotation", "org.acme.qute.IgnoreInjectAnnotation", // + "ignoreInjectAnnotation", resolvers); + + } + + private static void testValueResolversFromTemplateData(List resolvers) { + + // @TemplateData(target = BigDecimal.class) + // @TemplateData(ignoreSuperclasses = true) + // public class ItemWithTemplateData { + + // public static BigDecimal staticMethod(Item item) { + assertValueResolver("org_acme_qute_ItemWithTemplateData", + "staticMethod(item : org.acme.qute.Item) : java.math.BigDecimal", "org.acme.qute.ItemWithTemplateData", + resolvers); + + // public static String count; + assertValueResolver("org_acme_qute_ItemWithTemplateData", "count : java.lang.String", + "org.acme.qute.ItemWithTemplateData", resolvers); + + // @TemplateData + // @TemplateData(namespace = "FOO") + // @TemplateData(namespace = "BAR") + // public class Statuses { + + // public static final String ON = "on"; + assertValueResolver("FOO", "ON : java.lang.String", "org.acme.qute.Statuses", resolvers); + + // public static final String OFF = "off"; + assertValueResolver("FOO", "OFF : java.lang.String", "org.acme.qute.Statuses", resolvers); + + // public static String staticMethod(String state) { + assertValueResolver("FOO", "staticMethod(state : java.lang.String) : java.lang.String", + "org.acme.qute.Statuses", resolvers); + } + + private static void testValueResolversFromTemplateEnum(List resolvers) { + + // @TemplateEnum + // public enum StatusesEnum { + + // ON, + assertValueResolver("StatusesEnum", "ON : org.acme.qute.StatusesEnum", "org.acme.qute.StatusesEnum", resolvers); + // OFF + assertValueResolver("StatusesEnum", "OFF : org.acme.qute.StatusesEnum", "org.acme.qute.StatusesEnum", + resolvers); + } + + private static void testValueResolversFromTemplateGlobal(List resolvers) { + + // @TemplateGlobal + // public class Globals { + + // static int age = 40; + assertValueResolver(null, "age : int", "org.acme.qute.Globals", null, true, resolvers); + + // static String name; + assertValueResolver(null, "name : java.lang.String", "org.acme.qute.Globals", null, true, resolvers); - List resolvers = project.getValueResolvers(); - Assert.assertNotNull(resolvers); - Assert.assertFalse(resolvers.isEmpty()); + // static Color[] myColors() { + // return new Color[] { Color.RED, Color.BLUE }; + // } + assertValueResolver(null, "myColors() : org.acme.qute.Color[]", "org.acme.qute.Globals", null, true, resolvers); + + // @TemplateGlobal(name = "currentUser") + // static String user() { + // return "Mia"; + // } + assertValueResolver(null, "user() : java.lang.String", "org.acme.qute.Globals", "currentUser", true, resolvers); + // } + } + + @Test + public void quarkus3() throws Exception { + loadMavenProject(QuteMavenProjectName.quarkus3); + + QuteDataModelProjectParams params = new QuteDataModelProjectParams(QuteMavenProjectName.quarkus3); + DataModelProject> project = QuteSupportForTemplate.getInstance() + .getDataModelProject(params, getJDTUtils(), new EmptyProgressIndicator()); + Assert.assertNotNull(project); + + // Test value resolvers + List resolvers = project.getValueResolvers(); + + // should pick up the named bean + assertValueResolver("inject", "org.acme.Bean2", "org.acme.Bean2", resolvers); + } + + @Test + public void quteRecord() throws Exception { + loadMavenProject(QuteMavenProjectName.qute_record); - testValueResolversFromTemplateExtension(resolvers); - testValueResolversFromInject(resolvers); - testValueResolversFromTemplateData(resolvers); - testValueResolversFromTemplateEnum(resolvers); - testValueResolversFromTemplateGlobal(resolvers); - } - - private static void testTemplates(DataModelProject> project) { - List> templates = project.getTemplates(); - Assert.assertNotNull(templates); - Assert.assertFalse(templates.isEmpty()); - - templateField(project); - checkedTemplateInnerClass(project); - checkedTemplate(project); - } - - private static void templateField(DataModelProject> project) { - // Template hello; - - DataModelTemplate helloTemplate = project - .findDataModelTemplate("src/main/resources/templates/hello"); - Assert.assertNotNull(helloTemplate); - Assert.assertEquals("src/main/resources/templates/hello", helloTemplate.getTemplateUri()); - Assert.assertEquals("org.acme.qute.HelloResource", helloTemplate.getSourceType()); - Assert.assertEquals("hello", helloTemplate.getSourceField()); - - List parameters = helloTemplate.getParameters(); - Assert.assertNotNull(parameters); - - // hello.data("height", 1.50, "weight", 50L) - // .data("age", 12) - // .data("name", name); - - Assert.assertEquals(4, parameters.size()); - assertParameter("height", "double", true, parameters, 0); - assertParameter("weight", "long", true, parameters, 1); - assertParameter("age", "int", true, parameters, 2); - assertParameter("name", "java.lang.String", true, parameters, 3); - - // Template goodbye; - - DataModelTemplate goodbyeTemplate = project - .findDataModelTemplate("src/main/resources/templates/goodbye"); - Assert.assertNotNull(goodbyeTemplate); - Assert.assertEquals("src/main/resources/templates/goodbye", goodbyeTemplate.getTemplateUri()); - Assert.assertEquals("org.acme.qute.HelloResource", goodbyeTemplate.getSourceType()); - Assert.assertEquals("goodbye", goodbyeTemplate.getSourceField()); - - List parameters2 = goodbyeTemplate.getParameters(); - Assert.assertNotNull(parameters2); - - // goodbye.data("age2", 12); - // return goodbye.data("name2", name); - - Assert.assertEquals(2, parameters2.size()); - assertParameter("age2", "int", true, goodbyeTemplate); - assertParameter("name2", "java.lang.String", true, goodbyeTemplate); - - // Template hallo; - - DataModelTemplate halloTemplate = project - .findDataModelTemplate("src/main/resources/templates/detail/items2_v1.html"); - Assert.assertNotNull(halloTemplate); - Assert.assertEquals("src/main/resources/templates/detail/items2_v1.html", halloTemplate.getTemplateUri()); - Assert.assertEquals("org.acme.qute.HelloResource", halloTemplate.getSourceType()); - Assert.assertEquals("hallo", halloTemplate.getSourceField()); - - List parameters3 = halloTemplate.getParameters(); - Assert.assertNotNull(parameters3); - - // hallo.data("age3", 12); - // return hallo.data("name3", name); - - Assert.assertEquals(2, parameters3.size()); - assertParameter("age3", "int", true, halloTemplate); - assertParameter("name3", "java.lang.String", true, halloTemplate); - - } - - private static void checkedTemplateInnerClass(DataModelProject> project) { - // static native TemplateInstance items(List items); - DataModelTemplate items = project - .findDataModelTemplate("src/main/resources/templates/ItemResource/items"); - Assert.assertNotNull(items); - Assert.assertEquals("src/main/resources/templates/ItemResource/items", items.getTemplateUri()); - Assert.assertEquals("org.acme.qute.ItemResource$Templates", items.getSourceType()); - Assert.assertEquals("items", items.getSourceMethod()); - - List parameters = items.getParameters(); - Assert.assertNotNull(parameters); - - Assert.assertEquals(1, parameters.size()); - assertParameter("items", "java.util.List", false, items); - - // static native TemplateInstance map(Map> items, - // Map.Entry entry); - - DataModelTemplate map = project - .findDataModelTemplate("src/main/resources/templates/ItemResource/map"); - Assert.assertNotNull(map); - Assert.assertEquals("src/main/resources/templates/ItemResource/map", map.getTemplateUri()); - Assert.assertEquals("org.acme.qute.ItemResource$Templates", map.getSourceType()); - Assert.assertEquals("map", map.getSourceMethod()); - - parameters = map.getParameters(); - Assert.assertNotNull(parameters); - - Assert.assertEquals(2, parameters.size()); - assertParameter("items", "java.util.Map>", false, - map); - assertParameter("entry", "java.util.Map$Entry", false,map); - } - - private static void checkedTemplate(DataModelProject> project) { - // hello2 - DataModelTemplate hello2Template = project - .findDataModelTemplate("src/main/resources/templates/hello2"); - Assert.assertNotNull(hello2Template); - Assert.assertEquals("src/main/resources/templates/hello2", hello2Template.getTemplateUri()); - Assert.assertEquals("org.acme.qute.Templates", hello2Template.getSourceType()); - Assert.assertEquals("hello2", hello2Template.getSourceMethod()); - - List hello2Parameters = hello2Template.getParameters(); - Assert.assertNotNull(hello2Parameters); - - // public static native TemplateInstance hello2(String name); - - Assert.assertEquals(1, hello2Parameters.size()); - assertParameter("name", "java.lang.String", false, hello2Template); - - // hello3 - DataModelTemplate hello3Template = project - .findDataModelTemplate("src/main/resources/templates/hello3"); - Assert.assertNotNull(hello3Template); - Assert.assertEquals("src/main/resources/templates/hello3", hello3Template.getTemplateUri()); - Assert.assertEquals("org.acme.qute.Templates", hello3Template.getSourceType()); - Assert.assertEquals("hello3", hello3Template.getSourceMethod()); - - List hello3Parameters = hello3Template.getParameters(); - Assert.assertNotNull(hello3Parameters); - - // public static native TemplateInstance hello3(String name); - - Assert.assertEquals(1, hello3Parameters.size()); - assertParameter("name", "java.lang.String", false, hello3Template); - } - - private static void testValueResolversFromTemplateExtension(List resolvers) { - - // Resolver from Java sources - assertValueResolver(null, "discountedPrice(item : org.acme.qute.Item) : java.math.BigDecimal", - "org.acme.qute.ItemResource", resolvers); - // Resolver from Java binaries - // from io.quarkus.qute.runtime.extensions.CollectionTemplateExtensions - assertValueResolver(null, "get(list : java.util.List, index : int) : T", - "io.quarkus.qute.runtime.extensions.CollectionTemplateExtensions", resolvers); - assertValueResolver(null, "getByIndex(list : java.util.List, index : java.lang.String) : T", - "io.quarkus.qute.runtime.extensions.CollectionTemplateExtensions", resolvers); - - // from io.quarkus.qute.runtime.extensions.ConfigTemplateExtensions - assertValueResolver("config", "getConfigProperty(propertyName : java.lang.String) : java.lang.Object", - "io.quarkus.qute.runtime.extensions.ConfigTemplateExtensions", resolvers); - - // from io.quarkus.qute.runtime.extensions.MapTemplateExtensions - assertValueResolver(null, "map(map : java.util.Map, name : java.lang.String) : java.lang.Object", - "io.quarkus.qute.runtime.extensions.MapTemplateExtensions", resolvers); - assertValueResolver(null, "get(map : java.util.Map, key : java.lang.Object) : V", - "io.quarkus.qute.runtime.extensions.MapTemplateExtensions", resolvers); - - // from io.quarkus.qute.runtime.extensions.StringTemplateExtensions - assertValueResolver(null, "mod(number : java.lang.Integer, mod : java.lang.Integer) : java.lang.Integer", - "io.quarkus.qute.runtime.extensions.NumberTemplateExtensions", resolvers); - - // from io.quarkus.qute.runtime.extensions.StringTemplateExtensions - assertValueResolver(null, - "fmtInstance(format : java.lang.String, ignoredPropertyName : java.lang.String, args : java.lang.Object...) : java.lang.String", - "io.quarkus.qute.runtime.extensions.StringTemplateExtensions", resolvers); - assertValueResolver("str", - "fmt(ignoredPropertyName : java.lang.String, format : java.lang.String, args : java.lang.Object...) : java.lang.String", - "io.quarkus.qute.runtime.extensions.StringTemplateExtensions", resolvers); - - // from io.quarkus.qute.runtime.extensions.TimeTemplateExtensions - assertValueResolver(null, - "format(temporal : java.time.temporal.TemporalAccessor, pattern : java.lang.String) : java.lang.String", - "io.quarkus.qute.runtime.extensions.TimeTemplateExtensions", resolvers); - assertValueResolver("time", - "format(dateTimeObject : java.lang.Object, pattern : java.lang.String) : java.lang.String", - "io.quarkus.qute.runtime.extensions.TimeTemplateExtensions", resolvers); - - } - - private void testValueResolversFromInject(List resolvers) { - Assert.assertNotNull(resolvers); - Assert.assertFalse(resolvers.isEmpty()); - - // from org.acme.qute.InjectedData source - - // @Named - // public class InjectedData; - assertValueResolver("inject", "org.acme.qute.InjectedData", "org.acme.qute.InjectedData", // - "injectedData", resolvers); - - // @Named - // private String foo; - assertValueResolver("inject", "foo : java.lang.String", "org.acme.qute.InjectedData", // - "foo", resolvers); - - // @Named("bar") - // private String aBar; - assertValueResolver("inject", "aBar : java.lang.String", "org.acme.qute.InjectedData", // - "bar", resolvers); - - // @Named("user") - // private String getUser() {... - assertValueResolver("inject", "getUser() : java.lang.String", "org.acme.qute.InjectedData", // - "user", resolvers); - - // @Named - // private String getSystemUser() {... - assertValueResolver("inject", "getSystemUser() : java.lang.String", "org.acme.qute.InjectedData", // - "systemUser", resolvers); - - // from io.quarkus.vertx.http.runtime.CurrentRequestProducer - assertValueResolver("inject", - "getCurrentRequest(rc : io.vertx.ext.web.RoutingContext) : io.vertx.core.http.HttpServerRequest", - "io.quarkus.vertx.http.runtime.CurrentRequestProducer", // - "vertxRequest", resolvers); - - // @Named - // public @interface IgnoreInjectAnnotation - assertNotValueResolver("inject", "org.acme.qute.IgnoreInjectAnnotation", "org.acme.qute.IgnoreInjectAnnotation", // - "ignoreInjectAnnotation", resolvers); - - } - - private static void testValueResolversFromTemplateData(List resolvers) { - - // @TemplateData(target = BigDecimal.class) - // @TemplateData(ignoreSuperclasses = true) - // public class ItemWithTemplateData { - - // public static BigDecimal staticMethod(Item item) { - assertValueResolver("org_acme_qute_ItemWithTemplateData", - "staticMethod(item : org.acme.qute.Item) : java.math.BigDecimal", "org.acme.qute.ItemWithTemplateData", - resolvers); - - // public static String count; - assertValueResolver("org_acme_qute_ItemWithTemplateData", "count : java.lang.String", - "org.acme.qute.ItemWithTemplateData", resolvers); - - // @TemplateData - // @TemplateData(namespace = "FOO") - // @TemplateData(namespace = "BAR") - // public class Statuses { - - // public static final String ON = "on"; - assertValueResolver("FOO", "ON : java.lang.String", "org.acme.qute.Statuses", resolvers); - - // public static final String OFF = "off"; - assertValueResolver("FOO", "OFF : java.lang.String", "org.acme.qute.Statuses", resolvers); - - // public static String staticMethod(String state) { - assertValueResolver("FOO", "staticMethod(state : java.lang.String) : java.lang.String", - "org.acme.qute.Statuses", resolvers); - } - - private static void testValueResolversFromTemplateEnum(List resolvers) { - - // @TemplateEnum - // public enum StatusesEnum { - - // ON, - assertValueResolver("StatusesEnum", "ON : org.acme.qute.StatusesEnum", "org.acme.qute.StatusesEnum", resolvers); - // OFF - assertValueResolver("StatusesEnum", "OFF : org.acme.qute.StatusesEnum", "org.acme.qute.StatusesEnum", - resolvers); - } - - private static void testValueResolversFromTemplateGlobal(List resolvers) { - - // @TemplateGlobal - // public class Globals { - - // static int age = 40; - assertValueResolver(null, "age : int", "org.acme.qute.Globals", null, true, resolvers); - - // static String name; - assertValueResolver(null, "name : java.lang.String", "org.acme.qute.Globals", null, true, resolvers); + QuteDataModelProjectParams params = new QuteDataModelProjectParams(QuteMavenProjectName.qute_record); + DataModelProject> project = QuteSupportForTemplate.getInstance() + .getDataModelProject(params, getJDTUtils(), new EmptyProgressIndicator()); + Assert.assertNotNull(project); - // static Color[] myColors() { - // return new Color[] { Color.RED, Color.BLUE }; - // } - assertValueResolver(null, "myColors() : org.acme.qute.Color[]", "org.acme.qute.Globals", null, true, resolvers); - - // @TemplateGlobal(name = "currentUser") - // static String user() { - // return "Mia"; - // } - assertValueResolver(null, "user() : java.lang.String", "org.acme.qute.Globals", "currentUser", true, resolvers); - // } - } - - @Test - public void quarkus3() throws Exception { - loadMavenProject(QuteMavenProjectName.quarkus3); - - QuteDataModelProjectParams params = new QuteDataModelProjectParams(QuteMavenProjectName.quarkus3); - DataModelProject> project = QuteSupportForTemplate.getInstance() - .getDataModelProject(params, getJDTUtils(), new EmptyProgressIndicator()); - Assert.assertNotNull(project); + // public class HelloResource { + // record Hello(String name) implements TemplateInstance {} - // Test value resolvers - List resolvers = project.getValueResolvers(); - - // should pick up the named bean - assertValueResolver("inject", "org.acme.Bean2", "org.acme.Bean2", resolvers); - } + // Hello + DataModelTemplate helloTemplate = project + .findDataModelTemplate("src/main/resources/templates/Hello"); + Assert.assertNotNull(helloTemplate); + Assert.assertEquals("src/main/resources/templates/Hello", helloTemplate.getTemplateUri()); + Assert.assertEquals("org.acme.sample.HelloResource$Hello", helloTemplate.getSourceType()); + Assert.assertNull(helloTemplate.getSourceField()); + Assert.assertNull(helloTemplate.getSourceMethod()); + + List helloParameters = helloTemplate.getParameters(); + Assert.assertNotNull(helloParameters); + + Assert.assertEquals(2, helloParameters.size()); + + // record Hello(String name) implements TemplateInstance {} + assertParameter("name", "java.lang.String", false, helloParameters, 0); + + // public TemplateInstance get(@QueryParam("name") String name) { + // return new Hello(name).data("foo", 100); + assertParameter("foo", "int", true, helloParameters, 1); + } }