diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..549e00a --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +HELP.md +target/ +!.mvn/wrapper/maven-wrapper.jar +!**/src/main/**/target/ +!**/src/test/**/target/ + +### 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/ +!**/src/main/**/build/ +!**/src/test/**/build/ + +### VS Code ### +.vscode/ diff --git a/.mvn/wrapper/MavenWrapperDownloader.java b/.mvn/wrapper/MavenWrapperDownloader.java new file mode 100644 index 0000000..e76d1f3 --- /dev/null +++ b/.mvn/wrapper/MavenWrapperDownloader.java @@ -0,0 +1,117 @@ +/* + * 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..2cc7d4a 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 new file mode 100644 index 0000000..ffdc10e --- /dev/null +++ b/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +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 diff --git a/bdd.sql b/bdd.sql new file mode 100644 index 0000000..b0e7648 --- /dev/null +++ b/bdd.sql @@ -0,0 +1,198 @@ +create database UDEE; +use UDEE; +drop database UDEE; + +/*Facturas*/ +create table Bills ( + id_bill int not null, + id_user int not null, + id_address int not null, + number_measurer int not null, + measure_start int not null, + measure_end int not null, + consumption_total int not null, + date_time_start datetime,/*son solo fechas*/ + date_time_End datetime,/*son solo fechas*/ + id_rate int not null, + total int not null,/*(Consumo * Tarifa)*/ + CONSTRAINT `PK-Bill` PRIMARY KEY (id_bill), + CONSTRAINT `FK-IdUser` FOREIGN KEY (id_user) references Users(id_user), + CONSTRAINT `FK-IdAddress` FOREIGN KEY (id_address) references Address(id_address), + CONSTRAINT `FK-IdRate` FOREIGN KEY (id_rate) references Rates(id_rate)); + +/*Usuarios*/ +CREATE TABLE Users( + id_user INT NOT NULL AUTO_INCREMENT, + id_client int not null, + username VARCHAR(30) NOT NULL, + password VARCHAR(30) NOT NULL, + CONSTRAINT `PK-User` PRIMARY KEY (id_user), + CONSTRAINT `FK-IdClient` FOREIGN KEY (id_client) references Clients(id_client)); + +/*Clientes*/ +CREATE TABLE Clients( + id_client INT NOT NULL auto_increment, + id_address int not null, + name varchar(30) not null, + last_name varchar(30) not null, + email varchar(40) not null, + constraint `PK-Client` PRIMARY KEY(id_client), + CONSTRAINT `FK-IdAddress` FOREIGN KEY (id_address) references Address(id_address)); + + +/*direcciones*/ +create table Address( + id_address int not null auto_increment, + id_rate int not null, + street varchar(30) not null, + number int not null, + constraint `PK-Address` primary key(id_address), + constraint `FK-Rate` foreign key(id_rate) references Rates(id_rate) +); + +/*tarifas*/ +create table Rates( + id_rate int not null auto_increment, + price float not null, + constraint `PK-Rate` primary key(id_rate) +); + +/*Medidores*/ +create table meters( + id_meter int not null auto_increment, + id_address int not null, + serial_number varchar(30) not null, + password varchar(30) not null, + id_brand int not null, + id_model int not null, + constraint `PK-Meter` primary key(id_meter), + constraint `FK-Brand` foreign key(id_brand) references Brands(id_brand), + constraint `FK-Address` foreign key(id_address) references Address(id_address), + constraint `FK-Model` foreign key(id_model) references Models(id_model) +); + + +/*Mediciones*/ +create table Measurements( + id_measurement int not null auto_increment, + id_bill int not null, + id_meter int not null, + measurement varchar(30) not null, + date date not null, + constraint `PK-Measurement` primary key(id_measurement), + constraint `FK-Bill` foreign key(id_bill) references udee.bills(id_bill), + constraint `FK-Meter` foreign key(id_meter) references udee.meters(id_meter) +); +drop table Measurements; +/*Marcas*/ +create table Brands( + id_brand int not null auto_increment, + name varchar(30)not null, + constraint `PK-Brand` primary key(id_brand) +); + + +/*Modelos*/ +create table Models( + id_model int not null auto_increment, + name varchar(30) not null, + constraint `PK-Model` primary key(id_model) +); + + +select * from Brands; +select * from Models; +select * from Measures; +select * from Rates; +select * from Address; + + + +/* +uen dia + +Tenes las relaciones al revés en muchos csasos + +Por ej : + +Address tiene un id_measurement, no deberia ya que  Measurement +debería relacionarse con meter y meter con address. + +create table Address( + id_address int not null auto_increment, + //id_measure int not null, + id_rate int not null, + street varchar(30) not null, + number int not null, + constraint `PK-Address` primary key(id_address), + //constraint `FK-Measure` foreign key(id_measure) references Measures(id_measure), + constraint `FK-Rate` foreign key(id_rate) references Rates(id_rate) +); + +create table meters( + id_meter int not null auto_increment, + id_address int not null, + serial_number varchar(30) not null, + password varchar(30) not null, + id_brand int not null, + id_model int not null, + constraint `PK-Meter` primary key(id_meter), + constraint `FK-Brand` foreign key(id_brand) references Brands(id_brand), + constraint `FK-Address` foreign key(id_address) references Address(id_address), + constraint `FK-Model` foreign key(id_model) references Models(id_model) +); + +create table Measurements( + id_measurement int not null auto_increment, + id_bill int not null, + id_meter int not null, + measurement varchar(30) not null, + date date not null, + constraint `PK-Measurement` primary key(id_measurement), + constraint `FK-Bill` foreign key(id_bill) references Bills(id_bill), + constraint `FK-Meter` foreign key(id_meter) references Meters(id_meter) +); + + + +En bills también, un measurement debería tener un Bill. + +Es decir 1 BILL -> n MEASUREMENTS, en ese caso la relación siempre +se especifica por la propagación de la clave en el N . + +create table Bills ( + id_bill int not null, + id_user int not null, + id_address int not null, + id_bill int not null, + number_measurer int not null, + measure_start int not null, + measure_end int not null, + consumption_total int not null, + date_time_start datetime,/*son solo fechas + date_time_End datetime,/*son solo fechas + id_rate int not null, + total int not null,/*(Consumo * Tarifa) + CONSTRAINT `PK-Bill` PRIMARY KEY (id_bill), + CONSTRAINT `FK-IdUser` FOREIGN KEY (id_user) references Users(id_user), + CONSTRAINT `FK-IdAddress` FOREIGN KEY (id_address) references Address(id_address), + CONSTRAINT `FK-IdRate` FOREIGN KEY (id_rate) references Rates(id_rate)); + + +Por lo demás , esta bien , revisaría esas cosas, tabla de measurements +/ address / clients / bills y sus relaciones + +*/ + +/* +● Cliente +● Domicilio +● Numero de medidor +● Medición inicial +● Medición final +● Consumo total en Kwh +● Fecha y hora medición inicial +● Fecha y hora medición final +● Tipo de tarifa +● Total a pagar */ + diff --git a/modelo.mwb b/modelo.mwb new file mode 100644 index 0000000..d2365bd Binary files /dev/null and b/modelo.mwb differ diff --git a/mvnw b/mvnw new file mode 100644 index 0000000..a16b543 --- /dev/null +++ b/mvnw @@ -0,0 +1,310 @@ +#!/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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Maven 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)`" +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 + if [ -n "$MVNW_REPOURL" ]; then + jarUrl="$MVNW_REPOURL/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + else + jarUrl="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar" + fi + 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 $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget "$jarUrl" -O "$wrapperJarPath" + else + wget --http-user=$MVNW_USERNAME --http-password=$MVNW_PASSWORD "$jarUrl" -O "$wrapperJarPath" + fi + elif command -v curl > /dev/null; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl -o "$wrapperJarPath" "$jarUrl" -f + else + curl --user $MVNW_USERNAME:$MVNW_PASSWORD -o "$wrapperJarPath" "$jarUrl" -f + fi + + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + 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") + 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 + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +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/mvnw.cmd b/mvnw.cmd new file mode 100644 index 0000000..c8d4337 --- /dev/null +++ b/mvnw.cmd @@ -0,0 +1,182 @@ +@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 Maven 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 keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%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.5.6/maven-wrapper-0.5.6.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% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %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" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %DOWNLOAD_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%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/pom.xml b/pom.xml new file mode 100644 index 0000000..23bda91 --- /dev/null +++ b/pom.xml @@ -0,0 +1,130 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 2.4.5 + + + com.api + UDEE + 0.0.1-SNAPSHOT + UDEE + Demo project for Spring Boot + + 11 + + + + org.springframework.boot + spring-boot-starter-web + + + + org.projectlombok + lombok + true + + + org.springframework.boot + spring-boot-starter-test + test + + + org.springframework.boot + spring-boot-starter-data-jpa + + + org.springframework.boot + spring-boot-starter-validation + 2.4.0 + + + + mysql + mysql-connector-java + 8.0.21 + + + + org.glassfish + javax.el + 3.0.0 + + com.google.code.gson + gson + 2.8.6 + + + org.modelmapper + modelmapper + 2.4.0 + + + io.github.resilience4j + resilience4j-spring-boot2 + 1.6.1 + + + org.springframework.boot + spring-boot-starter-actuator + 2.4.0 + + + org.springframework.boot + spring-boot-starter-aop + 2.4.0 + + + org.apache.commons + commons-lang3 + 3.12.0 + + + org.modelmapper + modelmapper + 2.3.9 + + + net.kaczmarzyk + specification-arg-resolver + 2.6.2 + + + org.springframework.boot + spring-boot-starter-security + + + io.jsonwebtoken + jjwt + 0.9.1 + + + org.glassfish + javax.el + 3.0.0 + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/schema.mwb b/schema.mwb new file mode 100644 index 0000000..52ac3e4 Binary files /dev/null and b/schema.mwb differ diff --git a/src/main/java/com/api/UDEE/UdeeApplication.java b/src/main/java/com/api/UDEE/UdeeApplication.java new file mode 100644 index 0000000..65e819f --- /dev/null +++ b/src/main/java/com/api/UDEE/UdeeApplication.java @@ -0,0 +1,52 @@ +package com.api.UDEE; + +import com.api.UDEE.filter.JWTAuthorizationFilter; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +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.web.authentication.UsernamePasswordAuthenticationFilter; + +@SpringBootApplication +public class UdeeApplication { + + public static void main(String[] args) { + SpringApplication.run(UdeeApplication.class, args); + } + + @EnableWebSecurity + @Configuration + static class WebSecurityConfig extends WebSecurityConfigurerAdapter { + + @Override + protected void configure(HttpSecurity http) throws Exception { + http.csrf().disable() + .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class) + .authorizeRequests() + .antMatchers(HttpMethod.POST, "/auth/login").permitAll() + .antMatchers(HttpMethod.POST, "/auth/login2").permitAll() + .antMatchers(HttpMethod.POST, "/users2").permitAll() + .antMatchers(HttpMethod.GET, "/users2").permitAll() + .antMatchers(HttpMethod.POST, "/api/rates").permitAll() + .antMatchers(HttpMethod.POST, "/api/clients").permitAll() + .antMatchers(HttpMethod.POST, "/api/address").permitAll() + .anyRequest().authenticated(); + + /* + http.csrf().disable() + .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class) + .authorizeRequests() + .antMatchers(HttpMethod.POST, "/measurement").permitAll() + .antMatchers(HttpMethod.POST, "/login").permitAll() + .antMatchers(HttpMethod.POST, "/backoffice/login").permitAll() + .antMatchers("/console/**").permitAll() //TODO borrar esta linea + .antMatchers("/tariff/**").hasAuthority(User.TYPE.BLACKOFFICE.name()) + .antMatchers("/clients/**").hasAuthority(User.TYPE.BLACKOFFICE.name()) + .anyRequest().authenticated(); + */ + } + } +} diff --git a/src/main/java/com/api/UDEE/Utils/Constants.java b/src/main/java/com/api/UDEE/Utils/Constants.java new file mode 100644 index 0000000..243d542 --- /dev/null +++ b/src/main/java/com/api/UDEE/Utils/Constants.java @@ -0,0 +1,9 @@ +package com.api.UDEE.Utils; + +public class Constants { + + public static final String JWT_HEADER = "Authorization"; + public static final String JWT_PREFIX = "Bearer "; + public static final String JWT_SECRET = "UDEE"; + +} diff --git a/src/main/java/com/api/UDEE/Utils/EntityURLBuilder.java b/src/main/java/com/api/UDEE/Utils/EntityURLBuilder.java new file mode 100644 index 0000000..0826b75 --- /dev/null +++ b/src/main/java/com/api/UDEE/Utils/EntityURLBuilder.java @@ -0,0 +1,15 @@ +package com.api.UDEE.Utils; + +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +public class EntityURLBuilder { + + public static String buildURL(final String entity, final Integer id) { + return ServletUriComponentsBuilder + .fromCurrentContextPath() + .path("{entity}/{id}") + .buildAndExpand(entity,id) + .toUriString(); + } + +} diff --git a/src/main/java/com/api/UDEE/config/Conf.java b/src/main/java/com/api/UDEE/config/Conf.java new file mode 100644 index 0000000..ff9a20e --- /dev/null +++ b/src/main/java/com/api/UDEE/config/Conf.java @@ -0,0 +1,15 @@ +package com.api.UDEE.config; + +import org.modelmapper.ModelMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class Conf { + @Bean + public ModelMapper modelMapper() { + final ModelMapper modelMapper = new ModelMapper(); + modelMapper.getConfiguration().setSkipNullEnabled(true); + return modelMapper; + } +} diff --git a/src/main/java/com/api/UDEE/config/SpecsConfiguration.java b/src/main/java/com/api/UDEE/config/SpecsConfiguration.java new file mode 100644 index 0000000..6c56570 --- /dev/null +++ b/src/main/java/com/api/UDEE/config/SpecsConfiguration.java @@ -0,0 +1,18 @@ +package com.api.UDEE.config; + +import net.kaczmarzyk.spring.data.jpa.web.SpecificationArgumentResolver; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; + +@Configuration +public class SpecsConfiguration implements WebMvcConfigurer { + + @Override + public void addArgumentResolvers(List argumentResolverList){ + argumentResolverList.add((new SpecificationArgumentResolver())); + } + +} diff --git a/src/main/java/com/api/UDEE/controller/AddressController.java b/src/main/java/com/api/UDEE/controller/AddressController.java new file mode 100644 index 0000000..78b05f3 --- /dev/null +++ b/src/main/java/com/api/UDEE/controller/AddressController.java @@ -0,0 +1,65 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.domain.Address; +import com.api.UDEE.domain.User; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.exceptions.CountryExistsException; +import com.api.UDEE.service.AddressService; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.net.URI; +import java.util.List; + +@RestController +@RequestMapping(value = "/api/address") +public class AddressController { + + private AddressService addressService; + private ModelMapper modelMapper; + + @Autowired + public AddressController(AddressService addressService, ModelMapper modelMapper){ + this.addressService=addressService; + this.modelMapper=modelMapper; + } + + @PostMapping(consumes = "application/json") + public ResponseEntity newCountry(@RequestBody Address address) throws CountryExistsException { + Address newAddress = addressService.newAddress(address); + URI location = ServletUriComponentsBuilder + .fromCurrentRequest() + .path("/{id}") + .buildAndExpand(newAddress.getId()) + .toUri(); + return ResponseEntity.created(location).build(); + } + + @GetMapping() + public ResponseEntity> allAddress(Pageable pageable) { + Page page = addressService.allAddress(pageable); + return response(page); + } + + private ResponseEntity response(Page page) { + + HttpStatus httpStatus = page.getContent().isEmpty() ? HttpStatus.NO_CONTENT : HttpStatus.OK; + return ResponseEntity. + status(httpStatus). + header("X-Total-Count", Long.toString(page.getTotalElements())) + .header("X-Total-Pages", Long.toString(page.getTotalPages())) + .body(page.getContent()); + } + @GetMapping(value = "{id}", produces = "application/json") + public ResponseEntity
countriesByCode(@PathVariable("id") Integer id) throws AddressNotExistsException { + Address address = addressService.getAddressById(id); + return ResponseEntity.ok(address); + } + +} diff --git a/src/main/java/com/api/UDEE/controller/BillController.java b/src/main/java/com/api/UDEE/controller/BillController.java new file mode 100644 index 0000000..3b00a1e --- /dev/null +++ b/src/main/java/com/api/UDEE/controller/BillController.java @@ -0,0 +1,67 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.domain.Address; +import com.api.UDEE.domain.Bill; +import com.api.UDEE.domain.User; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.exceptions.CountryExistsException; +import com.api.UDEE.service.AddressService; +import com.api.UDEE.service.BillService; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.net.URI; +import java.util.List; + +@RestController +//@RequestMapping(value = "/api/bills") +public class BillController { + + private BillService billService; + private ModelMapper modelMapper; + + @Autowired + public BillController(BillService billService, ModelMapper modelMapper){ + this.billService=billService; + this.modelMapper=modelMapper; + } + + @PostMapping(value= "/api/bills",consumes = "application/json") + public ResponseEntity newCountry(@RequestBody Bill bill) throws CountryExistsException { + Bill newBill = billService.newBill(bill); + URI location = ServletUriComponentsBuilder + .fromCurrentRequest() + .path("/{id}") + .buildAndExpand(newBill.getId()) + .toUri(); + return ResponseEntity.created(location).build(); + } + + @GetMapping(value = "/api/bills") + public ResponseEntity> allBills(Pageable pageable) { + Page page = billService.allBills(pageable); + return response(page); + } + + private ResponseEntity response(Page page) { + + HttpStatus httpStatus = page.getContent().isEmpty() ? HttpStatus.NO_CONTENT : HttpStatus.OK; + return ResponseEntity. + status(httpStatus). + header("X-Total-Count", Long.toString(page.getTotalElements())) + .header("X-Total-Pages", Long.toString(page.getTotalPages())) + .body(page.getContent()); + } + + @GetMapping(value = "/api/bills/{id}", produces = "application/json") + public ResponseEntity billByCode(@PathVariable("id") Integer id) throws AddressNotExistsException { + Bill bill = billService.getBillById(id); + return ResponseEntity.ok(bill); + } +} diff --git a/src/main/java/com/api/UDEE/controller/BrandController.java b/src/main/java/com/api/UDEE/controller/BrandController.java new file mode 100644 index 0000000..a98feaa --- /dev/null +++ b/src/main/java/com/api/UDEE/controller/BrandController.java @@ -0,0 +1,65 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.domain.Brand; +import com.api.UDEE.domain.User; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.service.BrandService; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.net.URI; +import java.util.List; + +@RestController +@RequestMapping(value = "/api/brands") +public class BrandController { + + private final BrandService brandService; + private ModelMapper modelMapper; + + @Autowired + public BrandController(BrandService brandService,ModelMapper modelMapper){ + this.brandService=brandService; + this.modelMapper=modelMapper; + } + + + @PostMapping(consumes = "application/json") + public ResponseEntity newBrand(@RequestBody Brand brand){ + Brand newBrand = brandService.newBrand(brand); + URI location = ServletUriComponentsBuilder + .fromCurrentRequest() + .path("/{id}") + .buildAndExpand(newBrand.getId()) + .toUri(); + return ResponseEntity.created(location).build(); + } + + @GetMapping("/brands") + public ResponseEntity> allBrands(Pageable pageable) { + Page page = brandService.allBrands(pageable); + return response(page); + } + + private ResponseEntity response(Page page) { + + HttpStatus httpStatus = page.getContent().isEmpty() ? HttpStatus.NO_CONTENT : HttpStatus.OK; + return ResponseEntity. + status(httpStatus). + header("X-Total-Count", Long.toString(page.getTotalElements())) + .header("X-Total-Pages", Long.toString(page.getTotalPages())) + .body(page.getContent()); + } + + @GetMapping(value = "{id}", produces = "application/json") + public ResponseEntity brandByCode(@PathVariable("id") Integer id) throws AddressNotExistsException { + Brand brand = brandService.getBrandById(id); + return ResponseEntity.ok(brand); + } +} diff --git a/src/main/java/com/api/UDEE/controller/ClientController.java b/src/main/java/com/api/UDEE/controller/ClientController.java new file mode 100644 index 0000000..ceb6b60 --- /dev/null +++ b/src/main/java/com/api/UDEE/controller/ClientController.java @@ -0,0 +1,67 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.domain.Address; +import com.api.UDEE.domain.Client; +import com.api.UDEE.domain.Rate; +import com.api.UDEE.domain.User; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.service.ClientService; +import com.api.UDEE.service.RateService; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.net.URI; +import java.util.List; + +@RestController +@RequestMapping(value = "/api/clients") +public class ClientController { + + private ClientService clientService; + //private ModelMapper modelMapper; + + @Autowired + public ClientController(ClientService clientService){ + this.clientService=clientService; + //this.modelMapper=modelMapper; + } + + @PostMapping(consumes = "application/json") + public ResponseEntity newClient(@RequestBody Client client){ + Client newClient = clientService.newClient(client); + URI location = ServletUriComponentsBuilder + .fromCurrentRequest() + .path("/{id}") + .buildAndExpand(newClient.getId()) + .toUri(); + return ResponseEntity.created(location).build(); + } + + @GetMapping("/clients") + public ResponseEntity> allClients(Pageable pageable) { + Page page = clientService.allClients(pageable); + return response(page); + } + + private ResponseEntity response(Page page) { + + HttpStatus httpStatus = page.getContent().isEmpty() ? HttpStatus.NO_CONTENT : HttpStatus.OK; + return ResponseEntity. + status(httpStatus). + header("X-Total-Count", Long.toString(page.getTotalElements())) + .header("X-Total-Pages", Long.toString(page.getTotalPages())) + .body(page.getContent()); + } + + @GetMapping(value = "{id}", produces = "application/json") + public ResponseEntity clientByCode(@PathVariable("id") Integer id) throws AddressNotExistsException { + Client client = clientService.getClientById(id); + return ResponseEntity.ok(client); + } +} diff --git a/src/main/java/com/api/UDEE/controller/MeasurementController.java b/src/main/java/com/api/UDEE/controller/MeasurementController.java new file mode 100644 index 0000000..c5eb8b0 --- /dev/null +++ b/src/main/java/com/api/UDEE/controller/MeasurementController.java @@ -0,0 +1,65 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.domain.Client; +import com.api.UDEE.domain.Measurement; +import com.api.UDEE.domain.User; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.service.MeasurementService; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.net.URI; +import java.util.List; + +@RestController +@RequestMapping(value = "/api/measurements") +public class MeasurementController { + + private MeasurementService measurementService; + private ModelMapper modelMapper; + + @Autowired + public MeasurementController(MeasurementService measurementService, ModelMapper modelMapper){ + this.measurementService=measurementService; + this.modelMapper=modelMapper; + } + + @PostMapping(consumes = "application/json") + public ResponseEntity newReading(@RequestBody Measurement reading){ + Measurement newReading = measurementService.newMeasurement(reading); + URI location = ServletUriComponentsBuilder + .fromCurrentRequest() + .path("/{id}") + .buildAndExpand(newReading.getId()) + .toUri(); + return ResponseEntity.created(location).build(); + } + + @GetMapping("/measurements") + public ResponseEntity> allMeasurements(Pageable pageable) { + Page page = measurementService.allMeasurements(pageable); + return response(page); + } + + private ResponseEntity response(Page page) { + + HttpStatus httpStatus = page.getContent().isEmpty() ? HttpStatus.NO_CONTENT : HttpStatus.OK; + return ResponseEntity. + status(httpStatus). + header("X-Total-Count", Long.toString(page.getTotalElements())) + .header("X-Total-Pages", Long.toString(page.getTotalPages())) + .body(page.getContent()); + } + + @GetMapping(value = "{id}", produces = "application/json") + public ResponseEntity readingByCode(@PathVariable("id") Integer id) throws AddressNotExistsException { + Measurement reading = measurementService.getMeasurementById(id); + return ResponseEntity.ok(reading); + } +} diff --git a/src/main/java/com/api/UDEE/controller/MeterController.java b/src/main/java/com/api/UDEE/controller/MeterController.java new file mode 100644 index 0000000..601b950 --- /dev/null +++ b/src/main/java/com/api/UDEE/controller/MeterController.java @@ -0,0 +1,66 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.domain.Meter; +import com.api.UDEE.domain.User; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.exceptions.CountryExistsException; +import com.api.UDEE.service.MeterService; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + + +import java.net.URI; +import java.util.List; + +@RestController +@RequestMapping(value = "/api/meters") +public class MeterController { + + private MeterService meterService; + private ModelMapper modelMapper; + + @Autowired + public MeterController(MeterService meterService, ModelMapper modelMapper){ + this.meterService=meterService; + this.modelMapper=modelMapper; + } + + @PostMapping(consumes = "application/json") + public ResponseEntity newCountry(@RequestBody Meter meter) throws CountryExistsException { + Meter newMeasure = meterService.newMeter(meter); + URI location = ServletUriComponentsBuilder + .fromCurrentRequest() + .path("/{id}") + .buildAndExpand(newMeasure.getId()) + .toUri(); + return ResponseEntity.created(location).build(); + } + + @GetMapping("/meters") + public ResponseEntity> allMeters(Pageable pageable) { + Page page = meterService.allMeter(pageable); + return response(page); + } + + private ResponseEntity response(Page page) { + + HttpStatus httpStatus = page.getContent().isEmpty() ? HttpStatus.NO_CONTENT : HttpStatus.OK; + return ResponseEntity. + status(httpStatus). + header("X-Total-Count", Long.toString(page.getTotalElements())) + .header("X-Total-Pages", Long.toString(page.getTotalPages())) + .body(page.getContent()); + } + + @GetMapping(value = "{id}", produces = "application/json") + public ResponseEntity measureByCode(@PathVariable("id") Integer id) throws AddressNotExistsException { + Meter measure = meterService.getMeterById(id); + return ResponseEntity.ok(measure); + } +} diff --git a/src/main/java/com/api/UDEE/controller/ModelController.java b/src/main/java/com/api/UDEE/controller/ModelController.java new file mode 100644 index 0000000..ac67e9d --- /dev/null +++ b/src/main/java/com/api/UDEE/controller/ModelController.java @@ -0,0 +1,68 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.domain.Address; +import com.api.UDEE.domain.Model; +import com.api.UDEE.domain.User; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.service.ModelService; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.net.URI; +import java.util.List; + +@RestController +@RequestMapping(value = "/api/models") +public class ModelController { + + private ModelService modelService; + //private ModelMapper modelMapper; + + @Autowired + public ModelController(ModelService modelService){ + this.modelService=modelService; + //this.modelMapper=modelMapper; + } + + //@PreAuthorize(value = "hasAuthority(TypeUser.CLIENT)") + @PreAuthorize(value = "hasAuthority('CLIENT')") + @PostMapping(consumes = "application/json") + public ResponseEntity newModel(@RequestBody Model model){ + Model newModel = modelService.newModel(model); + URI location = ServletUriComponentsBuilder + .fromCurrentRequest() + .path("/{id}") + .buildAndExpand(newModel.getId()) + .toUri(); + return ResponseEntity.created(location).build(); + } + + @GetMapping("/models") + public ResponseEntity> allModels(Pageable pageable) { + Page page = modelService.allModels(pageable); + return response(page); + } + + private ResponseEntity response(Page page) { + + HttpStatus httpStatus = page.getContent().isEmpty() ? HttpStatus.NO_CONTENT : HttpStatus.OK; + return ResponseEntity. + status(httpStatus). + header("X-Total-Count", Long.toString(page.getTotalElements())) + .header("X-Total-Pages", Long.toString(page.getTotalPages())) + .body(page.getContent()); + } + + @GetMapping(value = "{id}", produces = "application/json") + public ResponseEntity ModelByCode(@PathVariable("id") Integer id) throws AddressNotExistsException { + Model model = modelService.getModelById(id); + return ResponseEntity.ok(model); + } +} diff --git a/src/main/java/com/api/UDEE/controller/RateController.java b/src/main/java/com/api/UDEE/controller/RateController.java new file mode 100644 index 0000000..cef6814 --- /dev/null +++ b/src/main/java/com/api/UDEE/controller/RateController.java @@ -0,0 +1,63 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.domain.PaginationResponse; +import com.api.UDEE.domain.PostResponse; +import com.api.UDEE.domain.Rate; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.service.RateService; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.domain.Sort.Order; + +import java.net.URI; +import java.util.List; + +@RestController +@RequestMapping(value = "api/rates") +public class RateController { + + private RateService rateService; + //private ModelMapper modelMapper; + + @Autowired + public RateController(RateService rateService){ + this.rateService=rateService; + //this.modelMapper=modelMapper; + } + + + @PostMapping + public PostResponse newRate(@RequestBody Rate rate) { + return rateService.newRate(rate); + } + + @GetMapping("/rates") + public ResponseEntity> allRates(Pageable pageable) { + Page page = rateService.allRates(pageable); + return response(page); + } + + private ResponseEntity response(Page page) { + + HttpStatus httpStatus = page.getContent().isEmpty() ? HttpStatus.NO_CONTENT : HttpStatus.OK; + return ResponseEntity. + status(httpStatus). + header("X-Total-Count", Long.toString(page.getTotalElements())) + .header("X-Total-Pages", Long.toString(page.getTotalPages())) + .body(page.getContent()); + } + + @GetMapping(value = "{id}", produces = "application/json") + public ResponseEntity RateByCode(@PathVariable("id") Integer id) throws AddressNotExistsException { + Rate rate= rateService.getRateById(id); + return ResponseEntity.ok(rate); + } +} diff --git a/src/main/java/com/api/UDEE/controller/UsuarioController.java b/src/main/java/com/api/UDEE/controller/UsuarioController.java new file mode 100644 index 0000000..46f5bb1 --- /dev/null +++ b/src/main/java/com/api/UDEE/controller/UsuarioController.java @@ -0,0 +1,117 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.domain.TypeUser; +import com.api.UDEE.domain.User; +import com.api.UDEE.domain.Usuario; +import com.api.UDEE.dto.LoginRequestDto; +import com.api.UDEE.dto.LoginResponseDto; +import com.api.UDEE.dto.UserDto; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.service.UsuarioService; +import com.fasterxml.jackson.databind.ObjectMapper; +import io.jsonwebtoken.Jwts; +import io.jsonwebtoken.SignatureAlgorithm; +import lombok.extern.slf4j.Slf4j; +import org.modelmapper.ModelMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.AuthorityUtils; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.net.URI; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +import static com.api.UDEE.Utils.Constants.JWT_SECRET; + +@Slf4j +@RestController +public class UsuarioController { + + private final UsuarioService usuarioService; + private final ModelMapper modelMapper; + private final ObjectMapper objectMapper; + + @Autowired + public UsuarioController(UsuarioService usuarioService,ModelMapper modelMapper, ObjectMapper objectMapper){ + this.usuarioService=usuarioService; + this.modelMapper=modelMapper; + this.objectMapper=objectMapper; + } + + private String generateToken(UserDto userDto, TypeUser typeUser) { + try { + String authRole; + if(typeUser.equals("CLIENT")) { + authRole="CLIENT"; + } + else { + authRole="EMPLOYEE"; + } + List grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(authRole); + String token = Jwts + .builder() + .setId("JWT") + .setSubject(userDto.getUsername()) + .claim("user", objectMapper.writeValueAsString(userDto)) + .claim("authorities",grantedAuthorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList())) + .setIssuedAt(new Date(System.currentTimeMillis())) + .setExpiration(new Date(System.currentTimeMillis() + 1800000)) + .signWith(SignatureAlgorithm.HS512, JWT_SECRET.getBytes()).compact(); + return token; + } catch(Exception e) { + return "dummy"; + } + } + + @PostMapping(value = "auth/login2") + public ResponseEntity login(@RequestBody LoginRequestDto loginRequestDto) { + //log.info(loginRequestDto.toString()); + Usuario user = usuarioService.login(loginRequestDto.getUsername(), loginRequestDto.getPassword()); + if (user!=null){ + UserDto dto = modelMapper.map(user, UserDto.class); + return ResponseEntity.ok(LoginResponseDto.builder().token(this.generateToken(dto,user.getTypeUser())).build()); + } else { + return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); + } + } + + @PostMapping(value = "users2",consumes = "application/json") + public ResponseEntity newClient(@RequestBody Usuario user){ + Usuario newUser = usuarioService.newUser(user); + URI location = ServletUriComponentsBuilder + .fromCurrentRequest() + .path("/{id}") + .buildAndExpand(newUser.getId()) + .toUri(); + return ResponseEntity.created(location).build(); + } + + @GetMapping("/users2") + public ResponseEntity> allUsers(Pageable pageable) { + Page page = usuarioService.allUsers(pageable); + return response(page); + } + + private ResponseEntity response(Page page) { + + HttpStatus httpStatus = page.getContent().isEmpty() ? HttpStatus.NO_CONTENT : HttpStatus.OK; + return ResponseEntity. + status(httpStatus). + header("X-Total-Count", Long.toString(page.getTotalElements())) + .header("X-Total-Pages", Long.toString(page.getTotalPages())) + .body(page.getContent()); + } + + @GetMapping(value = "/users2/{id}", produces = "application/json") + public ResponseEntity userByCode(@PathVariable("id") Integer id) throws AddressNotExistsException { + Usuario user = usuarioService.getUserById(id); + return ResponseEntity.ok(user); + } +} diff --git a/src/main/java/com/api/UDEE/domain/Address.java b/src/main/java/com/api/UDEE/domain/Address.java new file mode 100644 index 0000000..06fd9a9 --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/Address.java @@ -0,0 +1,40 @@ +package com.api.UDEE.domain; + +import com.fasterxml.jackson.annotation.JsonBackReference; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "address") +public class Address { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "address_id") + private Integer id; + + @OneToOne + @JoinColumn(name = "rate_id") + private Rate rate; + + /*@ManyToOne(fetch = FetchType.LAZY) + @JsonBackReference(value="client_id") + @JoinColumn(name="client_id") + private Client client;*/ + + @ManyToOne(fetch = FetchType.EAGER) + @JoinColumn(name = "id_user") + private User userClient; + + @Column(name = "street") + private String street; + + @Column(name = "number") + private Integer number; + +} diff --git a/src/main/java/com/api/UDEE/domain/Bill.java b/src/main/java/com/api/UDEE/domain/Bill.java new file mode 100644 index 0000000..f199fc7 --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/Bill.java @@ -0,0 +1,45 @@ +package com.api.UDEE.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Entity +@Data +@AllArgsConstructor +@NoArgsConstructor +@Table (name = "bills") +public class Bill { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id_bill") + private Integer id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "id_user") + private User userClient; + + @OneToOne + @JoinColumn(name = "id_address") + private Address address; + + private Integer number_measurer; + + private Integer measure_start; + + private Integer measure_end; + + private Integer consumption_total; + + private String date_time_start; + + private String date_time_end; + + @OneToOne + @JoinColumn(name = "rate_id") + private Rate rate; + + private Integer total; +} diff --git a/src/main/java/com/api/UDEE/domain/Brand.java b/src/main/java/com/api/UDEE/domain/Brand.java new file mode 100644 index 0000000..6d0b533 --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/Brand.java @@ -0,0 +1,29 @@ +package com.api.UDEE.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Builder +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "brands") +public class Brand { + + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id_brand") + private Integer id; + /* + * @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Integer id;*/ + + private String name; +} diff --git a/src/main/java/com/api/UDEE/domain/Client.java b/src/main/java/com/api/UDEE/domain/Client.java new file mode 100644 index 0000000..c5f52b9 --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/Client.java @@ -0,0 +1,36 @@ +package com.api.UDEE.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.util.List; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Entity +@Table(name = "clients") +public class Client { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "client_id") + private Integer id; + + + /* + @OneToMany(mappedBy = "client") + private List
addressList; + *@OneToMany(mappedBy = "id") + private List
address; + * */ + + private String name; + + private String last_name; + + private String email; + +} diff --git a/src/main/java/com/api/UDEE/domain/Employee.java b/src/main/java/com/api/UDEE/domain/Employee.java new file mode 100644 index 0000000..69621a2 --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/Employee.java @@ -0,0 +1,26 @@ +package com.api.UDEE.domain; + +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; +import java.util.List; + +@Data +@NoArgsConstructor +@Entity +@Table(name = "employees") +public class Employee { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id_employee") + private Integer id; + + private String name; + + private String last_name; + + private String email; + +} diff --git a/src/main/java/com/api/UDEE/domain/Measurement.java b/src/main/java/com/api/UDEE/domain/Measurement.java new file mode 100644 index 0000000..095ced2 --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/Measurement.java @@ -0,0 +1,32 @@ +package com.api.UDEE.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "measurements") + +public class Measurement { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id_measurement") + private Integer id; + + @OneToOne + private Bill bill; + + @OneToOne + @JoinColumn(name = "id_meter") + private Meter meter; + + private String measurement; + + private String date; + +} diff --git a/src/main/java/com/api/UDEE/domain/Meter.java b/src/main/java/com/api/UDEE/domain/Meter.java new file mode 100644 index 0000000..f2b7b0f --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/Meter.java @@ -0,0 +1,37 @@ +package com.api.UDEE.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Builder +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "meters") +public class Meter { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id_meter") + private Integer id; + + @OneToOne + @JoinColumn(name = "id_address") + private Address address; + + private String serial_number; + + private String password; + + @OneToOne + @JoinColumn(name = "id_brand") + private Brand brand; + + @OneToOne + @JoinColumn(name = "id_model") + private Model model; +} diff --git a/src/main/java/com/api/UDEE/domain/Model.java b/src/main/java/com/api/UDEE/domain/Model.java new file mode 100644 index 0000000..6b8eb3e --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/Model.java @@ -0,0 +1,24 @@ +package com.api.UDEE.domain; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Data +@Builder +@Entity +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "models") +public class Model { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id_model") + private Integer id; + + @Column(name = "name") + private String name; +} diff --git a/src/main/java/com/api/UDEE/domain/PaginationResponse.java b/src/main/java/com/api/UDEE/domain/PaginationResponse.java new file mode 100644 index 0000000..2443bc6 --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/PaginationResponse.java @@ -0,0 +1,17 @@ +package com.api.UDEE.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +@Data +@AllArgsConstructor +public class PaginationResponse implements Serializable { + + private List response; + private int totalPages; + private Long totalElements; + +} diff --git a/src/main/java/com/api/UDEE/domain/PostResponse.java b/src/main/java/com/api/UDEE/domain/PostResponse.java new file mode 100644 index 0000000..cc34ec1 --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/PostResponse.java @@ -0,0 +1,14 @@ +package com.api.UDEE.domain; + +import lombok.Builder; +import lombok.Data; +import org.springframework.http.HttpStatus; + +@Data +@Builder +public class PostResponse { + + private String url; + private HttpStatus status; + +} diff --git a/src/main/java/com/api/UDEE/domain/Rate.java b/src/main/java/com/api/UDEE/domain/Rate.java new file mode 100644 index 0000000..b3007a0 --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/Rate.java @@ -0,0 +1,23 @@ +package com.api.UDEE.domain; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import javax.persistence.*; + +@Entity +@Data +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "rates") +public class Rate { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "rate_id") + private Integer id; + + @Column(name = "price") + private Float price; +} diff --git a/src/main/java/com/api/UDEE/domain/TypeUser.java b/src/main/java/com/api/UDEE/domain/TypeUser.java new file mode 100644 index 0000000..145c7b6 --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/TypeUser.java @@ -0,0 +1,17 @@ +package com.api.UDEE.domain; + +public enum TypeUser { + + EMPLOYEE("EMPLOYEE"), + CLIENT("CLIENT"); + + private String name; + + TypeUser (String name){ + this.name=name; + } + + public String getName(){ + return this.name; + } +} diff --git a/src/main/java/com/api/UDEE/domain/User.java b/src/main/java/com/api/UDEE/domain/User.java new file mode 100644 index 0000000..fe74b6c --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/User.java @@ -0,0 +1,29 @@ +package com.api.UDEE.domain; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.AccessType; + +import javax.persistence.*; + +@Entity +@Data +@AllArgsConstructor +@NoArgsConstructor + + +@Table (name = "users") +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id_user") + private Integer id; + + private String username; + + private String password; + +} diff --git a/src/main/java/com/api/UDEE/domain/Usuario.java b/src/main/java/com/api/UDEE/domain/Usuario.java new file mode 100644 index 0000000..9ce1297 --- /dev/null +++ b/src/main/java/com/api/UDEE/domain/Usuario.java @@ -0,0 +1,52 @@ +package com.api.UDEE.domain; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import org.springframework.data.annotation.AccessType; + +import javax.persistence.*; +import java.util.List; + +@Builder +@Entity +@Data +@AllArgsConstructor +@NoArgsConstructor + +@Table (name = "usuarios") +public class Usuario { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id_user") + private Integer id; + + private String username; + + private String password; + + private String name; + + private String last_name; + + private String email; + + //@ManyToOne() + //@JoinColumn(name = "roles_id") + @Column(name = "user_type") + @AccessType(AccessType.Type.PROPERTY) + TypeUser typeUser; + + @JsonIgnore + @OneToMany(mappedBy = "userClient", cascade = CascadeType.ALL) + @Column(name = "id_bill") + private List billList; + + @JsonIgnore + @OneToMany(mappedBy = "userClient",fetch = FetchType.EAGER) + @Column(name = "address_id") + private List
addressList; + +} diff --git a/src/main/java/com/api/UDEE/dto/LoginRequestDto.java b/src/main/java/com/api/UDEE/dto/LoginRequestDto.java new file mode 100644 index 0000000..8f804f6 --- /dev/null +++ b/src/main/java/com/api/UDEE/dto/LoginRequestDto.java @@ -0,0 +1,13 @@ +package com.api.UDEE.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +public class LoginRequestDto { + String username; + String password; +} diff --git a/src/main/java/com/api/UDEE/dto/LoginResponseDto.java b/src/main/java/com/api/UDEE/dto/LoginResponseDto.java new file mode 100644 index 0000000..22467a9 --- /dev/null +++ b/src/main/java/com/api/UDEE/dto/LoginResponseDto.java @@ -0,0 +1,14 @@ +package com.api.UDEE.dto; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@AllArgsConstructor +@NoArgsConstructor +@Builder +public class LoginResponseDto { + String token; +} diff --git a/src/main/java/com/api/UDEE/dto/UserDto.java b/src/main/java/com/api/UDEE/dto/UserDto.java new file mode 100644 index 0000000..365de3b --- /dev/null +++ b/src/main/java/com/api/UDEE/dto/UserDto.java @@ -0,0 +1,17 @@ +package com.api.UDEE.dto; + +import com.api.UDEE.domain.TypeUser; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Builder +@Data +@AllArgsConstructor +@NoArgsConstructor + +public class UserDto { + int id; + String username; +} diff --git a/src/main/java/com/api/UDEE/exceptions/AddressNotExistsException.java b/src/main/java/com/api/UDEE/exceptions/AddressNotExistsException.java new file mode 100644 index 0000000..c1abc14 --- /dev/null +++ b/src/main/java/com/api/UDEE/exceptions/AddressNotExistsException.java @@ -0,0 +1,5 @@ +package com.api.UDEE.exceptions; + +public class AddressNotExistsException extends Throwable { + +} diff --git a/src/main/java/com/api/UDEE/exceptions/CountryExistsException.java b/src/main/java/com/api/UDEE/exceptions/CountryExistsException.java new file mode 100644 index 0000000..cda694f --- /dev/null +++ b/src/main/java/com/api/UDEE/exceptions/CountryExistsException.java @@ -0,0 +1,4 @@ +package com.api.UDEE.exceptions; + +public class CountryExistsException extends Throwable { +} diff --git a/src/main/java/com/api/UDEE/exceptions/CountryNotExistsException.java b/src/main/java/com/api/UDEE/exceptions/CountryNotExistsException.java new file mode 100644 index 0000000..c409f58 --- /dev/null +++ b/src/main/java/com/api/UDEE/exceptions/CountryNotExistsException.java @@ -0,0 +1,4 @@ +package com.api.UDEE.exceptions; + +public class CountryNotExistsException extends Throwable { +} diff --git a/src/main/java/com/api/UDEE/exceptions/ErrorMessage.java b/src/main/java/com/api/UDEE/exceptions/ErrorMessage.java new file mode 100644 index 0000000..71ad16e --- /dev/null +++ b/src/main/java/com/api/UDEE/exceptions/ErrorMessage.java @@ -0,0 +1,16 @@ +package com.api.UDEE.exceptions; + + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +@AllArgsConstructor +@Data +@NoArgsConstructor +@Builder +public class ErrorMessage { + String code; + String message; +} diff --git a/src/main/java/com/api/UDEE/filter/JWTAuthorizationFilter.java b/src/main/java/com/api/UDEE/filter/JWTAuthorizationFilter.java new file mode 100644 index 0000000..b67c9da --- /dev/null +++ b/src/main/java/com/api/UDEE/filter/JWTAuthorizationFilter.java @@ -0,0 +1,103 @@ +package com.api.UDEE.filter; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.api.UDEE.dto.UserDto; +import io.jsonwebtoken.*; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; +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; +import java.util.List; +import java.util.stream.Collectors; + +;import static com.api.UDEE.Utils.Constants.*; + + +public class JWTAuthorizationFilter extends OncePerRequestFilter { + + ObjectMapper objectMapper; + + public JWTAuthorizationFilter() { + this.objectMapper = new ObjectMapper(); + } + + /** + * Internal JWT Filter to check if the request is valid + * + * @param request + * @param response + * @param chain + * @throws ServletException + * @throws IOException + */ + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { + try { + if (containsJWT(request, response)) { + Claims claims = validateToken(request); + if (claims.get("user") != null) { + setUpSpringAuthentication(claims); + } else { + SecurityContextHolder.clearContext(); + } + } else { + SecurityContextHolder.clearContext(); + } + chain.doFilter(request, response); + } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException e) { + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + ((HttpServletResponse) response).sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); + return; + } + } + + + + /** + * Method to validate if the token is valid + * + * @param request + * @return + */ + + private Claims validateToken(HttpServletRequest request) { + String jwtToken = request.getHeader(JWT_HEADER).replace(JWT_PREFIX, ""); + return Jwts.parser().setSigningKey(JWT_SECRET.getBytes()).parseClaimsJws(jwtToken).getBody(); + } + + /** + * Authentication Method to authorize through Spring + * + * @param claims + */ + private void setUpSpringAuthentication(Claims claims) { + try { + List authorities = (List) claims.get("authorities"); + String userClaim = (String) claims.get("user"); + UserDto user = objectMapper.readValue(userClaim, UserDto.class); + UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, null, + authorities.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())); + SecurityContextHolder.getContext().setAuthentication(auth); + } catch (JsonProcessingException e) { + SecurityContextHolder.clearContext(); + } + + + } + + private boolean containsJWT(HttpServletRequest request, HttpServletResponse res) { + String authenticationHeader = request.getHeader(JWT_HEADER); + if (authenticationHeader == null || !authenticationHeader.startsWith(JWT_PREFIX)) + return false; + return true; + } + +} \ No newline at end of file diff --git a/src/main/java/com/api/UDEE/repository/AddressRepository.java b/src/main/java/com/api/UDEE/repository/AddressRepository.java new file mode 100644 index 0000000..719b630 --- /dev/null +++ b/src/main/java/com/api/UDEE/repository/AddressRepository.java @@ -0,0 +1,9 @@ +package com.api.UDEE.repository; + +import com.api.UDEE.domain.Address; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface AddressRepository extends JpaRepository { +} diff --git a/src/main/java/com/api/UDEE/repository/BillRepository.java b/src/main/java/com/api/UDEE/repository/BillRepository.java new file mode 100644 index 0000000..be915ed --- /dev/null +++ b/src/main/java/com/api/UDEE/repository/BillRepository.java @@ -0,0 +1,9 @@ +package com.api.UDEE.repository; + +import com.api.UDEE.domain.Bill; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface BillRepository extends JpaRepository { +} diff --git a/src/main/java/com/api/UDEE/repository/BrandRepository.java b/src/main/java/com/api/UDEE/repository/BrandRepository.java new file mode 100644 index 0000000..d63c642 --- /dev/null +++ b/src/main/java/com/api/UDEE/repository/BrandRepository.java @@ -0,0 +1,9 @@ +package com.api.UDEE.repository; + +import com.api.UDEE.domain.Brand; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface BrandRepository extends JpaRepository { +} diff --git a/src/main/java/com/api/UDEE/repository/ClientRepository.java b/src/main/java/com/api/UDEE/repository/ClientRepository.java new file mode 100644 index 0000000..2816947 --- /dev/null +++ b/src/main/java/com/api/UDEE/repository/ClientRepository.java @@ -0,0 +1,9 @@ +package com.api.UDEE.repository; + +import com.api.UDEE.domain.Client; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ClientRepository extends JpaRepository { +} diff --git a/src/main/java/com/api/UDEE/repository/MeasurementRepository.java b/src/main/java/com/api/UDEE/repository/MeasurementRepository.java new file mode 100644 index 0000000..b859ce9 --- /dev/null +++ b/src/main/java/com/api/UDEE/repository/MeasurementRepository.java @@ -0,0 +1,9 @@ +package com.api.UDEE.repository; + +import com.api.UDEE.domain.Measurement; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface MeasurementRepository extends JpaRepository { +} diff --git a/src/main/java/com/api/UDEE/repository/MeterRepository.java b/src/main/java/com/api/UDEE/repository/MeterRepository.java new file mode 100644 index 0000000..82d71df --- /dev/null +++ b/src/main/java/com/api/UDEE/repository/MeterRepository.java @@ -0,0 +1,9 @@ +package com.api.UDEE.repository; + +import com.api.UDEE.domain.Meter; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface MeterRepository extends JpaRepository { +} diff --git a/src/main/java/com/api/UDEE/repository/ModelRepository.java b/src/main/java/com/api/UDEE/repository/ModelRepository.java new file mode 100644 index 0000000..ecd839a --- /dev/null +++ b/src/main/java/com/api/UDEE/repository/ModelRepository.java @@ -0,0 +1,10 @@ +package com.api.UDEE.repository; + +import com.api.UDEE.domain.Model; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface ModelRepository extends JpaRepository { + +} diff --git a/src/main/java/com/api/UDEE/repository/RateRepository.java b/src/main/java/com/api/UDEE/repository/RateRepository.java new file mode 100644 index 0000000..f314149 --- /dev/null +++ b/src/main/java/com/api/UDEE/repository/RateRepository.java @@ -0,0 +1,9 @@ +package com.api.UDEE.repository; + +import com.api.UDEE.domain.Rate; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface RateRepository extends JpaRepository { +} diff --git a/src/main/java/com/api/UDEE/repository/UserRepository.java b/src/main/java/com/api/UDEE/repository/UserRepository.java new file mode 100644 index 0000000..5eb0ab8 --- /dev/null +++ b/src/main/java/com/api/UDEE/repository/UserRepository.java @@ -0,0 +1,11 @@ +package com.api.UDEE.repository; + +import com.api.UDEE.domain.User; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UserRepository extends JpaRepository { + + User findByUsernameAndPassword(String username, String password); +} diff --git a/src/main/java/com/api/UDEE/repository/UsuarioRepository.java b/src/main/java/com/api/UDEE/repository/UsuarioRepository.java new file mode 100644 index 0000000..96bbd73 --- /dev/null +++ b/src/main/java/com/api/UDEE/repository/UsuarioRepository.java @@ -0,0 +1,10 @@ +package com.api.UDEE.repository; + +import com.api.UDEE.domain.Usuario; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +@Repository +public interface UsuarioRepository extends JpaRepository { + Usuario findByUsernameAndPassword(String username, String password); +} diff --git a/src/main/java/com/api/UDEE/service/AddressService.java b/src/main/java/com/api/UDEE/service/AddressService.java new file mode 100644 index 0000000..d9868c5 --- /dev/null +++ b/src/main/java/com/api/UDEE/service/AddressService.java @@ -0,0 +1,35 @@ +package com.api.UDEE.service; + +import com.api.UDEE.domain.Address; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.repository.AddressRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +public class AddressService { + private final AddressRepository addressRepository; + @Autowired + public AddressService(AddressRepository addressRepository){ + this.addressRepository=addressRepository; + } + + public Address getAddressById(Integer id) throws AddressNotExistsException { + return addressRepository.findById(id).orElseThrow(AddressNotExistsException::new); + } + + public Address newAddress(Address address) { + if (!addressRepository.existsById(address.getId())) { + return addressRepository.save(address); + } + else{ + return null; + } + } + + public Page allAddress(Pageable pageable) { + return addressRepository.findAll(pageable); + } +} diff --git a/src/main/java/com/api/UDEE/service/BillService.java b/src/main/java/com/api/UDEE/service/BillService.java new file mode 100644 index 0000000..36f293a --- /dev/null +++ b/src/main/java/com/api/UDEE/service/BillService.java @@ -0,0 +1,37 @@ +package com.api.UDEE.service; + +import com.api.UDEE.domain.Address; +import com.api.UDEE.domain.Bill; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.repository.BillRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +public class BillService { + private final BillRepository billRepository; + @Autowired + public BillService(BillRepository billRepository){ + this.billRepository=billRepository; + } + + public Bill getBillById(Integer id) throws AddressNotExistsException { + return billRepository.findById(id).orElseThrow(AddressNotExistsException::new); + } + + public Bill newBill(Bill bill) { + if (!billRepository.existsById(bill.getId())) { + return billRepository.save(bill); + } + else{ + return null; + } + } + + public Page allBills(Pageable pageable) { + return billRepository.findAll(pageable); + } + +} diff --git a/src/main/java/com/api/UDEE/service/BrandService.java b/src/main/java/com/api/UDEE/service/BrandService.java new file mode 100644 index 0000000..e122b39 --- /dev/null +++ b/src/main/java/com/api/UDEE/service/BrandService.java @@ -0,0 +1,37 @@ +package com.api.UDEE.service; + +import com.api.UDEE.domain.Bill; +import com.api.UDEE.domain.Brand; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.repository.BrandRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +public class BrandService { + private final BrandRepository brandRepository; + @Autowired + public BrandService(BrandRepository brandRepository){ + this.brandRepository=brandRepository; + } + + public Brand getBrandById(Integer id) throws AddressNotExistsException { + return brandRepository.findById(id).orElseThrow(AddressNotExistsException::new); + } + + public Brand newBrand(Brand brand) { + //if (!brandRepository.existsById(brand.getId())) { + return brandRepository.save(brand); + /*} + else{ + return null; + }*/ + } + + public Page allBrands(Pageable pageable) { + return brandRepository.findAll(pageable); + } + +} diff --git a/src/main/java/com/api/UDEE/service/ClientService.java b/src/main/java/com/api/UDEE/service/ClientService.java new file mode 100644 index 0000000..16246d7 --- /dev/null +++ b/src/main/java/com/api/UDEE/service/ClientService.java @@ -0,0 +1,36 @@ +package com.api.UDEE.service; + +import com.api.UDEE.domain.Client; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.repository.ClientRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +public class ClientService { + private final ClientRepository clientRepository; + @Autowired + public ClientService(ClientRepository clientRepository){ + this.clientRepository=clientRepository; + } + + public Client getClientById(Integer id) throws AddressNotExistsException { + return clientRepository.findById(id).orElseThrow(AddressNotExistsException::new); + } + + public Client newClient(Client client) { + if (!clientRepository.existsById(client.getId())) { + return clientRepository.save(client); + } + else{ + return null; + } + } + + public Page allClients(Pageable pageable) { + return clientRepository.findAll(pageable); + } + +} diff --git a/src/main/java/com/api/UDEE/service/MeasurementService.java b/src/main/java/com/api/UDEE/service/MeasurementService.java new file mode 100644 index 0000000..6c558e7 --- /dev/null +++ b/src/main/java/com/api/UDEE/service/MeasurementService.java @@ -0,0 +1,36 @@ +package com.api.UDEE.service; + +import com.api.UDEE.domain.Measurement; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.repository.MeasurementRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +public class MeasurementService { + private final MeasurementRepository measurementRepository; + @Autowired + public MeasurementService(MeasurementRepository measurementRepository){ + this.measurementRepository=measurementRepository; + } + + public Measurement getMeasurementById(Integer id) throws AddressNotExistsException { + return measurementRepository.findById(id).orElseThrow(AddressNotExistsException::new); + } + + public Measurement newMeasurement(Measurement reading) { + if (!measurementRepository.existsById(reading.getId())) { + return measurementRepository.save(reading); + } + else{ + return null; + } + } + + public Page allMeasurements(Pageable pageable) { + return measurementRepository.findAll(pageable); + } + +} diff --git a/src/main/java/com/api/UDEE/service/MeterService.java b/src/main/java/com/api/UDEE/service/MeterService.java new file mode 100644 index 0000000..8cb84a0 --- /dev/null +++ b/src/main/java/com/api/UDEE/service/MeterService.java @@ -0,0 +1,36 @@ +package com.api.UDEE.service; + +import com.api.UDEE.domain.Meter; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.exceptions.CountryExistsException; +import com.api.UDEE.repository.MeterRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +public class MeterService { + private final MeterRepository meterRepository; + + @Autowired + public MeterService(MeterRepository meterRepository){ + this.meterRepository=meterRepository; + } + + public Meter getMeterById(Integer id) throws AddressNotExistsException { + return meterRepository.findById(id).orElseThrow(AddressNotExistsException::new); + } + + public Meter newMeter(Meter meter) throws CountryExistsException { + if (!meterRepository.existsById(meter.getId())) { + return meterRepository.save(meter); + } + else{ + throw new CountryExistsException(); + } + } + public Page allMeter(Pageable pageable) { + return meterRepository.findAll(pageable); + } +} diff --git a/src/main/java/com/api/UDEE/service/ModelService.java b/src/main/java/com/api/UDEE/service/ModelService.java new file mode 100644 index 0000000..286ea2f --- /dev/null +++ b/src/main/java/com/api/UDEE/service/ModelService.java @@ -0,0 +1,37 @@ +package com.api.UDEE.service; + +import com.api.UDEE.domain.Client; +import com.api.UDEE.domain.Model; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.repository.ModelRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +public class ModelService { + private final ModelRepository modelRepository; + @Autowired + public ModelService(ModelRepository modelRepository){ + this.modelRepository=modelRepository; + } + + public Model getModelById(Integer id) throws AddressNotExistsException { + return modelRepository.findById(id).orElseThrow(AddressNotExistsException::new); + } + + public Model newModel(Model model) { + //if (!modelRepository.existsById(model.getId())) { + return modelRepository.save(model); + /*} + else{ + return null; + }*/ + } + + public Page allModels(Pageable pageable) { + return modelRepository.findAll(pageable); + } + +} diff --git a/src/main/java/com/api/UDEE/service/RateService.java b/src/main/java/com/api/UDEE/service/RateService.java new file mode 100644 index 0000000..8aab3bb --- /dev/null +++ b/src/main/java/com/api/UDEE/service/RateService.java @@ -0,0 +1,53 @@ +package com.api.UDEE.service; + +import com.api.UDEE.Utils.EntityURLBuilder; +import com.api.UDEE.domain.Client; +import com.api.UDEE.domain.PaginationResponse; +import com.api.UDEE.domain.PostResponse; +import com.api.UDEE.domain.Rate; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.repository.RateRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; + +@Service +public class RateService { + private final RateRepository rateRepository; + private static final String RATE_PATH = "rate"; + @Autowired + public RateService(RateRepository rateRepository){ + this.rateRepository=rateRepository; + } + + public Rate getRateById(Integer id) throws AddressNotExistsException { + return rateRepository.findById(id).orElseThrow(AddressNotExistsException::new); + } + + /* + public Rate newRate(Rate rate) { + if (!rateRepository.existsById(rate.getId())) { + return rateRepository.save(rate); + } + else{ + return null; + } + }*/ + + public PostResponse newRate(Rate rate) { + Rate r = rateRepository.save(rate); + return PostResponse + .builder() + .status(HttpStatus.CREATED) + .url(EntityURLBuilder.buildURL(RATE_PATH, r.getId())) + .build(); + } + + public Page allRates(Pageable pageable){ + return this.rateRepository.findAll(pageable); + } + +} diff --git a/src/main/java/com/api/UDEE/service/UserService.java b/src/main/java/com/api/UDEE/service/UserService.java new file mode 100644 index 0000000..498bbaf --- /dev/null +++ b/src/main/java/com/api/UDEE/service/UserService.java @@ -0,0 +1,41 @@ +package com.api.UDEE.service; + +import com.api.UDEE.domain.User; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.repository.UserRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; + +@Service +public class UserService { + private final UserRepository userRepository; + + @Autowired + public UserService(UserRepository userRepository){ + this.userRepository=userRepository; + } + + public User login(String username, String password) { + return userRepository.findByUsernameAndPassword(username, password); + } + + public User getUserById(Integer id) throws AddressNotExistsException { + return userRepository.findById(id).orElseThrow(AddressNotExistsException::new); + } + + public User newUser(User user) { + if (!userRepository.existsById(user.getId())) { + return userRepository.save(user); + } + else{ + return null; + } + } + + public Page allUsers(Pageable pageable) { + return userRepository.findAll(pageable); + } + +} diff --git a/src/main/java/com/api/UDEE/service/UsuarioService.java b/src/main/java/com/api/UDEE/service/UsuarioService.java new file mode 100644 index 0000000..27b7f95 --- /dev/null +++ b/src/main/java/com/api/UDEE/service/UsuarioService.java @@ -0,0 +1,39 @@ +package com.api.UDEE.service; + +import com.api.UDEE.domain.Usuario; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.repository.UsuarioRepository; +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 java.util.Optional; + +@Service +public class UsuarioService { + + private final UsuarioRepository usuarioRepository; + + @Autowired + public UsuarioService(UsuarioRepository usuarioRepository){ + this.usuarioRepository=usuarioRepository; + } + + public Usuario login(String username, String password) { + return Optional.ofNullable(usuarioRepository.findByUsernameAndPassword(username, password)).orElseThrow(() -> new RuntimeException("User does not exists")); + } + + public Usuario getUserById(Integer id) throws AddressNotExistsException { + return usuarioRepository.findById(id).orElseThrow(AddressNotExistsException::new); + } + + public Usuario newUser(Usuario user) { + return usuarioRepository.save(user); + } + + public Page allUsers(Pageable pageable) { + return usuarioRepository.findAll(pageable); + } + +} diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml new file mode 100644 index 0000000..230c423 --- /dev/null +++ b/src/main/resources/application-dev.yml @@ -0,0 +1,11 @@ +Spring: + Datasource: + url: jdbc:mysql://localhost:3306/UDEE?serverTimezone=UTC + username: root + + jpa: + hibernate: + ddl-auto: none + dialect: org.hibernate.dialect.MySQL8Dialect + driverClassName: com.mysql.cj.jdbc.Drive + database: mysql diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1 @@ + diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml new file mode 100644 index 0000000..ad9a171 --- /dev/null +++ b/src/main/resources/application.yml @@ -0,0 +1,4 @@ +spring: + profiles: + active: dev + diff --git a/src/test/java/com/api/UDEE/AbstractController.java b/src/test/java/com/api/UDEE/AbstractController.java new file mode 100644 index 0000000..daf8d07 --- /dev/null +++ b/src/test/java/com/api/UDEE/AbstractController.java @@ -0,0 +1,28 @@ +package com.api.UDEE; + +import org.junit.jupiter.api.TestInstance; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureWebMvc; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +@AutoConfigureWebMvc +@AutoConfigureMockMvc +@ContextConfiguration +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public abstract class AbstractController { + + @Autowired + private WebApplicationContext webApplicationContext; + + public MockMvc mockMvc; + + protected MockMvc givenController() { + return MockMvcBuilders.webAppContextSetup(this.webApplicationContext) + .build(); + } + +} diff --git a/src/test/java/com/api/UDEE/UdeeApplicationTests.java b/src/test/java/com/api/UDEE/UdeeApplicationTests.java new file mode 100644 index 0000000..ee8af53 --- /dev/null +++ b/src/test/java/com/api/UDEE/UdeeApplicationTests.java @@ -0,0 +1,13 @@ +package com.api.UDEE; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class UdeeApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/src/test/java/com/api/UDEE/controller/ModelControllerTest.java b/src/test/java/com/api/UDEE/controller/ModelControllerTest.java new file mode 100644 index 0000000..0f61910 --- /dev/null +++ b/src/test/java/com/api/UDEE/controller/ModelControllerTest.java @@ -0,0 +1,52 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.AbstractController; +import com.api.UDEE.service.ModelService; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import static com.api.UDEE.utils.TestUtils.aModelJSON; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest(classes = ModelController.class) +public class ModelControllerTest extends AbstractController { + @MockBean + private ModelService modelService; + + @Test + public void allModel() throws Exception { + final ResultActions resultActions = givenController().perform(MockMvcRequestBuilders + .get("/api/models") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + assertEquals(HttpStatus.OK.value(), resultActions.andReturn().getResponse().getStatus()); + } + + @Test + public void getModelById() throws Exception { + final ResultActions resultActions = givenController().perform(MockMvcRequestBuilders + .get("/api/models/1") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + assertEquals(HttpStatus.OK.value(), resultActions.andReturn().getResponse().getStatus()); + } + + @Test + public void newModel() throws Exception { + final ResultActions resultActions = givenController().perform(MockMvcRequestBuilders + .post("/api/models") + .contentType(MediaType.APPLICATION_JSON) + .content(aModelJSON())) + .andExpect(status().isOk()); + + assertEquals(HttpStatus.OK.value(), resultActions.andReturn().getResponse().getStatus()); + } +} diff --git a/src/test/java/com/api/UDEE/controller/PersonaControllerTest.java b/src/test/java/com/api/UDEE/controller/PersonaControllerTest.java new file mode 100644 index 0000000..60bed8c --- /dev/null +++ b/src/test/java/com/api/UDEE/controller/PersonaControllerTest.java @@ -0,0 +1,65 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.AbstractController; +import com.api.UDEE.service.ClientService; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import static com.api.UDEE.utils.TestUtils.aRateJSON; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + + +@SpringBootTest(classes = ClientController.class) +public class PersonaControllerTest extends AbstractController { + + @MockBean + private ClientService clientService; + + @Test + public void allClients() throws Exception { + final ResultActions resultActions = givenController().perform(MockMvcRequestBuilders + .get("/api/clients") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + assertEquals(HttpStatus.OK.value(), resultActions.andReturn().getResponse().getStatus()); + } + + @Test + public void getClientById() throws Exception { + final ResultActions resultActions = givenController().perform(MockMvcRequestBuilders + .get("/clients/1") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + assertEquals(HttpStatus.OK.value(), resultActions.andReturn().getResponse().getStatus()); + } +/* + @Test + public void newClient() throws Exception { + final ResultActions resultActions = givenController().perform(MockMvcRequestBuilders + .post("/clients") + .contentType(MediaType.APPLICATION_JSON) + .content(aClientJSON())) + .andExpect(status().isOk()); + + assertEquals(HttpStatus.OK.value(), resultActions.andReturn().getResponse().getStatus()); + } +*/ + @Test + public void addPersonBadRequest() throws Exception { + final ResultActions resultActions = givenController().perform(MockMvcRequestBuilders + .post("/clients") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + + assertEquals(HttpStatus.BAD_REQUEST.value(), resultActions.andReturn().getResponse().getStatus()); + } + +} diff --git a/src/test/java/com/api/UDEE/controller/RateControllerTest.java b/src/test/java/com/api/UDEE/controller/RateControllerTest.java new file mode 100644 index 0000000..cb860b4 --- /dev/null +++ b/src/test/java/com/api/UDEE/controller/RateControllerTest.java @@ -0,0 +1,64 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.AbstractController; +import com.api.UDEE.service.RateService; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.ResultActions; +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; + +import static com.api.UDEE.utils.TestUtils.aRateJSON; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +@SpringBootTest(classes = RateController.class) +public class RateControllerTest extends AbstractController{ + @MockBean + private RateService rateService; + + @Test + public void allRate() throws Exception { + final ResultActions resultActions = givenController().perform(MockMvcRequestBuilders + .get("/api/rates") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + assertEquals(HttpStatus.OK.value(), resultActions.andReturn().getResponse().getStatus()); + } + + @Test + public void getRateById() throws Exception { + final ResultActions resultActions = givenController().perform(MockMvcRequestBuilders + .get("/rates/1") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); + + assertEquals(HttpStatus.OK.value(), resultActions.andReturn().getResponse().getStatus()); + } + + @Test + public void newRate() throws Exception { + final ResultActions resultActions = givenController().perform(MockMvcRequestBuilders + .post("/api/rates") + .contentType(MediaType.APPLICATION_JSON) + .content(aRateJSON())) + .andExpect(status().isOk()); + + assertEquals(HttpStatus.OK.value(), resultActions.andReturn().getResponse().getStatus()); + } + + /* + @Test + public void addPersonBadRequest() throws Exception { + final ResultActions resultActions = givenController().perform(MockMvcRequestBuilders + .post("/api/rates") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isBadRequest()); + + assertEquals(HttpStatus.BAD_REQUEST.value(), resultActions.andReturn().getResponse().getStatus()); + }*/ + +} diff --git a/src/test/java/com/api/UDEE/controller/UsuarioControllerTest.java b/src/test/java/com/api/UDEE/controller/UsuarioControllerTest.java new file mode 100644 index 0000000..baa660d --- /dev/null +++ b/src/test/java/com/api/UDEE/controller/UsuarioControllerTest.java @@ -0,0 +1,110 @@ +package com.api.UDEE.controller; + +import com.api.UDEE.domain.Usuario; +import com.api.UDEE.dto.UserDto; +import com.api.UDEE.service.UsuarioService; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.modelmapper.ModelMapper; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.support.ServletUriComponentsBuilder; + +import java.util.Collections; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class UsuarioControllerTest { + + private UsuarioService usuarioService; + private ModelMapper modelMapper; + private ObjectMapper objectMapper; + + private UsuarioController usuarioController; + + private static List EMPTY_LIST = Collections.emptyList(); + private static List USUARIO_LIST = List.of(Usuario.builder().username("nico").id(1).build(), + Usuario.builder().username("nicolas").id(2).build()); + + + @BeforeEach + public void setUp() { + usuarioService = mock(UsuarioService.class); + usuarioController = new UsuarioController(usuarioService,modelMapper,objectMapper); + } + + + // Vamos a testear que haya paises dentro de lo que se pidio + + @Test + public void testAllUsersHttpStatus200() { + + //given + Pageable pageable = PageRequest.of(1, 10); + Page mockedPage = mock(Page.class); + when(mockedPage.getTotalElements()).thenReturn(100L); + when(mockedPage.getTotalPages()).thenReturn(10); + when(mockedPage.getContent()).thenReturn(USUARIO_LIST); + when(usuarioService.allUsers(pageable)).thenReturn(mockedPage); + + //Then + ResponseEntity> response = usuarioController.allUsers(pageable); + + //Assert + assertEquals(HttpStatus.OK, response.getStatusCode()); + assertEquals(100L, Long.parseLong(response.getHeaders().get("X-Total-Count").get(0)) ); + assertEquals(10, Integer.parseInt(response.getHeaders().get("X-Total-Pages").get(0)) ); + assertEquals(USUARIO_LIST, response.getBody()); + } + + + //* Vamos a testear que haya paises dentro de lo que se pidio + + @Test + public void testAllUsersNoContent() { + //given + Pageable pageable = PageRequest.of(50, 10); + Page mockedPage = mock(Page.class); + when(mockedPage.getContent()).thenReturn(EMPTY_LIST); + when(usuarioService.allUsers(pageable)).thenReturn(mockedPage); + + //Then + ResponseEntity> response = usuarioController.allUsers(pageable); + + //Assert + assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode()); + assertEquals(0, response.getBody().size()); + } + + @Test + public void addClient_Test200(){ + MockHttpServletRequest request = new MockHttpServletRequest(); + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); + + //Date birtday = new SimpleDateFormat("yyyy-MM-dd").parse("2020-02-02"); + ServletUriComponentsBuilder location = mock(ServletUriComponentsBuilder.class); + + UserDto registerDto = UserDto.builder() + .id(1) + .username("nicolas") + .build(); + + Usuario usuario= Usuario.builder().id(1).username("nicolas").password("1234").build(); + + when(usuarioService.newUser(usuario)).thenReturn(usuario); + + ResponseEntity response = usuarioController.newClient(usuario); + + assertEquals(HttpStatus.CREATED, response.getStatusCode()); + } +} diff --git a/src/test/java/com/api/UDEE/service/UsuarioServiceTest.java b/src/test/java/com/api/UDEE/service/UsuarioServiceTest.java new file mode 100644 index 0000000..379bf40 --- /dev/null +++ b/src/test/java/com/api/UDEE/service/UsuarioServiceTest.java @@ -0,0 +1,131 @@ +package com.api.UDEE.service; + +import com.api.UDEE.domain.Usuario; +import com.api.UDEE.exceptions.AddressNotExistsException; +import com.api.UDEE.repository.UsuarioRepository; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatchers; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.Pageable; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import static com.api.UDEE.utils.TestUtils.*; +import static org.mockito.Mockito.*; +import static org.junit.jupiter.api.Assertions.*; +@ExtendWith(MockitoExtension.class) + +class UsuarioServiceTest { + + @InjectMocks + private UsuarioService usuarioService; + + @Mock + private UsuarioRepository usuarioRepository; + + /*@Mock + private UsuarioRepository usuarioRepository; +*/ + + @Test + void getUserById() throws AddressNotExistsException { + Usuario usuario= aUsuario(); + Mockito.when(usuarioRepository.findById(usuario.getId())).thenReturn(Optional.of(usuario)); + + Usuario response = usuarioService.getUserById(1); + assertNotNull(response); + assertEquals(usuario, response); + } + + @Test + void shouldSaveUser() throws AddressNotExistsException { + + Usuario usuario= aUsuario(); + + Mockito.when(usuarioRepository.save(usuario)).thenReturn(usuario); + + assertNotNull(usuario); + + usuarioRepository.save(usuario); + + } + + @Test + void badRequestSaveUser(){ + Usuario usuario= aUsuario(); + + when(usuarioRepository.save(usuario)).thenReturn(usuario); + + //when(usuarioService.getReduceUser(user.getIdUser())).thenReturn(userReduce); + when(usuarioRepository.findById(usuario.getId())).thenReturn(null); + + //assertEquals(400, response.getStatusCodeValue()); + //assertNull(response.getBody()); + } + + @Test + void shouldLogin(){ + Usuario usuario= new Usuario();//(1,"nico","1234"); + String username="nico"; + String password="1234"; + usuario.setUsername(username); + usuario.setPassword(password); + when(usuarioRepository.findByUsernameAndPassword(username,password)).thenReturn(usuario); + Usuario response= usuarioService.login(username,password); + + assertNotNull(response); + assertEquals(usuario,response); + } + + + @Test + void badRequestLogin(){ + Usuario usuario= new Usuario(); + String username="nico"; + String password="1234"; + usuario.setUsername(username); + usuario.setPassword(password); + + Mockito.when(usuarioRepository.findByUsernameAndPassword(username, password)).thenReturn(null); + + assertThrows(RuntimeException.class, () -> { + usuarioService.login(username, password); + }); + } + + @Test + void shouldGetAll() { + /*Usuario usuario= new Usuario(1,"nicolas","roldan"); + Usuario usuario2= new Usuario(2,"rodrigo","villarroel"); + List usersList = new ArrayList<>(); + usersList.add(usuario); + usersList.add(usuario2); + Page user = new PageImpl<>(usersList); + + when(usuarioRepository.findAll()).thenReturn(user); + Page response = usuarioService.allUsers((Pageable) user); + + assertNotNull(response); + assertEquals(usersList, response); +*/ + + Pageable pageable = aPageable(); + Page page = aUsuarioPage(); + + when(usuarioRepository.findAll(pageable)).thenReturn(page); + + Page u = usuarioService.allUsers(pageable); + + //assertEquals(page.getContent().get(0).getDni(),c.getContent().get(0).getDni()); + assertEquals(page.getContent().get(0).getId(),u.getContent().get(0).getId()); + //assertEquals(pageable.getPageNumber(),u.getTotalPages()); + } +} diff --git a/src/test/java/com/api/UDEE/utils/LocalDateDeserializer.java b/src/test/java/com/api/UDEE/utils/LocalDateDeserializer.java new file mode 100644 index 0000000..6e8fc50 --- /dev/null +++ b/src/test/java/com/api/UDEE/utils/LocalDateDeserializer.java @@ -0,0 +1,18 @@ +package com.api.UDEE.utils; + +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; + +import java.lang.reflect.Type; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +public class LocalDateDeserializer implements JsonDeserializer { + + @Override + public LocalDate deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { + return LocalDate.parse(jsonElement.getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd")); + } +} diff --git a/src/test/java/com/api/UDEE/utils/LocalDateSerializer.java b/src/test/java/com/api/UDEE/utils/LocalDateSerializer.java new file mode 100644 index 0000000..bc3f3d0 --- /dev/null +++ b/src/test/java/com/api/UDEE/utils/LocalDateSerializer.java @@ -0,0 +1,17 @@ +package com.api.UDEE.utils; + +import com.google.gson.*; + +import java.lang.reflect.Type; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +public class LocalDateSerializer implements JsonSerializer { + + public static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + + @Override + public JsonElement serialize(LocalDate localDate, Type type, JsonSerializationContext jsonSerializationContext) { + return new JsonPrimitive(formatter.format(localDate)); + } +} diff --git a/src/test/java/com/api/UDEE/utils/TestUtils.java b/src/test/java/com/api/UDEE/utils/TestUtils.java new file mode 100644 index 0000000..ee35e15 --- /dev/null +++ b/src/test/java/com/api/UDEE/utils/TestUtils.java @@ -0,0 +1,87 @@ +package com.api.UDEE.utils; + +import com.api.UDEE.domain.Client; +import com.api.UDEE.domain.Model; +import com.api.UDEE.domain.Rate; +import com.api.UDEE.domain.Usuario; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; + +import java.time.LocalDate; +import java.util.List; + +public class TestUtils { + + public static String aRateJSON() { + final Gson gson = new GsonBuilder() + .registerTypeAdapter(LocalDate.class, new LocalDateSerializer()) + .registerTypeAdapter(LocalDate.class, new LocalDateDeserializer()) + .setPrettyPrinting().create(); + + return gson.toJson(aRate()); + } + + public static Rate aRate(){ + Rate r= new Rate(); + r.setId(1); + r.setPrice(350.5F); + return r; + } + + public static String aModelJSON() { + final Gson gson = new GsonBuilder() + .registerTypeAdapter(LocalDate.class, new LocalDateSerializer()) + .registerTypeAdapter(LocalDate.class, new LocalDateDeserializer()) + .setPrettyPrinting().create(); + + return gson.toJson(aModel()); + } + + public static Model aModel(){ + Model m= new Model(); + m.setId(1); + m.setName("a10"); + return m; + } + + public static Pageable aPageable(){ + return PageRequest.of(0,10); + } + + public static Page aUsuarioPage(){ + return new PageImpl<>(List.of(aUsuario())); + } + //aClientPage + + public static Usuario aUsuario(){ + Usuario u = new Usuario(); + u.setId(1); + u.setUsername("nico"); + u.setPassword("1234"); + return u; + } + + public static Client aClient() { + Client c = new Client(); + c.setEmail("nicolasroldan31@gmail.com"); + c.setId(1); + c.setName("nicolas"); + c.setLast_name("roldan"); + return c; + } + /* + public static Persona aPersona() { + Persona p = new Persona(); + p.setApellido("apellido"); + p.setNombre("nombre"); + p.setDireccion("calle falsa 123"); + p.setDni("dni"); + p.setVehiculoList(new ArrayList<>()); + return p; + } + */ +}