diff --git a/.gitignore b/.gitignore index 1370f42..549e00a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,116 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ -# Created by https://www.toptal.com/developers/gitignore/api/eclipse,maven,java,code-java -# Edit at https://www.toptal.com/developers/gitignore?templates=eclipse,maven,java,code-java - -### Code-Java ### -# Language Support for Java(TM) by Red Hat extension for Visual Studio Code - https://marketplace.visualstudio.com/items?itemName=redhat.java - -.project +### STS ### +.apt_generated .classpath -factoryConfiguration.json - -### Eclipse ### -.metadata -bin/ -tmp/ -*.tmp -*.bak -*.swp -*~.nib -local.properties -.settings/ -.loadpath -.recommenders - -# External tool builders -.externalToolBuilders/ - -# Locally stored "Eclipse launch configurations" -*.launch - -# PyDev specific (Python IDE for Eclipse) -*.pydevproject - -# CDT-specific (C/C++ Development Tooling) -.cproject - -# CDT- autotools -.autotools - -# Java annotation processor (APT) .factorypath - -# PDT-specific (PHP Development Tools) -.buildpath - -# sbteclipse plugin -.target - -# Tern plugin -.tern-project - -# TeXlipse plugin -.texlipse - -# STS (Spring Tool Suite) +.project +.settings .springBeans - -# Code Recommenders -.recommenders/ - -# Annotation Processing -.apt_generated/ -.apt_generated_test/ - -# Scala IDE specific (Scala & Java development for Eclipse) -.cache-main -.scala_dependencies -.worksheet - -# Uncomment this line if you wish to ignore the project description file. -# Typically, this file would be tracked if it contains build/dependency configurations: -#.project - -### Eclipse Patch ### -# Spring Boot Tooling -.sts4-cache/ - -### Java ### -# Compiled class file -*.class - -# Log file -*.log - -# BlueJ files -*.ctxt - -# Mobile Tools for Java (J2ME) -.mtj.tmp/ - -# Package Files # -*.jar -*.war -*.nar -*.ear -*.zip -*.tar.gz -*.rar - -# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml -hs_err_pid* - -### Maven ### -target/ -pom.xml.tag -pom.xml.releaseBackup -pom.xml.versionsBackup -pom.xml.next -release.properties -dependency-reduced-pom.xml -buildNumber.properties -.mvn/timing.properties -# https://github.com/takari/maven-wrapper#usage-without-binary-jar -.mvn/wrapper/maven-wrapper.jar - -# End of https://www.toptal.com/developers/gitignore/api/eclipse,maven,java,code-java +.sts4-cache + +### IntelliJ IDEA ### +.idea +*.iws +*.iml +*.ipr + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ +build/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/.idea/.gitignore b/.idea/.gitignore deleted file mode 100644 index 13566b8..0000000 --- a/.idea/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml diff --git a/.idea/compiler.xml b/.idea/compiler.xml index e05cc19..b0a043f 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -2,21 +2,17 @@ - - + - - - \ No newline at end of file diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml deleted file mode 100644 index d9ebe70..0000000 --- a/.idea/dataSources.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - mysql.8 - true - com.mysql.cj.jdbc.Driver - jdbc:mysql://localhost:3306 - $ProjectFileDir$ - - - \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml index 41bd1a0..4258c62 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -8,5 +8,7 @@ - + + + \ No newline at end of file diff --git a/.idea/uiDesigner.xml b/.idea/uiDesigner.xml deleted file mode 100644 index 2b63946..0000000 --- a/.idea/uiDesigner.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml deleted file mode 100644 index 288b36b..0000000 --- a/.idea/vcs.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java deleted file mode 100644 index e76d1f3..0000000 --- a/.mvn/wrapper/MavenWrapperDownloader.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2007-present the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import java.net.*; -import java.io.*; -import java.nio.channels.*; -import java.util.Properties; - -public class MavenWrapperDownloader { - - private static final String WRAPPER_VERSION = "0.5.6"; - /** - * 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/" - + WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".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 directory '" + 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 { - if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) { - String username = System.getenv("MVNW_USERNAME"); - char[] password = System.getenv("MVNW_PASSWORD").toCharArray(); - Authenticator.setDefault(new Authenticator() { - @Override - protected PasswordAuthentication getPasswordAuthentication() { - return new PasswordAuthentication(username, password); - } - }); - } - 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/.mvn/wrapper/maven-wrapper.jar b/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 0000000..cb28b0e Binary files /dev/null and b/.mvn/wrapper/maven-wrapper.jar differ diff --git a/.mvn/wrapper/maven-wrapper.properties b/.mvn/wrapper/maven-wrapper.properties index ffdc10e..b27a13f 100644 --- a/.mvn/wrapper/maven-wrapper.properties +++ b/.mvn/wrapper/maven-wrapper.properties @@ -1,2 +1,2 @@ -distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.1/apache-maven-3.8.1-bin.zip -wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.2/apache-maven-3.9.2-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar diff --git a/README.md b/README.md deleted file mode 100644 index b7b6736..0000000 --- a/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# BackendWeb -* David Sánchez -* Orlando Figueroa -* Andrés Omaña - -Link wiki: -https://replit.com/@JuanPaez49/WikiProyectoWeb?s=app diff --git a/mvnw b/mvnw index a16b543..66df285 100755 --- a/mvnw +++ b/mvnw @@ -19,7 +19,7 @@ # ---------------------------------------------------------------------------- # ---------------------------------------------------------------------------- -# Maven Start Up Batch script +# Apache Maven Wrapper startup batch script, version 3.2.0 # # Required ENV vars: # ------------------ @@ -27,7 +27,6 @@ # # 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 @@ -36,6 +35,10 @@ if [ -z "$MAVEN_SKIP_RC" ] ; then + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + if [ -f /etc/mavenrc ] ; then . /etc/mavenrc fi @@ -50,7 +53,7 @@ fi cygwin=false; darwin=false; mingw=false -case "`uname`" in +case "$(uname)" in CYGWIN*) cygwin=true ;; MINGW*) mingw=true;; Darwin*) darwin=true @@ -58,9 +61,9 @@ case "`uname`" in # 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`" + JAVA_HOME="$(/usr/libexec/java_home)"; export JAVA_HOME else - export JAVA_HOME="/Library/Java/Home" + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME fi fi ;; @@ -68,68 +71,38 @@ esac if [ -z "$JAVA_HOME" ] ; then if [ -r /etc/gentoo-release ] ; then - JAVA_HOME=`java-config --jre-home` + 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"` + JAVA_HOME=$(cygpath --unix "$JAVA_HOME") [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --unix "$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)`" + [ -n "$JAVA_HOME" ] && [ -d "$JAVA_HOME" ] && + JAVA_HOME="$(cd "$JAVA_HOME" || (echo "cannot cd into $JAVA_HOME."; exit 1); pwd)" fi if [ -z "$JAVA_HOME" ]; then - javaExecutable="`which javac`" - if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + 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 + readLink=$(which readlink) + if [ ! "$(expr "$readLink" : '\([^ ]*\)')" = "no" ]; then if $darwin ; then - javaHome="`dirname \"$javaExecutable\"`" - javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + javaHome="$(dirname "\"$javaExecutable\"")" + javaExecutable="$(cd "\"$javaHome\"" && pwd -P)/javac" else - javaExecutable="`readlink -f \"$javaExecutable\"`" + javaExecutable="$(readlink -f "\"$javaExecutable\"")" fi - javaHome="`dirname \"$javaExecutable\"`" - javaHome=`expr "$javaHome" : '\(.*\)/bin'` + javaHome="$(dirname "\"$javaExecutable\"")" + javaHome=$(expr "$javaHome" : '\(.*\)/bin') JAVA_HOME="$javaHome" export JAVA_HOME fi @@ -145,7 +118,7 @@ if [ -z "$JAVACMD" ] ; then JAVACMD="$JAVA_HOME/bin/java" fi else - JAVACMD="`which java`" + JAVACMD="$(\unset -f command 2>/dev/null; \command -v java)" fi fi @@ -159,12 +132,9 @@ 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" @@ -180,96 +150,99 @@ find_maven_basedir() { fi # workaround for JBEAP-8937 (on Solaris 10/Sparc) if [ -d "${wdir}" ]; then - wdir=`cd "$wdir/.."; pwd` + wdir=$(cd "$wdir/.." || exit 1; pwd) fi # end of workaround done - echo "${basedir}" + printf '%s' "$(cd "$basedir" || exit 1; pwd)" } # concatenates all lines of a file concat_lines() { if [ -f "$1" ]; then - echo "$(tr -s '\n' ' ' < "$1")" + # Remove \r in case we run on Windows within Git Bash + # and check out the repository with auto CRLF management + # enabled. Otherwise, we may read lines that are delimited with + # \r\n and produce $'-Xarg\r' rather than -Xarg due to word + # splitting rules. + tr -s '\r\n' ' ' < "$1" + fi +} + +log() { + if [ "$MVNW_VERBOSE" = true ]; then + printf '%s\n' "$1" fi } -BASE_DIR=`find_maven_basedir "$(pwd)"` +BASE_DIR=$(find_maven_basedir "$(dirname "$0")") if [ -z "$BASE_DIR" ]; then exit 1; fi +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +log "$MAVEN_PROJECTBASEDIR" + ########################################################################################## # Extension to allow automatically downloading the maven-wrapper.jar from Maven-central # This allows using the maven wrapper in projects that prohibit checking in binary data. ########################################################################################## -if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found .mvn/wrapper/maven-wrapper.jar" - fi +wrapperJarPath="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" +if [ -r "$wrapperJarPath" ]; then + log "Found $wrapperJarPath" else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." - fi + log "Couldn't find $wrapperJarPath, downloading it ..." + if [ -n "$MVNW_REPOURL" ]; then - jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" else - jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" fi - while IFS="=" read key value; do - case "$key" in (wrapperUrl) jarUrl="$value"; break ;; + while IFS="=" read -r key value; do + # Remove '\r' from value to allow usage on windows as IFS does not consider '\r' as a separator ( considers space, tab, new line ('\n'), and custom '=' ) + safeValue=$(echo "$value" | tr -d '\r') + case "$key" in (wrapperUrl) wrapperUrl="$safeValue"; break ;; esac - done < "$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" + done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" + log "Downloading from: $wrapperUrl" + if $cygwin; then - wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + wrapperJarPath=$(cygpath --path --windows "$wrapperJarPath") fi if command -v wget > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found wget ... using wget" - fi + log "Found wget ... using wget" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--quiet" if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - wget "$jarUrl" -O "$wrapperJarPath" + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" else - wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" || rm -f "$wrapperJarPath" fi elif command -v curl > /dev/null; then - if [ "$MVNW_VERBOSE" = true ]; then - echo "Found curl ... using curl" - fi + log "Found curl ... using curl" + [ "$MVNW_VERBOSE" = true ] && QUIET="" || QUIET="--silent" if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then - curl -o "$wrapperJarPath" "$jarUrl" -f + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" else - curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L || rm -f "$wrapperJarPath" fi - else - if [ "$MVNW_VERBOSE" = true ]; then - echo "Falling back to using Java to download" - fi - javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + log "Falling back to using Java to download" + javaSource="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$MAVEN_PROJECTBASEDIR/.mvn/wrapper/MavenWrapperDownloader.class" # For Cygwin, switch paths to Windows format before running javac if $cygwin; then - javaClass=`cygpath --path --windows "$javaClass"` + javaSource=$(cygpath --path --windows "$javaSource") + javaClass=$(cygpath --path --windows "$javaClass") fi - 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") + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + log " - Compiling MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/javac" "$javaSource") 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") + if [ -e "$javaClass" ]; then + log " - Running MavenWrapperDownloader.java ..." + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$wrapperUrl" "$wrapperJarPath") || rm -f "$wrapperJarPath" fi fi fi @@ -278,33 +251,58 @@ fi # End of extension ########################################################################################## -export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} -if [ "$MVNW_VERBOSE" = true ]; then - echo $MAVEN_PROJECTBASEDIR +# If specified, validate the SHA-256 sum of the Maven wrapper jar file +wrapperSha256Sum="" +while IFS="=" read -r key value; do + case "$key" in (wrapperSha256Sum) wrapperSha256Sum=$value; break ;; + esac +done < "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.properties" +if [ -n "$wrapperSha256Sum" ]; then + wrapperSha256Result=false + if command -v sha256sum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | sha256sum -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + elif command -v shasum > /dev/null; then + if echo "$wrapperSha256Sum $wrapperJarPath" | shasum -a 256 -c > /dev/null 2>&1; then + wrapperSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." + echo "Please install either command, or disable validation by removing 'wrapperSha256Sum' from your maven-wrapper.properties." + exit 1 + fi + if [ $wrapperSha256Result = false ]; then + echo "Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised." >&2 + echo "Investigate or delete $wrapperJarPath to attempt a clean download." >&2 + echo "If you updated your Maven version, you need to update the specified wrapperSha256Sum property." >&2 + exit 1 + fi fi + MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" # For Cygwin, switch paths to Windows format before running java if $cygwin; then - [ -n "$M2_HOME" ] && - M2_HOME=`cygpath --path --windows "$M2_HOME"` [ -n "$JAVA_HOME" ] && - JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + JAVA_HOME=$(cygpath --path --windows "$JAVA_HOME") [ -n "$CLASSPATH" ] && - CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + CLASSPATH=$(cygpath --path --windows "$CLASSPATH") [ -n "$MAVEN_PROJECTBASEDIR" ] && - MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` + MAVEN_PROJECTBASEDIR=$(cygpath --path --windows "$MAVEN_PROJECTBASEDIR") fi # Provide a "standardized" way to retrieve the CLI args that will # work with both Windows and non-Windows executions. -MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $*" export MAVEN_CMD_LINE_ARGS WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain +# shellcheck disable=SC2086 # safe args exec "$JAVACMD" \ $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ - "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/mvnw.cmd b/mvnw.cmd index c8d4337..95ba6f5 100644 --- a/mvnw.cmd +++ b/mvnw.cmd @@ -18,13 +18,12 @@ @REM ---------------------------------------------------------------------------- @REM ---------------------------------------------------------------------------- -@REM Maven Start Up Batch script +@REM Apache Maven Wrapper startup batch script, version 3.2.0 @REM @REM Required ENV vars: @REM JAVA_HOME - location of a JDK home dir @REM @REM Optional ENV vars -@REM 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 keystroke before ending @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven @@ -46,8 +45,8 @@ 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" +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* :skipRcPre @setlocal @@ -120,10 +119,10 @@ 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.5.6/maven-wrapper-0.5.6.jar" +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" -FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( - IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B ) @REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central @@ -134,11 +133,11 @@ if exist %WRAPPER_JAR% ( ) ) else ( if not "%MVNW_REPOURL%" == "" ( - SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.2.0/maven-wrapper-3.2.0.jar" ) if "%MVNW_VERBOSE%" == "true" ( echo Couldn't find %WRAPPER_JAR%, downloading it ... - echo Downloading from: %DOWNLOAD_URL% + echo Downloading from: %WRAPPER_URL% ) powershell -Command "&{"^ @@ -146,7 +145,7 @@ if exist %WRAPPER_JAR% ( "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ "}"^ - "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ "}" if "%MVNW_VERBOSE%" == "true" ( echo Finished downloading %WRAPPER_JAR% @@ -154,11 +153,35 @@ if exist %WRAPPER_JAR% ( ) @REM End of extension +@REM If specified, validate the SHA-256 sum of the Maven wrapper jar file +SET WRAPPER_SHA_256_SUM="" +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperSha256Sum" SET WRAPPER_SHA_256_SUM=%%B +) +IF NOT %WRAPPER_SHA_256_SUM%=="" ( + powershell -Command "&{"^ + "$hash = (Get-FileHash \"%WRAPPER_JAR%\" -Algorithm SHA256).Hash.ToLower();"^ + "If('%WRAPPER_SHA_256_SUM%' -ne $hash){"^ + " Write-Output 'Error: Failed to validate Maven wrapper SHA-256, your Maven wrapper might be compromised.';"^ + " Write-Output 'Investigate or delete %WRAPPER_JAR% to attempt a clean download.';"^ + " Write-Output 'If you updated your Maven version, you need to update the specified wrapperSha256Sum property.';"^ + " exit 1;"^ + "}"^ + "}" + if ERRORLEVEL 1 goto error +) + @REM Provide a "standardized" way to retrieve the CLI args that will @REM work with both Windows and non-Windows executions. set MAVEN_CMD_LINE_ARGS=%* -%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +%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 @@ -168,15 +191,15 @@ set ERROR_CODE=1 :end @endlocal & set ERROR_CODE=%ERROR_CODE% -if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +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" +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" :skipRcPost @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' -if "%MAVEN_BATCH_PAUSE%" == "on" pause +if "%MAVEN_BATCH_PAUSE%"=="on" pause -if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% -exit /B %ERROR_CODE% +cmd /C exit /B %ERROR_CODE% diff --git a/pom.xml b/pom.xml index f49e51e..a15ba4f 100644 --- a/pom.xml +++ b/pom.xml @@ -1,18 +1,17 @@ - 4.0.0 org.springframework.boot spring-boot-starter-parent - 2.5.3 - + 3.1.0 + com.example - BackendWeb2 + demo 0.0.1-SNAPSHOT - ob-spring-security-jwt + demo Demo project for Spring Boot 17 @@ -27,49 +26,21 @@ spring-boot-starter-web - - org.springframework.boot - spring-boot-devtools - runtime - true - com.mysql mysql-connector-j - 8.0.32 - - - org.springframework.boot - spring-boot-starter-test - test + runtime - io.springfox - springfox-boot-starter - 3.0.0 + org.projectlombok + lombok + true - - - - org.projectlombok - lombok - true - org.springframework.boot - spring-boot-starter-security - - - org.springframework.security - spring-security-test + spring-boot-starter-test test - - io.jsonwebtoken - jjwt - 0.9.1 - - @@ -77,6 +48,14 @@ org.springframework.boot spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + diff --git a/src/main/java/com/example/demo/SpringBootApp.java b/src/main/java/com/example/demo/DemoApplication.java similarity index 67% rename from src/main/java/com/example/demo/SpringBootApp.java rename to src/main/java/com/example/demo/DemoApplication.java index 8fd49ee..64b538a 100644 --- a/src/main/java/com/example/demo/SpringBootApp.java +++ b/src/main/java/com/example/demo/DemoApplication.java @@ -4,11 +4,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication -public class SpringBootApp { +public class DemoApplication { public static void main(String[] args) { - // contenedor de beans - SpringApplication.run(SpringBootApp.class, args); + SpringApplication.run(DemoApplication.class, args); } } diff --git a/src/main/java/com/example/demo/domain/Equipo.java b/src/main/java/com/example/demo/domain/Equipo.java deleted file mode 100644 index 7aa2f72..0000000 --- a/src/main/java/com/example/demo/domain/Equipo.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.example.demo.domain; - -import java.util.HashSet; -import java.util.Set; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import org.hibernate.annotations.SQLDelete; - -import lombok.Singular; -import org.hibernate.annotations.Where; - -import javax.persistence.*; - -@Data -@Builder -@AllArgsConstructor -@Entity -@Table(name = "equipo") -public class Equipo { - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private int id; - private String nombreEquipo; - private String siglas; - private boolean eliminado= Boolean.FALSE; - - @ManyToMany(mappedBy = "equipos_participe", cascade = CascadeType.REMOVE) - private Set jugadores_en_equipo; - - @OneToMany(mappedBy = "equipo", cascade = CascadeType.REMOVE) - private Set solicitudes_de_jugadores; - - @OneToMany(mappedBy = "equipo", cascade = CascadeType.REMOVE) - private Set invitaciones_a_jugadores; - public Equipo() { - this.jugadores_en_equipo = new HashSet<>(); - } - -} diff --git a/src/main/java/com/example/demo/domain/Invitacion.java b/src/main/java/com/example/demo/domain/Invitacion.java deleted file mode 100644 index 316990b..0000000 --- a/src/main/java/com/example/demo/domain/Invitacion.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.example.demo.domain; - -import lombok.Data; - -import javax.persistence.*; - -@Data -@Entity -@Table(name ="invitacion", uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id", "team_id"})}) -public class Invitacion { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - Long id; - Boolean aceptada; - - - @ManyToOne() - @JoinColumn(name="user_id",nullable=false,referencedColumnName="id") - Usuario usuario; - - @ManyToOne() - @JoinColumn(name="team_id") - Equipo equipo; -} diff --git a/src/main/java/com/example/demo/domain/Libro.java b/src/main/java/com/example/demo/domain/Libro.java new file mode 100644 index 0000000..b4c230f --- /dev/null +++ b/src/main/java/com/example/demo/domain/Libro.java @@ -0,0 +1,22 @@ +package com.example.demo.domain; +import jakarta.persistence.*; +import lombok.*; + +@Getter +@Setter +@Builder +@AllArgsConstructor +@NoArgsConstructor +@Entity +@Table(name = "libro_lealsa") + +public class libro { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + private String titulo; + private String referencia; + private String autor; + private double precio; + private String ubicacion; +} diff --git a/src/main/java/com/example/demo/domain/Solicitud.java b/src/main/java/com/example/demo/domain/Solicitud.java deleted file mode 100644 index 02a4054..0000000 --- a/src/main/java/com/example/demo/domain/Solicitud.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.example.demo.domain; - - -import lombok.Data; - -import javax.persistence.*; - -@Data -@Entity -@Table(name ="solicitud", uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id", "team_id"})}) -public class Solicitud { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - Long id; - Boolean aceptada; - - @ManyToOne - @JoinColumn(name="user_id",nullable = false,referencedColumnName="id") - Usuario usuario; - - @ManyToOne() - @JoinColumn(name = "team_id") - Equipo equipo; -} diff --git a/src/main/java/com/example/demo/domain/Usuario.java b/src/main/java/com/example/demo/domain/Usuario.java deleted file mode 100644 index 5b241c4..0000000 --- a/src/main/java/com/example/demo/domain/Usuario.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.example.demo.domain; - -import java.util.Set; -import lombok.Data; - -import javax.persistence.*; - - -@Data -@Entity -@Table(name = "usuario") -public class Usuario { - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - private long id; - private String username; - private String email; - private String password; - public Usuario(String username, String email, String password) { - this.username = username; - this.email = email; - this.password = password; - } - @ManyToMany(cascade = CascadeType.REMOVE) - @JoinTable( - name = "jugadores_en_equipo", - joinColumns = @JoinColumn(name = "usuario_id"), - inverseJoinColumns = @JoinColumn(name = "equipo_id") - ) - private Set equipos_participe; - - @OneToMany(mappedBy = "usuario",cascade= CascadeType.REMOVE) - private Set invitaciones_de_equipos; - - @OneToMany(mappedBy = "usuario",cascade = CascadeType.REMOVE) - private Set solicitudes_a_equipos; - - public Usuario() { - - } -} - diff --git a/src/main/java/com/example/demo/dto/CountDTO.java b/src/main/java/com/example/demo/dto/CountDTO.java deleted file mode 100644 index dcbba8a..0000000 --- a/src/main/java/com/example/demo/dto/CountDTO.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.example.demo.dto; - -/** - * Data transfer Object - */ -public class CountDTO { - - private Long count; - private String message; - - public CountDTO() { - } - - public CountDTO(Long count) { - this.count = count; - } - - public Long getCount() { - return count; - } - - public void setCount(Long count) { - this.count = count; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - - -} diff --git a/src/main/java/com/example/demo/dto/EquipoListDTO.java b/src/main/java/com/example/demo/dto/EquipoListDTO.java deleted file mode 100644 index 8894ec2..0000000 --- a/src/main/java/com/example/demo/dto/EquipoListDTO.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.example.demo.dto; - -import com.example.demo.domain.Equipo; - -import java.util.List; - -public class EquipoListDTO { - - private List equipos; - - public EquipoListDTO() {} - - public List getCars() { - return equipos; - } - - public void setCars(List cars) { - this.equipos = cars; - } - -} diff --git a/src/main/java/com/example/demo/dto/MessageDTO.java b/src/main/java/com/example/demo/dto/MessageDTO.java deleted file mode 100644 index f5d1d03..0000000 --- a/src/main/java/com/example/demo/dto/MessageDTO.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.example.demo.dto; - -public class MessageDTO { - - private String message; - - public MessageDTO() { - - } - - public MessageDTO(String message) { - this.message = message; - } - - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } - - - -} diff --git a/src/main/java/com/example/demo/repository/EquipoRepository.java b/src/main/java/com/example/demo/repository/EquipoRepository.java deleted file mode 100644 index 98307a8..0000000 --- a/src/main/java/com/example/demo/repository/EquipoRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.example.demo.repository; - - -import com.example.demo.domain.Equipo; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface EquipoRepository extends JpaRepository { -} diff --git a/src/main/java/com/example/demo/repository/InvitacionRepository.java b/src/main/java/com/example/demo/repository/InvitacionRepository.java deleted file mode 100644 index aa65d1a..0000000 --- a/src/main/java/com/example/demo/repository/InvitacionRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.example.demo.repository; - -import com.example.demo.domain.Invitacion; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface InvitacionRepository extends JpaRepository{ - -} diff --git a/src/main/java/com/example/demo/repository/SolicitudRepository.java b/src/main/java/com/example/demo/repository/SolicitudRepository.java deleted file mode 100644 index d5498b2..0000000 --- a/src/main/java/com/example/demo/repository/SolicitudRepository.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.example.demo.repository; - -import com.example.demo.domain.Solicitud; -import org.springframework.data.jpa.repository.JpaRepository; - -public interface SolicitudRepository extends JpaRepository{ - -} diff --git a/src/main/java/com/example/demo/repository/UsuarioRepository.java b/src/main/java/com/example/demo/repository/UsuarioRepository.java deleted file mode 100644 index 1446115..0000000 --- a/src/main/java/com/example/demo/repository/UsuarioRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.example.demo.repository; - -import com.example.demo.domain.Usuario; -import org.springframework.data.jpa.repository.JpaRepository; - -import java.util.Optional; - -public interface UsuarioRepository extends JpaRepository{ - Optional findByUsername(String username); - - Boolean existsByUsername(String username); - - Boolean existsByEmail(String email); -} diff --git a/src/main/java/com/example/demo/repository/libroRepository.java b/src/main/java/com/example/demo/repository/libroRepository.java new file mode 100644 index 0000000..b15970a --- /dev/null +++ b/src/main/java/com/example/demo/repository/libroRepository.java @@ -0,0 +1,7 @@ +package com.example.demo.repository; + +import com.example.demo.domain.libro; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface libroRepository extends JpaRepository { +} diff --git a/src/main/java/com/example/demo/rest/AuthController.java b/src/main/java/com/example/demo/rest/AuthController.java deleted file mode 100644 index f92de25..0000000 --- a/src/main/java/com/example/demo/rest/AuthController.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.example.demo.rest; - -import com.example.demo.domain.Usuario; -import com.example.demo.repository.UsuarioRepository; -import com.example.demo.security.jwt.JwtTokenUtil; -import com.example.demo.security.payload.JwtResponse; -import com.example.demo.security.payload.LoginRequest; -import com.example.demo.security.payload.MessageResponse; -import com.example.demo.security.payload.RegisterRequest; -import org.springframework.http.ResponseEntity; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * Controlador para llevar a cabo la autenticación utilizando JWT - * - * Se utiliza AuthenticationManager para autenticar las credenciales que son el - * usuario y password que llegan por POST en el cuerpo de la petición - * - * Si las credenciales son válidas se genera un token JWT como respuesta - */ -// @CrossOrigin(origins = "http://localhost:8081") -@RestController -@RequestMapping("/api/auth") -public class AuthController { - - private final AuthenticationManager authManager; - private final UsuarioRepository userRepository; - private final PasswordEncoder encoder; - private final JwtTokenUtil jwtTokenUtil; - - public AuthController(AuthenticationManager authManager, - UsuarioRepository usuarioRepository, - PasswordEncoder encoder, - JwtTokenUtil jwtTokenUtil){ - this.authManager = authManager; - this.userRepository = usuarioRepository; - this.encoder = encoder; - this.jwtTokenUtil = jwtTokenUtil; - } - - @PostMapping("/login") - public ResponseEntity login(@RequestBody LoginRequest loginRequest){ - - Authentication authentication = authManager.authenticate( - new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); - - SecurityContextHolder.getContext().setAuthentication(authentication); - String jwt = jwtTokenUtil.generateJwtToken(authentication); - - // UserDetails userDetails = (UserDetails) authentication.getPrincipal(); - - return ResponseEntity.ok(new JwtResponse(jwt)); - } - - @PostMapping("/register") - public ResponseEntity register(@RequestBody RegisterRequest signUpRequest) { - - // Check 1: username - if (userRepository.existsByUsername(signUpRequest.getUsername())) { - return ResponseEntity - .badRequest() - .body(new MessageResponse("Error: Username is already taken!")); - } - - // Check 2: email - if (userRepository.existsByEmail(signUpRequest.getEmail())) { - return ResponseEntity - .badRequest() - .body(new MessageResponse("Error: Email is already in use!")); - } - - // Create new user's account - Usuario user = new Usuario(signUpRequest.getUsername(), - signUpRequest.getEmail(), - encoder.encode(signUpRequest.getPassword())); - - userRepository.save(user); - - return ResponseEntity.ok(new MessageResponse("User registered successfully!")); - } -} diff --git a/src/main/java/com/example/demo/rest/EquipoController.java b/src/main/java/com/example/demo/rest/EquipoController.java deleted file mode 100644 index 20c85e2..0000000 --- a/src/main/java/com/example/demo/rest/EquipoController.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.example.demo.rest; - - -import com.example.demo.domain.Equipo; -import com.example.demo.repository.EquipoRepository; -import com.example.demo.service.EquipoService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import java.util.List; - -@RestController -@RequestMapping("/api") -public class EquipoController { - @Autowired - EquipoRepository equipoRepository; - @Autowired - EquipoService equipoService; - @GetMapping("/equipos") - public List findAll() { - return equipoRepository.findAll(); - } - @GetMapping("/equipos/{id}") - public ResponseEntity obtenerEquipo(@PathVariable Long id) { - Equipo equipo = equipoService.findById(id); - if (equipo == null) { - return ResponseEntity.notFound().build(); - } - System.out.println(equipo.getSolicitudes_de_jugadores().toString()); - return ResponseEntity.ok(equipo); - } - -} diff --git a/src/main/java/com/example/demo/rest/InvitacionController.java b/src/main/java/com/example/demo/rest/InvitacionController.java deleted file mode 100644 index 3a37224..0000000 --- a/src/main/java/com/example/demo/rest/InvitacionController.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.example.demo.rest; - - -import com.example.demo.domain.Invitacion; -import com.example.demo.service.InvitacionService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; - -import java.util.List; - -@RestController -@RequestMapping("/invitacion") -public class InvitacionController { - @Autowired - private InvitacionService invitacionService; - - @PostMapping("/agregar/{equipoId}/{usuarioId}") - public void crearInvitacion(@PathVariable Long equipoId, @PathVariable Long usuarioId) { - invitacionService.crearInvitacion(equipoId, usuarioId); - } - @GetMapping("/invitaciones") - public ResponseEntity> obtenerTodasLasInvitaciones() { - List invitaciones = (List) invitacionService.findAll(); - return ResponseEntity.ok().body(invitaciones); - } -} diff --git a/src/main/java/com/example/demo/rest/libroController.java b/src/main/java/com/example/demo/rest/libroController.java new file mode 100644 index 0000000..e955b5a --- /dev/null +++ b/src/main/java/com/example/demo/rest/libroController.java @@ -0,0 +1,26 @@ +package com.example.demo.rest; + +import com.example.demo.domain.libro; +import com.example.demo.services.libroService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +@RestController +@RequestMapping("/libros") +public class libroController { + + @Autowired + private libroService libroService; + + @PostMapping("/anadir") + public void crearlibro(@RequestBody libro libro){ + libroService.ingresarLibro(libro); + } + + @GetMapping("/lista") + public List obtenerlibros(){ + return libroService.obtenerLibros(); + } +} diff --git a/src/main/java/com/example/demo/security/config/SecurityConfig.java b/src/main/java/com/example/demo/security/config/SecurityConfig.java deleted file mode 100644 index 2e72e4c..0000000 --- a/src/main/java/com/example/demo/security/config/SecurityConfig.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.example.demo.security.config; - -import com.example.demo.security.jwt.JwtAuthEntryPoint; -import com.example.demo.security.jwt.JwtRequestFilter; -import com.example.demo.security.service.UserDetailsServiceImpl; -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.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.CorsConfigurationSource; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; - -import java.util.List; - -/** - * Clase para la configuración de seguridad Spring Security - */ -@Configuration -@EnableWebSecurity // permite a Spring aplicar esta configuracion a la configuraicon de seguridad global -public class SecurityConfig extends WebSecurityConfigurerAdapter { - - @Autowired - private UserDetailsServiceImpl userDetailsService; - - @Autowired - private JwtAuthEntryPoint unauthorizedHandler; - - // ================ CREACIÓN DE BEANS ====================== - @Bean - public JwtRequestFilter authenticationJwtTokenFilter() { - return new JwtRequestFilter(); - } - - @Bean - @Override - public AuthenticationManager authenticationManagerBean() throws Exception { - return super.authenticationManagerBean(); - } - - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } - - /** - * Configuracion global de CORS para toda la aplicacion - */ - @Bean - CorsConfigurationSource corsConfigurationSource() - { - CorsConfiguration configuration = new CorsConfiguration(); - // configuration.setAllowedOrigins(List.of("http://localhost:4200", "https://angular-springboot-*.vercel.app")); - configuration.setAllowedOriginPatterns(List.of("http://localhost:4200", "https://angular-springboot1-beta.vercel.app")); - configuration.setAllowedMethods(List.of("GET", "POST", "OPTIONS", "DELETE", "PUT", "PATCH")); - configuration.setAllowedHeaders(List.of("Access-Control-Allow-Origin", "X-Requested-With", "Origin", "Content-Type", "Accept", "Authorization")); - configuration.setAllowCredentials(true); - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - source.registerCorsConfiguration("/**", configuration); - return source; - } - - // ========================= OVERRIDE: SOBREESCRIBIR FUNCIONALIDAD SECURITY POR DEFECTO ====== - @Override - public void configure(AuthenticationManagerBuilder auth) throws Exception { - auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); - } - - @Override - protected void configure(HttpSecurity http) throws Exception { - // Cross-Site Request Forgery CSRF - // CORS (Cross-origin resource sharing) - http.cors().and().csrf().disable() - .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() - .authorizeRequests().antMatchers("/api/auth/**").permitAll() - .antMatchers("/v2/api-docs", "/configuration/**", "/swagger*/**", "/webjars/**").permitAll() - .antMatchers("/api/hello/**").permitAll() - .antMatchers("/").permitAll() - .anyRequest().authenticated(); - - http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); - } - -} diff --git a/src/main/java/com/example/demo/security/jwt/JwtAuthEntryPoint.java b/src/main/java/com/example/demo/security/jwt/JwtAuthEntryPoint.java deleted file mode 100644 index 31b48ef..0000000 --- a/src/main/java/com/example/demo/security/jwt/JwtAuthEntryPoint.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.example.demo.security.jwt; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.security.core.AuthenticationException; -import org.springframework.security.web.AuthenticationEntryPoint; -import org.springframework.stereotype.Component; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * Rechaza peticiones no autenticadas devolviendo - * un código de error 401 unauthorized - */ -@Component -public class JwtAuthEntryPoint implements AuthenticationEntryPoint { - - private static final Logger log = LoggerFactory.getLogger(JwtAuthEntryPoint.class); - - @Override - public void commence(HttpServletRequest httpServletRequest, - HttpServletResponse httpServletResponse, - AuthenticationException e) throws IOException, ServletException { - log.error("Unauthorized error: {}", e.getMessage()); - httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Error: Unauthorized"); - } -} diff --git a/src/main/java/com/example/demo/security/jwt/JwtRequestFilter.java b/src/main/java/com/example/demo/security/jwt/JwtRequestFilter.java deleted file mode 100644 index 057a3ac..0000000 --- a/src/main/java/com/example/demo/security/jwt/JwtRequestFilter.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.example.demo.security.jwt; - -import com.example.demo.security.service.UserDetailsServiceImpl; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.security.web.authentication.WebAuthenticationDetailsSource; -import org.springframework.util.StringUtils; -import org.springframework.web.filter.OncePerRequestFilter; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; - -/** - * Filters incoming requests and installs a Spring Security principal if a header corresponding to a valid user is - * found. - * Se ejecuta por cada petición entrante con el fin de validar el token JWT - * en caso de que lo sea se añade al contexto para indicar que un usuario está autenticado - */ -public class JwtRequestFilter extends OncePerRequestFilter { - - private static final Logger logger = LoggerFactory.getLogger(JwtRequestFilter.class); - public static final String BEARER = "Bearer "; - - @Autowired - private JwtTokenUtil jwtTokenUtil; - - @Autowired - private UserDetailsServiceImpl userDetailsService; - - /** - * Same contract as for {@code doFilter}, but guaranteed to be - * just invoked once per request within a single request thread. - * See {@link #shouldNotFilterAsyncDispatch()} for details. - *

