diff --git a/.vscode/settings.json b/.vscode/settings.json index e0f15db..9bd06c2 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,4 @@ { - "java.configuration.updateBuildConfiguration": "automatic" + "java.configuration.updateBuildConfiguration": "automatic", + "java.debug.settings.onBuildFailureProceed": true } \ No newline at end of file diff --git a/java-analyzer-bundle.core/.classpath b/java-analyzer-bundle.core/.classpath index a1120f3..e31d837 100644 --- a/java-analyzer-bundle.core/.classpath +++ b/java-analyzer-bundle.core/.classpath @@ -1,6 +1,7 @@ - + + diff --git a/java-analyzer-bundle.core/src/main/java/io/konveyor/tackle/core/internal/SampleDelegateCommandHandler.java b/java-analyzer-bundle.core/src/main/java/io/konveyor/tackle/core/internal/SampleDelegateCommandHandler.java index 7681de9..39cda7a 100644 --- a/java-analyzer-bundle.core/src/main/java/io/konveyor/tackle/core/internal/SampleDelegateCommandHandler.java +++ b/java-analyzer-bundle.core/src/main/java/io/konveyor/tackle/core/internal/SampleDelegateCommandHandler.java @@ -1,12 +1,14 @@ package io.konveyor.tackle.core.internal; import static java.lang.String.format; +import static org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin.debugTrace; import static org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin.logInfo; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import java.util.stream.Collectors; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; @@ -150,7 +152,7 @@ private static SearchPattern mapLocationToSearchPatternLocation(int location, St * "import": 8, * "variable_declaration": 9, * "type": 10, - * "package": 11, + * "package": 1 * "field": 12, * "method_declaration": 13, * "class_declaration": 14, @@ -199,7 +201,7 @@ private static SearchPattern getPatternSingleQuery(int location, String query) t throw new Exception("unable to create search pattern"); } - private static List search(String projectName, ArrayList includedPaths, String query, AnnotationQuery annotationQuery, int location, String analysisMode, + protected static List search(String projectName, ArrayList includedPaths, String query, AnnotationQuery annotationQuery, int location, String analysisMode, boolean includeOpenSourceLibraries, String mavenLocalRepoPath, String mavenIndexPath, IProgressMonitor monitor) throws Exception { IJavaProject[] targetProjects; IJavaProject project = ProjectUtils.getJavaProject(projectName); @@ -209,7 +211,7 @@ private static List search(String projectName, ArrayList search(String projectName, ArrayList + String.format("\n-------------------------\nSymbol name: %s\nkind: %s\nLocation: %s",si.getName(), si.getKind(), si.getLocation()) + ) + .collect(Collectors.joining()); + debugTrace("KONVEYOR_DEBUG: " + result); return symbols; diff --git a/java-analyzer-bundle.test/.classpath b/java-analyzer-bundle.test/.classpath index ef6fc42..9d92a71 100644 --- a/java-analyzer-bundle.test/.classpath +++ b/java-analyzer-bundle.test/.classpath @@ -1,6 +1,7 @@ - + + diff --git a/java-analyzer-bundle.test/META-INF/MANIFEST.MF b/java-analyzer-bundle.test/META-INF/MANIFEST.MF index 6b7d331..39ec46d 100644 --- a/java-analyzer-bundle.test/META-INF/MANIFEST.MF +++ b/java-analyzer-bundle.test/META-INF/MANIFEST.MF @@ -6,6 +6,8 @@ Bundle-Version: 1.0.0.qualifier Fragment-Host: java-analyzer-bundle.core;bundle-version="1.0.0" Bundle-RequiredExecutionEnvironment: JavaSE-17 Require-Bundle: org.eclipse.jdt.junit4.runtime;bundle-version="1.1.0", - org.junit;bundle-version="4.12", - org.eclipse.m2e.core - + org.apache.commons.io, + org.apache.commons.lang3, + org.junit;bundle-version="4.12", + org.eclipse.m2e.core, + org.eclipse.buildship.core \ No newline at end of file diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/.project b/java-analyzer-bundle.test/projects/maven/springboot-todo/.project new file mode 100644 index 0000000..04e1093 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/.project @@ -0,0 +1,23 @@ + + + springboot-todo + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/README.md b/java-analyzer-bundle.test/projects/maven/springboot-todo/README.md new file mode 100644 index 0000000..5b90e29 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/README.md @@ -0,0 +1,118 @@ +# Awesome To-Do App + +## Overview + +**Awesome To-Do App** is a versatile task management application tailored to assist users in organizing tasks, managing deadlines, and prioritizing activities. The app offers an intuitive user interface complete with a spectrum of features including task creation, deletion, pagination, and advanced error handling. + +In this README, you'll find a comprehensive guide that details your project, enumerates its key functionalities, lists the technologies employed, provides installation instructions, and articulates usage instructions. + +![Tasks Empty](https://github.com/adampeer/spring-boot-todo-app/assets/90769663/aed896df-0c77-4fe2-845a-e12460ea5b2b) + +![Tasks Full](https://github.com/adampeer/spring-boot-todo-app/assets/90769663/3bac6e08-6e5a-4c2c-a69a-520c5a8ff4ec) + +## Features + +### Task Management + +- Create and manage tasks with essential details such as titles, descriptions, and due dates. +- Tasks are elegantly presented in card format, enhancing visibility and comprehension. +- Effortlessly delete tasks with permanent removal from the application. + +### Pagination + +- Enhance user experience by paginating tasks, ensuring a clutter-free view. +- Navigate seamlessly through the task list with "Previous" and "Next" buttons for effortless organization. + +### Error Handling + +- Robust error handling, encompassing gracefully displayed custom error pages and user-friendly messages. +- Guard against requests that seek pages beyond the total available count, offering a polished and secure user experience. + +### Advanced Features + +- Responsive design adapting to diverse devices, guaranteeing a harmonious experience on any platform. +- Intuitive pop-up modals for confirming task deletion, enriching user interaction. + +## Technologies Used + +**Frontend:** + +- HTML +- Thymeleaf (for server-side rendering) +- JavaScript +- jQuery +- Bootstrap (for styling and modals) + +**Backend:** + +- Spring Boot (Java-based framework) +- Spring MVC +- Spring Data JPA (for database access) +- MySQL (as the database) + +## Installation + +1. **Clone the Repository:** + + ```bash + git clone https://github.com/adampeer/spring-boot-todo-app.git + cd awesome-todo-app + ``` + +2. **Database Configuration:** + + - Install MySQL and create a database. + - Update the `application.properties` file with your database jdtLSConfiguration such as username, password, database name and port number. + +3. **Build and Run the Application:** + + ```bash + ./mvnw clean package + java -jar target/awesome-todo-app-0.1.jar + ``` + +4. **Access the Application:** + + Open a web browser and go to `http://localhost:8080` or whatever port you've set in application.properties file. + +## Usage + +1. **Create a Task:** + + - Fill out the task creation form, providing a title, description, and due date. + - Click the "Create Task" button. + +2. **Pagination:** + + - Use the "Previous" and "Next" buttons to navigate through your task list. + - Each page typically displays 6 tasks. + +3. **Delete a Task:** + + - Each task card includes a "Delete" button. + - Click the "Delete" button to trigger a confirmation modal. + - Confirm the task deletion by clicking "Yes" in the modal. + +4. **Error Handling:** + + - Error pages and messages are displayed for various error scenarios. + - Friendly error messages are shown to users. + +5. **Advanced Features:** + + - Responsive design ensures a seamless experience on different devices. + - Confirmation modal for task deletion adds a layer of user interaction. + +## Feedback and Support + +We welcome your feedback and suggestions. If you encounter any issues or have ideas for improvements, please open an issue on our GitHub repository. + +## License + +This project is licensed under the MIT License. Feel free to use it, modify it, and share it as you see fit. + +## Author + +- [Adam Peer](https://github.com/adampeer) + +--- diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/mvnw b/java-analyzer-bundle.test/projects/maven/springboot-todo/mvnw new file mode 100644 index 0000000..66df285 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# 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/java-analyzer-bundle.test/projects/maven/springboot-todo/mvnw.cmd b/java-analyzer-bundle.test/projects/maven/springboot-todo/mvnw.cmd new file mode 100644 index 0000000..95ba6f5 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/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 https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM 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/java-analyzer-bundle.test/projects/maven/springboot-todo/pom.xml b/java-analyzer-bundle.test/projects/maven/springboot-todo/pom.xml new file mode 100644 index 0000000..44ed398 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/pom.xml @@ -0,0 +1,106 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.3 + + + com.todo + app + 0.0.1-SNAPSHOT + app + Demo project for Spring Boot + + 21 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + com.mysql + mysql-connector-j + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + io.jsonwebtoken + jjwt + 0.9.1 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/README.md b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/README.md new file mode 100644 index 0000000..5b90e29 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/README.md @@ -0,0 +1,118 @@ +# Awesome To-Do App + +## Overview + +**Awesome To-Do App** is a versatile task management application tailored to assist users in organizing tasks, managing deadlines, and prioritizing activities. The app offers an intuitive user interface complete with a spectrum of features including task creation, deletion, pagination, and advanced error handling. + +In this README, you'll find a comprehensive guide that details your project, enumerates its key functionalities, lists the technologies employed, provides installation instructions, and articulates usage instructions. + +![Tasks Empty](https://github.com/adampeer/spring-boot-todo-app/assets/90769663/aed896df-0c77-4fe2-845a-e12460ea5b2b) + +![Tasks Full](https://github.com/adampeer/spring-boot-todo-app/assets/90769663/3bac6e08-6e5a-4c2c-a69a-520c5a8ff4ec) + +## Features + +### Task Management + +- Create and manage tasks with essential details such as titles, descriptions, and due dates. +- Tasks are elegantly presented in card format, enhancing visibility and comprehension. +- Effortlessly delete tasks with permanent removal from the application. + +### Pagination + +- Enhance user experience by paginating tasks, ensuring a clutter-free view. +- Navigate seamlessly through the task list with "Previous" and "Next" buttons for effortless organization. + +### Error Handling + +- Robust error handling, encompassing gracefully displayed custom error pages and user-friendly messages. +- Guard against requests that seek pages beyond the total available count, offering a polished and secure user experience. + +### Advanced Features + +- Responsive design adapting to diverse devices, guaranteeing a harmonious experience on any platform. +- Intuitive pop-up modals for confirming task deletion, enriching user interaction. + +## Technologies Used + +**Frontend:** + +- HTML +- Thymeleaf (for server-side rendering) +- JavaScript +- jQuery +- Bootstrap (for styling and modals) + +**Backend:** + +- Spring Boot (Java-based framework) +- Spring MVC +- Spring Data JPA (for database access) +- MySQL (as the database) + +## Installation + +1. **Clone the Repository:** + + ```bash + git clone https://github.com/adampeer/spring-boot-todo-app.git + cd awesome-todo-app + ``` + +2. **Database Configuration:** + + - Install MySQL and create a database. + - Update the `application.properties` file with your database jdtLSConfiguration such as username, password, database name and port number. + +3. **Build and Run the Application:** + + ```bash + ./mvnw clean package + java -jar target/awesome-todo-app-0.1.jar + ``` + +4. **Access the Application:** + + Open a web browser and go to `http://localhost:8080` or whatever port you've set in application.properties file. + +## Usage + +1. **Create a Task:** + + - Fill out the task creation form, providing a title, description, and due date. + - Click the "Create Task" button. + +2. **Pagination:** + + - Use the "Previous" and "Next" buttons to navigate through your task list. + - Each page typically displays 6 tasks. + +3. **Delete a Task:** + + - Each task card includes a "Delete" button. + - Click the "Delete" button to trigger a confirmation modal. + - Confirm the task deletion by clicking "Yes" in the modal. + +4. **Error Handling:** + + - Error pages and messages are displayed for various error scenarios. + - Friendly error messages are shown to users. + +5. **Advanced Features:** + + - Responsive design ensures a seamless experience on different devices. + - Confirmation modal for task deletion adds a layer of user interaction. + +## Feedback and Support + +We welcome your feedback and suggestions. If you encounter any issues or have ideas for improvements, please open an issue on our GitHub repository. + +## License + +This project is licensed under the MIT License. Feel free to use it, modify it, and share it as you see fit. + +## Author + +- [Adam Peer](https://github.com/adampeer) + +--- diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/AppApplication.java b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/AppApplication.java new file mode 100644 index 0000000..f681c49 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/AppApplication.java @@ -0,0 +1,13 @@ +package com.todo.app; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AppApplication { + + public static void main(String[] args) { + SpringApplication.run(AppApplication.class, args); + } + +} \ No newline at end of file diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/controller/TaskController.java b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/controller/TaskController.java new file mode 100644 index 0000000..376294a --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/controller/TaskController.java @@ -0,0 +1,91 @@ +package com.todo.app.controller; + +import java.util.List; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.ResponseBody; + +import org.springframework.data.domain.Page; + +import com.todo.app.entity.Task; +import com.todo.app.service.TaskService; + +@Controller +public class TaskController { + + @Autowired + private TaskService taskService; + + @GetMapping("/error") + public String viewErrorPage() { + return "error"; + } + + @GetMapping("/") + public String viewIndexPage() { + return "redirect:/home"; + } + + @GetMapping("/home") + public String viewHome(Model model) { + model.addAttribute("task", new Task()); + return findPaginated(1, model); + } + + @GetMapping("/home/{pageNo}") + public String findPaginated(@PathVariable(value = "pageNo") int pageNo, Model model) { + + model.addAttribute("task", new Task()); + + int pageSize = 6; + + Page page = taskService.getAllTasksPage(pageNo, pageSize); + List tasks = page.getContent(); + + if (tasks.isEmpty()) { + model.addAttribute("noTasks", true); + if (pageNo > 1) { + return "redirect:/home/" + (pageNo - 1); + } + } else { + model.addAttribute("currentPage", pageNo); + model.addAttribute("totalPages", page.getTotalPages()); + model.addAttribute("totalItems", page.getTotalElements()); + model.addAttribute("tasks", tasks); + + if (pageNo > page.getTotalPages()) { + return "redirect:/home/" + page.getTotalPages(); + } + if (pageNo < 1) { + return "redirect:/home"; + } + } + + return "home"; + } + + // Create task using AJAX request + @PostMapping("/home") + @ResponseBody + public ResponseEntity> createTask(@RequestBody Task task) { + taskService.addTask(task); + List tasks = taskService.getAllTasks(); + return ResponseEntity.ok(tasks); + } + + // Delete task using AJAX request + @DeleteMapping("/home/{taskId}") + public ResponseEntity deleteTask(@PathVariable Long taskId) { + taskService.deleteTask(taskId); + return ResponseEntity.ok().build(); + } + +} \ No newline at end of file diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/entity/Task.java b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/entity/Task.java new file mode 100644 index 0000000..ab9c0a8 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/entity/Task.java @@ -0,0 +1,64 @@ +package com.todo.app.entity; + +import jakarta.persistence.*; +import org.springframework.format.annotation.DateTimeFormat; + +import java.time.LocalDate; + +@Entity +@Table(name = "tasks") +public class Task { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private Long id; + + private String title; + + private String description; + + @DateTimeFormat(pattern = "yyyy-MM-dd") + private LocalDate dueDate; + + public Task() { + } + + public Task(Long id, String title, String description, LocalDate dueDate) { + this.id = id; + this.title = title; + this.description = description; + this.dueDate = dueDate; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getTitle() { + return title; + } + + public String getDescription() { + return description; + } + + public LocalDate getDueDate() { + return dueDate; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setDescription(String description) { + this.description = description; + } + + public void setDueDate(LocalDate dueDate) { + this.dueDate = dueDate; + } +} \ No newline at end of file diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/repository/TaskRepository.java b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/repository/TaskRepository.java new file mode 100644 index 0000000..be7933a --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/repository/TaskRepository.java @@ -0,0 +1,8 @@ +package com.todo.app.repository; + +import com.todo.app.entity.Task; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface TaskRepository extends JpaRepository { + +} \ No newline at end of file diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/service/TaskService.java b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/service/TaskService.java new file mode 100644 index 0000000..267ad55 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/service/TaskService.java @@ -0,0 +1,28 @@ +package com.todo.app.service; + +import com.todo.app.entity.Task; +import org.springframework.data.domain.Page; + +import java.util.List; + +public interface TaskService { + + // Add task + public void addTask(Task task); + + // Delete task + public void deleteTaskById(Long id); + + // Update task by id + public void updateTaskById(Long id, Task task); + + // Get all tasks + public List getAllTasks(); + + // Delete task by id + public void deleteTask(Long taskId); + + // Get task by page + Page getAllTasksPage(int pageNo, int pageSize); + +} \ No newline at end of file diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/service/TaskServiceImpl.java b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/service/TaskServiceImpl.java new file mode 100644 index 0000000..d840593 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/java/com/todo/app/service/TaskServiceImpl.java @@ -0,0 +1,50 @@ +package com.todo.app.service; + +import com.todo.app.entity.Task; +import com.todo.app.repository.TaskRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class TaskServiceImpl implements TaskService { + + @Autowired + private TaskRepository taskRepository; + + @Override + public void addTask(Task task) { + taskRepository.save(task); + } + + @Override + public void deleteTaskById(Long id) { + taskRepository.deleteById(id); + } + + @Override + public void updateTaskById(Long id, Task task) { + taskRepository.save(task); + } + + @Override + public List getAllTasks() { + return taskRepository.findAll(); + } + + @Override + public void deleteTask(Long taskId) { + taskRepository.deleteById(taskId); + } + + @Override + public Page getAllTasksPage(int pageNo, int pageSize) { + Pageable pageable = PageRequest.of(pageNo - 1, pageSize); + return taskRepository.findAll(pageable); + } + +} diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/application.properties b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/application.properties new file mode 100644 index 0000000..62d369e --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/application.properties @@ -0,0 +1,13 @@ +# Change port to 8081 +server.port=8081 + +# MySQL datasource jdtLSConfiguration +spring.datasource.url=jdbc:mysql://127.0.0.1:3306/todo +spring.datasource.username=root +spring.datasource.password=root +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver + +# Hibernate jdtLSConfiguration +spring.jpa.hibernate.ddl-auto=update +spring.jpa.show-sql=true +spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect \ No newline at end of file diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/static/favicon.ico b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/static/favicon.ico new file mode 100644 index 0000000..8b5e476 Binary files /dev/null and b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/static/favicon.ico differ diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/static/js/home.js b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/static/js/home.js new file mode 100644 index 0000000..efaf661 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/static/js/home.js @@ -0,0 +1,50 @@ +$(document).ready(function () { + // Handle form submission + $("#taskForm").submit(function (event) { + event.preventDefault(); // Prevent the default form submission + + // Get form data + let title = $("#title").val(); + let description = $("#description").val(); + let dueDate = $("#dueDate").val(); + + let csrfToken = $("meta[name='_csrf']").attr("content"); + let csrfHeader = $("meta[name='_csrf_header']").attr("content"); + + // Send a POST request to your server + $.ajax({ + type: "POST", + url: "/home", // Replace with your server endpoint + contentType: "application/json; charset=utf-8", + data: JSON.stringify({ 'title': title, 'description': description, 'dueDate': dueDate }), + headers: { + [csrfHeader]: csrfToken + }, + success: function (response) { + $.ajax({ + type: "GET", + url: window.location.href, + contentType: "text/html; charset=UTF-8", + headers: { + [csrfHeader]: csrfToken + }, + success: function (response) { + confirm("Task created successfully!"); + $("body").html(response); + }, + error: function (error) { + console.error("Error getting tasks: " + error.responseText); + } + }) + }, + error: function (error) { + console.error("Error creating task: " + error.responseText); + } + }); + + // Clear form fields + $("#title").val(""); + $("#description").val(""); + $("#dueDate").val(""); + }); +}); \ No newline at end of file diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/templates/error.html b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/templates/error.html new file mode 100644 index 0000000..f070522 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/templates/error.html @@ -0,0 +1,62 @@ + + + + + ToDo | Error Page + + + + + + + + + + + + +
+
+

Oops! It seems there's a bug 🐞

+

We're sorry for this. Let's go back to home.

+

Go to Home

+
+
+ + + \ No newline at end of file diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/templates/home.html b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/templates/home.html new file mode 100644 index 0000000..dd030fb --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/main/resources/templates/home.html @@ -0,0 +1,145 @@ + + + + + + ToDo App + + + + + + + + + + +
+ + +

Awesome To-Do App

+
+ +
+

Create a Task

+
+
+ +
+
+ +
+
+ +
+ +
+
+
+ + +
+

Task List

+
+ +
+
+
+
+
+

+

+ Due Date: +

+ +
+
+
+
+
+
+
+ No tasks created yet. You can create a task using the form above. +
+
+
+
+ +
+
+ + + + + \ No newline at end of file diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/mvnw b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/mvnw new file mode 100644 index 0000000..66df285 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/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 +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# 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/java-analyzer-bundle.test/projects/maven/springboot-todo/src/mvnw.cmd b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/mvnw.cmd new file mode 100644 index 0000000..95ba6f5 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/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 https://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM 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/java-analyzer-bundle.test/projects/maven/springboot-todo/src/pom.xml b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/pom.xml new file mode 100644 index 0000000..2fa8bf0 --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/pom.xml @@ -0,0 +1,106 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.3 + + + com.todo + app + 0.0.1-SNAPSHOT + app + Demo project for Spring Boot + + 21 + + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-thymeleaf + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + com.mysql + mysql-connector-j + runtime + + + org.springframework.boot + spring-boot-starter-test + test + + + + + io.jsonwebtoken + jjwt + 0.9.1 + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + + spring-milestones + Spring Milestones + https://repo.spring.io/milestone + + false + + + + spring-snapshots + Spring Snapshots + https://repo.spring.io/snapshot + + false + + + + + diff --git a/java-analyzer-bundle.test/projects/maven/springboot-todo/src/test/java/com/todo/app/AppApplicationTests.java b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/test/java/com/todo/app/AppApplicationTests.java new file mode 100644 index 0000000..1ead13d --- /dev/null +++ b/java-analyzer-bundle.test/projects/maven/springboot-todo/src/test/java/com/todo/app/AppApplicationTests.java @@ -0,0 +1,13 @@ +package com.todo.app; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class AppApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/CommandHandlerTest.java b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/CommandHandlerTest.java new file mode 100644 index 0000000..9c449e9 --- /dev/null +++ b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/CommandHandlerTest.java @@ -0,0 +1,37 @@ +package io.konveyor.tackle.core.internal; + +import static org.junit.Assert.assertEquals; + +import java.util.List; +import java.util.ArrayList; +import java.util.Map; +import java.util.Collections; + +import org.eclipse.core.runtime.NullProgressMonitor; +import org.junit.Test; + +/** +* Sample integration test. In Eclipse, right-click > Run As > JUnit-Plugin.
+* In Maven CLI, run "mvn integration-test". +*/ +public class CommandHandlerTest extends ProjectUtilsTest { + + @Test + public void sampleCmdShouldReturnHelloWorld() throws Exception { + assertEquals("Hello World", cmdHandler.executeCommand(SampleDelegateCommandHandler.COMMAND_ID, null, null)); + } + + @Test + public void ruleEntryCmdShouldReturnEmptyListAsProjectIsNull() throws Exception { + List params = new ArrayList(); + Map param = Map.of( + "project", "project", + "query", "customresourcedefinition", + "location","0", + "analysisMode", ANALYSIS_MODE_SOURCE_ONLY); + params.add(param); + + var result = cmdHandler.executeCommand(SampleDelegateCommandHandler.RULE_ENTRY_COMMAND_ID, params, new NullProgressMonitor()); + assertEquals(Collections.emptyList(), result); + } +} \ No newline at end of file diff --git a/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/JavaAnnotationTest.java b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/JavaAnnotationTest.java new file mode 100644 index 0000000..0c5a81e --- /dev/null +++ b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/JavaAnnotationTest.java @@ -0,0 +1,92 @@ +package io.konveyor.tackle.core.internal; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.lsp4j.Location; +import org.eclipse.lsp4j.Position; +import org.eclipse.lsp4j.Range; +import org.eclipse.lsp4j.SymbolInformation; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +public class JavaAnnotationTest extends ProjectUtilsTest { + + private static boolean existingDebugFlag = false; + + @BeforeClass + public static void setupOnce() throws Exception { + existingDebugFlag = Boolean.getBoolean("jdt.ls.debug"); + System.setProperty("jdt.ls.debug", "true"); + //System.out.println("########## jdt.ls.debug: " + System.getProperty("jdt.ls.debug")); + } + + @AfterClass + public static void cleanUpOnce() throws Exception { + System.setProperty("jdt.ls.debug", Boolean.toString(existingDebugFlag)); + } + + @Test + public void shouldMatchSpringResponseBodyAnnotationTest() throws Exception { + IJavaProject javaProject = loadMavenProject(MavenProjectName.springboot_todo_project); + System.out.println("=== Java Project name : " + javaProject.getProject().getName()); + System.out.println("=== Env jdt log variable: " + System.getProperty("jdt.ls.debug")); + + // String aQuery = "org.springframework.web.bind.annotation.ResponseBody"; // + // !! We got 2 SymbolInformation: ResponseBody and PostMapping - + // https://github.com/konveyor/java-analyzer-bundle/issues/175 + + String aQuery = "ResponseBody"; + + // Query to search an annotation + Map mapArgs = Map.of( + "project", javaProject.getProject().getName(), + "location", LOCATION_TYPE_ANNOTATION, + "query", aQuery, + "analysisMode", ANALYSIS_MODE_SOURCE_ONLY); + + RuleEntryParams params = new RuleEntryParams(RULE_ENTRY_COMMAND_ID, List.of(mapArgs)); + Assert.assertNotNull(params); + + SampleDelegateCommandHandler sdch = new SampleDelegateCommandHandler(); + List results = sdch.search(params.getProjectName(), + params.getIncludedPaths(), params.getQuery(), + params.getAnnotationQuery(), params.getLocation(), params.getAnalysisMode(), + params.getIncludeOpenSourceLibraries(), params.getMavenLocalRepoPath(), + params.getMavenIndexPath(), new NullProgressMonitor()); + Assert.assertNotNull(results); + + // Search within the results the symbol matching thge annotation to search + String targetAnnotation = "ResponseBody"; + Optional foundSymbol = results.stream() + .filter(symbol -> symbol.getName().equals(targetAnnotation)) + .findFirst(); + + Assert.assertNotNull(foundSymbol.get()); + + Location loc = foundSymbol.get().getLocation(); + Assert.assertNotNull(loc); + + // The annotation org.springframework.web.bind.annotation.ResponseBody is + // included + // within the file com.todo.app.controller.TaskController.java + Assert.assertEquals(true, loc.getUri().contains("TaskController.java")); + + // Verify the location where the annotation has been declared using the Range + Range range = loc.getRange(); + Assert.assertNotNull(range); + + Position posStart = range.getStart(); + Position posEnd = range.getEnd(); + Assert.assertEquals(76, posStart.getLine()); + Assert.assertEquals(5, posStart.getCharacter()); + + Assert.assertEquals(76, posEnd.getLine()); + Assert.assertEquals(17, posEnd.getCharacter()); + } +} \ No newline at end of file diff --git a/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/JavaUtils.java b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/JavaUtils.java new file mode 100644 index 0000000..df6a748 --- /dev/null +++ b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/JavaUtils.java @@ -0,0 +1,133 @@ +package io.konveyor.tackle.core.internal; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringUtils; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectDescription; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.OperationCanceledException; +import org.eclipse.core.runtime.Path; +import org.eclipse.jdt.core.IClasspathEntry; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; + +/** + * Java utilities. + * + * @author Angelo ZERR + * + */ +public class JavaUtils { + + private JavaUtils() { + + } + + /** + * Create a Java project with the given JAR. + * + * @param projectName the Java project name + * @param jars the JARS paths list + * @return the Java project + * @throws Exception + */ + public static IJavaProject createJavaProject(String projectName, String[] jars) throws Exception { + IProject testProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); + createJavaProject(testProject, new Path(getWorkingProjectDirectory().getAbsolutePath()).append(projectName), + "src", "bin", jars, new NullProgressMonitor()); + waitForBackgroundJobs(); + return JavaCore.create(testProject); + } + + private static void waitForBackgroundJobs() { + + } + + private static IProject createJavaProject(IProject project, IPath projectLocation, String src, String bin, + String[] jars, IProgressMonitor monitor) throws CoreException, OperationCanceledException { + if (project.exists()) { + return project; + } + IProjectDescription description = ResourcesPlugin.getWorkspace().newProjectDescription(project.getName()); + if (projectLocation != null) { + description.setLocation(projectLocation); + } + project.create(description, monitor); + project.open(monitor); + + // Turn into Java project + description = project.getDescription(); + description.setNatureIds(new String[] { JavaCore.NATURE_ID }); + project.setDescription(description, monitor); + + IJavaProject javaProject = JavaCore.create(project); + // configureJVMSettings(javaProject); + + // Add build output folder + if (StringUtils.isNotBlank(bin)) { + IFolder output = project.getFolder(bin); + if (!output.exists()) { + output.create(true, true, monitor); + } + javaProject.setOutputLocation(output.getFullPath(), monitor); + } + + List classpaths = new ArrayList<>(); + // Add source folder + if (StringUtils.isNotBlank(src)) { + IFolder source = project.getFolder(src); + if (!source.exists()) { + source.create(true, true, monitor); + } + IClasspathEntry srcClasspath = JavaCore.newSourceEntry(source.getFullPath()); + classpaths.add(srcClasspath); + } + + // Add library + if (jars != null) { + for (String jar : jars) { + IClasspathEntry libClasspath = JavaCore.newLibraryEntry(new Path(jar), null, null); + classpaths.add(libClasspath); + } + } + + // Find default JVM + // IClasspathEntry jre = JavaRuntime.getDefaultJREContainerEntry(); + // classpaths.add(jre); + + // Add JVM to project class path + javaProject.setRawClasspath(classpaths.toArray(new IClasspathEntry[0]), monitor); + + return project; + + } + + public static File getWorkingProjectDirectory() throws IOException { + File dir = new File("target", "workingProjects"); + FileUtils.forceMkdir(dir); + return dir; + } + + /** + * Returns the JAR path. + * + * @param jar the JAR name. + * + * @return the JAR path. + */ + public static String getJarPath(String jar) { + java.nio.file.Path jarPath = Paths.get("jars", jar); + return jarPath.toAbsolutePath().toString(); + } +} \ No newline at end of file diff --git a/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/JobHelpers.java b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/JobHelpers.java new file mode 100644 index 0000000..2322b62 --- /dev/null +++ b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/JobHelpers.java @@ -0,0 +1,216 @@ +package io.konveyor.tackle.core.internal; + +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; + +import org.eclipse.core.resources.IWorkspace; +import org.eclipse.core.resources.IWorkspaceRunnable; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.resources.WorkspaceJob; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.IStatus; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.jobs.IJobManager; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; +import org.eclipse.jdt.ls.core.internal.handlers.InitHandler; +import org.eclipse.m2e.core.internal.embedder.MavenExecutionContext; +import org.eclipse.m2e.core.internal.jobs.IBackgroundProcessingQueue; + +/** + * Copied from m2e's org.eclipse.m2e.tests.common/src/org/eclipse/m2e/tests/common/JobHelpers.java + * + */ +@SuppressWarnings("restriction") +public final class JobHelpers { + + private JobHelpers() { + //no instantiation + } + + private static final int POLLING_DELAY = 10; + public static final int MAX_TIME_MILLIS = 300000; + + public static void waitForJobsToComplete() { + try { + waitForJobsToComplete(new NullProgressMonitor()); + } catch(Exception ex) { + throw new IllegalStateException(ex); + } + } + + public static void waitForJobsToComplete(IProgressMonitor monitor) throws InterruptedException, CoreException { + waitForBuildJobs(); + + /* + * First, make sure refresh job gets all resource change events + * + * Resource change events are delivered after WorkspaceJob#runInWorkspace returns + * and during IWorkspace#run. Each change notification is delivered by + * only one thread/job, so we make sure no other workspaceJob is running then + * call IWorkspace#run from this thread. + * + * Unfortunately, this does not catch other jobs and threads that call IWorkspace#run + * so we have to hard-code workarounds + * + * See http://www.eclipse.org/articles/Article-Resource-deltas/resource-deltas.html + */ + IWorkspace workspace = ResourcesPlugin.getWorkspace(); + IJobManager jobManager = Job.getJobManager(); + jobManager.suspend(); + try { + Job[] jobs = jobManager.find(null); + for(int i = 0; i < jobs.length; i++ ) { + if(jobs[i] instanceof WorkspaceJob || jobs[i].getClass().getName().endsWith("JREUpdateJob")) { + jobs[i].join(); + } + } + workspace.run(new IWorkspaceRunnable() { + @Override + public void run(IProgressMonitor monitor) { + } + }, workspace.getRoot(), 0, monitor); + + // Now we flush all background processing queues + boolean processed = flushProcessingQueues(jobManager, monitor); + for(int i = 0; i < 10 && processed; i++ ) { + processed = flushProcessingQueues(jobManager, monitor); + try { + Thread.sleep(10); + } catch(InterruptedException e) { + } + } + if (processed) { + JavaLanguageServerPlugin.logInfo("Could not flush background processing queues: " + getProcessingQueues(jobManager)); + } + } finally { + jobManager.resume(); + } + + waitForBuildJobs(); + } + + private static boolean flushProcessingQueues(IJobManager jobManager, IProgressMonitor monitor) + throws InterruptedException, CoreException { + boolean processed = false; + for(IBackgroundProcessingQueue queue : getProcessingQueues(jobManager)) { + queue.join(); + if(!queue.isEmpty()) { + Deque context = MavenExecutionContext.suspend(); + try { + IStatus status = queue.run(monitor); + if(!status.isOK()) { + throw new CoreException(status); + } + processed = true; + } finally { + MavenExecutionContext.resume(context); + } + } + if(queue.isEmpty()) { + queue.cancel(); + } + } + return processed; + } + + private static List getProcessingQueues(IJobManager jobManager) { + ArrayList queues = new ArrayList<>(); + for(Job job : jobManager.find(null)) { + if(job instanceof IBackgroundProcessingQueue) { + queues.add((IBackgroundProcessingQueue) job); + } + } + return queues; + } + + private static void waitForBuildJobs() { + waitForBuildJobs(MAX_TIME_MILLIS); + } + + public static void waitForBuildJobs(int maxTimeMilis) { + waitForJobs(BuildJobMatcher.INSTANCE, maxTimeMilis); + } + + public static void waitForInitializeJobs() { + waitForJobs(InitializeJobMatcher.INSTANCE, MAX_TIME_MILLIS); + } + + public static void waitForDownloadSourcesJobs(int maxTimeMillis) { + waitForJobs(DownloadSourcesJobMatcher.INSTANCE, maxTimeMillis); + } + + public static void waitForJobs(IJobMatcher matcher, int maxWaitMillis) { + final long limit = System.currentTimeMillis() + maxWaitMillis; + while(true) { + Job job = getJob(matcher); + if(job == null) { + return; + } + boolean timeout = System.currentTimeMillis() > limit; + if (timeout) { + JavaLanguageServerPlugin.logInfo("Timeout while waiting for completion of job: " + job); + break; + } + job.wakeUp(); + try { + Thread.sleep(POLLING_DELAY); + } catch(InterruptedException e) { + // ignore and keep waiting + } + } + } + + private static Job getJob(IJobMatcher matcher) { + Job[] jobs = Job.getJobManager().find(null); + for(Job job : jobs) { + if(matcher.matches(job)) { + return job; + } + } + return null; + } + + interface IJobMatcher { + + boolean matches(Job job); + + } + + static class BuildJobMatcher implements IJobMatcher { + + public static final IJobMatcher INSTANCE = new BuildJobMatcher(); + + @Override + public boolean matches(Job job) { + return (job instanceof WorkspaceJob) || job.getClass().getName().matches("(.*\\.AutoBuild.*)") + || job.getClass().getName().endsWith("JREUpdateJob"); + } + + } + + static class InitializeJobMatcher implements IJobMatcher { + + public static final IJobMatcher INSTANCE = new InitializeJobMatcher(); + + @Override + public boolean matches(Job job) { + return job.belongsTo(InitHandler.JAVA_LS_INITIALIZATION_JOBS); + } + + } + + static class DownloadSourcesJobMatcher implements IJobMatcher { + + public static final IJobMatcher INSTANCE = new DownloadSourcesJobMatcher(); + + @Override + public boolean matches(Job job) { + return ("org.eclipse.m2e.jdt.internal.DownloadSourcesJob".equals(job.getClass().getName())); + } + + } + +} \ No newline at end of file diff --git a/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/PomDependencyTest.java b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/PomDependencyTest.java new file mode 100644 index 0000000..2fea8df --- /dev/null +++ b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/PomDependencyTest.java @@ -0,0 +1,18 @@ +package io.konveyor.tackle.core.internal; + +import static org.junit.Assert.assertEquals; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.Path; +import org.eclipse.jdt.core.IJavaProject; +import org.junit.Test; + +public class PomDependencyTest extends ProjectUtilsTest { + @Test + public void mavenProjectTest() throws Exception { + IJavaProject javaProject = loadMavenProject(MavenProjectName.springboot_todo_project); + IFile pomfile = javaProject.getProject().getFile(new Path("pom.xml")); + + assertEquals(String.format("/%s/pom.xml",MavenProjectName.springboot_todo_project), pomfile.getFullPath().toString()); + } +} \ No newline at end of file diff --git a/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/ProjectUtilsTest.java b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/ProjectUtilsTest.java new file mode 100644 index 0000000..82546a2 --- /dev/null +++ b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/ProjectUtilsTest.java @@ -0,0 +1,246 @@ +package io.konveyor.tackle.core.internal; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +import org.apache.commons.io.FileUtils; +import org.eclipse.buildship.core.internal.CorePlugin; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IFolder; +import org.eclipse.core.resources.IProject; +import org.eclipse.core.resources.IProjectDescription; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.IProgressMonitor; +import org.eclipse.core.runtime.NullProgressMonitor; +import org.eclipse.core.runtime.Path; +import org.eclipse.core.runtime.jobs.Job; +import org.eclipse.jdt.core.IJavaProject; +import org.eclipse.jdt.core.JavaCore; +import org.eclipse.jdt.core.JavaModelException; +import org.eclipse.jdt.ls.core.internal.JavaLanguageServerPlugin; +import org.eclipse.lsp4j.ClientCapabilities; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.BeforeClass; + +/** + * Base Utility class to load a project for testing + * + * @author Charles Moulliard + * + */ +public class ProjectUtilsTest { + + private static final Logger LOGGER = Logger.getLogger(ProjectUtilsTest.class.getSimpleName()); + private static Level oldLevel; + + public final String RULE_ENTRY_COMMAND_ID = "io.konveyor.tackle.ruleEntry"; + public final String ANALYSIS_MODE_SOURCE_ONLY = "source-only"; + public final String LOCATION_TYPE_ANNOTATION = "4"; + + public static class MavenProjectName { + public static String empty_maven_project = "empty-maven"; + public static String springboot_todo_project = "springboot-todo"; + } + + public static class GradleProjectName { + public static String empty_gradle_project = "empty-gradle-project"; + public static String quarkus_gradle_project = "quarkus-gradle-project"; + } + + public static SampleDelegateCommandHandler cmdHandler; + + @BeforeClass + public static void setUp() { + oldLevel = LOGGER.getLevel(); + LOGGER.setLevel(Level.INFO); + enableClassFileContentsSupport(); + + cmdHandler = new SampleDelegateCommandHandler(); + } + + @AfterClass + public static void tearDown() { + LOGGER.setLevel(oldLevel); + } + + @After + public void cleanWorkspace() { + try { + IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects(); + for (IProject project : projects) { + project.delete(true, null); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public static IJavaProject loadMavenProject(String mavenProject) throws CoreException, Exception { + return loadJavaProjects(new String[] { "maven/" + mavenProject })[0]; + } + + public static IJavaProject loadGradleProject(String gradleProject) throws CoreException, Exception { + var gradleJavaProject = loadJavaProjects(new String[] { "gradle/" + gradleProject })[0]; + Job.getJobManager().join(CorePlugin.GRADLE_JOB_FAMILY, new NullProgressMonitor()); + return gradleJavaProject; + } + + public static IJavaProject loadMavenProjectFromSubFolder(String mavenProject, String subFolder) throws Exception { + return loadJavaProjects(new String[] { "maven/" + subFolder + "/" + mavenProject })[0]; + } + + public static IJavaProject[] loadJavaProjects(String[] parentSlashName) { + + List paths = new ArrayList<>(); + List javaProjects = new ArrayList<>(); + + try { + for (String parentSlashNameEntry : parentSlashName) { + String parentDirName = parentSlashNameEntry.substring(0, parentSlashNameEntry.lastIndexOf('/')); + String projectName = parentSlashNameEntry.substring(parentSlashNameEntry.lastIndexOf('/') + 1); + + // Move project to working directory + File projectFolder = copyProjectToWorkingDirectory(projectName, parentDirName); + IPath path = new Path(projectFolder.getAbsolutePath()); + paths.add(path); + } + + JavaLanguageServerPlugin.getPreferencesManager().initialize(); + JavaLanguageServerPlugin.getPreferencesManager().updateClientPrefences(new ClientCapabilities(), + new HashMap<>()); + JavaLanguageServerPlugin.getProjectsManager().initializeProjects(paths, new NullProgressMonitor()); + + IProgressMonitor monitor = new NullProgressMonitor(); + waitForBackgroundJobs(monitor); + org.eclipse.jdt.ls.core.internal.JobHelpers.waitUntilIndexesReady(); + + for (IPath path : paths) { + IProjectDescription description = ResourcesPlugin.getWorkspace() + .loadProjectDescription(path.append(".project")); + IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(description.getName()); + javaProjects.add(JavaCore.create(project)); + } + + } catch (Exception e) { + e.printStackTrace(); + } + + // Set the rootPaths manually. This is is needed when running the tests + JavaLanguageServerPlugin.getPreferencesManager().getPreferences().setRootPaths(paths); + + return javaProjects.toArray(new IJavaProject[0]); + } + + private static File copyProjectToWorkingDirectory(String projectName, String parentDirName) throws IOException { + File from = new File("projects/" + parentDirName + "/" + projectName); + File to = new File(JavaUtils.getWorkingProjectDirectory(), + java.nio.file.Paths.get(parentDirName, projectName).toString()); + + if (to.exists()) { + FileUtils.forceDelete(to); + } + + if (from.isDirectory()) { + FileUtils.copyDirectory(from, to); + } else { + FileUtils.copyFile(from, to); + } + + return to; + } + + private static void waitForBackgroundJobs(IProgressMonitor monitor) throws Exception { + JobHelpers.waitForJobsToComplete(monitor); + } + + private static void createFile(IFile file, String contents) throws CoreException { + createParentFolders(file); + file.refreshLocal(IResource.DEPTH_ZERO, null); + InputStream fileContents = new ByteArrayInputStream(contents.getBytes()); + if (file.exists()) { + file.setContents(fileContents, IResource.NONE, null); + } else { + file.create(fileContents, true, null); + } + } + + private static void createParentFolders(final IResource resource) throws CoreException { + if (resource == null || resource.exists()) + return; + if (!resource.getParent().exists()) + createParentFolders(resource.getParent()); + switch (resource.getType()) { + case IResource.FOLDER: + ((IFolder) resource).create(IResource.FORCE, true, new NullProgressMonitor()); + break; + case IResource.PROJECT: + ((IProject) resource).create(new NullProgressMonitor()); + ((IProject) resource).open(new NullProgressMonitor()); + break; + } + } + + private static void updateFile(IFile file, String content) throws CoreException { + // For Mac OS, Linux OS, the call of Files.getLastModifiedTime is working for 1 + // second. + // Here we wait for > 1s to be sure that call of Files.getLastModifiedTime will + // work. + try { + Thread.sleep(1050); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + createFile(file, content); + } + + protected static void saveFile(String configFileName, String content, IJavaProject javaProject) + throws CoreException { + saveFile(configFileName, content, javaProject, false); + } + + protected static void saveFile(String configFileName, String content, IJavaProject javaProject, boolean inSource) + throws CoreException { + IFile file = getFile(configFileName, javaProject, inSource); + updateFile(file, content); + } + + protected static void deleteFile(String configFileName, IJavaProject javaProject) + throws IOException, CoreException { + deleteFile(configFileName, javaProject, false); + } + + protected static void deleteFile(String configFileName, IJavaProject javaProject, boolean inSource) + throws IOException, CoreException { + IFile file = getFile(configFileName, javaProject, inSource); + file.delete(true, new NullProgressMonitor()); + } + + private static IFile getFile(String configFileName, IJavaProject javaProject, boolean inSource) + throws JavaModelException { + if (inSource) { + return javaProject.getProject().getFile(new Path("src/main/java/" + configFileName)); + } + IPath output = javaProject.getOutputLocation(); + IPath filePath = output.append(configFileName); + return ResourcesPlugin.getWorkspace().getRoot().getFile(filePath); + } + + private static void enableClassFileContentsSupport() { + Map extendedClientCapabilities = new HashMap<>(); + extendedClientCapabilities.put("classFileContentsSupport", "true"); + JavaLanguageServerPlugin.getPreferencesManager().updateClientPrefences(new ClientCapabilities(), + extendedClientCapabilities); + } +} diff --git a/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/SampleDelegateCommandHandlerTest.java b/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/SampleDelegateCommandHandlerTest.java deleted file mode 100644 index e973fac..0000000 --- a/java-analyzer-bundle.test/src/main/java/io/konveyor/tackle/core/internal/SampleDelegateCommandHandlerTest.java +++ /dev/null @@ -1,41 +0,0 @@ -package io.konveyor.tackle.core.internal; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import java.util.List; -import java.util.ArrayList; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.Collections; -import org.junit.Before; -import org.junit.Test; - -/** -* Sample integration test. In Eclipse, right-click > Run As > JUnit-Plugin.
-* In Maven CLI, run "mvn integration-test". -*/ -public class SampleDelegateCommandHandlerTest { - - private SampleDelegateCommandHandler commandHandler; - - @Before - public void setUp() { - commandHandler = new SampleDelegateCommandHandler(); - } - - @Test - public void veryStupidTest() throws Exception { - assertEquals("Hello World", commandHandler.executeCommand(SampleDelegateCommandHandler.COMMAND_ID, null, null)); - - // Test call with params in list - - List params = new ArrayList(); - - Map param = Map.of("project", "project", "query", "customresourcedefinition"); - params.add(param); - - - assertEquals(Collections.emptyList(), commandHandler.executeCommand(SampleDelegateCommandHandler.RULE_ENTRY_COMMAND_ID, params, null)); - } -} \ No newline at end of file diff --git a/pom.xml b/pom.xml index ccdc200..5ab0f6e 100644 --- a/pom.xml +++ b/pom.xml @@ -72,6 +72,7 @@ true ${tycho.test.jvmArgs} + true 60