diff --git a/school - Shortcut.lnk b/school - Shortcut.lnk new file mode 100644 index 0000000..dcb81eb Binary files /dev/null and b/school - Shortcut.lnk differ diff --git a/school/.gitignore b/school/.gitignore new file mode 100644 index 0000000..153c933 --- /dev/null +++ b/school/.gitignore @@ -0,0 +1,29 @@ +HELP.md +/target/ +!.mvn/wrapper/maven-wrapper.jar + +### STS ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +/build/ + +### VS Code ### +.vscode/ diff --git a/school/.mvn/wrapper/MavenWrapperDownloader.java b/school/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..f059db3 --- /dev/null +++ b/school/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,128 @@ +/* +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. +*/ + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.util.Properties; + +public class MavenWrapperDownloader +{ + + /** + * Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided. + */ + private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar"; + + /** + * Path to the maven-wrapper.properties file, which might contain a downloadUrl property to + * use instead of the default one. + */ + private static final String MAVEN_WRAPPER_PROPERTIES_PATH = ".mvn/wrapper/maven-wrapper.properties"; + + /** + * Path where the maven-wrapper.jar will be saved to. + */ + private static final String MAVEN_WRAPPER_JAR_PATH = ".mvn/wrapper/maven-wrapper.jar"; + + /** + * Name of the property which should be used to override the default download url for the wrapper. + */ + private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl"; + + public static void main(String args[]) + { + System.out.println("- Downloader started"); + File baseDirectory = new File(args[0]); + System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath()); + + // If the maven-wrapper.properties exists, read it and check if it contains a custom + // wrapperUrl parameter. + File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH); + String url = DEFAULT_DOWNLOAD_URL; + if (mavenWrapperPropertyFile.exists()) + { + FileInputStream mavenWrapperPropertyFileInputStream = null; + try + { + mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile); + Properties mavenWrapperProperties = new Properties(); + mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream); + url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url); + } + catch (IOException e) + { + System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'"); + } + finally + { + try + { + if (mavenWrapperPropertyFileInputStream != null) + { + mavenWrapperPropertyFileInputStream.close(); + } + } + catch (IOException e) + { + // Ignore ... + } + } + } + System.out.println("- Downloading from: : " + url); + + File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH); + if (!outputFile.getParentFile().exists()) + { + if (!outputFile.getParentFile().mkdirs()) + { + System.out.println("- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'"); + } + } + System.out.println("- Downloading to: " + outputFile.getAbsolutePath()); + try + { + downloadFileFromURL(url, outputFile); + System.out.println("Done"); + System.exit(0); + } + catch (Throwable e) + { + System.out.println("- Error downloading"); + e.printStackTrace(); + System.exit(1); + } + } + + private static void downloadFileFromURL(String urlString, File destination) throws Exception + { + URL website = new URL(urlString); + ReadableByteChannel rbc; + rbc = Channels.newChannel(website.openStream()); + FileOutputStream fos = new FileOutputStream(destination); + fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); + fos.close(); + rbc.close(); + } + +} diff --git a/school/.mvn/wrapper/maven-wrapper.jar b/school/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..01e6799 Binary files /dev/null and b/school/.mvn/wrapper/maven-wrapper.jar differ diff --git a/school/.mvn/wrapper/maven-wrapper.properties b/school/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000..cd0d451 --- /dev/null +++ b/school/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip diff --git a/school/mvnw b/school/mvnw new file mode 100644 index 0000000..8b9da3b --- /dev/null +++ b/school/mvnw @@ -0,0 +1,286 @@ +#!/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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven2 Start Up Batch script +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# M2_HOME - location of maven2's installed home dir +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + export JAVA_HOME="`/usr/libexec/java_home`" + else + export JAVA_HOME="/Library/Java/Home" + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +if [ -z "$M2_HOME" ] ; then + ## resolve links - $0 may be a link to maven's home + PRG="$0" + + # need this for relative symlinks + while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG="`dirname "$PRG"`/$link" + fi + done + + saveddir=`pwd` + + M2_HOME=`dirname "$PRG"`/.. + + # make it fully qualified + M2_HOME=`cd "$M2_HOME" && pwd` + + cd "$saveddir" + # echo Using m2 at $M2_HOME +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$M2_HOME" ] && + M2_HOME=`cygpath --unix "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$M2_HOME" ] && + M2_HOME="`(cd "$M2_HOME"; pwd)`" + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" + # TODO classpath? +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`which java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + echo "${basedir}" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=`find_maven_basedir "$(pwd)"` +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +########################################################################################## +# 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. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" + while IFS="=" read key value; do + case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $jarUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + wget "$jarUrl" -O "$wrapperJarPath" + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + curl -o "$wrapperJarPath" "$jarUrl" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + if [ -e "$javaClass" ]; then + if [ ! -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaClass") + fi + if [ -e "$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +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 "$M2_HOME" ] && + M2_HOME=`cygpath --path --windows "$M2_HOME"` + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/school/mvnw.cmd b/school/mvnw.cmd new file mode 100644 index 0000000..fef5a8f --- /dev/null +++ b/school/mvnw.cmd @@ -0,0 +1,161 @@ +@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 Maven2 Start Up Batch script +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM M2_HOME - location of maven2's installed home dir +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" +if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar" +FOR /F "tokens=1,2 delims==" %%A IN (%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties) DO ( + IF "%%A"=="wrapperUrl" SET DOWNLOAD_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% ( + echo Found %WRAPPER_JAR% +) else ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + powershell -Command "(New-Object Net.WebClient).DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')" + echo Finished downloading %WRAPPER_JAR% +) +@REM End of extension + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" +if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%" == "on" pause + +if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% + +exit /B %ERROR_CODE% diff --git a/school/pom.xml b/school/pom.xml new file mode 100644 index 0000000..1f1122b --- /dev/null +++ b/school/pom.xml @@ -0,0 +1,158 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.1.4.RELEASE + + + com.lambdaschool + school + 0.0.1-SNAPSHOT + school + Demo project for Spring Boot + jar + + + 11 + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-security + + + org.springframework.boot + spring-boot-starter-web + + + org.postgresql + postgresql + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + + + + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.security + spring-security-test + test + + + + + com.fasterxml.jackson.core + jackson-databind + 2.9.9 + + + + + org.springframework.security.oauth + spring-security-oauth2 + 2.3.6.RELEASE + + + + + javax.xml.bind + jaxb-api + 2.3.1 + + + + + javax.activation + activation + 1.1.1 + + + + + org.glassfish.jaxb + jaxb-runtime + 2.3.2 + + + + + io.springfox + springfox-swagger2 + 2.9.2 + + + + + io.springfox + springfox-swagger-ui + 2.9.2 + + + + + org.slf4j + slf4j-api + 1.7.26 + + + + io.rest-assured + spring-mock-mvc + 3.3.0 + test + + + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + + + + com.heroku.sdk + heroku-maven-plugin + 2.0.3 + + naught-school + false + + + ${project.build.directory}\${project.build.finalName}.jar + + ${java.version} + + java $JAVA_OPTS -Dserver.port=$PORT -jar target/${project.build.finalName}.jar + + + + + + + diff --git a/school/src/main/java/com/lambdaschool/school/SchoolApplication.java b/school/src/main/java/com/lambdaschool/school/SchoolApplication.java new file mode 100644 index 0000000..a5d0d9c --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/SchoolApplication.java @@ -0,0 +1,21 @@ +package com.lambdaschool.school; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.ApplicationContext; +import org.springframework.data.jpa.repository.config.EnableJpaAuditing; +import org.springframework.web.servlet.DispatcherServlet; + +import javax.swing.*; + +@SpringBootApplication +@EnableJpaAuditing +public class SchoolApplication +{ + + public static void main(String[] args) + { + SpringApplication.run(SchoolApplication.class, args); + } + +} diff --git a/school/src/main/java/com/lambdaschool/school/SeedData.java b/school/src/main/java/com/lambdaschool/school/SeedData.java new file mode 100644 index 0000000..68a5bd8 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/SeedData.java @@ -0,0 +1,41 @@ +package com.lambdaschool.school; + +import com.lambdaschool.school.model.Role; +import com.lambdaschool.school.model.User; +import com.lambdaschool.school.model.UserRoles; +import com.lambdaschool.school.repository.RoleRepository; +import com.lambdaschool.school.repository.UserRepository; +import org.springframework.boot.CommandLineRunner; +import org.springframework.stereotype.Component; +import org.springframework.transaction.annotation.Transactional; + +import java.util.ArrayList; + +@Transactional +@Component +public class SeedData implements CommandLineRunner +{ + RoleRepository rolerepos; + UserRepository userrepos; + + public SeedData(RoleRepository rolerepos, UserRepository userrepos) + { + this.rolerepos = rolerepos; + this.userrepos = userrepos; + } + + @Override + public void run(String[] args) throws Exception + { + Role r1 = new Role("user"); + + ArrayList users = new ArrayList<>(); + users.add(new UserRoles(new User(), r1)); + + rolerepos.save(r1); + + User u1 = new User("naught", "password", users); + + userrepos.save(u1); + } +} \ No newline at end of file diff --git a/school/src/main/java/com/lambdaschool/school/config/AuthorizationServerConfig.java b/school/src/main/java/com/lambdaschool/school/config/AuthorizationServerConfig.java new file mode 100644 index 0000000..f828029 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/config/AuthorizationServerConfig.java @@ -0,0 +1,56 @@ +package com.lambdaschool.school.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; +import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; +import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; +import org.springframework.security.oauth2.provider.token.TokenStore; + +@Configuration +@EnableAuthorizationServer +public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter +{ + static final String CLIENT_ID = "lambda-client"; + static final String CLIENT_SECRET = "lambda-secret"; + static final String GRANT_TYPE_PASSWORD = "password"; + static final String AUTHORIZATION_CODE = "authorization_code"; + static final String REFRESH_TOKEN = "refresh_token"; + static final String IMPLICIT = "implicit"; + static final String SCOPE_READ = "read"; + static final String SCOPE_WRITE = "write"; + static final String TRUST = "trust"; + static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1*60*60; + static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6*60*60; + + @Autowired + private TokenStore tokenStore; + + @Autowired + private AuthenticationManager authenticationManager; + + @Autowired + private PasswordEncoder encoder; + + @Override + public void configure(ClientDetailsServiceConfigurer configurer) throws Exception { + + configurer + .inMemory() + .withClient(CLIENT_ID) + .secret(encoder.encode(CLIENT_SECRET)) + .authorizedGrantTypes(GRANT_TYPE_PASSWORD, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT ) + .scopes(SCOPE_READ, SCOPE_WRITE, TRUST) + .accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS) + .refreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS); + } + + @Override + public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { + endpoints.tokenStore(tokenStore) + .authenticationManager(authenticationManager); + } +} \ No newline at end of file diff --git a/school/src/main/java/com/lambdaschool/school/config/ResourceServerConfig.java b/school/src/main/java/com/lambdaschool/school/config/ResourceServerConfig.java new file mode 100644 index 0000000..c991aa1 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/config/ResourceServerConfig.java @@ -0,0 +1,46 @@ +package com.lambdaschool.school.config; + +import org.springframework.context.annotation.Configuration; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; +import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; +import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; +import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler; + +@Configuration +@EnableResourceServer +public class ResourceServerConfig extends ResourceServerConfigurerAdapter +{ + + private static final String RESOURCE_ID = "resource_id"; + + @Override + public void configure(ResourceServerSecurityConfigurer resources) + { + resources.resourceId(RESOURCE_ID).stateless(false); + } + + @Override + public void configure(HttpSecurity http) throws Exception + { + // http.anonymous().disable(); + http.authorizeRequests() + .antMatchers("/", // h2 + "/h2-console/**", // h2 + "/v2/api-docs", // swagger + "/swagger-resources", // swagger + "/swagger-resources/**", // swagger + "/configuration/ui", // swagger + "/configuration/security", // swagger + "/swagger-ui.html", // swagger + "/webjars/**" // swagger + ).permitAll() + .antMatchers("/users/**").authenticated() + .antMatchers( "/students", "/courses", "/actuator/**").hasAnyRole( "user") + .and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler()); + + // http.requiresChannel().anyRequest().requiresSecure(); + http.csrf().disable(); + http.headers().frameOptions().disable(); + } +} diff --git a/school/src/main/java/com/lambdaschool/school/config/SecurityConfig.java b/school/src/main/java/com/lambdaschool/school/config/SecurityConfig.java new file mode 100644 index 0000000..b2e87c3 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/config/SecurityConfig.java @@ -0,0 +1,53 @@ +package com.lambdaschool.school.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; +import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; +import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; +import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore; + +import javax.annotation.Resource; + +@Configuration +@EnableWebSecurity +@EnableGlobalMethodSecurity(prePostEnabled = true) +public class SecurityConfig extends WebSecurityConfigurerAdapter +{ + + @Resource(name = "userService") + private UserDetailsService userDetailsService; + + @Override + @Bean + public AuthenticationManager authenticationManagerBean() throws Exception + { + return super.authenticationManagerBean(); + } + + @Autowired + public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception + { + auth.userDetailsService(userDetailsService) + .passwordEncoder(encoder()); + } + + @Bean + public TokenStore tokenStore() + { + return new InMemoryTokenStore(); + } + + @Bean + public PasswordEncoder encoder() + { + return new BCryptPasswordEncoder(); + } +} \ No newline at end of file diff --git a/school/src/main/java/com/lambdaschool/school/config/SimpleCorsFilter.java b/school/src/main/java/com/lambdaschool/school/config/SimpleCorsFilter.java new file mode 100644 index 0000000..2be6c27 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/config/SimpleCorsFilter.java @@ -0,0 +1,49 @@ +package com.lambdaschool.school.config; + +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Component; + +import javax.servlet.*; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; + +@Component +@Order(Ordered.HIGHEST_PRECEDENCE) +public class SimpleCorsFilter implements Filter +{ + + public SimpleCorsFilter() + { + } + + @Override + public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException + { + HttpServletResponse response = (HttpServletResponse) res; + HttpServletRequest request = (HttpServletRequest) req; + response.setHeader("Access-Control-Allow-Origin", "*"); + response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); + response.setHeader("Access-Control-Max-Age", "3600"); + response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, content-type, access_token"); + + if ("OPTIONS".equalsIgnoreCase(request.getMethod())) + { + response.setStatus(HttpServletResponse.SC_OK); + } else + { + chain.doFilter(req, res); + } + } + + @Override + public void init(FilterConfig filterConfig) + { + } + + @Override + public void destroy() + { + } +} \ No newline at end of file diff --git a/school/src/main/java/com/lambdaschool/school/config/Swagger2Config.java b/school/src/main/java/com/lambdaschool/school/config/Swagger2Config.java new file mode 100644 index 0000000..99bf08c --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/config/Swagger2Config.java @@ -0,0 +1,42 @@ +package com.lambdaschool.school.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.domain.Pageable; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@Configuration +@EnableSwagger2 +public class Swagger2Config +{ + @Bean + public Docket api() + { + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors + .basePackage("com.lambdaschool.school")) + .paths(PathSelectors.regex("/.*")) + .build() + .useDefaultResponseMessages(false) // Allows only my exception responses + .ignoredParameterTypes(Pageable.class) // allows only my paging parameter list + .apiInfo(apiEndPointsInfo()); + } + + private ApiInfo apiEndPointsInfo() + { + return new ApiInfoBuilder().title("School Example") + .description("School Example Description") + .contact(new Contact("Jacob Ryans", "http://www.lambdaschool.com", "aemidzero@gmail.com")) + .license("MIT").licenseUrl("https://github.com/LambdaSchool/java-crudysnacks/blob/master/LICENSE") + .version("1.0.0").build(); + } +} + diff --git a/school/src/main/java/com/lambdaschool/school/controller/CourseController.java b/school/src/main/java/com/lambdaschool/school/controller/CourseController.java new file mode 100644 index 0000000..2c999e4 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/controller/CourseController.java @@ -0,0 +1,49 @@ +package com.lambdaschool.school.controller; + +import com.lambdaschool.school.exception.ResourceNotFoundException; +import com.lambdaschool.school.model.Course; +import com.lambdaschool.school.service.CourseService; +import com.lambdaschool.school.view.CountStudentsInCourses; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import javax.persistence.EntityNotFoundException; +import java.util.ArrayList; + +@RestController +@RequestMapping(value = "/courses") +public class CourseController +{ + @Autowired + private CourseService courseService; + + @GetMapping(value = "/courses", produces = {"application/json"}) + public ResponseEntity listAllCourses() + { + ArrayList myCourses = courseService.findAll(); + if(myCourses.size() == 0) { + throw new EntityNotFoundException("No data to pull"); + } else { + return new ResponseEntity<>(myCourses, HttpStatus.OK); + } + } + + @GetMapping(value = "/studcount", produces = {"application/json"}) + public ResponseEntity getCountStudentsInCourses() + { + return new ResponseEntity<>(courseService.getCountStudentsInCourse(), HttpStatus.OK); + } + + @DeleteMapping("/courses/{courseid}") + public ResponseEntity deleteCourseById(@PathVariable long courseid) + { + if(courseService.findCourseById(courseid) == null) { + throw new EntityNotFoundException("Course ID invalid"); + } else { + courseService.delete(courseid); + return new ResponseEntity<>(HttpStatus.OK); + } + } +} diff --git a/school/src/main/java/com/lambdaschool/school/controller/StudentController.java b/school/src/main/java/com/lambdaschool/school/controller/StudentController.java new file mode 100644 index 0000000..0b59989 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/controller/StudentController.java @@ -0,0 +1,131 @@ +package com.lambdaschool.school.controller; + +import com.lambdaschool.school.model.ErrorDetail; +import com.lambdaschool.school.model.Student; +import com.lambdaschool.school.service.StudentService; +import io.swagger.annotations.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import javax.persistence.EntityNotFoundException; +import javax.validation.Valid; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +@RestController +@RequestMapping("/students") +public class StudentController +{ + @Autowired + private StudentService studentService; + + // Please note there is no way to add students to course yet! + + @ApiOperation(value = "return all Students", response = Student.class, responseContainer = "List") + @ApiImplicitParams({ + @ApiImplicitParam(name = "page", dataType = "integr", paramType = "query", + value = "Results page you want to retrieve (0..N)"), + @ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", + value = "Number of records per page."), + @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query", + value = "Sorting criteria in the format: property(,asc|desc). " + + "Default sort order is ascending. " + + "Multiple sort criteria are supported.")}) + @GetMapping(value = "/students", produces = {"application/json"}) + public ResponseEntity listAllStudents(@PageableDefault(page = 0, size=5) Pageable pageable) + { + List myStudents = studentService.findAll(pageable); + return new ResponseEntity<>(myStudents, HttpStatus.OK); + } + + @ApiOperation(value = "Retrieves a student associated with the studentid", response = Student.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Student Found", response = Student.class), + @ApiResponse(code = 404, message = "Student Not Found", response = ErrorDetail.class) + }) + @GetMapping(value = "/Student/{StudentId}", + produces = {"application/json"}) + public ResponseEntity getStudentById( + @PageableDefault(page = 0, size = 5) Pageable pageable, + @PathVariable + Long StudentId) + { + Student r = studentService.findStudentById(StudentId); + return new ResponseEntity<>(r, HttpStatus.OK); + } + + @ApiOperation(value = "Retrieves a student by name", response=Student.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Student Found", response = Student.class), + @ApiResponse(code = 404, message = "Student Not Found", response = ErrorDetail.class) + }) + @GetMapping(value = "/student/namelike/{name}", + produces = {"application/json"}) + public ResponseEntity getStudentByNameContaining( + @PathVariable String name, @PageableDefault(page=0, size=5) Pageable pageable) + { + List myStudents = studentService.findStudentByNameLike(name, pageable); + return new ResponseEntity<>(myStudents, HttpStatus.OK); + } + + @ApiOperation(value = "Creates a new Student", notes = "The newly created student id will be sent in the location header", response = void.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Student Created Successfully", response = void.class), + @ApiResponse(code = 500, message = "Error creating student", response = ErrorDetail.class) + }) + @PostMapping(value = "/Student", + consumes = {"application/json"}, + produces = {"application/json"}) + public ResponseEntity addNewStudent(@Valid + @RequestBody + Student newStudent) throws URISyntaxException + { + newStudent = studentService.save(newStudent); + + // set the location header for the newly created resource + HttpHeaders responseHeaders = new HttpHeaders(); + URI newStudentURI = ServletUriComponentsBuilder.fromCurrentRequest().path("/{Studentid}").buildAndExpand(newStudent.getStudid()).toUri(); + responseHeaders.setLocation(newStudentURI); + + return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED); + } + + @ApiOperation(value = "Updating student with new information.", response=Student.class) + @ApiResponses(value = { + @ApiResponse(code=200, message = "Student Updated Successfully", response = Student.class), + @ApiResponse(code=404, message = "Student ID not relevant.", response = EntityNotFoundException.class), + @ApiResponse(code=500, message = "Request body incorrect.", response = ErrorDetail.class) + }) + @PutMapping(value = "/Student/{Studentid}") + public ResponseEntity updateStudent( + @RequestBody + Student updateStudent, + @PathVariable + long Studentid) + { + studentService.update(updateStudent, Studentid); + return new ResponseEntity<>(HttpStatus.OK); + } + + @ApiOperation(value = "Student deleted successfully", response=String.class) + @ApiResponses(value = { + @ApiResponse(code=201, message = "Student deleted Successfully", response = String.class), + @ApiResponse(code=404, message = "Student ID not provided.", response = EntityNotFoundException.class) + }) + @DeleteMapping("/Student/{Studentid}") + public ResponseEntity deleteStudentById( + @PathVariable + long Studentid) + { + studentService.delete(Studentid); + return new ResponseEntity<>("Student deleted succesfully.", HttpStatus.OK); + } + +} diff --git a/school/src/main/java/com/lambdaschool/school/exception/ResourceNotFoundException.java b/school/src/main/java/com/lambdaschool/school/exception/ResourceNotFoundException.java new file mode 100644 index 0000000..a430a2c --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/exception/ResourceNotFoundException.java @@ -0,0 +1,20 @@ +package com.lambdaschool.school.exception; + +import org.springframework.http.HttpStatus; +import org.springframework.web.bind.annotation.ResponseStatus; + +@ResponseStatus(value= HttpStatus.NOT_FOUND) +public class ResourceNotFoundException extends RuntimeException +{ + private static final long serialVersionUID = 1L; + + public ResourceNotFoundException(String message) + { + super(message); + } + + public ResourceNotFoundException(String message, Throwable cause) + { + super(message, cause); + } +} \ No newline at end of file diff --git a/school/src/main/java/com/lambdaschool/school/exception/ValidationError.java b/school/src/main/java/com/lambdaschool/school/exception/ValidationError.java new file mode 100644 index 0000000..c28acaa --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/exception/ValidationError.java @@ -0,0 +1,27 @@ +package com.lambdaschool.school.exception; + +public class ValidationError +{ + private String Code; + private String message; + + public String getCode() + { + return Code; + } + + public void setCode(String code) + { + Code = code; + } + + public String getMessage() + { + return message; + } + + public void setMessage(String message) + { + this.message = message; + } +} diff --git a/school/src/main/java/com/lambdaschool/school/model/Auditable.java b/school/src/main/java/com/lambdaschool/school/model/Auditable.java new file mode 100644 index 0000000..208d4af --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/Auditable.java @@ -0,0 +1,33 @@ +package com.lambdaschool.school.model; + +import org.springframework.data.annotation.CreatedBy; +import org.springframework.data.annotation.CreatedDate; +import org.springframework.data.annotation.LastModifiedBy; +import org.springframework.data.annotation.LastModifiedDate; +import org.springframework.data.jpa.domain.support.AuditingEntityListener; + +import javax.persistence.EntityListeners; +import javax.persistence.MappedSuperclass; +import javax.persistence.Temporal; +import java.util.Date; + +import static javax.persistence.TemporalType.TIMESTAMP; + +@MappedSuperclass +@EntityListeners(AuditingEntityListener.class) +abstract class Auditable +{ + @CreatedBy + protected String createdBy; + + @CreatedDate + @Temporal(TIMESTAMP) + protected Date createdDate; + + @LastModifiedBy + protected String lastModifiedBy; + + @LastModifiedDate + @Temporal(TIMESTAMP) + protected Date lastModifiedDate; +} diff --git a/school/src/main/java/com/lambdaschool/school/model/Course.java b/school/src/main/java/com/lambdaschool/school/model/Course.java new file mode 100644 index 0000000..720a5b3 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/Course.java @@ -0,0 +1,90 @@ +package com.lambdaschool.school.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; + +@ApiModel(value = "Course", description = "The course entity") +@Entity +@Table(name = "course") +public class Course +{ + @ApiModelProperty(name = "courseid", value = "Primary key for course", required = true, example = "1") + @Id + @GeneratedValue(strategy = GenerationType.AUTO) +// @JsonView(View.CoursesOnly.class) + private long courseid; + +// @JsonView(View.CoursesOnly.class) + @ApiModelProperty(name = "coursename", value = "Name for course", required = true, example = "Math") + private String coursename; + + @ManyToOne + @JoinColumn(name = "instructid") + @JsonIgnoreProperties("courses") +// @JsonView(View.CoursesOnly.class) + private Instructor instructor; + + @ManyToMany(mappedBy = "courses") + @JsonIgnoreProperties("courses") + private List students = new ArrayList<>(); + + public Course() + { + } + + public Course(String coursename) + { + this.coursename = coursename; + } + + public Course(String coursename, Instructor instructor) + { + this.coursename = coursename; + this.instructor = instructor; + } + + public long getCourseid() + { + return courseid; + } + + public void setCourseid(long courseid) + { + this.courseid = courseid; + } + + public String getCoursename() + { + return coursename; + } + + public void setCoursename(String coursename) + { + this.coursename = coursename; + } + + public Instructor getInstructor() + { + return instructor; + } + + public void setInstructor(Instructor instructor) + { + this.instructor = instructor; + } + + public List getStudents() + { + return students; + } + + public void setStudents(List students) + { + this.students = students; + } +} diff --git a/school/src/main/java/com/lambdaschool/school/model/ErrorDetail.java b/school/src/main/java/com/lambdaschool/school/model/ErrorDetail.java new file mode 100644 index 0000000..379cb55 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/ErrorDetail.java @@ -0,0 +1,80 @@ +package com.lambdaschool.school.model; + +import com.lambdaschool.school.exception.ValidationError; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +// adapted from https://tools.ietf.org/html/rfc7807 +public class ErrorDetail +{ + private String title; + private int status; + private String detail; + private String timestamp; + private String developerMessage; + private Map> errors = new HashMap>(); + + public String getTitle() + { + return title; + } + + public void setTitle(String title) + { + this.title = title; + } + + public int getStatus() + { + return status; + } + + public void setStatus(int status) + { + this.status = status; + } + + public String getDetail() + { + return detail; + } + + public void setDetail(String detail) + { + this.detail = detail; + } + + public String getTimestamp() + { + return timestamp; + } + + public void setTimestamp(Long timestamp) + { + this.timestamp = new SimpleDateFormat("dd MMM yyyy HH:mm:ss:SSS Z").format(new Date(timestamp)); + } + + public String getDeveloperMessage() + { + return developerMessage; + } + + public void setDeveloperMessage(String developerMessage) + { + this.developerMessage = developerMessage; + } + + public Map> getErrors() + { + return errors; + } + + public void setErrors(Map> errors) + { + this.errors = errors; + } +} diff --git a/school/src/main/java/com/lambdaschool/school/model/Instructor.java b/school/src/main/java/com/lambdaschool/school/model/Instructor.java new file mode 100644 index 0000000..a35bacd --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/Instructor.java @@ -0,0 +1,66 @@ +package com.lambdaschool.school.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; + +@ApiModel(value = "Instructor", description = "The instructor entity") +@Entity +@Table(name = "instructor") +public class Instructor +{ + @ApiModelProperty(name = "instructid", value = "Primary key for instructor", required = true, example = "1") + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long instructid; + + @ApiModelProperty(name = "instructname", value = "Name for instructor", required = true, example = "John") + private String instructname; + + @OneToMany(mappedBy = "instructor") + @JsonIgnoreProperties("instructors") + private List courses = new ArrayList<>(); + + public Instructor() + { + } + + public Instructor(String instructname) + { + this.instructname = instructname; + } + + public long getInstructid() + { + return instructid; + } + + public void setInstructid(long instructid) + { + this.instructid = instructid; + } + + public String getInstructname() + { + return instructname; + } + + public void setInstructname(String instructname) + { + this.instructname = instructname; + } + + public List getCourses() + { + return courses; + } + + public void setCourses(List courses) + { + this.courses = courses; + } +} diff --git a/school/src/main/java/com/lambdaschool/school/model/Role.java b/school/src/main/java/com/lambdaschool/school/model/Role.java new file mode 100644 index 0000000..f26bb14 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/Role.java @@ -0,0 +1,64 @@ +package com.lambdaschool.school.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; + +@Entity +@Table(name = "roles") +public class Role extends Auditable +{ + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long roleid; + + @Column(nullable = false, + unique = true) + private String name; + + @OneToMany(mappedBy = "role", + cascade = CascadeType.ALL) + @JsonIgnoreProperties("role") + private List userRoles = new ArrayList<>(); + + public Role() + { + } + + public Role(String name) + { + this.name = name; + } + + public long getRoleid() + { + return roleid; + } + + public void setRoleid(long roleid) + { + this.roleid = roleid; + } + + public String getName() + { + return name; + } + + public void setName(String name) + { + this.name = name; + } + + public List getUserRoles() + { + return userRoles; + } + + public void setUserRoles(List userRoles) + { + this.userRoles = userRoles; + } +} diff --git a/school/src/main/java/com/lambdaschool/school/model/Student.java b/school/src/main/java/com/lambdaschool/school/model/Student.java new file mode 100644 index 0000000..198d232 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/Student.java @@ -0,0 +1,70 @@ +package com.lambdaschool.school.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import javax.persistence.*; +import java.lang.reflect.Array; +import java.util.ArrayList; +import java.util.List; + +@ApiModel(value="Student", description = "The student entity.") +@Entity +@Table(name = "student") +public class Student +{ + @ApiModelProperty(name = "studid", value = "Primary key for student", required = true, example = "1") + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long studid; + + @ApiModelProperty(name = "studname", value = "Name for student", required = true, example = "Harry") + private String studname; + + @ManyToMany + @JoinTable(name = "studcourses", + joinColumns = {@JoinColumn(name = "studid")}, + inverseJoinColumns = {@JoinColumn(name = "courseid")}) + @JsonIgnoreProperties("students") + private List courses = new ArrayList<>(); + + public Student() + { + } + + public Student(String studname) + { + this.studname = studname; + } + + public long getStudid() + { + return studid; + } + + public void setStudid(long studid) + { + this.studid = studid; + } + + public String getStudname() + { + return studname; + } + + public void setStudname(String studname) + { + this.studname = studname; + } + + public List getCourses() + { + return courses; + } + + public void setCourses(List courses) + { + this.courses = courses; + } +} diff --git a/school/src/main/java/com/lambdaschool/school/model/User.java b/school/src/main/java/com/lambdaschool/school/model/User.java new file mode 100644 index 0000000..0c2d6ed --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/User.java @@ -0,0 +1,108 @@ +package com.lambdaschool.school.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; + +import javax.persistence.*; +import java.util.ArrayList; +import java.util.List; + +// User is considered the parent entity + +@Entity +@Table(name = "users") +public class User extends Auditable +{ + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long userid; + + @Column(nullable = false, + unique = true) + private String username; + + @Column(nullable = false) + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + private String password; + + @OneToMany(mappedBy = "user", + cascade = CascadeType.ALL) + @JsonIgnoreProperties("user") + private List userRoles = new ArrayList<>(); + + public User() + { + } + + public User(String username, String password, List userRoles) + { + setUsername(username); + setPassword(password); + for (UserRoles ur : userRoles) + { + ur.setUser(this); + } + this.userRoles = userRoles; + } + + public long getUserid() + { + return userid; + } + + public void setUserid(long userid) + { + this.userid = userid; + } + + public String getUsername() + { + return username; + } + + public void setUsername(String username) + { + this.username = username; + } + + public String getPassword() + { + return password; + } + + public void setPassword(String password) + { + BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + this.password = passwordEncoder.encode(password); + } + + public void setPasswordNoEncrypt(String password) + { + this.password = password; + } + + public List getUserRoles() + { + return userRoles; + } + + public void setUserRoles(List userRoles) + { + this.userRoles = userRoles; + } + + public List getAuthority() + { + List rtnList = new ArrayList<>(); + + for (UserRoles r : this.userRoles) + { + String myRole = "ROLE_" + r.getRole().getName().toUpperCase(); + rtnList.add(new SimpleGrantedAuthority(myRole)); + } + + return rtnList; + } +} diff --git a/school/src/main/java/com/lambdaschool/school/model/UserRoles.java b/school/src/main/java/com/lambdaschool/school/model/UserRoles.java new file mode 100644 index 0000000..f83174e --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/UserRoles.java @@ -0,0 +1,75 @@ +package com.lambdaschool.school.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.Objects; + +@Entity +@Table(name = "userroles") +public class UserRoles extends Auditable implements Serializable +{ + @Id + @ManyToOne + @JoinColumn(name = "userid") + @JsonIgnoreProperties("userRoles") + private User user; + + @Id + @ManyToOne + @JoinColumn(name = "roleid") + @JsonIgnoreProperties("userRoles") + private Role role; + + public UserRoles() + { + } + + public UserRoles(User user, Role role) + { + this.user = user; + this.role = role; + } + + public User getUser() + { + return user; + } + + public void setUser(User user) + { + this.user = user; + } + + public Role getRole() + { + return role; + } + + public void setRole(Role role) + { + this.role = role; + } + + @Override + public boolean equals(Object o) + { + if (this == o) + { + return true; + } + if (!(o instanceof UserRoles)) + { + return false; + } + UserRoles userRoles = (UserRoles) o; + return getUser().equals(userRoles.getUser()) && getRole().equals(userRoles.getRole()); + } + + @Override + public int hashCode() + { + return Objects.hash(getUser(), getRole()); + } +} diff --git a/school/src/main/java/com/lambdaschool/school/repository/CourseRepository.java b/school/src/main/java/com/lambdaschool/school/repository/CourseRepository.java new file mode 100644 index 0000000..caab79d --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/repository/CourseRepository.java @@ -0,0 +1,23 @@ +package com.lambdaschool.school.repository; + +import com.lambdaschool.school.model.Course; +import com.lambdaschool.school.view.CountStudentsInCourses; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; + +import java.util.ArrayList; +import java.util.List; + +public interface CourseRepository extends CrudRepository +{ + ArrayList findCoursesByCoursenameEquals(String name); + + @Modifying + @Query(value = "DELETE FROM studcourses WHERE courseid = :courseid", nativeQuery = true) + void deleteCourseFromStudcourses(long courseid); + + @Query(value = "SELECT s.courseid, coursename, count(studid) as countstudents FROM studcourses s INNER JOIN course c on s.courseid=c.courseid GROUP BY s.courseid, coursename", nativeQuery = true) + ArrayList getCountStudentsInCourse(); +} + diff --git a/school/src/main/java/com/lambdaschool/school/repository/InstructorRepository.java b/school/src/main/java/com/lambdaschool/school/repository/InstructorRepository.java new file mode 100644 index 0000000..f282b59 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/repository/InstructorRepository.java @@ -0,0 +1,12 @@ +package com.lambdaschool.school.repository; + +import com.lambdaschool.school.model.Instructor; +import org.springframework.data.repository.CrudRepository; + +import java.lang.reflect.Array; +import java.util.ArrayList; + +public interface InstructorRepository extends CrudRepository +{ + ArrayList findInstructorsByInstructnameEquals (String name); +} diff --git a/school/src/main/java/com/lambdaschool/school/repository/RoleRepository.java b/school/src/main/java/com/lambdaschool/school/repository/RoleRepository.java new file mode 100644 index 0000000..87e05e3 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/repository/RoleRepository.java @@ -0,0 +1,20 @@ +package com.lambdaschool.school.repository; + +import com.lambdaschool.school.model.Role; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.CrudRepository; +import org.springframework.transaction.annotation.Transactional; + +public interface RoleRepository extends CrudRepository +{ + @Transactional + @Modifying + @Query(value = "DELETE from UserRoles where userid = :userid") + void deleteUserRolesByUserId(long userid); + + @Transactional + @Modifying + @Query(value = "INSERT INTO UserRoles(userid, roleid) values (:userid, :roleid)", nativeQuery = true) + void insertUserRoles(long userid, long roleid); +} diff --git a/school/src/main/java/com/lambdaschool/school/repository/StudentRepository.java b/school/src/main/java/com/lambdaschool/school/repository/StudentRepository.java new file mode 100644 index 0000000..5ed87c6 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/repository/StudentRepository.java @@ -0,0 +1,14 @@ +package com.lambdaschool.school.repository; + +import com.lambdaschool.school.model.Student; +import org.springframework.data.domain.Pageable; +import org.springframework.data.repository.CrudRepository; +import org.springframework.data.repository.PagingAndSortingRepository; + +import java.util.ArrayList; +import java.util.List; + +public interface StudentRepository extends PagingAndSortingRepository +{ + List findByStudnameContainingIgnoreCase(String name, Pageable pageable); +} diff --git a/school/src/main/java/com/lambdaschool/school/repository/UserRepository.java b/school/src/main/java/com/lambdaschool/school/repository/UserRepository.java new file mode 100644 index 0000000..0c73da1 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/repository/UserRepository.java @@ -0,0 +1,9 @@ +package com.lambdaschool.school.repository; + +import com.lambdaschool.school.model.User; +import org.springframework.data.repository.CrudRepository; + +public interface UserRepository extends CrudRepository +{ + User findByUsername(String username); +} diff --git a/school/src/main/java/com/lambdaschool/school/service/CourseService.java b/school/src/main/java/com/lambdaschool/school/service/CourseService.java new file mode 100644 index 0000000..2404224 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/CourseService.java @@ -0,0 +1,19 @@ +package com.lambdaschool.school.service; + +import com.lambdaschool.school.model.Course; +import com.lambdaschool.school.view.CountStudentsInCourses; + +import java.util.ArrayList; + +public interface CourseService +{ + ArrayList findAll(); + + ArrayList getCountStudentsInCourse(); + + Course findCourseById(long id); + + void delete(long id); + + Course save(Course course); +} diff --git a/school/src/main/java/com/lambdaschool/school/service/CourseServiceImpl.java b/school/src/main/java/com/lambdaschool/school/service/CourseServiceImpl.java new file mode 100644 index 0000000..c121aa1 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/CourseServiceImpl.java @@ -0,0 +1,65 @@ +package com.lambdaschool.school.service; + +import com.lambdaschool.school.model.Course; +import com.lambdaschool.school.repository.CourseRepository; +import com.lambdaschool.school.view.CountStudentsInCourses; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityNotFoundException; +import java.util.ArrayList; + +@Service(value = "courseService") +public class CourseServiceImpl implements CourseService +{ + @Autowired + private CourseRepository courserepos; + + @Override + public ArrayList findAll() + { + ArrayList list = new ArrayList<>(); + courserepos.findAll().iterator().forEachRemaining(list::add); + return list; + } + + @Override + public Course findCourseById(long id) + { + return courserepos.findById(id) + .orElseThrow(() -> new EntityNotFoundException(Long.toString(id))); + } + + @Override + public ArrayList getCountStudentsInCourse() + { + return courserepos.getCountStudentsInCourse(); + } + + @Transactional + @Override + public void delete(long id) throws EntityNotFoundException + { + if (courserepos.findById(id).isPresent()) + { + courserepos.deleteCourseFromStudcourses(id); + courserepos.deleteById(id); + } else + { + throw new EntityNotFoundException(Long.toString(id)); + } + } + + @Transactional + @Override + public Course save(Course course) + { + Course newCourse = new Course(); + + newCourse.setCoursename(course.getCoursename()); + newCourse.setInstructor(course.getInstructor()); + + return courserepos.save(newCourse); + } +} diff --git a/school/src/main/java/com/lambdaschool/school/service/InstructorService.java b/school/src/main/java/com/lambdaschool/school/service/InstructorService.java new file mode 100644 index 0000000..a2668b1 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/InstructorService.java @@ -0,0 +1,5 @@ +package com.lambdaschool.school.service; + +public interface InstructorService +{ +} diff --git a/school/src/main/java/com/lambdaschool/school/service/InstructorServiceImpl.java b/school/src/main/java/com/lambdaschool/school/service/InstructorServiceImpl.java new file mode 100644 index 0000000..2d7966f --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/InstructorServiceImpl.java @@ -0,0 +1,12 @@ +package com.lambdaschool.school.service; + +import com.lambdaschool.school.repository.InstructorRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service(value = "instructorService") +public class InstructorServiceImpl implements InstructorService +{ + @Autowired + private InstructorRepository instructrepos; +} diff --git a/school/src/main/java/com/lambdaschool/school/service/RoleService.java b/school/src/main/java/com/lambdaschool/school/service/RoleService.java new file mode 100644 index 0000000..c0bf468 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/RoleService.java @@ -0,0 +1,16 @@ +package com.lambdaschool.school.service; + +import com.lambdaschool.school.model.Role; + +import java.util.List; + +public interface RoleService +{ + List findAll(); + + Role findRoleById(long id); + + void delete(long id); + + Role save(Role role); +} \ No newline at end of file diff --git a/school/src/main/java/com/lambdaschool/school/service/RoleServiceImpl.java b/school/src/main/java/com/lambdaschool/school/service/RoleServiceImpl.java new file mode 100644 index 0000000..59e5c15 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/RoleServiceImpl.java @@ -0,0 +1,49 @@ +package com.lambdaschool.school.service; + +import com.lambdaschool.school.model.Role; +import com.lambdaschool.school.repository.RoleRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityNotFoundException; +import java.util.ArrayList; +import java.util.List; + +@Service(value = "roleService") +public class RoleServiceImpl implements RoleService +{ + @Autowired + RoleRepository rolerepos; + + @Override + public List findAll() + { + List list = new ArrayList<>(); + rolerepos.findAll().iterator().forEachRemaining(list::add); + return list; + } + + + @Override + public Role findRoleById(long id) + { + return rolerepos.findById(id).orElseThrow(() -> new EntityNotFoundException(Long.toString(id))); + } + + + @Override + public void delete(long id) + { + rolerepos.findById(id).orElseThrow(() -> new EntityNotFoundException(Long.toString(id))); + rolerepos.deleteById(id); + } + + + @Transactional + @Override + public Role save(Role role) + { + return rolerepos.save(role); + } +} diff --git a/school/src/main/java/com/lambdaschool/school/service/StudentService.java b/school/src/main/java/com/lambdaschool/school/service/StudentService.java new file mode 100644 index 0000000..67e4f79 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/StudentService.java @@ -0,0 +1,21 @@ +package com.lambdaschool.school.service; + +import com.lambdaschool.school.model.Student; +import org.springframework.data.domain.Pageable; + +import java.util.List; + +public interface StudentService +{ + List findAll(Pageable pageable); + + Student findStudentById(long id); + + List findStudentByNameLike(String name, Pageable pageable); + + void delete(long id); + + Student save (Student student); + + Student update(Student student, long id); +} diff --git a/school/src/main/java/com/lambdaschool/school/service/StudentServiceImpl.java b/school/src/main/java/com/lambdaschool/school/service/StudentServiceImpl.java new file mode 100644 index 0000000..66a53c4 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/StudentServiceImpl.java @@ -0,0 +1,104 @@ +package com.lambdaschool.school.service; + +import com.lambdaschool.school.model.Course; +import com.lambdaschool.school.model.ErrorDetail; +import com.lambdaschool.school.model.Student; +import com.lambdaschool.school.repository.StudentRepository; +import io.swagger.annotations.*; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Pageable; +import org.springframework.data.web.PageableDefault; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityNotFoundException; +import java.util.ArrayList; +import java.util.List; + +@Service(value = "studentService") +public class StudentServiceImpl implements StudentService +{ + @Autowired + private StudentRepository studrepos; + + @ApiOperation(value = "return all Students", response = Student.class, responseContainer = "List") + @ApiImplicitParams({ + @ApiImplicitParam(name = "page", dataType = "integr", paramType = "query", + value = "Results page you want to retrieve (0..N)"), + @ApiImplicitParam(name = "size", dataType = "integer", paramType = "query", + value = "Number of records per page."), + @ApiImplicitParam(name = "sort", allowMultiple = true, dataType = "string", paramType = "query", + value = "Sorting criteria in the format: property(,asc|desc). " + + "Default sort order is ascending. " + + "Multiple sort criteria are supported.")}) + @Override + public List findAll(Pageable pageable) + { + List list = new ArrayList<>(); + studrepos.findAll(pageable).iterator().forEachRemaining(list::add); + return list; + } + + @ApiOperation(value = "Retrieves a student associated with the studentid", response = Student.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Student Found", response = Student.class), + @ApiResponse(code = 404, message = "Student Not Found", response = ErrorDetail.class) + }) + @Override + public Student findStudentById(long id) throws EntityNotFoundException + { + return studrepos.findById(id) + .orElseThrow(() -> new EntityNotFoundException(Long.toString(id))); + } + + @ApiOperation(value = "Retrieves a student by name", response=Student.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Student Found", response = Student.class), + @ApiResponse(code = 404, message = "Student Not Found", response = ErrorDetail.class) + }) + @Override + public List findStudentByNameLike(String name, Pageable pageable) + { + List list = new ArrayList<>(); + studrepos.findByStudnameContainingIgnoreCase(name, pageable).iterator().forEachRemaining(list::add); + return list; + } + + + @Override + public void delete(long id) throws EntityNotFoundException + { + if (studrepos.findById(id).isPresent()) + { + studrepos.deleteById(id); + } else + { + throw new EntityNotFoundException(Long.toString(id)); + } + } + + @Transactional + @Override + public Student save(Student student) + { + Student newStudent = new Student(); + + newStudent.setStudname(student.getStudname()); + + return studrepos.save(newStudent); + } + + @Override + public Student update(Student student, long id) + { + Student currentStudent = studrepos.findById(id) + .orElseThrow(() -> new EntityNotFoundException(Long.toString(id))); + + if (student.getStudname() != null) + { + currentStudent.setStudname(student.getStudname()); + } + + return studrepos.save(currentStudent); + } +} diff --git a/school/src/main/java/com/lambdaschool/school/service/UserAuditing.java b/school/src/main/java/com/lambdaschool/school/service/UserAuditing.java new file mode 100644 index 0000000..c64dbd2 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/UserAuditing.java @@ -0,0 +1,30 @@ +package com.lambdaschool.school.service; + +import org.springframework.data.domain.AuditorAware; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Component; + +import java.util.Optional; + +@Component +public class UserAuditing implements AuditorAware +{ + + @Override + public Optional getCurrentAuditor() + { + String uname; + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + if (authentication != null) + { + uname = authentication.getName(); + } + else + { + uname = "SYSTEM"; + } + return Optional.of(uname); + } + +} \ No newline at end of file diff --git a/school/src/main/java/com/lambdaschool/school/service/UserService.java b/school/src/main/java/com/lambdaschool/school/service/UserService.java new file mode 100644 index 0000000..529a327 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/UserService.java @@ -0,0 +1,18 @@ +package com.lambdaschool.school.service; + +import com.lambdaschool.school.model.User; + +import java.util.List; + +public interface UserService { + + List findAll(); + + User findUserById(long id); + + void delete(long id); + + User save(User user); + + User update(User user, long id); +} \ No newline at end of file diff --git a/school/src/main/java/com/lambdaschool/school/service/UserServiceImpl.java b/school/src/main/java/com/lambdaschool/school/service/UserServiceImpl.java new file mode 100644 index 0000000..1ad1a96 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/UserServiceImpl.java @@ -0,0 +1,134 @@ +package com.lambdaschool.school.service; + +import com.lambdaschool.school.model.User; +import com.lambdaschool.school.model.UserRoles; +import com.lambdaschool.school.repository.RoleRepository; +import com.lambdaschool.school.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.core.userdetails.UserDetails; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.core.userdetails.UsernameNotFoundException; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.persistence.EntityNotFoundException; +import java.util.ArrayList; +import java.util.List; + + +@Service(value = "userService") +public class UserServiceImpl implements UserDetailsService, UserService +{ + + @Autowired + private UserRepository userrepos; + + @Autowired + private RoleRepository rolerepos; + + @Transactional + public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException + { + User user = userrepos.findByUsername(username); + if (user == null) + { + throw new UsernameNotFoundException("Invalid username or password."); + } + return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getAuthority()); + } + + public User findUserById(long id) throws EntityNotFoundException + { + return userrepos.findById(id) + .orElseThrow(() -> new EntityNotFoundException(Long.toString(id))); + } + + public List findAll() + { + List list = new ArrayList<>(); + userrepos.findAll().iterator().forEachRemaining(list::add); + return list; + } + + @Override + public void delete(long id) + { + if (userrepos.findById(id).isPresent()) + { + userrepos.deleteById(id); + } + else + { + throw new EntityNotFoundException(Long.toString(id)); + } + } + + @Transactional + @Override + public User save(User user) + { + User newUser = new User(); + newUser.setUsername(user.getUsername()); + newUser.setPasswordNoEncrypt(user.getPassword()); + + ArrayList newRoles = new ArrayList<>(); + for (UserRoles ur : user.getUserRoles()) + { + newRoles.add(new UserRoles(newUser, ur.getRole())); + } + newUser.setUserRoles(newRoles); + + return userrepos.save(newUser); + } + + @Transactional + @Override + public User update(User user, long id) + { + Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); + User currentUser = userrepos.findByUsername(authentication.getName()); + + if (currentUser != null) + { + if (id == currentUser.getUserid()) + { + if (user.getUsername() != null) + { + currentUser.setUsername(user.getUsername()); + } + + if (user.getPassword() != null) + { + currentUser.setPasswordNoEncrypt(user.getPassword()); + } + + if (user.getUserRoles().size() > 0) + { + // with so many relationships happening, I decided to go + // with old school queries + // delete the old ones + rolerepos.deleteUserRolesByUserId(currentUser.getUserid()); + + // add the new ones + for (UserRoles ur : user.getUserRoles()) + { + rolerepos.insertUserRoles(id, ur.getRole().getRoleid()); + } + } + + return userrepos.save(currentUser); + } + else + { + throw new EntityNotFoundException(Long.toString(id) + " Not current user"); + } + } + else + { + throw new EntityNotFoundException(authentication.getName()); + } + + } +} diff --git a/school/src/main/java/com/lambdaschool/school/view/CountStudentsInCourses.java b/school/src/main/java/com/lambdaschool/school/view/CountStudentsInCourses.java new file mode 100644 index 0000000..c15e832 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/view/CountStudentsInCourses.java @@ -0,0 +1,8 @@ +package com.lambdaschool.school.view; + +public interface CountStudentsInCourses +{ + long getCourseid(); + String getCoursename(); + int getCountstudents(); +} diff --git a/school/src/main/resources/application.properties b/school/src/main/resources/application.properties new file mode 100644 index 0000000..ec46e75 --- /dev/null +++ b/school/src/main/resources/application.properties @@ -0,0 +1,24 @@ +server.port=${PORT:2019} + +#Feature that determines what happens when no accessors are found for a type +#(and there are no annotations to indicate it is meant to be serialized). +spring.jackson.serialization.FAIL_ON_EMPTY_BEANS=false + +#drop n create table again, good for testing, comment this in production +spring.jpa.hibernate.ddl-auto=create +spring.datasource.initialization-mode=always + +server.error.whitelabel.enabled=false + +## For h2 database +#spring.h2.console.enabled=true +#spring.h2.console.path=/h2-console + +spring.datasource.url=${SPRING_DATA_URL:jdbc:postgresql://ec2-23-21-156-171.compute-1.amazonaws.com:5432/dbhrhgcalo9orc?user=dkuclsxeyvkidq&password=8d8b44055419060abfc0ae51c17d3f244b15efba3dabc87d617c97b488a4916f&sslmode=require} +spring.datasource.username=dkuclsxeyvkidq +spring.datasource.password=8d8b44055419060abfc0ae51c17d3f244b15efba3dabc87d617c97b488a4916f +spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true + + + + diff --git a/school/src/main/resources/data.sql b/school/src/main/resources/data.sql new file mode 100644 index 0000000..f715596 --- /dev/null +++ b/school/src/main/resources/data.sql @@ -0,0 +1,49 @@ +DELETE +FROM studcourses; + +DELETE +FROM course; + +DELETE +FROM student; + +DELETE +FROM instructor; + +INSERT INTO instructor (instructid, instructname) + VALUES(1, 'Sally'), + (2, 'Lucy'), + (3, 'Charlie'); + +INSERT INTO course (courseid, coursename, instructid) + VALUES (1, 'Data Science', 1), + (2, 'JavaScript', 1), + (3, 'Node.js', 1), + (4, 'Java Back End', 2), + (5, 'Mobile IOS', 2), + (6, 'Mobile Android', 3); + +INSERT INTO student (studid, studname) + VALUES (1, 'John'), + (2, 'Julian'), + (3, 'Mary'), + (4, 'Julian'), + (5, 'Tyler'), + (6, 'Kim'), + (7, 'Juan'), + (8, 'Robby'), + (9, 'Roberto'), + (10, 'Bob'), + (11, 'Liz'), + (12, 'June'), + (13, 'April'); + +INSERT INTO studcourses (studid, courseid) + VALUES (1, 1), + (1, 4), + (2, 2), + (3, 3), + (3, 1), + (3, 6); + +alter sequence hibernate_sequence restart with 20; \ No newline at end of file diff --git a/school/src/main/resources/documentation/curl_reqs.txt b/school/src/main/resources/documentation/curl_reqs.txt new file mode 100644 index 0000000..c799191 --- /dev/null +++ b/school/src/main/resources/documentation/curl_reqs.txt @@ -0,0 +1,13 @@ +username - naught +password - password +access_token - 4fd1fa87-4632-4c79-a79e-df8841805ca5 + +1 - GET /courses/courses +curl -X GET -H "Accept: application/json" -H "Authorization: Bearer 4fd1fa87-4632-4c79-a79e-df8841805ca5" https://naught-school.herokuapp.com/courses/courses + +2 - GET /courses/studcount +curl -X GET -H "Accept: application/json" -H "Authorization: Bearer 4fd1fa87-4632-4c79-a79e-df8841805ca5" https://naught-school.herokuapp.com/courses/studcount + +3 - DELETE /courses/courses/{id} +curl -X DELETE -H "Authorization: Bearer 4fd1fa87-4632-4c79-a79e-df8841805ca5" http://naught-school.herokuapp.com/courses/courses/2 +