Provides HttpServletRequest and HttpServletResponse arguments instead of the - * default ServletRequest and ServletResponse ones. - * - * @param request - * @param response - * @param filterChain - */ - @Override - protected void doFilterInternal(HttpServletRequest request, - HttpServletResponse response, - FilterChain filterChain) throws ServletException, IOException { - try { - String jwt = parseJwt(request); - if (jwt != null && jwtTokenUtil.validateJwtToken(jwt)) { - String username = jwtTokenUtil.getUserNameFromJwtToken(jwt); - - UserDetails userDetails = userDetailsService.loadUserByUsername(username); - UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken( - userDetails, null, userDetails.getAuthorities()); - authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); - - SecurityContextHolder.getContext().setAuthentication(authentication); - } - } catch (Exception e) { - logger.error("Cannot set user authentication: {}", e); - } - - filterChain.doFilter(request, response); - } - - /** - * A partir de una cabecera Authorization extrae el token - * @param request - * @return - */ - private String parseJwt(HttpServletRequest request) { - String headerAuth = request.getHeader("Authorization"); - - if (StringUtils.hasText(headerAuth) && headerAuth.startsWith(BEARER)) - return headerAuth.substring(BEARER.length()); - - return null; - } - -} diff --git a/src/main/java/com/example/demo/security/jwt/JwtTokenUtil.java b/src/main/java/com/example/demo/security/jwt/JwtTokenUtil.java deleted file mode 100644 index 598d11a..0000000 --- a/src/main/java/com/example/demo/security/jwt/JwtTokenUtil.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.example.demo.security.jwt; - -import io.jsonwebtoken.*; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.userdetails.UserDetails; -import org.springframework.stereotype.Component; - -import java.util.Date; - -/** - * Métodos para generar y validar los token JWT - */ -@Component -public class JwtTokenUtil { - - private static final Logger log = LoggerFactory.getLogger(JwtTokenUtil.class); - - @Value("${app.jwt.secret}") - private String jwtSecret; - - @Value("${app.jwt.expiration-ms}") - private int jwtExpirationMs; - - public String generateJwtToken(Authentication authentication) { - - UserDetails userPrincipal = (UserDetails) authentication.getPrincipal(); - - return Jwts.builder() - .setSubject((userPrincipal.getUsername())) - .setIssuedAt(new Date()) - .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs)) - .signWith(SignatureAlgorithm.HS512, jwtSecret) - .compact(); - } - - public String getUserNameFromJwtToken(String token) { - return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject(); - } - - public boolean validateJwtToken(String authToken) { - try { - Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken); - return true; - } catch (SignatureException e) { - log.error("Invalid JWT signature: {}", e.getMessage()); - } catch (MalformedJwtException e) { - log.error("Invalid JWT token: {}", e.getMessage()); - } catch (ExpiredJwtException e) { - log.error("JWT token is expired: {}", e.getMessage()); - } catch (UnsupportedJwtException e) { - log.error("JWT token is unsupported: {}", e.getMessage()); - } catch (IllegalArgumentException e) { - log.error("JWT claims string is empty: {}", e.getMessage()); - } - - return false; - } -} - diff --git a/src/main/java/com/example/demo/security/payload/JwtResponse.java b/src/main/java/com/example/demo/security/payload/JwtResponse.java deleted file mode 100644 index 74c3948..0000000 --- a/src/main/java/com/example/demo/security/payload/JwtResponse.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.example.demo.security.payload; - -public class JwtResponse { - - private String token; - - public JwtResponse() { - } - public JwtResponse(String token) { - this.token = token; - } - - public String getToken() { - return token; - } - - public void setToken(String token) { - this.token = token; - } - -} - diff --git a/src/main/java/com/example/demo/security/payload/LoginRequest.java b/src/main/java/com/example/demo/security/payload/LoginRequest.java deleted file mode 100644 index f1bed9b..0000000 --- a/src/main/java/com/example/demo/security/payload/LoginRequest.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.example.demo.security.payload; - -public class LoginRequest { - - private String username; - private String password; - - public LoginRequest() { - } - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} diff --git a/src/main/java/com/example/demo/security/payload/MessageResponse.java b/src/main/java/com/example/demo/security/payload/MessageResponse.java deleted file mode 100644 index c43de5f..0000000 --- a/src/main/java/com/example/demo/security/payload/MessageResponse.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.example.demo.security.payload; - -public class MessageResponse { - - private String message; - - public MessageResponse(String message) { - this.message = message; - } - - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} diff --git a/src/main/java/com/example/demo/security/payload/RegisterRequest.java b/src/main/java/com/example/demo/security/payload/RegisterRequest.java deleted file mode 100644 index 2fcf17d..0000000 --- a/src/main/java/com/example/demo/security/payload/RegisterRequest.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.example.demo.security.payload; - -public class RegisterRequest { - - private String username; - private String email; - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } -} diff --git a/src/main/java/com/example/demo/security/service/UserDetailsServiceImpl.java b/src/main/java/com/example/demo/security/service/UserDetailsServiceImpl.java deleted file mode 100644 index 32d761f..0000000 --- a/src/main/java/com/example/demo/security/service/UserDetailsServiceImpl.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.example.demo.security.service; - -import com.example.demo.repository.UsuarioRepository; -import org.springframework.beans.factory.annotation.Autowired; -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 java.util.ArrayList; - -/** - * Autentica un usuario de la base de datos - * - * Authentication Manager llama al método loadUserByUsername de esta clase - * para obtener los detalles del usuario de la base de datos cuando - * se intente autenticar un usuario - */ -@Service -public class UserDetailsServiceImpl implements UserDetailsService { - - @Autowired - private UsuarioRepository userRepository; - - @Override - public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { - com.example.demo.domain.Usuario user = userRepository.findByUsername(username) - .orElseThrow(() -> new UsernameNotFoundException("User Not Found with username: " + username)); - - return new org.springframework.security.core.userdetails.User( - user.getUsername() ,user.getPassword(),new ArrayList<>()); - } -} diff --git a/src/main/java/com/example/demo/service/EquipoService.java b/src/main/java/com/example/demo/service/EquipoService.java deleted file mode 100644 index 52b4eaf..0000000 --- a/src/main/java/com/example/demo/service/EquipoService.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.example.demo.service; - - -import com.example.demo.domain.Equipo; -import com.example.demo.domain.Invitacion; -import com.example.demo.repository.EquipoRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.Optional; - -@Service -public class EquipoService { - - @Autowired - private EquipoRepository equipoRepository; - - public Equipo create(Equipo equipo) { - return equipoRepository.save(equipo); - } - - public void remove(Long id){ - Optional equipoOptional = equipoRepository.findById(id); - if (equipoOptional.isPresent()) { - Equipo equipo = equipoOptional.get(); - equipo.setEliminado(true); // establecer el valor de "eliminado" a false - equipoRepository.save(equipo); // guardar el objeto actualizado en la base de datos - } - } - public Iterable findAll(){ - return equipoRepository.findAll(); - } - public Equipo findById(Long id) { - Optional equipoOptional = equipoRepository.findById(id); - return equipoOptional.orElseThrow(() -> new RuntimeException("Equipo no encontrado")); - } - public Equipo save(Equipo equipo) { - return equipoRepository.save(equipo); - } - public void agregarInvitacion(Invitacion invitacion){ - - } -} diff --git a/src/main/java/com/example/demo/service/InvitacionService.java b/src/main/java/com/example/demo/service/InvitacionService.java deleted file mode 100644 index 8a3f291..0000000 --- a/src/main/java/com/example/demo/service/InvitacionService.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.example.demo.service; - -import com.example.demo.domain.Equipo; -import com.example.demo.domain.Invitacion; -import com.example.demo.domain.Usuario; -import com.example.demo.repository.InvitacionRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class InvitacionService { - @Autowired - InvitacionRepository invitacionRepository; - - @Autowired - EquipoService equipoService; - - @Autowired - UsuarioService usuarioService; - - public void crearInvitacion(Long equipoId, Long usuarioId) { - Equipo equipo = equipoService.findById(equipoId); - Usuario usuario = usuarioService.findById(usuarioId); - - Invitacion invitacion = new Invitacion(); - invitacion.setEquipo(equipo); - invitacion.setUsuario(usuario); - - invitacionRepository.save(invitacion); - } - public Invitacion save(Invitacion invitacion){ - return invitacionRepository.save(invitacion); - } - public Iterable findAll(){ - return invitacionRepository.findAll(); - } - - - -} diff --git a/src/main/java/com/example/demo/service/UsuarioService.java b/src/main/java/com/example/demo/service/UsuarioService.java deleted file mode 100644 index 2510e24..0000000 --- a/src/main/java/com/example/demo/service/UsuarioService.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.example.demo.service; - -import com.example.demo.domain.Usuario; -import com.example.demo.repository.UsuarioRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import java.util.NoSuchElementException; - -@Service -public class UsuarioService { - @Autowired - UsuarioRepository usuarioRepository; - - public Usuario findById(Long id) { - return usuarioRepository.findById(id).orElseThrow(() -> new NoSuchElementException("Usuario no encontrado")); - } - - public Usuario save(Usuario usuario) { - return usuarioRepository.save(usuario); - } -} diff --git a/src/main/java/com/example/demo/services/libroService.java b/src/main/java/com/example/demo/services/libroService.java new file mode 100644 index 0000000..7e65ae6 --- /dev/null +++ b/src/main/java/com/example/demo/services/libroService.java @@ -0,0 +1,21 @@ +package com.example.demo.services; + +import com.example.demo.domain.libro; +import com.example.demo.repository.libroRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; + +@Service +public class libroService { + @Autowired + libroRepository libroRepository; + + public List obtenerLibros(){ + return libroRepository.findAll(); + } + public void ingresarLibro(libro libro){ + libroRepository.save(libro); + } +} diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 80b6144..87440f0 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -1,10 +1,8 @@ -spring.datasource.url=jdbc:mysql://localhost:3306/equiposdb -spring.datasource.username=admin -spring.datasource.password=admin +spring.datasource.url=jdbc:mysql://66.70.137.253:3306/Javeriana +spring.datasource.username=javeriana +spring.datasource.password=87654321 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver -spring.jpa.hibernate.ddl-auto = update - -# ONLY DEBUG +spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true diff --git a/src/test/java/com/example/demo/SpringBootAppTests.java b/src/test/java/com/example/demo/DemoApplicationTests.java similarity index 85% rename from src/test/java/com/example/demo/SpringBootAppTests.java rename to src/test/java/com/example/demo/DemoApplicationTests.java index ec0d921..2778a6a 100644 --- a/src/test/java/com/example/demo/SpringBootAppTests.java +++ b/src/test/java/com/example/demo/DemoApplicationTests.java @@ -4,7 +4,7 @@ import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest -class SpringBootAppTests { +class DemoApplicationTests { @Test void contextLoads() { diff --git a/src/test/java/com/example/demo/libroServiceTest.java b/src/test/java/com/example/demo/libroServiceTest.java new file mode 100644 index 0000000..2960b51 --- /dev/null +++ b/src/test/java/com/example/demo/libroServiceTest.java @@ -0,0 +1,64 @@ +package com.example.demo; + +import com.example.demo.domain.libro; +import com.example.demo.repository.libroRepository; +import com.example.demo.services.libroService; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.*; + +@SpringBootTest +public class libroServiceTest { + + @Autowired + private libroRepository libroRepository; + + @Autowired + private libroRepository libroService; + + @Captor + private ArgumentCaptor libroCaptor; + + public void setUp() { + MockitoAnnotations.openMocks(this); + } + + @Test + public void testCrearLibro() { + int canti = (int) libroRepository.count(); + libro libro = new libro(); + libro.setReferencia("Libor213"); + libro.setAutor("Dummy autor"); + libro.setPrecio(10000L); + libro.setUbicacion("Panamericana"); + + libroRepository.save(libro); + + int cantiNueva = (int) libroRepository.count(); + assertTrue(cantiNueva == canti+1); + } + @Test + public void testListaLibros(){ + libro libro = new libro(); + libro.setReferencia("Libor213"); + libro.setAutor("Dummy autor"); + libro.setPrecio(10000L); + libro.setUbicacion("Panamericana"); + + libroRepository.save(libro); + List libroList = libroService.findAll(); + + assertTrue(libroList.contains(libro)); + } +} \ No newline at end of file diff --git a/system.properties b/system.properties deleted file mode 100644 index c6b145d..0000000 --- a/system.properties +++ /dev/null @@ -1 +0,0 @@ -java.runtime.version=16 \ No newline at end of file diff --git a/target/classes/application.properties b/target/classes/application.properties index 80b6144..87440f0 100644 --- a/target/classes/application.properties +++ b/target/classes/application.properties @@ -1,10 +1,8 @@ -spring.datasource.url=jdbc:mysql://localhost:3306/equiposdb -spring.datasource.username=admin -spring.datasource.password=admin +spring.datasource.url=jdbc:mysql://66.70.137.253:3306/Javeriana +spring.datasource.username=javeriana +spring.datasource.password=87654321 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver -spring.jpa.hibernate.ddl-auto = update - -# ONLY DEBUG +spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.format_sql=true