diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 7a4bc7f..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2019 Lambda, Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index aaaf939..0000000 --- a/README.md +++ /dev/null @@ -1,18 +0,0 @@ -# java-schooldeploy - -## Introduction - -## Instructions - -Start with your School Swagger and Pageable from Yesterday - -* Deploy the school application to Heroku using a PostgreSQL database -* Under Resources create a folder called documentation -* Under this documenation folder create a file called CURL.TXT - * In this file list a curl command for each endpoint in CourseController and in StudentController. - * Do test this command prior to putting it into the CURL.TXT document. -* After running curl - * Add user authentication using OAuth2 - * One role - user. A user and only a user can access any endpoint - * Anyone can access the swagger documentation - 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..9604f3a --- /dev/null +++ b/school/pom.xml @@ -0,0 +1,148 @@ + + + 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 + + + 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.springframework.boot + spring-boot-devtools + runtime + true + + + com.h2database + h2 + + + + 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 + + + org.postgresql + postgresql + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + com.heroku.sdk + heroku-maven-plugin + 2.0.3 + + jake-esveld-starthere + 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..be3f0f3 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/SchoolApplication.java @@ -0,0 +1,15 @@ +package com.lambdaschool.school; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class SchoolApplication +{ + + public static void main(String[] args) + { + SpringApplication.run(SchoolApplication.class, args); + } + +} 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..52f4351 --- /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) + .ignoredParameterTypes(Pageable.class) + .apiInfo(apiEndPointsInfo()); + } + + private ApiInfo apiEndPointsInfo() + { + return new ApiInfoBuilder().title("School") + .description("School Example") + .contact(new Contact("John Mitchell", "http://www.lambdaschool.com", "john@lambdaschool.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..6daf67e --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/controller/CourseController.java @@ -0,0 +1,39 @@ +package com.lambdaschool.school.controller; + +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 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(); + 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) + { + 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..824ff34 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/controller/StudentController.java @@ -0,0 +1,127 @@ +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.validation.Valid; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +@RestController +@RequestMapping("/students") +public class StudentController +{ + @Autowired + private StudentService studentService; + + @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 = "Return student with given Student ID", response = Student.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Successfully found student", response = Student.class), + @ApiResponse(code = 404, message = "Could not find student", response = ErrorDetail.class) + }) + @GetMapping(value = "/Student/{StudentId}", + produces = {"application/json"}) + public ResponseEntity getStudentById(@ApiParam(value = "Student ID", required = true, example = "1") + @PathVariable + Long StudentId) + { + Student r = studentService.findStudentById(StudentId); + return new ResponseEntity<>(r, HttpStatus.OK); + } + + @ApiOperation(value = "Return students with a name containing entry", response = Student.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Sucessfully found students in given parameters", response = Student.class, responseContainer = "List"), + @ApiResponse(code = 500, message = "An Error occurred while locating students", response = ErrorDetail.class) + }) + @GetMapping(value = "/student/namelike/{name}", + produces = {"application/json"}) + public ResponseEntity getStudentByNameContaining(@ApiParam(value = "Student name Substring", required = true, example = "Jo") + @PathVariable String name, @PageableDefault(page = 0, size = 5) Pageable pageable) + { + List myStudents = studentService.findStudentByNameLike(name, pageable); + return new ResponseEntity<>(myStudents, HttpStatus.OK); + } + + @ApiOperation(value = "Create a new student", notes = "URL for new student will be in location header", response = void.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Successfully created student", response = void.class), + @ApiResponse(code = 500, message = "Failed to create 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 = "Update a current student", response = void.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Successfully updated student", response = void.class), + @ApiResponse(code = 500, message = "Failed to update student", response = ErrorDetail.class) + }) + @PutMapping(value = "/Student/{Studentid}") + public ResponseEntity updateStudent( + @RequestBody + Student updateStudent, + @ApiParam(value = "Student ID", required = true, example = "1") + @PathVariable + long Studentid) + { + studentService.update(updateStudent, Studentid); + return new ResponseEntity<>(HttpStatus.OK); + } + + @ApiOperation(value = "Delete a current student", response = void.class) + @ApiResponses(value = { + @ApiResponse(code = 201, message = "Succesfully deleted student", response = void.class), + @ApiResponse(code = 500, message = "Failed to delete student", response = ErrorDetail.class) + }) + @DeleteMapping("/Student/{Studentid}") + public ResponseEntity deleteStudentById(@ApiParam(value = "Student ID", required = true) + @PathVariable + long Studentid) + { + studentService.delete(Studentid); + return new ResponseEntity<>(HttpStatus.OK); + } + +} 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..d041384 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/exception/ValidationError.java @@ -0,0 +1,26 @@ +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; + } +} \ No newline at end of file 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..3f6a245 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/Course.java @@ -0,0 +1,92 @@ +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 = "Course ID", value = "The Primary Key ID for the course", required = true, example = "1") + @Id + @GeneratedValue(strategy = GenerationType.AUTO) +// @JsonView(View.CoursesOnly.class) + private long courseid; + +// @JsonView(View.CoursesOnly.class) + @ApiModelProperty(name = "Course Name", value = "The name of the course", required = true, example = "Course 1") + private String coursename; + + @ApiModelProperty(name = "Course Instructor", value = "The Instructor for the course", required = true) + @ManyToOne + @JoinColumn(name = "instructid") + @JsonIgnoreProperties("courses") +// @JsonView(View.CoursesOnly.class) + private Instructor instructor; + + @ApiModelProperty(name = "Students", value = "The students in the course", required = true) + @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..f5f4ebb --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/ErrorDetail.java @@ -0,0 +1,79 @@ +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; + } +} \ No newline at end of file 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..d679f3b --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/Instructor.java @@ -0,0 +1,67 @@ +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 +@Entity +@Table(name = "instructor") +public class Instructor +{ + @ApiModelProperty(name = "Instructor ID", value = "The Primary key ID for the instructor", required = true, example = "1") + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long instructid; + + @ApiModelProperty(name = "Instructor Name", value = "The instructors name", required = true, example = "John Doe") + private String instructname; + + @ApiModelProperty(name = "Instructor Courses", value = "The Courses the instructor teaches", required = true) + @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/Student.java b/school/src/main/java/com/lambdaschool/school/model/Student.java new file mode 100644 index 0000000..efed18b --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/model/Student.java @@ -0,0 +1,71 @@ +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 +@Entity +@Table(name = "student") +public class Student +{ + @ApiModelProperty(name = "Student ID", value = "The primary key ID for the student", required = true, example = "1") + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + private long studid; + + @ApiModelProperty(name = "Student Name", value = "The name of the student", required = true, example = "Jane Doe") + private String studname; + + @ApiModelProperty(name = "Student Courses", value = "The courses assigned to the student") + @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/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/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/service/CourseService.java b/school/src/main/java/com/lambdaschool/school/service/CourseService.java new file mode 100644 index 0000000..965131b --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/CourseService.java @@ -0,0 +1,15 @@ +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(); + + void delete(long id); +} 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..11193b6 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/CourseServiceImpl.java @@ -0,0 +1,46 @@ +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 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)); + } + } +} 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/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..34b0d54 --- /dev/null +++ b/school/src/main/java/com/lambdaschool/school/service/StudentServiceImpl.java @@ -0,0 +1,81 @@ +package com.lambdaschool.school.service; + +import com.lambdaschool.school.model.Course; +import com.lambdaschool.school.model.Student; +import com.lambdaschool.school.repository.StudentRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +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; + + @Override + public List findAll(Pageable pageable) + { + List list = new ArrayList<>(); + studrepos.findAll().iterator().forEachRemaining(list::add); + return list; + } + + @Override + public Student findStudentById(long id) throws EntityNotFoundException + { + return studrepos.findById(id) + .orElseThrow(() -> new EntityNotFoundException(Long.toString(id))); + } + + @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/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..bfebfa3 --- /dev/null +++ b/school/src/main/resources/application.properties @@ -0,0 +1,19 @@ +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 + +spring.datasource.url=${SPRING_DATA_URL:jdbc:postgresql://ec2-75-101-147-226.compute-1.amazonaws.com:5432/da2i0dhvik809o?user=wcqucgxukgihfn&password=47bf42ae0031e47f0f4a1035a86d34591981619e819b7bd882c670ebf5b26907&sslmode=require} +spring.datasource.username=wcqucgxukgihfn +spring.datasource.password=47bf42ae0031e47f0f4a1035a86d34591981619e819b7bd882c670ebf5b26907 +spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true + +#drop n create table again, good for testing, comment this in production +spring.jpa.hibernate.ddl-auto=none +spring.datasource.initialization-mode=never + + + + + 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/test/java/com/lambdaschool/school/SchoolApplicationTests.java b/school/src/test/java/com/lambdaschool/school/SchoolApplicationTests.java new file mode 100644 index 0000000..63a43af --- /dev/null +++ b/school/src/test/java/com/lambdaschool/school/SchoolApplicationTests.java @@ -0,0 +1,18 @@ +package com.lambdaschool.school; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest +public class SchoolApplicationTests +{ + + @Test + public void contextLoads() + { + } + +}