├── caracteristicas-da-linguagem-java-2 ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ ├── fors │ └── For.java │ ├── ifs │ └── IF.java │ ├── operadores │ ├── Igualdade.java │ ├── Incremento.java │ ├── Logicos.java │ ├── Matematicos.java │ └── Relacionais.java │ ├── strings │ ├── StringBuilder.java │ ├── StringFormat.java │ └── Strings.java │ └── whiles │ └── While.java ├── caracteristicas-da-linguagem-java ├── .gitignore ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ └── main │ └── java │ └── one │ └── digitalinnovation │ ├── abstracts │ ├── FormaGeometrica.java │ ├── Programa.java │ └── Quadrado.java │ ├── classes │ ├── Programa.java │ ├── cliente │ │ ├── Cliente.java │ │ └── ProgramaDoCliente.java │ ├── pessoa │ │ ├── Pessoa.java │ │ ├── PessoaFisica.java │ │ ├── ProgramaDoCliente.java │ │ ├── ProgramaDoUsuario.java │ │ ├── ProgramaPessoaFisica.java │ │ └── Usuario.java │ └── usuario │ │ ├── ProgramaDoSuperUsuario.java │ │ └── SuperUsuario.java │ ├── enums │ ├── Programa.java │ ├── Status.java │ └── TipoVeiculo.java │ ├── finals │ ├── CasualGamer.java │ ├── Gamer.java │ ├── HardcoreGamer.java │ └── Programa.java │ ├── interfaces │ ├── Automovel.java │ ├── Carro.java │ ├── Fiesta.java │ ├── Gol.java │ ├── Programa.java │ ├── Trator.java │ └── Veiculo.java │ ├── statics │ ├── Cachorro.java │ └── Programa.java │ └── tipos │ ├── naoprimitivos │ ├── NaoPrimitivos.java │ └── Unboxing.java │ ├── primitivos │ ├── DefaultValues.java │ └── Primitivos.java │ ├── tipagem │ ├── Escopo.java │ ├── TipagemEstatica.java │ ├── TipagemForte.java │ └── TipoInferido.java │ └── wrappers │ └── Wrappers.java ├── cities-api-full-ci-cd ├── .gitignore ├── .travis.yml ├── Procfile ├── README.md ├── build.gradle ├── google_checks.xml ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── pmd-ruleset.xml ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── github │ │ │ └── andrelugomes │ │ │ ├── CitiesApplication.java │ │ │ ├── cities │ │ │ ├── entities │ │ │ │ ├── City.java │ │ │ │ └── PointType.java │ │ │ ├── repositories │ │ │ │ └── CityRepository.java │ │ │ ├── resources │ │ │ │ ├── CityResource.java │ │ │ │ └── DistanceResource.java │ │ │ └── service │ │ │ │ ├── DistanceService.java │ │ │ │ └── EarthRadius.java │ │ │ ├── countries │ │ │ ├── entities │ │ │ │ └── Country.java │ │ │ ├── repositories │ │ │ │ └── CountryRepository.java │ │ │ └── resources │ │ │ │ └── CountryResource.java │ │ │ ├── states │ │ │ ├── entities │ │ │ │ └── State.java │ │ │ ├── repositories │ │ │ │ └── StateRepository.java │ │ │ └── resources │ │ │ │ └── StateResource.java │ │ │ └── utils │ │ │ └── StringLocationUtils.java │ └── resources │ │ ├── application-heroku.properties │ │ ├── application.properties │ │ └── db │ │ └── migration │ │ ├── V1__create_paises.sql │ │ ├── V2__create_estados.sql │ │ ├── V3__create_cidades.sql │ │ └── V4__enable_postgres_extentions.sql │ └── test │ ├── java │ └── com │ │ └── github │ │ └── andrelugomes │ │ ├── cities │ │ ├── resources │ │ │ └── CityResourceTest.java │ │ └── service │ │ │ └── DistanceServiceTest.java │ │ ├── countries │ │ └── resources │ │ │ └── CountryResourceTest.java │ │ ├── states │ │ └── resources │ │ │ └── StateResourceTest.java │ │ └── utils │ │ └── StringLocationUtilsTest.java │ └── resources │ ├── application.properties │ ├── data.sql │ └── schema.sql ├── cities-api-nearby-service ├── .gitignore ├── .travis.yml ├── Procfile ├── README.md ├── build.gradle ├── google_checks.xml ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── pmd-ruleset.xml ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── github │ │ │ └── andrelugomes │ │ │ ├── CitiesApplication.java │ │ │ ├── cities │ │ │ ├── entities │ │ │ │ ├── City.java │ │ │ │ └── PointType.java │ │ │ ├── repositories │ │ │ │ └── CityRepository.java │ │ │ ├── resources │ │ │ │ ├── CityResource.java │ │ │ │ ├── DistanceResource.java │ │ │ │ └── NearbyResource.java │ │ │ └── service │ │ │ │ ├── DistanceService.java │ │ │ │ └── EarthRadius.java │ │ │ ├── countries │ │ │ ├── entities │ │ │ │ └── Country.java │ │ │ ├── repositories │ │ │ │ └── CountryRepository.java │ │ │ └── resources │ │ │ │ └── CountryResource.java │ │ │ ├── states │ │ │ ├── entities │ │ │ │ └── State.java │ │ │ ├── repositories │ │ │ │ └── StateRepository.java │ │ │ └── resources │ │ │ │ └── StateResource.java │ │ │ └── utils │ │ │ └── StringLocationUtils.java │ └── resources │ │ ├── application-heroku.properties │ │ ├── application.properties │ │ └── db │ │ └── migration │ │ ├── V1__create_paises.sql │ │ ├── V2__create_estados.sql │ │ ├── V3__create_cidades.sql │ │ ├── V4__enable_postgres_extentions.sql │ │ └── V5__delete_last_city_called_exterior.sql │ └── test │ ├── java │ └── com │ │ └── github │ │ └── andrelugomes │ │ ├── cities │ │ ├── resources │ │ │ └── CityResourceTest.java │ │ └── service │ │ │ └── DistanceServiceTest.java │ │ ├── countries │ │ └── resources │ │ │ └── CountryResourceTest.java │ │ ├── states │ │ └── resources │ │ │ └── StateResourceTest.java │ │ └── utils │ │ └── StringLocationUtilsTest.java │ └── resources │ ├── application.properties │ ├── data.sql │ └── schema.sql ├── cities-api ├── .gitignore ├── Procfile ├── README.md ├── build.gradle ├── gradle │ └── wrapper │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src │ ├── main │ ├── java │ │ └── com │ │ │ └── github │ │ │ └── andrelugomes │ │ │ ├── CitiesApplication.java │ │ │ ├── cities │ │ │ ├── entities │ │ │ │ ├── City.java │ │ │ │ └── PointType.java │ │ │ ├── repositories │ │ │ │ └── CityRepository.java │ │ │ ├── resources │ │ │ │ ├── CityResource.java │ │ │ │ └── DistanceResource.java │ │ │ └── service │ │ │ │ ├── DistanceService.java │ │ │ │ └── EarthRadius.java │ │ │ ├── countries │ │ │ ├── entities │ │ │ │ └── Country.java │ │ │ ├── repositories │ │ │ │ └── CountryRepository.java │ │ │ └── resources │ │ │ │ └── CountryResource.java │ │ │ ├── staties │ │ │ ├── entities │ │ │ │ └── State.java │ │ │ ├── repositories │ │ │ │ └── StateRepository.java │ │ │ └── resources │ │ │ │ └── StateResource.java │ │ │ └── utils │ │ │ └── StringLocationUtils.java │ └── resources │ │ ├── application-heroku.properties │ │ └── application.properties │ └── test │ ├── java │ └── com │ │ └── github │ │ └── andrelugomes │ │ ├── cities │ │ └── service │ │ │ └── DistanceServiceTest.java │ │ └── utils │ │ └── StringLocationUtilsTest.java │ └── resources │ └── application.properties └── debug-de-codigo ├── .gitignore ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src └── main └── java └── one └── innovation └── digital ├── Programa.java ├── imc └── CalculadorDeImc.java └── pessoa └── Pessoa.java /caracteristicas-da-linguagem-java-2/.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | ### Example user template template 3 | ### Example user template 4 | 5 | # IntelliJ project files 6 | .idea 7 | *.iml 8 | out 9 | gen 10 | /build 11 | .gradle 12 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'one.digitalinnovation' 6 | version '1.0-SNAPSHOT' 7 | 8 | sourceCompatibility = 1.11 9 | 10 | repositories { 11 | mavenCentral() 12 | } 13 | 14 | dependencies { 15 | testCompile group: 'junit', name: 'junit', version: '4.12' 16 | } 17 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andrelugomes/digital-innovation-one/31982544848f282a20f776efc7c8a64e4ba40560/caracteristicas-da-linguagem-java-2/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.3.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | ifs expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | ifs [ -n "$JAVA_HOME" ] ; then 71 | ifs [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | ifs [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors ifs we can. 92 | ifs [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | ifs [ $? -eq 0 ] ; then 95 | ifs [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | ifs [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | ifs $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | ifs $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | ifs [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine ifs an option 135 | 136 | ifs [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | ifs [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/gradlew.bat: -------------------------------------------------------------------------------- 1 | @ifs "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | ifs "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | ifs "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | ifs defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | ifs "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | ifs exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | ifs not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | ifs "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | ifs "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE ifs you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | ifs not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | ifs "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'caracteristicas-da-linguagem-java-2' 2 | 3 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/src/main/java/fors/For.java: -------------------------------------------------------------------------------- 1 | package fors; 2 | 3 | public class For { 4 | 5 | public static void main(String[] args) { 6 | 7 | for (int i = 0; i <= 10; i = i + 1) { 8 | System.out.println("I=" + i); 9 | } 10 | 11 | for (int x = 0; x <= 5; x++) 12 | System.out.println("X=" + x); 13 | 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/src/main/java/ifs/IF.java: -------------------------------------------------------------------------------- 1 | package ifs; 2 | 3 | public class IF { 4 | 5 | public static void main(String[] args) { 6 | 7 | final var condicao = false; 8 | 9 | if (condicao) { 10 | System.out.println("A condição é verdadeira"); 11 | } else { 12 | System.out.println("A condição é falsa"); 13 | } 14 | 15 | if (condicao) 16 | System.out.println("Uma única linha..."); 17 | 18 | final var ternario = condicao ? "é verdadeira" : "é falsa"; 19 | 20 | System.out.println(ternario); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/src/main/java/operadores/Igualdade.java: -------------------------------------------------------------------------------- 1 | package operadores; 2 | 3 | public class Igualdade { 4 | 5 | public static void main(String[] args) { 6 | 7 | final var numero = 11; 8 | 9 | if (numero == 10) { 10 | System.out.println("O número é 10"); 11 | } else { 12 | System.out.println("O número não é 10"); 13 | } 14 | 15 | if (numero != 10) { 16 | System.out.println("O número não é 10"); 17 | } else { 18 | System.out.println("O número é 10"); 19 | } 20 | 21 | final var letra = "B"; 22 | 23 | if ("A".equals(letra)) { 24 | System.out.println("É a letra A"); 25 | } 26 | 27 | if (!letra.equals("A")) { 28 | System.out.println("Não é a letra A"); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/src/main/java/operadores/Incremento.java: -------------------------------------------------------------------------------- 1 | package operadores; 2 | 3 | public class Incremento { 4 | 5 | public static void main(String[] args) { 6 | 7 | var numero = 1; 8 | 9 | System.out.println(++numero); 10 | 11 | var variavel = 10; 12 | 13 | System.out.println(variavel--); 14 | System.out.println(variavel); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/src/main/java/operadores/Logicos.java: -------------------------------------------------------------------------------- 1 | package operadores; 2 | 3 | public class Logicos { 4 | 5 | public static void main(String[] args) { 6 | 7 | final var numero = 2; 8 | final var letra = "A"; 9 | 10 | //Sort Circuit 11 | if (numero < 5 && letra.equals("A")) { 12 | System.out.println("Atendeu a condição"); 13 | } 14 | 15 | if (numero < 5 || letra.equals("A")) { 16 | System.out.println("Atendeu a outracondição"); 17 | } 18 | 19 | if ((10 - 5) > 1 && (5 - 3) > 1) { 20 | System.out.println("Lógica maluca..."); 21 | } 22 | 23 | //Non Sort Circuit 24 | /*if (verifica(15) | verifica("A")) { 25 | System.out.println("OK"); 26 | } else { 27 | System.out.println("Não OK"); 28 | }*/ 29 | 30 | } 31 | 32 | private static boolean verifica(String letra) { 33 | System.out.println("Verificando letra..."); 34 | return letra.equals("A"); 35 | } 36 | 37 | private static boolean verifica(Integer numero) { 38 | System.out.println("verificando numero..."); 39 | return numero > 10; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/src/main/java/operadores/Matematicos.java: -------------------------------------------------------------------------------- 1 | package operadores; 2 | 3 | public class Matematicos { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.println(0 + 1); 8 | 9 | System.out.println(3 - 1); 10 | 11 | System.out.println(3 * 1); 12 | 13 | System.out.println(8 / 2); 14 | 15 | System.out.println(8 % 2); //módulo - resto da divisão 16 | 17 | var numero = 10; 18 | numero *= 2; 19 | System.out.println(numero); 20 | 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/src/main/java/operadores/Relacionais.java: -------------------------------------------------------------------------------- 1 | package operadores; 2 | 3 | public class Relacionais { 4 | 5 | public static void main(String[] args) { 6 | 7 | final var numero = 6; 8 | 9 | if (numero > 20) { 10 | System.out.println("O número é maior que 20"); 11 | } else if (numero >= 10) { 12 | System.out.println("O número é maior ou igual a 10"); 13 | } else if (numero <= 5) { 14 | System.out.println("O número é menor ou igual que 5"); 15 | } else { 16 | System.out.println("nenhuma da anteriores"); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/src/main/java/strings/StringBuilder.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class StringBuilder { 4 | 5 | public static void main(String[] args) { 6 | 7 | var nome = "André"; 8 | 9 | final var builder = new java.lang.StringBuilder(nome); 10 | System.out.println(builder.append("Luis")); 11 | 12 | final var reverse = builder.reverse(); 13 | 14 | System.out.println(reverse); 15 | 16 | final var insert = reverse.insert(0, "#").insert(reverse.length(), "#"); 17 | System.out.println(insert); 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/src/main/java/strings/StringFormat.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class StringFormat { 4 | 5 | public static void main(String[] args) { 6 | 7 | var nome = "André"; 8 | var sobreNome = "Gomes"; 9 | final var nomeCompleto = nome + sobreNome; 10 | 11 | System.out.println(nome); 12 | System.out.println("Nome do cliente : " + nome); 13 | System.out.println("Nome completo do cliente : " + nomeCompleto); 14 | final var mensagem = String.format("O cliente %s possui sobre nome %s ", nome, sobreNome); 15 | System.out.println(mensagem); 16 | 17 | System.out.println(String.format("Numero %.2f ", 1.2375d)); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/src/main/java/strings/Strings.java: -------------------------------------------------------------------------------- 1 | package strings; 2 | 3 | public class Strings { 4 | 5 | public static void main(String[] args) { 6 | 7 | var nome = "André"; 8 | var sobreNome = "Gomes"; 9 | final var nomeCompleto = nome + sobreNome; 10 | 11 | System.out.println(nome); 12 | System.out.println("Nome do cliente : " + nome); 13 | System.out.println("Nome completo do cliente : " + nomeCompleto); 14 | var string = new String(" Minha String "); 15 | 16 | System.out.println("Char na posição : " + string.charAt(5)); 17 | System.out.println("Quantidade=" + string.length()); 18 | System.out.println("Sem Trim [" + string + "]"); 19 | System.out.println("Com Trim [" + string.trim() + "]"); 20 | System.out.println("Lower " + string.toLowerCase()); 21 | System.out.println("Upper " + string.toUpperCase()); 22 | System.out.println("Contém M? " + string.contains("M")); 23 | System.out.println("Contém X? " + string.contains("X")); 24 | System.out.println("Replace " + string.replace("n", "$")); 25 | System.out.println("Equals? " + string.equals(" Minha String ")); 26 | System.out.println("EqualsIgnoreCase? " + string.equalsIgnoreCase(" minha sTrinG ")); 27 | System.out.println("Substring(1,6)=" + string.substring(1, 6)); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java-2/src/main/java/whiles/While.java: -------------------------------------------------------------------------------- 1 | package whiles; 2 | 3 | public class While { 4 | 5 | public static void main(String[] args) { 6 | 7 | var x = 0; 8 | 9 | //Testa a condição antes 10 | while (x < 1) { 11 | System.out.println("Dentro do while..."); 12 | x++; 13 | } 14 | 15 | var y = 0; 16 | 17 | //Testa a condição depois 18 | do { 19 | System.out.println("Dentro do do/while..."); 20 | } while (y++ < 1); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ project files 2 | .idea 3 | *.iml 4 | out 5 | gen 6 | build 7 | .gradle 8 | 9 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'one.innovation.digital' 6 | version '1.0-SNAPSHOT' 7 | 8 | sourceCompatibility = 1.11 9 | 10 | repositories { 11 | mavenCentral() 12 | } 13 | 14 | dependencies { 15 | testCompile group: 'junit', name: 'junit', version: '4.12' 16 | } 17 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andrelugomes/digital-innovation-one/31982544848f282a20f776efc7c8a64e4ba40560/caracteristicas-da-linguagem-java/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'caracteristicas-da-liguagem-java' 2 | 3 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/abstracts/FormaGeometrica.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.abstracts; 2 | 3 | public abstract class FormaGeometrica { 4 | 5 | public abstract String nome(); 6 | public abstract Double area(); 7 | 8 | public String desenha(int x , int y) { 9 | return "Desenhando nas coordenadas X="+x+" Y:"+y; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/abstracts/Programa.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.abstracts; 2 | 3 | public class Programa { 4 | 5 | public static void main(String[] args) { 6 | 7 | //final FormaGeometrica formaGeometrica = new FormaGeometrica(); 8 | 9 | final FormaGeometrica quadadro = new Quadrado("quadadro", 10.0); 10 | 11 | System.out.println(quadadro); 12 | 13 | System.out.println(quadadro.desenha(12,34)); 14 | System.out.println(quadadro.nome()); 15 | System.out.println(quadadro.area()); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/abstracts/Quadrado.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.abstracts; 2 | 3 | public class Quadrado extends FormaGeometrica { 4 | 5 | private String nome; 6 | private Double area; 7 | 8 | public Quadrado(final String nome, final Double area) { 9 | this.nome = nome; 10 | this.area = area; 11 | } 12 | 13 | @Override 14 | public String nome() { 15 | 16 | return nome; 17 | } 18 | 19 | @Override 20 | public Double area() { 21 | return area; 22 | } 23 | 24 | @Override 25 | public String toString() { 26 | final StringBuilder builder = new StringBuilder()// 27 | .append("Quadrado [")// 28 | .append("nome=\"")// 29 | .append(nome).append("\"")// 30 | .append(",area=")// 31 | .append(area)// 32 | .append("]"); 33 | return builder.toString(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/classes/Programa.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.classes; 2 | 3 | public class Programa { 4 | 5 | public static void main(String[] args) { 6 | 7 | System.out.println("Hello world!"); 8 | } 9 | 10 | } 11 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/classes/cliente/Cliente.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.classes.cliente; 2 | 3 | import one.digitalinnovation.classes.pessoa.Pessoa; 4 | 5 | public class Cliente extends Pessoa { 6 | 7 | public Cliente(final Integer idade) { 8 | super(idade); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/classes/cliente/ProgramaDoCliente.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.classes.cliente; 2 | 3 | public class ProgramaDoCliente { 4 | 5 | public static void main(String[] args) { 6 | final var cliente = new Cliente(18); 7 | 8 | cliente.getIdade(); 9 | 10 | cliente.getPeso(); 11 | 12 | //System.out.println(cliente.relatorio()); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/classes/pessoa/Pessoa.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.classes.pessoa; 2 | 3 | public class Pessoa { 4 | 5 | private Integer idade; 6 | private Float peso; 7 | 8 | public Pessoa() { 9 | } 10 | 11 | public Pessoa(final Integer idade) { 12 | 13 | this.idade = idade; 14 | } 15 | 16 | public Pessoa(final Integer idade, final Float peso) { 17 | this.idade = idade; 18 | this.peso = peso; 19 | } 20 | 21 | public Integer getIdade() { 22 | return this.idade; 23 | } 24 | 25 | public Float getPeso() { 26 | return peso; 27 | } 28 | 29 | protected String relatorio() { 30 | return "Idade : " +idade+" e Peso: "+ peso; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/classes/pessoa/PessoaFisica.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.classes.pessoa; 2 | 3 | public class PessoaFisica extends Pessoa { 4 | 5 | public PessoaFisica(final Integer idade, final Float peso) { 6 | super(idade, peso); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/classes/pessoa/ProgramaDoCliente.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.classes.pessoa; 2 | 3 | import one.digitalinnovation.classes.cliente.Cliente; 4 | 5 | public class ProgramaDoCliente { 6 | 7 | public static void main(String[] args) { 8 | final var cliente = new Cliente(18); 9 | 10 | cliente.getIdade(); 11 | 12 | cliente.getPeso(); 13 | 14 | System.out.println(cliente.relatorio()); //OK 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/classes/pessoa/ProgramaDoUsuario.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.classes.pessoa; 2 | 3 | import one.digitalinnovation.classes.usuario.SuperUsuario; 4 | 5 | public class ProgramaDoUsuario { 6 | 7 | public static void main(String[] args) { 8 | final var batman = new SuperUsuario("batman", "1234%$#@"); 9 | 10 | batman.getLogin(); 11 | 12 | //batman.getSenha(); //ERRO 13 | 14 | //String nomeDoCliente = batman.nome; //ERRO 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/classes/pessoa/ProgramaPessoaFisica.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.classes.pessoa; 2 | 3 | public class ProgramaPessoaFisica { 4 | 5 | public static void main(String[] args) { 6 | final PessoaFisica pessoaFisica = new PessoaFisica(33, 100.5f); 7 | 8 | System.out.println(pessoaFisica.relatorio()); 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/classes/pessoa/Usuario.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.classes.pessoa; 2 | 3 | import one.digitalinnovation.classes.usuario.SuperUsuario; 4 | 5 | public class Usuario extends SuperUsuario { 6 | 7 | public Usuario(final String login, final String senha) { 8 | super(login, senha); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/classes/usuario/ProgramaDoSuperUsuario.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.classes.usuario; 2 | 3 | public class ProgramaDoSuperUsuario { 4 | 5 | public static void main(String[] args) { 6 | final var superUsuario = new SuperUsuario("root", "1234%$#@"); 7 | 8 | 9 | superUsuario.getLogin(); 10 | 11 | superUsuario.getSenha(); 12 | 13 | String root = superUsuario.nome; 14 | 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/classes/usuario/SuperUsuario.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.classes.usuario; 2 | 3 | public class SuperUsuario { 4 | 5 | private String login; 6 | private String senha; 7 | String nome; 8 | 9 | public SuperUsuario(final String login, final String senha) { 10 | this.login = login; 11 | this.senha = senha; 12 | } 13 | 14 | public String getLogin() { 15 | 16 | return login; 17 | } 18 | 19 | protected String getSenha() { 20 | 21 | return senha; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/enums/Programa.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.enums; 2 | 3 | public class Programa { 4 | 5 | public static void main(String[] args) { 6 | //final TipoVeiculo tipoVeiculo = new TipoVeiculo(); 7 | 8 | System.out.println(TipoVeiculo.TERRESTRE); 9 | System.out.println(TipoVeiculo.AQUATICO); 10 | 11 | 12 | //System.out.println(TipoVeiculo.valueOf("aero")); 13 | System.out.println(TipoVeiculo.valueOf("AEREO")); 14 | 15 | 16 | for (TipoVeiculo tipo : TipoVeiculo.values()) { 17 | System.out.println("Tipo: "+tipo); 18 | } 19 | 20 | System.out.println("Código do Status CLOSE :"+Status.CLOSE.getCod()); 21 | System.out.println("Texto do Status OPEN :"+Status.OPEN.getTexto()); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/enums/Status.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.enums; 2 | 3 | public enum Status { 4 | OPEN(13, "Aberto"), 5 | CLOSE(02, "Fechado"); 6 | 7 | private int cod; 8 | private String texto; 9 | 10 | Status(final int cod, final String texto) { 11 | 12 | this.cod = cod; 13 | this.texto = texto; 14 | } 15 | 16 | public int getCod() { 17 | return cod; 18 | } 19 | 20 | public String getTexto() { 21 | return texto; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/enums/TipoVeiculo.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.enums; 2 | 3 | public enum TipoVeiculo { 4 | 5 | TERRESTRE, 6 | AQUATICO, 7 | AEREO 8 | 9 | } 10 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/finals/CasualGamer.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.finals; 2 | 3 | public class CasualGamer extends Gamer { 4 | 5 | @Override 6 | public String keyboard() { 7 | return "Simple keyboard..."; 8 | } 9 | 10 | /* @Override 11 | public String mouse() { 12 | return super.mouse(); 13 | }*/ 14 | 15 | public String play(final String game) { 16 | //game = "WoW"; 17 | 18 | return "Jogando "+ game; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/finals/Gamer.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.finals; 2 | 3 | public class Gamer { 4 | 5 | public String keyboard() { 6 | return "Keyboard Gamer!"; 7 | } 8 | 9 | public final String mouse() { 10 | return "Mouse Gamer!"; 11 | } 12 | 13 | 14 | 15 | } 16 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/finals/HardcoreGamer.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.finals; 2 | 3 | public final class HardcoreGamer { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/finals/Programa.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.finals; 2 | 3 | public class Programa { 4 | 5 | public static void main(String[] args) { 6 | final HardcoreGamer hardcoreGamer = new HardcoreGamer(); 7 | 8 | final Gamer gamer = new Gamer(); 9 | 10 | final CasualGamer casualGamer = new CasualGamer(); 11 | 12 | final var game = "PUBG"; 13 | 14 | //game = "WoW"; 15 | 16 | System.out.println(casualGamer.play(game)); 17 | 18 | 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/interfaces/Automovel.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.interfaces; 2 | 3 | public interface Automovel { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/interfaces/Carro.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.interfaces; 2 | 3 | public interface Carro extends Automovel{ 4 | 5 | String marca(); 6 | 7 | Double valor(); 8 | 9 | default void ligar() { 10 | 11 | System.out.println("Ligando o carro!"); 12 | } 13 | 14 | default String codigoRenavan() { 15 | return "6533jijiio"; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/interfaces/Fiesta.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.interfaces; 2 | 3 | public class Fiesta implements Carro, Veiculo { 4 | 5 | @Override 6 | public String marca() { 7 | return "Ford"; 8 | } 9 | 10 | @Override 11 | public Double valor() { 12 | return null; 13 | } 14 | 15 | @Override 16 | public String registro() { 17 | return "123AFG547TR"; 18 | } 19 | 20 | @Override 21 | public void ligar() { 22 | //codigo 23 | 24 | Carro.super.ligar(); 25 | 26 | Veiculo.super.ligar(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/interfaces/Gol.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.interfaces; 2 | 3 | public class Gol implements Carro { 4 | 5 | @Override 6 | public String marca() { 7 | 8 | return "Volkswagen"; 9 | } 10 | 11 | @Override 12 | public Double valor() { 13 | return null; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/interfaces/Programa.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.interfaces; 2 | 3 | public class Programa { 4 | 5 | public static void main(String[] args) { 6 | 7 | final Carro gol = new Gol(); 8 | System.out.println("Marca do Gol : "+gol.marca()); 9 | gol.ligar(); 10 | 11 | final Veiculo trator = new Trator(); 12 | System.out.println("Registro do Trator :"+trator.registro()); 13 | trator.ligar(); 14 | 15 | final Fiesta fiesta = new Fiesta(); 16 | 17 | System.out.println("Marca do Fiesta : "+fiesta.marca()); 18 | System.out.println("Registro do Fiesta : "+fiesta.registro()); 19 | 20 | fiesta.ligar(); 21 | 22 | //Carro.super.ligar(); //só pode ser acessado por que implementa 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/interfaces/Trator.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.interfaces; 2 | 3 | public class Trator implements Veiculo { 4 | 5 | @Override 6 | public String registro() { 7 | return "AWD12387465GFDA"; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/interfaces/Veiculo.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.interfaces; 2 | 3 | public interface Veiculo { 4 | 5 | String registro(); 6 | 7 | default void ligar() { 8 | 9 | System.out.println("Ligando o veículo!"); 10 | } 11 | 12 | //void desligar(); 13 | 14 | /*default void desligar() { 15 | System.out.println("Desligando o veículo!"); 16 | }*/ 17 | } 18 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/statics/Cachorro.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.statics; 2 | 3 | public class Cachorro { 4 | 5 | //public String zoologia = "Quadrupede"; //Uma instância 6 | public static String zoologia = "Quadrupede"; //Todas instâncias 7 | 8 | public static String late() { 9 | return "Au!Au!"; 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/statics/Programa.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.statics; 2 | 3 | public class Programa { 4 | 5 | public static void main(String[] args) { 6 | final Cachorro pitbull = new Cachorro(); 7 | pitbull.zoologia = "Bipede"; 8 | 9 | final Cachorro viraLatas = new Cachorro(); 10 | 11 | System.out.println(pitbull.zoologia); 12 | System.out.println(viraLatas.zoologia); 13 | 14 | Cachorro.late(); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/tipos/naoprimitivos/NaoPrimitivos.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.tipos.naoprimitivos; 2 | 3 | public class NaoPrimitivos { 4 | 5 | public static void main(String[] args) { 6 | 7 | String texto = "Meu texto para apresentação"; //Sequência de caracteres 8 | 9 | Void v; //Tipo válido 10 | 11 | Object o = new Object(); 12 | 13 | Number numero = Integer.valueOf(100); 14 | 15 | numero.toString(); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/tipos/naoprimitivos/Unboxing.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.tipos.naoprimitivos; 2 | 3 | public class Unboxing { 4 | 5 | public static void main(String[] args) { 6 | int i = new Integer(3); 7 | 8 | int inteiro = Integer.valueOf(1024); 9 | 10 | //boolean b = new Boolean(true); 11 | boolean b2 = Boolean.TRUE; 12 | boolean b3 = Boolean.getBoolean("false"); 13 | 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/tipos/primitivos/DefaultValues.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.tipos.primitivos; 2 | 3 | public class DefaultValues { 4 | 5 | public static void main(String[] args) { 6 | 7 | final Default d = new Default(); 8 | 9 | System.out.println(d.getI()); 10 | 11 | System.out.println(d.isActive()); 12 | 13 | } 14 | } 15 | 16 | class Default { 17 | 18 | int i; 19 | boolean active; 20 | 21 | public int getI() { 22 | return i; 23 | } 24 | 25 | public boolean isActive() { 26 | return active; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/tipos/primitivos/Primitivos.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.tipos.primitivos; 2 | 3 | public class Primitivos { 4 | 5 | public static void main(String[] args) { 6 | //INTEIROS 7 | 8 | //byte nullByte = null; 9 | 10 | byte b; //8 bits 11 | byte b1 = 127; 12 | byte b2 = -128; 13 | //byte b3 = 129; //to large 14 | 15 | char c; //16 bits 16 | char c1 = 'A'; 17 | char c2 = 15; 18 | //char c3 = 'AA'; //NOK 19 | //char c4 = -100; //NOK 20 | 21 | short s; //16 bits 22 | short s1 = 32767; 23 | short s2 = -32768; 24 | 25 | int i = 2147483647; //32 bits 26 | int i2 = -2147483648; 27 | //int i3 = -2147483649; //to large 28 | 29 | 30 | long l = 9223372036854775807l; //64 bits 31 | long l2 = -9223372036854775808L; 32 | //long l3 = 9223372036854775808L; //to large 33 | 34 | //FLUTUANTES 35 | 36 | float f = 65f; //32 bits 3.402,823,5 E+38 37 | float f2 = 65.0f; 38 | float f3 = -0.5f; //1.4 E-45 39 | 40 | 41 | double d = 1024.99; //64 bits 1.797,693,134,862,315,7 E+308 42 | double d2 = 10.2456; // 4.9 E-324 43 | 44 | //Boleano 45 | 46 | boolean bo = true; 47 | boolean bo2 = false; 48 | //boolean bo3 = "false"; //NOK 49 | //boolean bo4 = 'true'; //NOK 50 | 51 | 52 | //void v; //palavra reservada 53 | 54 | 55 | //System.out.println("byte : " + b); //ERROR 56 | 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/tipos/tipagem/Escopo.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.tipos.tipagem; 2 | 3 | public class Escopo { 4 | 5 | public static void main(String[] args) { 6 | final var escopo = new TesteDeEscopo(); 7 | System.out.println("O número definido é : "+escopo.defineNumeroMinimo(2)); 8 | } 9 | 10 | } 11 | 12 | class TesteDeEscopo { 13 | 14 | int numeroMinimo; 15 | Integer NumeroMaximo; 16 | 17 | public int defineNumeroMinimo(int numeroMinimo) { 18 | 19 | if (numeroMinimo > 10) { 20 | 21 | this.numeroMinimo = numeroMinimo; 22 | } 23 | 24 | return this.numeroMinimo; 25 | } 26 | 27 | public Integer defineNumeroMaximo(Integer numeroMaximo) { 28 | return this.NumeroMaximo; 29 | } 30 | 31 | 32 | } 33 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/tipos/tipagem/TipagemEstatica.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.tipos.tipagem; 2 | 3 | public class TipagemEstatica { 4 | 5 | public static void main(String[] args) { 6 | 7 | //Integer numero = "123456789"; //ERROR 8 | 9 | } 10 | 11 | } 12 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/tipos/tipagem/TipagemForte.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.tipos.tipagem; 2 | 3 | public class TipagemForte { 4 | 5 | public static void main(String[] args) { 6 | 7 | String texto = "meu texto"; 8 | 9 | //texto = 1000; //NOK 10 | 11 | Integer numero = Integer.valueOf("1024"); 12 | 13 | numero = 512; //OK 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/tipos/tipagem/TipoInferido.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.tipos.tipagem; 2 | 3 | public class TipoInferido { 4 | 5 | public static void main(String[] args) { 6 | 7 | var numero = Integer.valueOf("123456"); 8 | 9 | var texto = "O Numero é : " ; 10 | 11 | System.out.println(texto + numero); 12 | 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /caracteristicas-da-linguagem-java/src/main/java/one/digitalinnovation/tipos/wrappers/Wrappers.java: -------------------------------------------------------------------------------- 1 | package one.digitalinnovation.tipos.wrappers; 2 | 3 | public class Wrappers { 4 | 5 | public static void main(String[] args) { 6 | //Autoboxing 7 | 8 | Byte b = 127; //byte 9 | Byte b2 = -128; 10 | Byte nullByte = null; 11 | 12 | Character c = 'A'; //char 13 | Character c2 = 15; 14 | 15 | Short s = 32767; //short 16 | Short s2 = -32768; 17 | 18 | Integer i = 2147483647; //int 19 | Integer i2 = -2147483648; 20 | 21 | Long l = 9223372036854775807L; //long 22 | Long l2 = -9223372036854775808L; 23 | 24 | Float f = 65f; //float 25 | Float f2 = 65.0f; 26 | Float f3 = -0.5f; 27 | 28 | Double d = 1024.99; //Double 29 | Double d2 = 10.2456; 30 | 31 | Boolean bo = true; //boolean 32 | Boolean bo2 = false; 33 | 34 | Boolean bo3 = Boolean.getBoolean("false"); //OK 35 | Boolean bo4 = Boolean.valueOf("true"); //OK 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | out/ 22 | 23 | ### NetBeans ### 24 | /nbproject/private/ 25 | /nbbuild/ 26 | /dist/ 27 | /nbdist/ 28 | /.nb-gradle/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | os: linux 4 | dist: trusty 5 | jdk: oraclejdk8 6 | 7 | jobs: 8 | include: 9 | - stage: "Build project" 10 | script: 11 | - ./gradlew build 12 | 13 | deploy: 14 | provider: heroku 15 | app: dio-cities-api-2 16 | api_key: $HEROKU_KEY_BLA -------------------------------------------------------------------------------- /cities-api-full-ci-cd/Procfile: -------------------------------------------------------------------------------- 1 | web: java -jar -Dspring.profiles.active=heroku build/libs/cities-api-0.0.1-SNAPSHOT.jar -------------------------------------------------------------------------------- /cities-api-full-ci-cd/README.md: -------------------------------------------------------------------------------- 1 | # Cities API 2 | 3 | ## Requirements 4 | 5 | * Linux 6 | * Git 7 | * Java 8 8 | * Docker 9 | * IntelliJ Community 10 | * Heroku CLI 11 | * Travis CLI 12 | 13 | ## DataBase 14 | 15 | ### Postgres 16 | 17 | * [Postgres Docker Hub](https://hub.docker.com/_/postgres) 18 | 19 | ```shell script 20 | docker run --name cities-db -d -p 5432:5432 -e POSTGRES_USER=postgres_user_city -e POSTGRES_PASSWORD=super_password -e POSTGRES_DB=cities postgres 21 | ``` 22 | 23 | * [Postgres Earth distance](https://www.postgresql.org/docs/current/earthdistance.html) 24 | * [earthdistance--1.0--1.1.sql](https://github.com/postgres/postgres/blob/master/contrib/earthdistance/earthdistance--1.0--1.1.sql) 25 | * [OPERATOR <@>](https://github.com/postgres/postgres/blob/master/contrib/earthdistance/earthdistance--1.1.sql) 26 | * [postgrescheatsheet](https://postgrescheatsheet.com/#/tables) 27 | * [datatype-geometric](https://www.postgresql.org/docs/current/datatype-geometric.html) 28 | 29 | ### Access 30 | 31 | ```shell script 32 | docker exec -it cities-db /bin/bash 33 | 34 | psql -U postgres_user_city cities 35 | ``` 36 | 37 | ### Query Earth Distance 38 | 39 | Point 40 | ```roomsql 41 | select ((select lat_lon from cidade where id = 4929) <@> (select lat_lon from cidade where id=5254)) as distance; 42 | ``` 43 | 44 | Cube 45 | ```roomsql 46 | select earth_distance( 47 | ll_to_earth(-21.95840072631836,-47.98820114135742), 48 | ll_to_earth(-22.01740074157715,-47.88600158691406) 49 | ) as distance; 50 | ``` 51 | 52 | ## Spring Boot 53 | 54 | * [https://start.spring.io/](https://start.spring.io/) 55 | 56 | + Java 8 57 | + Gradle Project 58 | + Jar 59 | + Spring Web 60 | + Spring Data JPA 61 | + PostgreSQL Driver 62 | 63 | ### Spring Data 64 | 65 | * [jpa.query-methods](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods) 66 | 67 | ### Properties 68 | 69 | * [appendix-application-properties](https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html) 70 | * [jdbc-database-connectio](https://www.codejava.net/java-se/jdbc/jdbc-database-connection-url-for-common-databases) 71 | 72 | ### Types 73 | 74 | * [JsonTypes](https://github.com/vladmihalcea/hibernate-types) 75 | * [UserType](https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/usertype/UserType.html) 76 | 77 | ## Heroku 78 | 79 | * [DevCenter](https://devcenter.heroku.com/articles/getting-started-with-gradle-on-heroku) 80 | 81 | ```shell script 82 | heroku create dio-cities-api --addons=heroku-postgresql 83 | ``` 84 | 85 | ## Code Quality 86 | 87 | ### PMD 88 | 89 | + https://pmd.github.io/pmd-6.8.0/index.html 90 | 91 | ### Checkstyle 92 | 93 | + https://checkstyle.org/ 94 | 95 | + https://checkstyle.org/google_style.html 96 | 97 | + http://google.github.io/styleguide/javaguide.html 98 | 99 | ```shell script 100 | wget https://raw.githubusercontent.com/checkstyle/checkstyle/master/src/main/resources/google_checks.xml 101 | ``` 102 | 103 | ## InMemory Database Testing 104 | 105 | + http://www.h2database.com/html/features.html 106 | 107 | 108 | ## Migrations 109 | 110 | + https://flywaydb.org/ 111 | 112 | ## CI 113 | 114 | ### Travis 115 | + https://github.com/travis-ci/travis.rb#readme 116 | 117 | + https://docs.travis-ci.com/user/tutorial/ 118 | 119 | #### extra 120 | 121 | + https://docs.travis-ci.com/user/conditional-builds-stages-jobs/ 122 | + https://docs.travis-ci.com/user/deployment-v2/conditional 123 | 124 | + [Heroku Deployment](https://docs.travis-ci.com/user/deployment/heroku/) 125 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'io.spring.dependency-management' version '1.0.9.RELEASE' 3 | id 'org.springframework.boot' version '2.2.6.RELEASE' 4 | id 'checkstyle' 5 | id 'java' 6 | id 'pmd' 7 | } 8 | 9 | group = 'com.github.andrelugomes' 10 | version = '0.0.1-SNAPSHOT' 11 | sourceCompatibility = '1.8' 12 | 13 | repositories { 14 | mavenCentral() 15 | } 16 | 17 | dependencies { 18 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 19 | implementation 'org.springframework.boot:spring-boot-starter-web' 20 | implementation 'com.vladmihalcea:hibernate-types-52:2.9.8' 21 | implementation 'org.postgresql:postgresql' 22 | implementation 'org.flywaydb:flyway-core' 23 | 24 | testImplementation('org.springframework.boot:spring-boot-starter-test') { 25 | exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' 26 | } 27 | testImplementation 'com.h2database:h2:1.4.200' 28 | 29 | } 30 | 31 | test { 32 | useJUnitPlatform() 33 | } 34 | 35 | pmd { 36 | consoleOutput = true 37 | toolVersion = "6.21.0" 38 | rulePriority = 5 39 | ruleSetFiles = files("pmd-ruleset.xml") 40 | ruleSets = [] 41 | //ruleSets = ["category/java/bestpractices.xml"] 42 | } 43 | 44 | checkstyle { 45 | toolVersion "8.31" 46 | configFile file("google_checks.xml") 47 | } 48 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andrelugomes/digital-innovation-one/31982544848f282a20f776efc7c8a64e4ba40560/cities-api-full-ci-cd/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /cities-api-full-ci-cd/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | @rem Execute Gradle 88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 89 | 90 | :end 91 | @rem End local scope for the variables with windows NT shell 92 | if "%ERRORLEVEL%"=="0" goto mainEnd 93 | 94 | :fail 95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 96 | rem the _cmd.exe /c_ return code! 97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 98 | exit /b 1 99 | 100 | :mainEnd 101 | if "%OS%"=="Windows_NT" endlocal 102 | 103 | :omega 104 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/pmd-ruleset.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 9 | Cities API PDM rules 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'cities-api' 2 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/CitiesApplication.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class CitiesApplication { 8 | 9 | public static void main(final String[] args) { 10 | SpringApplication.run(CitiesApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/cities/entities/City.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.entities; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.Id; 6 | import javax.persistence.Table; 7 | import org.hibernate.annotations.Type; 8 | import org.hibernate.annotations.TypeDef; 9 | import org.hibernate.annotations.TypeDefs; 10 | import org.springframework.data.geo.Point; 11 | 12 | 13 | @Entity 14 | @Table(name = "cidade") 15 | @TypeDefs(value = { 16 | @TypeDef(name = "point", typeClass = PointType.class) 17 | }) 18 | public class City { 19 | 20 | @Id 21 | private Long id; 22 | 23 | @Column(name = "nome") 24 | private String name; 25 | 26 | private Integer uf; 27 | 28 | private Integer ibge; 29 | 30 | // 1st 31 | @Column(name = "lat_lon") 32 | private String geolocation; 33 | 34 | // 2nd 35 | @Type(type = "point") 36 | @Column(name = "lat_lon", updatable = false, insertable = false) 37 | private Point location; 38 | 39 | public City() { 40 | } 41 | 42 | /** 43 | * 44 | * @param id 45 | * @param name 46 | * @param uf 47 | * @param ibge 48 | * @param geolocation 49 | * @param location 50 | */ 51 | public City(final Long id, final String name, final Integer uf, final Integer ibge, 52 | final String geolocation, final Point location) { 53 | this.id = id; 54 | this.name = name; 55 | this.uf = uf; 56 | this.ibge = ibge; 57 | this.geolocation = geolocation; 58 | this.location = location; 59 | } 60 | 61 | public Long getId() { 62 | return id; 63 | } 64 | 65 | public String getName() { 66 | return name; 67 | } 68 | 69 | public Integer getUf() { 70 | return uf; 71 | } 72 | 73 | public Integer getIbge() { 74 | return ibge; 75 | } 76 | 77 | public String getGeolocation() { 78 | return geolocation; 79 | } 80 | 81 | public Point getLocation() { 82 | return location; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/cities/entities/PointType.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.entities; 2 | 3 | import com.github.andrelugomes.utils.StringLocationUtils; 4 | import java.io.Serializable; 5 | import java.sql.PreparedStatement; 6 | import java.sql.ResultSet; 7 | import java.sql.SQLException; 8 | import org.hibernate.HibernateException; 9 | import org.hibernate.engine.spi.SharedSessionContractImplementor; 10 | import org.hibernate.usertype.UserType; 11 | import org.springframework.data.geo.Point; 12 | 13 | public class PointType implements UserType { 14 | 15 | @Override 16 | public int[] sqlTypes() { 17 | return new int[] {java.sql.Types.OTHER}; 18 | } 19 | 20 | @Override 21 | public Class returnedClass() { 22 | return Point.class; 23 | } 24 | 25 | @Override 26 | public boolean equals(Object x, Object y) throws HibernateException { 27 | return false; 28 | } 29 | 30 | @Override 31 | public int hashCode(Object x) throws HibernateException { 32 | return 0; 33 | } 34 | 35 | @Override 36 | public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, 37 | Object owner) throws HibernateException, SQLException { 38 | /* 1st */ 39 | Object object = rs.getObject(names[0]); 40 | Double[] points = StringLocationUtils.transform(object.toString()); 41 | return new Point(points[0], points[1]); 42 | 43 | /* 2nd */ 44 | /*PGpoint value = (PGpoint) rs.getObject(names[0]); 45 | return new Point(value.x, value.y);*/ 46 | } 47 | 48 | @Override 49 | public void nullSafeSet(PreparedStatement st, Object value, int index, 50 | SharedSessionContractImplementor session) 51 | throws HibernateException, SQLException { 52 | 53 | } 54 | 55 | @Override 56 | public Object deepCopy(Object value) throws HibernateException { 57 | return null; 58 | } 59 | 60 | @Override 61 | public boolean isMutable() { 62 | return false; 63 | } 64 | 65 | @Override 66 | public Serializable disassemble(Object value) throws HibernateException { 67 | return null; 68 | } 69 | 70 | @Override 71 | public Object assemble(Serializable cached, Object owner) throws HibernateException { 72 | return null; 73 | } 74 | 75 | @Override 76 | public Object replace(Object original, Object target, Object owner) throws HibernateException { 77 | return null; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/cities/repositories/CityRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.repositories; 2 | 3 | import com.github.andrelugomes.cities.entities.City; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Query; 6 | 7 | public interface CityRepository extends JpaRepository { 8 | 9 | String QUERY = "SELECT ((SELECT lat_lon FROM cidade WHERE id=?1) <@> " 10 | + "(SELECT lat_lon FROM cidade WHERE id=?2)) as distance"; 11 | 12 | @Query(value = QUERY, nativeQuery = true) 13 | Double distanceByPoints(final Long cityId1, final Long cityId2); 14 | 15 | @Query(value = "SELECT earth_distance(ll_to_earth(?1,?2), ll_to_earth(?3,?4)) as distance", nativeQuery = true) 16 | Double distanceByCube(final Double lat1, final Double lon1, final Double lat2, final Double lon2); 17 | } 18 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/cities/resources/CityResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.resources; 2 | 3 | import com.github.andrelugomes.cities.entities.City; 4 | import com.github.andrelugomes.cities.repositories.CityRepository; 5 | import org.springframework.data.domain.Page; 6 | import org.springframework.data.domain.Pageable; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | @RequestMapping("cities") 13 | public class CityResource { 14 | 15 | private final CityRepository repository; 16 | 17 | public CityResource(final CityRepository repository) { 18 | this.repository = repository; 19 | } 20 | 21 | /* 1st 22 | @GetMapping 23 | public List cities() { 24 | return repository.findAll(); 25 | }*/ 26 | 27 | // 2nd - Pageable 28 | @GetMapping 29 | public Page cities(final Pageable page) { 30 | return repository.findAll(page); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/cities/resources/DistanceResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.resources; 2 | 3 | import com.github.andrelugomes.cities.service.DistanceService; 4 | import com.github.andrelugomes.cities.service.EarthRadius; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestParam; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | @RestController 13 | @RequestMapping("/distances") 14 | public class DistanceResource { 15 | 16 | private final DistanceService service; 17 | Logger log = LoggerFactory.getLogger(DistanceResource.class); 18 | 19 | public DistanceResource(DistanceService service) { 20 | this.service = service; 21 | } 22 | 23 | @GetMapping("/by-points") 24 | public Double byPoints(@RequestParam(name = "from") final Long city1, 25 | @RequestParam(name = "to") final Long city2) { 26 | log.info("byPoints"); 27 | return service.distanceByPointsInMiles(city1, city2); 28 | } 29 | 30 | @GetMapping("/by-cube") 31 | public Double byCube(@RequestParam(name = "from") final Long city1, 32 | @RequestParam(name = "to") final Long city2) { 33 | log.info("byCube"); 34 | return service.distanceByCubeInMeters(city1, city2); 35 | } 36 | 37 | @GetMapping("/by-math") 38 | public Double byMath(@RequestParam(name = "from") final Long city1, 39 | @RequestParam(name = "to") final Long city2, 40 | @RequestParam final EarthRadius unit) { 41 | log.info("byMath"); 42 | return service.distanceUsingMath(city1, city2, unit); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/cities/service/DistanceService.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.service; 2 | 3 | import static java.lang.Math.atan2; 4 | import static java.lang.Math.cos; 5 | import static java.lang.Math.sin; 6 | import static java.lang.Math.sqrt; 7 | import static java.lang.Math.toRadians; 8 | 9 | import com.github.andrelugomes.cities.entities.City; 10 | import com.github.andrelugomes.cities.repositories.CityRepository; 11 | import com.github.andrelugomes.utils.StringLocationUtils; 12 | import java.util.Arrays; 13 | import java.util.List; 14 | import org.slf4j.Logger; 15 | import org.slf4j.LoggerFactory; 16 | import org.springframework.data.geo.Point; 17 | import org.springframework.stereotype.Service; 18 | 19 | @Service 20 | public class DistanceService { 21 | 22 | private final CityRepository cityRepository; 23 | Logger log = LoggerFactory.getLogger(DistanceService.class); 24 | 25 | public DistanceService(final CityRepository cityRepository) { 26 | this.cityRepository = cityRepository; 27 | } 28 | 29 | /** 30 | * 1st option 31 | * 32 | * @param city1 Long 33 | * @param city2 Long 34 | * @param unit EarthRadius 35 | * @return Double 36 | */ 37 | public Double distanceUsingMath(final Long city1, final Long city2, final EarthRadius unit) { 38 | log.info("distanceUsingMath({}, {}, {})", city1, city2, unit); 39 | final List cities = cityRepository.findAllById((Arrays.asList(city1, city2))); 40 | 41 | final Double[] location1 = StringLocationUtils.transform(cities.get(0).getGeolocation()); 42 | final Double[] location2 = StringLocationUtils.transform(cities.get(1).getGeolocation()); 43 | 44 | return doCalculation(location1[0], location1[1], location2[0], location2[1], unit); 45 | } 46 | 47 | /** 48 | * 2nd option 49 | * 50 | * @param city1 51 | * @param city2 52 | * @return 53 | */ 54 | public Double distanceByPointsInMiles(final Long city1, final Long city2) { 55 | log.info("nativePostgresInMiles({}, {})", city1, city2); 56 | return cityRepository.distanceByPoints(city1, city2); 57 | } 58 | 59 | /** 60 | * 3rd option 61 | * 62 | * @param city1 63 | * @param city2 64 | * @param unit 65 | * @return 66 | */ 67 | public Double distanceUsingPoints(final Long city1, final Long city2, final EarthRadius unit) { 68 | log.info("distanceUsingPoints({}, {}, {})", city1, city2, unit); 69 | final List cities = cityRepository.findAllById((Arrays.asList(city1, city2))); 70 | 71 | Point p1 = cities.get(0).getLocation(); 72 | Point p2 = cities.get(1).getLocation(); 73 | 74 | return doCalculation(p1.getX(), p1.getY(), p2.getX(), p2.getY(), unit); 75 | } 76 | 77 | /** 78 | * 4th option 79 | * 80 | * @param city1 81 | * @param city2 82 | * @return 83 | */ 84 | public Double distanceByCubeInMeters(Long city1, Long city2) { 85 | log.info("distanceByCubeInMeters({}, {})", city1, city2); 86 | final List cities = cityRepository.findAllById((Arrays.asList(city1, city2))); 87 | 88 | Point p1 = cities.get(0).getLocation(); 89 | Point p2 = cities.get(1).getLocation(); 90 | 91 | return cityRepository.distanceByCube(p1.getX(), p1.getY(), p2.getX(), p2.getY()); 92 | } 93 | 94 | private double doCalculation(final double lat1, final double lon1, final double lat2, 95 | final double lng2, final EarthRadius earthRadius) { 96 | double lat = toRadians(lat2 - lat1); 97 | double lon = toRadians(lng2 - lon1); 98 | double a = sin(lat / 2) * sin(lat / 2) 99 | + cos(toRadians(lat1)) * cos(toRadians(lat2)) * sin(lon / 2) * sin(lon / 2); 100 | double c = 2 * atan2(sqrt(a), sqrt(1 - a)); 101 | 102 | return earthRadius.getValue() * c; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/cities/service/EarthRadius.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.service; 2 | 3 | public enum EarthRadius { 4 | METERS("m", 6378168), 5 | KILOMETERS("km", 6378.168f), 6 | MILES("mi", 3958.747716f); 7 | 8 | private final String unit; 9 | private final float value; 10 | 11 | EarthRadius(final String unit, final float value) { 12 | this.unit = unit; 13 | this.value = value; 14 | } 15 | 16 | public float getValue() { 17 | return value; 18 | } 19 | 20 | public String getUnit() { 21 | return unit; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/countries/entities/Country.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.countries.entities; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.Id; 6 | import javax.persistence.Table; 7 | 8 | @Entity(name = "Country") 9 | @Table(name = "pais") 10 | public class Country { 11 | 12 | @Id 13 | private Long id; 14 | 15 | @Column(name = "nome") 16 | private String name; 17 | 18 | @Column(name = "nome_pt") 19 | private String portugueseName; 20 | 21 | @Column(name = "sigla") 22 | private String code; 23 | 24 | private Integer bacen; 25 | 26 | public Country() { 27 | } 28 | 29 | public Long getId() { 30 | return id; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public String getPortugueseName() { 38 | return portugueseName; 39 | } 40 | 41 | public String getCode() { 42 | return code; 43 | } 44 | 45 | public Integer getBacen() { 46 | return bacen; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/countries/repositories/CountryRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.countries.repositories; 2 | 3 | import com.github.andrelugomes.countries.entities.Country; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface CountryRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/countries/resources/CountryResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.countries.resources; 2 | 3 | import com.github.andrelugomes.countries.entities.Country; 4 | import com.github.andrelugomes.countries.repositories.CountryRepository; 5 | import java.util.List; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | public class CountryResource { 11 | 12 | private final CountryRepository repository; 13 | 14 | public CountryResource(final CountryRepository repository) { 15 | this.repository = repository; 16 | } 17 | 18 | @GetMapping("/countries") 19 | public List cities() { 20 | 21 | return repository.findAll(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/states/entities/State.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.states.entities; 2 | 3 | import com.github.andrelugomes.countries.entities.Country; 4 | import com.vladmihalcea.hibernate.type.json.JsonBinaryType; 5 | import java.util.List; 6 | import javax.persistence.Basic; 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.FetchType; 10 | import javax.persistence.Id; 11 | import javax.persistence.JoinColumn; 12 | import javax.persistence.ManyToOne; 13 | import javax.persistence.Table; 14 | import org.hibernate.annotations.Type; 15 | import org.hibernate.annotations.TypeDef; 16 | import org.hibernate.annotations.TypeDefs; 17 | 18 | @Entity(name = "State") 19 | @Table(name = "estado") 20 | @TypeDefs({ 21 | @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) 22 | }) 23 | public class State { 24 | 25 | @Id 26 | private Long id; 27 | 28 | @Column(name = "nome") 29 | private String name; 30 | 31 | private String uf; 32 | 33 | private Integer ibge; 34 | 35 | /* 1st 36 | @Column(name = "pais") 37 | private Integer countryId;*/ 38 | 39 | // 2nd - @ManyToOne 40 | @ManyToOne 41 | @JoinColumn(name = "pais", referencedColumnName = "id") 42 | private Country country; 43 | 44 | @Type(type = "jsonb") 45 | @Basic(fetch = FetchType.LAZY) 46 | @Column(name = "ddd", columnDefinition = "jsonb") 47 | private List ddd; 48 | 49 | public State() { 50 | } 51 | 52 | /** 53 | * 54 | * @param id 55 | * @param name 56 | * @param uf 57 | * @param ibge 58 | * @param country 59 | * @param ddd 60 | */ 61 | public State(Long id, String name, String uf, Integer ibge, 62 | Country country, List ddd) { 63 | this.id = id; 64 | this.name = name; 65 | this.uf = uf; 66 | this.ibge = ibge; 67 | this.country = country; 68 | this.ddd = ddd; 69 | } 70 | 71 | public Long getId() { 72 | return id; 73 | } 74 | 75 | public String getName() { 76 | return name; 77 | } 78 | 79 | public String getUf() { 80 | return uf; 81 | } 82 | 83 | public Integer getIbge() { 84 | return ibge; 85 | } 86 | 87 | public List getDdd() { 88 | return ddd; 89 | } 90 | 91 | public Country getCountry() { 92 | return country; 93 | } 94 | 95 | /*public Integer getCountryId() { 96 | return countryId; 97 | }*/ 98 | } 99 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/states/repositories/StateRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.states.repositories; 2 | 3 | import com.github.andrelugomes.states.entities.State; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface StateRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/states/resources/StateResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.states.resources; 2 | 3 | import com.github.andrelugomes.states.entities.State; 4 | import com.github.andrelugomes.states.repositories.StateRepository; 5 | import java.util.List; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | @RestController 11 | @RequestMapping("/states") 12 | public class StateResource { 13 | 14 | private final StateRepository repository; 15 | 16 | public StateResource(final StateRepository repository) { 17 | this.repository = repository; 18 | } 19 | 20 | @GetMapping 21 | public List states() { 22 | return repository.findAll(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/java/com/github/andrelugomes/utils/StringLocationUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.utils; 2 | 3 | public class StringLocationUtils { 4 | /** 5 | * 6 | * @param geolocation String 7 | * @return Double[] 8 | */ 9 | public static Double[] transform(String geolocation) { 10 | String result = geolocation.replace("(", "").replace(")", ""); 11 | String[] strings = result.trim().split(","); 12 | return new Double[] {Double.valueOf(strings[0]), Double.valueOf(strings[1])}; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/resources/application-heroku.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=${DATABASE_URL} 2 | 3 | spring.jpa.show-sql=false 4 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=${PORT:8080} 2 | 3 | spring.datasource.url=jdbc:postgresql://localhost:5432/cities 4 | spring.datasource.username=postgres_user_city 5 | spring.datasource.password=super_password 6 | 7 | spring.jpa.show-sql=true 8 | 9 | spring.jpa.properties.hibernate.format_sql=true 10 | 11 | #show sql statement 12 | #logging.level.org.hibernate.SQL=debug 13 | 14 | #show sql values 15 | #logging.level.org.hibernate.type.descriptor.sql=trace -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/resources/db/migration/V2__create_estados.sql: -------------------------------------------------------------------------------- 1 | -- 2 | -- Estrutura da tabela "estado" 3 | -- 4 | 5 | CREATE TABLE estado ( 6 | id bigserial NOT NULL, 7 | nome varchar(60), 8 | uf varchar(2), 9 | ibge integer, 10 | pais integer, 11 | ddd json, 12 | /* Keys */ 13 | CONSTRAINT estado_pkey 14 | PRIMARY KEY (id) 15 | ); 16 | 17 | COMMENT ON TABLE estado 18 | IS 'Unidades Federativas'; 19 | 20 | -- 21 | -- Inserindo dados na tabela "estado" 22 | -- 23 | 24 | INSERT INTO "estado" (id, nome, uf, ibge, pais, ddd) VALUES 25 | (1, 'Acre', 'AC', 12, 1, '[68]'), 26 | (2, 'Alagoas', 'AL', 27, 1, '[82]'), 27 | (3, 'Amazonas', 'AM', 13, 1, '[97,92]'), 28 | (4, 'Amapá', 'AP', 16, 1, '[96]'), 29 | (5, 'Bahia', 'BA', 29, 1, '[77,75,73,74,71]'), 30 | (6, 'Ceará', 'CE', 23, 1, '[88,85]'), 31 | (7, 'Distrito Federal', 'DF', 53, 1, '[61]'), 32 | (8, 'Espírito Santo', 'ES', 32, 1, '[28,27]'), 33 | (9, 'Goiás', 'GO', 52, 1, '[62,64,61]'), 34 | (10, 'Maranhão', 'MA', 21, 1, '[99,98]'), 35 | (11, 'Minas Gerais', 'MG', 31, 1, '[34,37,31,33,35,38,32]'), 36 | (12, 'Mato Grosso do Sul', 'MS', 50, 1, '[67]'), 37 | (13, 'Mato Grosso', 'MT', 51, 1, '[65,66]'), 38 | (14, 'Pará', 'PA', 15, 1, '[91,94,93]'), 39 | (15, 'Paraíba', 'PB', 25, 1, '[83]'), 40 | (16, 'Pernambuco', 'PE', 26, 1, '[81,87]'), 41 | (17, 'Piauí', 'PI', 22, 1, '[89,86]'), 42 | (18, 'Paraná', 'PR', 41, 1, '[43,41,42,44,45,46]'), 43 | (19, 'Rio de Janeiro', 'RJ', 33, 1, '[24,22,21]'), 44 | (20, 'Rio Grande do Norte', 'RN', 24, 1, '[84]'), 45 | (21, 'Rondônia', 'RO', 11, 1, '[69]'), 46 | (22, 'Roraima', 'RR', 14, 1, '[95]'), 47 | (23, 'Rio Grande do Sul', 'RS', 43, 1, '[53,54,55,51]'), 48 | (24, 'Santa Catarina', 'SC', 42, 1, '[47,48,49]'), 49 | (25, 'Sergipe', 'SE', 28, 1, '[79]'), 50 | (26, 'São Paulo', 'SP', 35, 1, '[11,12,13,14,15,16,17,18,19]'), 51 | (27, 'Tocantins', 'TO', 17, 1, '[63]'), 52 | (99, 'Exterior', 'EX', 99, NULL, NULL); 53 | 54 | ALTER SEQUENCE estado_id_seq 55 | RESTART 99; 56 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/main/resources/db/migration/V4__enable_postgres_extentions.sql: -------------------------------------------------------------------------------- 1 | CREATE EXTENSION cube; 2 | CREATE EXTENSION earthdistance; -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/test/java/com/github/andrelugomes/cities/resources/CityResourceTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.resources; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.web.client.TestRestTemplate; 9 | import org.springframework.boot.web.server.LocalServerPort; 10 | import org.springframework.test.context.ActiveProfiles; 11 | 12 | @ActiveProfiles("test") 13 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 14 | class CityResourceTest { 15 | 16 | @LocalServerPort 17 | private int port; 18 | 19 | @Autowired 20 | private TestRestTemplate restTemplate; 21 | 22 | @Test 23 | public void shouldReturnAPageOfCity() { 24 | String response = 25 | restTemplate.getForObject("http://localhost:" + port + "/cities", String.class); 26 | 27 | assertThat(response).contains("Ibaté"); 28 | assertThat(response).contains("São Carlos"); 29 | } 30 | } -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/test/java/com/github/andrelugomes/cities/service/DistanceServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.service; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.assertj.core.data.Offset.offset; 5 | import static org.mockito.ArgumentMatchers.anyList; 6 | import static org.mockito.BDDMockito.given; 7 | 8 | import com.github.andrelugomes.cities.entities.City; 9 | import com.github.andrelugomes.cities.repositories.CityRepository; 10 | import java.util.Arrays; 11 | import org.junit.jupiter.api.BeforeEach; 12 | import org.junit.jupiter.api.Test; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.boot.test.context.SpringBootTest; 15 | import org.springframework.boot.test.mock.mockito.MockBean; 16 | import org.springframework.data.geo.Point; 17 | 18 | @SpringBootTest 19 | class DistanceServiceTest { 20 | 21 | @Autowired 22 | private DistanceService service; 23 | 24 | @MockBean 25 | private CityRepository cityRepository; 26 | 27 | private City saoCarlos; 28 | private City ibate; 29 | 30 | @BeforeEach 31 | public void setUp() { 32 | ibate = new City(4929L, "Ibaté", 26, 3519303, "(-21.95840072631836,-47.98820114135742)", 33 | new Point(-21.95840072631836, -47.98820114135742)); 34 | saoCarlos = 35 | new City(5254L, "São Carlos", 26, 3548906, "(-22.01740074157715,-47.88600158691406)", 36 | new Point(-22.01740074157715, -47.88600158691406)); 37 | } 38 | 39 | @Test 40 | public void shouldCalculateInMetersUsingMath() { 41 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 42 | 43 | Double distance = service.distanceUsingMath(4929L, 5254L, EarthRadius.METERS); 44 | 45 | assertThat(distance).isEqualTo(12426.810463475855); 46 | } 47 | 48 | @Test 49 | public void shouldCalculateInKilometersUsingMath() { 50 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 51 | 52 | Double distance = service.distanceUsingMath(4929L, 5254L, EarthRadius.KILOMETERS); 53 | 54 | assertThat(distance).isCloseTo(12.426, offset(0.001d)); 55 | } 56 | 57 | @Test 58 | public void shouldCalculateInMilesUsingMath() { 59 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 60 | 61 | Double distance = service.distanceUsingMath(4929L, 5254L, EarthRadius.MILES); 62 | 63 | assertThat(distance).isCloseTo(7.71, offset(0.01d)); 64 | } 65 | 66 | @Test 67 | public void shouldCalculateInMetersUsingPoints() { 68 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 69 | 70 | Double distance = service.distanceUsingPoints(4929L, 5254L, EarthRadius.METERS); 71 | 72 | assertThat(distance).isEqualTo(12426.810463475855); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/test/java/com/github/andrelugomes/countries/resources/CountryResourceTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.countries.resources; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.web.client.TestRestTemplate; 9 | import org.springframework.boot.web.server.LocalServerPort; 10 | 11 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 12 | class CountryResourceTest { 13 | 14 | public static final String URL = "http://localhost:"; 15 | 16 | @LocalServerPort 17 | private int port; 18 | 19 | @Autowired 20 | private TestRestTemplate restTemplate; 21 | 22 | @Test 23 | public void shouldReturnCountries() { 24 | String response = restTemplate.getForObject(URL + port + "/countries", String.class); 25 | 26 | assertThat(response).contains("Brasil"); 27 | assertThat(response).contains("Brazil"); 28 | } 29 | } -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/test/java/com/github/andrelugomes/states/resources/StateResourceTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.states.resources; 2 | 3 | import static java.util.Arrays.asList; 4 | import static org.hamcrest.Matchers.is; 5 | import static org.mockito.Mockito.when; 6 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 7 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 8 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 9 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 10 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 11 | 12 | import com.github.andrelugomes.countries.entities.Country; 13 | import com.github.andrelugomes.states.entities.State; 14 | import com.github.andrelugomes.states.repositories.StateRepository; 15 | import org.junit.jupiter.api.Test; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 18 | import org.springframework.boot.test.mock.mockito.MockBean; 19 | import org.springframework.test.web.servlet.MockMvc; 20 | 21 | @WebMvcTest(StateResource.class) 22 | class StateResourceTest { 23 | 24 | @Autowired 25 | private MockMvc mockMvc; 26 | 27 | @MockBean 28 | private StateRepository repository; 29 | 30 | @Test 31 | public void shouldReturnStates() throws Exception { 32 | State state = new State(1L, "São Paulo", "SP", 35, new Country(), asList(1, 2, 3)); 33 | when(repository.findAll()).thenReturn(asList( 34 | state)); 35 | 36 | mockMvc.perform(get("/states").accept("application/json;charset=UTF-8")) 37 | .andDo(print()) 38 | .andExpect(status().isOk()) 39 | .andExpect(content().contentType("application/json;charset=UTF-8")) 40 | .andExpect(jsonPath("$[0].name", is("São Paulo"))) 41 | .andExpect(jsonPath("$[0].uf", is("SP"))); 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/test/java/com/github/andrelugomes/utils/StringLocationUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.utils; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | class StringLocationUtilsTest { 8 | 9 | @Test 10 | public void shouldExtractGeoLocationsFormString() { 11 | String geoLocation = "(123, 321)"; 12 | 13 | Double[] transform = StringLocationUtils.transform(geoLocation); 14 | 15 | assertEquals(123.0, transform[0], "Not equal"); 16 | assertEquals(321, transform[1], "Not equal"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.flyway.enabled=false 2 | 3 | spring.datasource.url=jdbc:h2:mem:cities-memory-db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=TRUE 4 | spring.datasource.username=sa 5 | spring.datasource.password= 6 | spring.datasource.driverClassName=org.h2.Driver 7 | 8 | spring.jpa.hibernate.ddl-auto=none 9 | spring.jpa.database-platform=org.hibernate.dialect.H2Dialect 10 | spring.jpa.show-sql=true 11 | spring.jpa.properties.hibernate.format_sql=true 12 | 13 | #show sql statement 14 | logging.level.org.hibernate.SQL=debug 15 | 16 | #show sql values 17 | logging.level.org.hibernate.type.descriptor.sql=trace -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/test/resources/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO pais (id, nome, nome_pt, sigla, bacen) VALUES (1, 'Brazil', 'Brasil', 'BR', 1058); 2 | 3 | INSERT INTO estado (id, nome, uf, ibge, pais, ddd) VALUES (26, 'São Paulo', 'SP', 35, 1, '[11,12,13,14,15,16,17,18,19]'); 4 | 5 | INSERT INTO cidade (id, nome, uf, ibge, lat_lon) VALUES (4929, 'Ibaté', 26, 3519303, '(-21.958400726318359,-47.988201141357422)'); 6 | INSERT INTO cidade (id, nome, uf, ibge, lat_lon) VALUES (5254, 'São Carlos', 26, 3548906, '(-22.017400741577148,-47.886001586914063)'); -------------------------------------------------------------------------------- /cities-api-full-ci-cd/src/test/resources/schema.sql: -------------------------------------------------------------------------------- 1 | CREATE domain IF NOT EXISTS jsonb AS TEXT; 2 | CREATE domain IF NOT EXISTS POINT AS TEXT; 3 | 4 | DROP TABLE IF EXISTS pais; 5 | DROP TABLE IF EXISTS estado; 6 | DROP TABLE IF EXISTS cidade; 7 | 8 | CREATE TABLE pais ( 9 | id bigserial NOT NULL, 10 | nome varchar(60), 11 | nome_pt varchar(60), 12 | sigla varchar(2), 13 | bacen integer, 14 | /* Keys */ 15 | CONSTRAINT pais_pkey 16 | PRIMARY KEY (id) 17 | ); 18 | 19 | CREATE TABLE estado ( 20 | id bigserial NOT NULL, 21 | nome varchar(60), 22 | uf varchar(2), 23 | ibge integer, 24 | pais integer, 25 | ddd json, 26 | /* Keys */ 27 | CONSTRAINT estado_pkey 28 | PRIMARY KEY (id) 29 | ); 30 | 31 | CREATE TABLE cidade ( 32 | id bigint NOT NULL, 33 | nome varchar(120), 34 | uf integer, 35 | ibge integer, 36 | lat_lon varchar(120) 37 | ); -------------------------------------------------------------------------------- /cities-api-nearby-service/.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | out/ 22 | 23 | ### NetBeans ### 24 | /nbproject/private/ 25 | /nbbuild/ 26 | /dist/ 27 | /nbdist/ 28 | /.nb-gradle/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /cities-api-nearby-service/.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | os: linux 4 | dist: trusty 5 | jdk: oraclejdk8 6 | 7 | jobs: 8 | include: 9 | - stage: "Build project" 10 | script: 11 | - ./gradlew build 12 | 13 | deploy: 14 | provider: heroku 15 | app: dio-cities-api-2 16 | api_key: $HEROKU_KEY_BLA -------------------------------------------------------------------------------- /cities-api-nearby-service/Procfile: -------------------------------------------------------------------------------- 1 | web: java -jar -Dspring.profiles.active=heroku build/libs/cities-api-0.0.1-SNAPSHOT.jar -------------------------------------------------------------------------------- /cities-api-nearby-service/README.md: -------------------------------------------------------------------------------- 1 | # Cities API 2 | 3 | Calculate distance between cities and find cities by radius 4 | 5 | ## Requirements 6 | 7 | * Linux 8 | * Git 9 | * Java 8 10 | * Docker 11 | * IntelliJ Community 12 | * Heroku CLI 13 | * Travis CLI 14 | 15 | ## DataBase 16 | 17 | ### Postgres 18 | 19 | * [Postgres Docker Hub](https://hub.docker.com/_/postgres) 20 | 21 | ```shell script 22 | docker run --name cities-db -d -p 5432:5432 -e POSTGRES_USER=postgres_user_city -e POSTGRES_PASSWORD=super_password -e POSTGRES_DB=cities postgres 23 | ``` 24 | 25 | * [Postgres Earth distance](https://www.postgresql.org/docs/current/earthdistance.html) 26 | * [earthdistance--1.0--1.1.sql](https://github.com/postgres/postgres/blob/master/contrib/earthdistance/earthdistance--1.0--1.1.sql) 27 | * [OPERATOR <@>](https://github.com/postgres/postgres/blob/master/contrib/earthdistance/earthdistance--1.1.sql) 28 | * [postgrescheatsheet](https://postgrescheatsheet.com/#/tables) 29 | * [datatype-geometric](https://www.postgresql.org/docs/current/datatype-geometric.html) 30 | * [Cube @>](https://www.postgresql.org/docs/current/cube.html) 31 | * [Cube Tutorial](https://www.postgresqltutorial.com/postgresql-cube/) 32 | 33 | + earth_distance(earth, earth) return float8 34 | Returns the great circle distance between two points on the surface of the Earth. 35 | + ll_to_earth(float8, float8) return earth 36 | Returns the location of a point on the surface of the Earth given its latitude (argument 1) and longitude (argument 2) in degrees. 37 | + earth_box(earth, float8) return cube 38 | Returns a box suitable for an indexed search using the cube @> operator for points within a given great circle distance of a location. Some points in this box are further than the specified great circle distance from the location, so a second check using earth_distance should be included in the query. 39 | 40 | ### Access 41 | 42 | ```shell script 43 | docker exec -it cities-db /bin/bash 44 | 45 | psql -U postgres_user_city cities 46 | ``` 47 | 48 | ### Query Earth Distance 49 | 50 | lat_lon as Point data type 51 | ```roomsql 52 | select ((select lat_lon from cidade where id = 4929) <@> (select lat_lon from cidade where id=5254)) as distance; 53 | ``` 54 | 55 | Cube 56 | ```roomsql 57 | select earth_distance( 58 | ll_to_earth(-21.95840072631836,-47.98820114135742), 59 | ll_to_earth(-22.01740074157715,-47.88600158691406) 60 | ) as distance; 61 | ``` 62 | 63 | ### Query Earth Box 64 | 65 | + 30000 is the radius 66 | 67 | Get a Cube 68 | ```roomsql 69 | SELECT earth_box(ll_to_earth(-21.95840072631836, -47.98820114135742), 30000) as cube; 70 | ``` 71 | The Cube contains? (ll_to_earth) 72 | ```roomsql 73 | SELECT earth_box(ll_to_earth(-21.95840072631836, -47.98820114135742), 30000) @> ll_to_earth(-21.95840072631836, -47.98820114135742) as contains; 74 | ``` 75 | 76 | All Cities Where The Cube contains ll_to_earth 77 | ```roomsql 78 | SELECT cidade.id, cidade.nome, cidade.lat_lon 79 | FROM cidade 80 | WHERE earth_box(ll_to_earth(-21.95840072631836, -47.98820114135742), 30000) @> ll_to_earth(cidade.lat_lon[0],cidade.lat_lon[1]); 81 | ``` 82 | 83 | ### Query Earth Box by Radius 84 | 85 | ```roomsql 86 | SELECT cidade.id, cidade.nome, cidade.lat_lon 87 | FROM cidade 88 | WHERE earth_box(ll_to_earth(-21.95840072631836, -47.98820114135742), 30000) @> ll_to_earth(cidade.lat_lon[0],cidade.lat_lon[1]) 89 | AND earth_distance(ll_to_earth(-21.95840072631836, -47.98820114135742), ll_to_earth(cidade.lat_lon[0],cidade.lat_lon[1])) < 30000; 90 | ``` 91 | 92 | ## Spring Boot 93 | 94 | * [https://start.spring.io/](https://start.spring.io/) 95 | 96 | + Java 8 97 | + Gradle Project 98 | + Jar 99 | + Spring Web 100 | + Spring Data JPA 101 | + PostgreSQL Driver 102 | 103 | ### Spring Data 104 | 105 | * [jpa.query-methods](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods) 106 | 107 | ### Properties 108 | 109 | * [appendix-application-properties](https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html) 110 | * [jdbc-database-connectio](https://www.codejava.net/java-se/jdbc/jdbc-database-connection-url-for-common-databases) 111 | 112 | ### Types 113 | 114 | * [JsonTypes](https://github.com/vladmihalcea/hibernate-types) 115 | * [UserType](https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/usertype/UserType.html) 116 | 117 | ## Heroku 118 | 119 | * [DevCenter](https://devcenter.heroku.com/articles/getting-started-with-gradle-on-heroku) 120 | 121 | ```shell script 122 | heroku create dio-cities-api --addons=heroku-postgresql 123 | ``` 124 | 125 | ## Code Quality 126 | 127 | ### PMD 128 | 129 | + https://pmd.github.io/pmd-6.8.0/index.html 130 | 131 | ### Checkstyle 132 | 133 | + https://checkstyle.org/ 134 | 135 | + https://checkstyle.org/google_style.html 136 | 137 | + http://google.github.io/styleguide/javaguide.html 138 | 139 | ```shell script 140 | wget https://raw.githubusercontent.com/checkstyle/checkstyle/master/src/main/resources/google_checks.xml 141 | ``` 142 | 143 | ## InMemory Database Testing 144 | 145 | + http://www.h2database.com/html/features.html 146 | 147 | 148 | ## Migrations 149 | 150 | + https://flywaydb.org/ 151 | 152 | ## CI 153 | 154 | ### Travis 155 | + https://github.com/travis-ci/travis.rb#readme 156 | 157 | + https://docs.travis-ci.com/user/tutorial/ 158 | 159 | #### extra 160 | 161 | + https://docs.travis-ci.com/user/conditional-builds-stages-jobs/ 162 | + https://docs.travis-ci.com/user/deployment-v2/conditional 163 | 164 | + [Heroku Deployment](https://docs.travis-ci.com/user/deployment/heroku/) 165 | -------------------------------------------------------------------------------- /cities-api-nearby-service/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'io.spring.dependency-management' version '1.0.9.RELEASE' 3 | id 'org.springframework.boot' version '2.2.6.RELEASE' 4 | id 'checkstyle' 5 | id 'java' 6 | id 'pmd' 7 | } 8 | 9 | group = 'com.github.andrelugomes' 10 | version = '0.0.1-SNAPSHOT' 11 | sourceCompatibility = '1.8' 12 | 13 | repositories { 14 | mavenCentral() 15 | } 16 | 17 | dependencies { 18 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 19 | implementation 'org.springframework.boot:spring-boot-starter-web' 20 | implementation 'com.vladmihalcea:hibernate-types-52:2.9.8' 21 | implementation 'org.postgresql:postgresql' 22 | implementation 'org.flywaydb:flyway-core' 23 | 24 | testImplementation('org.springframework.boot:spring-boot-starter-test') { 25 | exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' 26 | } 27 | testImplementation 'com.h2database:h2:1.4.200' 28 | } 29 | 30 | test { 31 | useJUnitPlatform() 32 | } 33 | 34 | pmd { 35 | consoleOutput = true 36 | toolVersion = "6.21.0" 37 | rulePriority = 5 38 | ruleSetFiles = files("pmd-ruleset.xml") 39 | ruleSets = [] 40 | //ruleSets = ["category/java/bestpractices.xml"] 41 | } 42 | 43 | checkstyle { 44 | toolVersion "8.31" 45 | configFile file("google_checks.xml") 46 | } 47 | -------------------------------------------------------------------------------- /cities-api-nearby-service/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andrelugomes/digital-innovation-one/31982544848f282a20f776efc7c8a64e4ba40560/cities-api-nearby-service/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /cities-api-nearby-service/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /cities-api-nearby-service/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /cities-api-nearby-service/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | @rem Execute Gradle 88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 89 | 90 | :end 91 | @rem End local scope for the variables with windows NT shell 92 | if "%ERRORLEVEL%"=="0" goto mainEnd 93 | 94 | :fail 95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 96 | rem the _cmd.exe /c_ return code! 97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 98 | exit /b 1 99 | 100 | :mainEnd 101 | if "%OS%"=="Windows_NT" endlocal 102 | 103 | :omega 104 | -------------------------------------------------------------------------------- /cities-api-nearby-service/pmd-ruleset.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 | 9 | Cities API PDM rules 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /cities-api-nearby-service/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'cities-api' 2 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/CitiesApplication.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class CitiesApplication { 8 | 9 | public static void main(final String[] args) { 10 | SpringApplication.run(CitiesApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/cities/entities/City.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.entities; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.Id; 6 | import javax.persistence.Table; 7 | import org.hibernate.annotations.Type; 8 | import org.hibernate.annotations.TypeDef; 9 | import org.hibernate.annotations.TypeDefs; 10 | import org.springframework.data.geo.Point; 11 | 12 | 13 | @Entity 14 | @Table(name = "cidade") 15 | @TypeDefs(value = { 16 | @TypeDef(name = "point", typeClass = PointType.class) 17 | }) 18 | public class City { 19 | 20 | @Id 21 | private Long id; 22 | 23 | @Column(name = "nome") 24 | private String name; 25 | 26 | private Integer uf; 27 | 28 | private Integer ibge; 29 | 30 | // 1st 31 | @Column(name = "lat_lon") 32 | private String geolocation; 33 | 34 | // 2nd 35 | @Type(type = "point") 36 | @Column(name = "lat_lon", updatable = false, insertable = false) 37 | private Point location; 38 | 39 | public City() { 40 | } 41 | 42 | /** 43 | * 44 | * @param id 45 | * @param name 46 | * @param uf 47 | * @param ibge 48 | * @param geolocation 49 | * @param location 50 | */ 51 | public City(final Long id, final String name, final Integer uf, final Integer ibge, 52 | final String geolocation, final Point location) { 53 | this.id = id; 54 | this.name = name; 55 | this.uf = uf; 56 | this.ibge = ibge; 57 | this.geolocation = geolocation; 58 | this.location = location; 59 | } 60 | 61 | public Long getId() { 62 | return id; 63 | } 64 | 65 | public String getName() { 66 | return name; 67 | } 68 | 69 | public Integer getUf() { 70 | return uf; 71 | } 72 | 73 | public Integer getIbge() { 74 | return ibge; 75 | } 76 | 77 | public String getGeolocation() { 78 | return geolocation; 79 | } 80 | 81 | public Point getLocation() { 82 | return location; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/cities/entities/PointType.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.entities; 2 | 3 | import java.io.Serializable; 4 | import java.sql.PreparedStatement; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | import org.hibernate.HibernateException; 8 | import org.hibernate.engine.spi.SharedSessionContractImplementor; 9 | import org.hibernate.usertype.UserType; 10 | import org.postgresql.geometric.PGpoint; 11 | import org.springframework.data.geo.Point; 12 | 13 | public class PointType implements UserType { 14 | 15 | @Override 16 | public int[] sqlTypes() { 17 | return new int[] {java.sql.Types.OTHER}; 18 | } 19 | 20 | @Override 21 | public Class returnedClass() { 22 | return Point.class; 23 | } 24 | 25 | @Override 26 | public boolean equals(Object x, Object y) throws HibernateException { 27 | return false; 28 | } 29 | 30 | @Override 31 | public int hashCode(Object x) throws HibernateException { 32 | return 0; 33 | } 34 | 35 | @Override 36 | public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, 37 | Object owner) throws HibernateException, SQLException { 38 | /* 1st */ 39 | /*Object object = rs.getObject(names[0]); 40 | Double[] points = StringLocationUtils.transform(object.toString()); 41 | return new Point(points[0], points[1]);*/ 42 | 43 | /* 2nd */ 44 | /*PGpoint value = (PGpoint) rs.getObject(names[0]); 45 | return new Point(value.x, value.y);*/ 46 | 47 | /* 3rd */ 48 | Object object = rs.getObject(names[0]); 49 | PGpoint point = new PGpoint(object.toString()); 50 | return new Point(point.x, point.y); 51 | } 52 | 53 | @Override 54 | public void nullSafeSet(PreparedStatement st, Object value, int index, 55 | SharedSessionContractImplementor session) 56 | throws HibernateException, SQLException { 57 | 58 | } 59 | 60 | @Override 61 | public Object deepCopy(Object value) throws HibernateException { 62 | return null; 63 | } 64 | 65 | @Override 66 | public boolean isMutable() { 67 | return false; 68 | } 69 | 70 | @Override 71 | public Serializable disassemble(Object value) throws HibernateException { 72 | return null; 73 | } 74 | 75 | @Override 76 | public Object assemble(Serializable cached, Object owner) throws HibernateException { 77 | return null; 78 | } 79 | 80 | @Override 81 | public Object replace(Object original, Object target, Object owner) throws HibernateException { 82 | return null; 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/cities/repositories/CityRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.repositories; 2 | 3 | import com.github.andrelugomes.cities.entities.City; 4 | import java.util.List; 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.jpa.repository.Query; 7 | 8 | public interface CityRepository extends JpaRepository { 9 | 10 | String QUERY_POINTS = "SELECT ((SELECT lat_lon FROM cidade WHERE id=?1) <@> " 11 | + "(SELECT lat_lon FROM cidade WHERE id=?2)) as distance"; 12 | 13 | String QUERY_CUBE = "SELECT earth_distance(ll_to_earth(?1,?2), ll_to_earth(?3,?4)) as distance"; 14 | 15 | String QUERY_RADIUS_AREA = "SELECT * FROM cidade as c " 16 | + "WHERE earth_box(ll_to_earth(?1, ?2), ?3) @> ll_to_earth(c.lat_lon[0], c.lat_lon[1]) " 17 | + "AND earth_distance(ll_to_earth(?1, ?2), ll_to_earth(c.lat_lon[0], c.lat_lon[1])) < ?3"; 18 | 19 | @Query(value = QUERY_POINTS, nativeQuery = true) 20 | Double distanceByPoints(final Long cityId1, final Long cityId2); 21 | 22 | @Query(value = QUERY_CUBE, nativeQuery = true) 23 | Double distanceByCube(final Double lat1, final Double lon1, final Double lat2, final Double lon2); 24 | 25 | @Query(value = QUERY_RADIUS_AREA, nativeQuery = true) 26 | List citiesByRadius(final double lat, final double lon, final double radius); 27 | } 28 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/cities/resources/CityResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.resources; 2 | 3 | import com.github.andrelugomes.cities.entities.City; 4 | import com.github.andrelugomes.cities.repositories.CityRepository; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.data.domain.Page; 8 | import org.springframework.data.domain.Pageable; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | @RestController 14 | @RequestMapping("cities") 15 | public class CityResource { 16 | 17 | private static Logger log = LoggerFactory.getLogger(CityResource.class); 18 | private final CityRepository repository; 19 | 20 | public CityResource(final CityRepository repository) { 21 | this.repository = repository; 22 | } 23 | 24 | @GetMapping 25 | public Page cities(final Pageable page) { 26 | log.info("cities, {}", page); 27 | return repository.findAll(page); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/cities/resources/DistanceResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.resources; 2 | 3 | import com.github.andrelugomes.cities.service.DistanceService; 4 | import com.github.andrelugomes.cities.service.EarthRadius; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestParam; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | @RestController 13 | @RequestMapping("/distances") 14 | public class DistanceResource { 15 | 16 | private static Logger log = LoggerFactory.getLogger(DistanceResource.class); 17 | private final DistanceService service; 18 | 19 | public DistanceResource(DistanceService service) { 20 | this.service = service; 21 | } 22 | 23 | @GetMapping("/by-points") 24 | public Double byPoints(@RequestParam(name = "from") final Long city1, 25 | @RequestParam(name = "to") final Long city2) { 26 | log.info("byPoints, from={}, to={}", city1, city2); 27 | return service.distanceByPointsInMiles(city1, city2); 28 | } 29 | 30 | @GetMapping("/by-cube") 31 | public Double byCube(@RequestParam(name = "from") final Long city1, 32 | @RequestParam(name = "to") final Long city2) { 33 | log.info("byCube, from={}, to={}", city1, city2); 34 | return service.distanceByCubeInMeters(city1, city2); 35 | } 36 | 37 | @GetMapping("/by-math") 38 | public Double byMath(@RequestParam(name = "from") final Long city1, 39 | @RequestParam(name = "to") final Long city2, 40 | @RequestParam final EarthRadius unit) { 41 | log.info("byMath, from={}, to={}", city1, city2); 42 | return service.distanceUsingMath(city1, city2, unit); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/cities/resources/NearbyResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.resources; 2 | 3 | import com.github.andrelugomes.cities.entities.City; 4 | import com.github.andrelugomes.cities.service.DistanceService; 5 | import java.util.List; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RequestParam; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | @RestController 14 | @RequestMapping("/nearby") 15 | public class NearbyResource { 16 | 17 | private static Logger log = LoggerFactory.getLogger(NearbyResource.class); 18 | private final DistanceService service; 19 | 20 | public NearbyResource(DistanceService service) { 21 | this.service = service; 22 | } 23 | 24 | @GetMapping 25 | public List nearby(@RequestParam(name = "city_id") final Long cityId, 26 | @RequestParam(name = "radius") final Double radius) { 27 | log.info("nearby, city_id={}, radius={}", cityId, radius); 28 | return service.nearby(cityId, radius); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/cities/service/DistanceService.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.service; 2 | 3 | import static java.lang.Math.atan2; 4 | import static java.lang.Math.cos; 5 | import static java.lang.Math.sin; 6 | import static java.lang.Math.sqrt; 7 | import static java.lang.Math.toRadians; 8 | 9 | import com.github.andrelugomes.cities.entities.City; 10 | import com.github.andrelugomes.cities.repositories.CityRepository; 11 | import com.github.andrelugomes.utils.StringLocationUtils; 12 | import java.util.Arrays; 13 | import java.util.Collections; 14 | import java.util.List; 15 | import java.util.Optional; 16 | import org.slf4j.Logger; 17 | import org.slf4j.LoggerFactory; 18 | import org.springframework.data.geo.Point; 19 | import org.springframework.stereotype.Service; 20 | 21 | @Service 22 | public class DistanceService { 23 | 24 | private static Logger log = LoggerFactory.getLogger(DistanceService.class); 25 | private final CityRepository cityRepository; 26 | 27 | public DistanceService(final CityRepository cityRepository) { 28 | this.cityRepository = cityRepository; 29 | } 30 | 31 | /** 32 | * 1st option 33 | * 34 | * @param city1 Long 35 | * @param city2 Long 36 | * @param unit EarthRadius 37 | * @return Double 38 | */ 39 | public Double distanceUsingMath(final Long city1, final Long city2, final EarthRadius unit) { 40 | log.info("distanceUsingMath({}, {}, {})", city1, city2, unit); 41 | final List cities = cityRepository.findAllById((Arrays.asList(city1, city2))); 42 | 43 | final Double[] location1 = StringLocationUtils.transform(cities.get(0).getGeolocation()); 44 | final Double[] location2 = StringLocationUtils.transform(cities.get(1).getGeolocation()); 45 | 46 | return doCalculation(location1[0], location1[1], location2[0], location2[1], unit); 47 | } 48 | 49 | /** 50 | * 2nd option 51 | * 52 | * @param city1 53 | * @param city2 54 | * @return 55 | */ 56 | public Double distanceByPointsInMiles(final Long city1, final Long city2) { 57 | log.info("nativePostgresInMiles({}, {})", city1, city2); 58 | return cityRepository.distanceByPoints(city1, city2); 59 | } 60 | 61 | /** 62 | * 3rd option 63 | * 64 | * @param city1 65 | * @param city2 66 | * @param unit 67 | * @return 68 | */ 69 | public Double distanceUsingPoints(final Long city1, final Long city2, final EarthRadius unit) { 70 | log.info("distanceUsingPoints({}, {}, {})", city1, city2, unit); 71 | final List cities = cityRepository.findAllById((Arrays.asList(city1, city2))); 72 | 73 | Point p1 = cities.get(0).getLocation(); 74 | Point p2 = cities.get(1).getLocation(); 75 | 76 | return doCalculation(p1.getX(), p1.getY(), p2.getX(), p2.getY(), unit); 77 | } 78 | 79 | /** 80 | * 4th option 81 | * 82 | * @param city1 83 | * @param city2 84 | * @return 85 | */ 86 | public Double distanceByCubeInMeters(Long city1, Long city2) { 87 | log.info("distanceByCubeInMeters({}, {})", city1, city2); 88 | final List cities = cityRepository.findAllById((Arrays.asList(city1, city2))); 89 | 90 | Point p1 = cities.get(0).getLocation(); 91 | Point p2 = cities.get(1).getLocation(); 92 | 93 | return cityRepository.distanceByCube(p1.getX(), p1.getY(), p2.getX(), p2.getY()); 94 | } 95 | 96 | /** 97 | * Find cities nearby another 98 | * @param id 99 | * @param radius 100 | * @return 101 | */ 102 | public List nearby(Long id, Double radius) { 103 | log.info("nearby({}, {})", id, radius); 104 | Optional city = cityRepository.findById(id); 105 | 106 | if (city.isPresent()) { 107 | Point location = city.get().getLocation(); 108 | return cityRepository.citiesByRadius(location.getX(), location.getY(), radius); 109 | } 110 | 111 | return Collections.emptyList(); 112 | } 113 | 114 | private double doCalculation(final double lat1, final double lon1, final double lat2, 115 | final double lng2, final EarthRadius earthRadius) { 116 | double lat = toRadians(lat2 - lat1); 117 | double lon = toRadians(lng2 - lon1); 118 | double a = sin(lat / 2) * sin(lat / 2) 119 | + cos(toRadians(lat1)) * cos(toRadians(lat2)) * sin(lon / 2) * sin(lon / 2); 120 | double c = 2 * atan2(sqrt(a), sqrt(1 - a)); 121 | 122 | return earthRadius.getValue() * c; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/cities/service/EarthRadius.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.service; 2 | 3 | public enum EarthRadius { 4 | METERS("m", 6378168), 5 | KILOMETERS("km", 6378.168f), 6 | MILES("mi", 3958.747716f); 7 | 8 | private final String unit; 9 | private final float value; 10 | 11 | EarthRadius(final String unit, final float value) { 12 | this.unit = unit; 13 | this.value = value; 14 | } 15 | 16 | public float getValue() { 17 | return value; 18 | } 19 | 20 | public String getUnit() { 21 | return unit; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/countries/entities/Country.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.countries.entities; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.Id; 6 | import javax.persistence.Table; 7 | 8 | @Entity(name = "Country") 9 | @Table(name = "pais") 10 | public class Country { 11 | 12 | @Id 13 | private Long id; 14 | 15 | @Column(name = "nome") 16 | private String name; 17 | 18 | @Column(name = "nome_pt") 19 | private String portugueseName; 20 | 21 | @Column(name = "sigla") 22 | private String code; 23 | 24 | private Integer bacen; 25 | 26 | public Country() { 27 | } 28 | 29 | public Long getId() { 30 | return id; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public String getPortugueseName() { 38 | return portugueseName; 39 | } 40 | 41 | public String getCode() { 42 | return code; 43 | } 44 | 45 | public Integer getBacen() { 46 | return bacen; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/countries/repositories/CountryRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.countries.repositories; 2 | 3 | import com.github.andrelugomes.countries.entities.Country; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface CountryRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/countries/resources/CountryResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.countries.resources; 2 | 3 | import com.github.andrelugomes.cities.resources.CityResource; 4 | import com.github.andrelugomes.countries.entities.Country; 5 | import com.github.andrelugomes.countries.repositories.CountryRepository; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import org.springframework.data.domain.Page; 9 | import org.springframework.data.domain.Pageable; 10 | import org.springframework.web.bind.annotation.GetMapping; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | import org.springframework.web.bind.annotation.RestController; 13 | 14 | @RestController 15 | @RequestMapping("countries") 16 | public class CountryResource { 17 | 18 | private static Logger log = LoggerFactory.getLogger(CityResource.class); 19 | private final CountryRepository repository; 20 | 21 | public CountryResource(final CountryRepository repository) { 22 | this.repository = repository; 23 | } 24 | 25 | @GetMapping 26 | public Page countries(final Pageable page) { 27 | log.info("countries, {}", page); 28 | return repository.findAll(page); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/states/entities/State.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.states.entities; 2 | 3 | import com.github.andrelugomes.countries.entities.Country; 4 | import com.vladmihalcea.hibernate.type.json.JsonBinaryType; 5 | import java.util.List; 6 | import javax.persistence.Basic; 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.FetchType; 10 | import javax.persistence.Id; 11 | import javax.persistence.JoinColumn; 12 | import javax.persistence.ManyToOne; 13 | import javax.persistence.Table; 14 | import org.hibernate.annotations.Type; 15 | import org.hibernate.annotations.TypeDef; 16 | import org.hibernate.annotations.TypeDefs; 17 | 18 | @Entity(name = "State") 19 | @Table(name = "estado") 20 | @TypeDefs({ 21 | @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) 22 | }) 23 | public class State { 24 | 25 | @Id 26 | private Long id; 27 | 28 | @Column(name = "nome") 29 | private String name; 30 | 31 | private String uf; 32 | 33 | private Integer ibge; 34 | 35 | /* 1st 36 | @Column(name = "pais") 37 | private Integer countryId;*/ 38 | 39 | // 2nd - @ManyToOne 40 | @ManyToOne 41 | @JoinColumn(name = "pais", referencedColumnName = "id") 42 | private Country country; 43 | 44 | @Type(type = "jsonb") 45 | @Basic(fetch = FetchType.LAZY) 46 | @Column(name = "ddd", columnDefinition = "jsonb") 47 | private List ddd; 48 | 49 | public State() { 50 | } 51 | 52 | /** 53 | * 54 | * @param id 55 | * @param name 56 | * @param uf 57 | * @param ibge 58 | * @param country 59 | * @param ddd 60 | */ 61 | public State(Long id, String name, String uf, Integer ibge, 62 | Country country, List ddd) { 63 | this.id = id; 64 | this.name = name; 65 | this.uf = uf; 66 | this.ibge = ibge; 67 | this.country = country; 68 | this.ddd = ddd; 69 | } 70 | 71 | public Long getId() { 72 | return id; 73 | } 74 | 75 | public String getName() { 76 | return name; 77 | } 78 | 79 | public String getUf() { 80 | return uf; 81 | } 82 | 83 | public Integer getIbge() { 84 | return ibge; 85 | } 86 | 87 | public List getDdd() { 88 | return ddd; 89 | } 90 | 91 | public Country getCountry() { 92 | return country; 93 | } 94 | 95 | /*public Integer getCountryId() { 96 | return countryId; 97 | }*/ 98 | } 99 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/states/repositories/StateRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.states.repositories; 2 | 3 | import com.github.andrelugomes.states.entities.State; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface StateRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/states/resources/StateResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.states.resources; 2 | 3 | import com.github.andrelugomes.states.entities.State; 4 | import com.github.andrelugomes.states.repositories.StateRepository; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.data.domain.Page; 8 | import org.springframework.data.domain.Pageable; 9 | import org.springframework.web.bind.annotation.GetMapping; 10 | import org.springframework.web.bind.annotation.RequestMapping; 11 | import org.springframework.web.bind.annotation.RestController; 12 | 13 | @RestController 14 | @RequestMapping("states") 15 | public class StateResource { 16 | 17 | private static Logger log = LoggerFactory.getLogger(StateResource.class); 18 | private final StateRepository repository; 19 | 20 | public StateResource(final StateRepository repository) { 21 | this.repository = repository; 22 | } 23 | 24 | @GetMapping 25 | public Page states(final Pageable page) { 26 | log.info("states, {}", page); 27 | return repository.findAll(page); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/java/com/github/andrelugomes/utils/StringLocationUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.utils; 2 | 3 | public class StringLocationUtils { 4 | /** 5 | * 6 | * @param geolocation String 7 | * @return Double[] 8 | */ 9 | public static Double[] transform(String geolocation) { 10 | String result = geolocation.replace("(", "").replace(")", ""); 11 | String[] strings = result.trim().split(","); 12 | return new Double[] {Double.valueOf(strings[0]), Double.valueOf(strings[1])}; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/resources/application-heroku.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=${DATABASE_URL} 2 | 3 | spring.jpa.show-sql=false 4 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=${PORT:8080} 2 | 3 | spring.datasource.url=jdbc:postgresql://localhost:5432/cities 4 | spring.datasource.username=postgres_user_city 5 | spring.datasource.password=super_password 6 | 7 | spring.jpa.show-sql=true 8 | 9 | spring.jpa.properties.hibernate.format_sql=true 10 | 11 | #show sql statement 12 | #logging.level.org.hibernate.SQL=debug 13 | 14 | #show sql values 15 | #logging.level.org.hibernate.type.descriptor.sql=trace -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/resources/db/migration/V2__create_estados.sql: -------------------------------------------------------------------------------- 1 | -- 2 | -- Estrutura da tabela "estado" 3 | -- 4 | 5 | CREATE TABLE estado ( 6 | id bigserial NOT NULL, 7 | nome varchar(60), 8 | uf varchar(2), 9 | ibge integer, 10 | pais integer, 11 | ddd json, 12 | /* Keys */ 13 | CONSTRAINT estado_pkey 14 | PRIMARY KEY (id) 15 | ); 16 | 17 | COMMENT ON TABLE estado 18 | IS 'Unidades Federativas'; 19 | 20 | -- 21 | -- Inserindo dados na tabela "estado" 22 | -- 23 | 24 | INSERT INTO "estado" (id, nome, uf, ibge, pais, ddd) VALUES 25 | (1, 'Acre', 'AC', 12, 1, '[68]'), 26 | (2, 'Alagoas', 'AL', 27, 1, '[82]'), 27 | (3, 'Amazonas', 'AM', 13, 1, '[97,92]'), 28 | (4, 'Amapá', 'AP', 16, 1, '[96]'), 29 | (5, 'Bahia', 'BA', 29, 1, '[77,75,73,74,71]'), 30 | (6, 'Ceará', 'CE', 23, 1, '[88,85]'), 31 | (7, 'Distrito Federal', 'DF', 53, 1, '[61]'), 32 | (8, 'Espírito Santo', 'ES', 32, 1, '[28,27]'), 33 | (9, 'Goiás', 'GO', 52, 1, '[62,64,61]'), 34 | (10, 'Maranhão', 'MA', 21, 1, '[99,98]'), 35 | (11, 'Minas Gerais', 'MG', 31, 1, '[34,37,31,33,35,38,32]'), 36 | (12, 'Mato Grosso do Sul', 'MS', 50, 1, '[67]'), 37 | (13, 'Mato Grosso', 'MT', 51, 1, '[65,66]'), 38 | (14, 'Pará', 'PA', 15, 1, '[91,94,93]'), 39 | (15, 'Paraíba', 'PB', 25, 1, '[83]'), 40 | (16, 'Pernambuco', 'PE', 26, 1, '[81,87]'), 41 | (17, 'Piauí', 'PI', 22, 1, '[89,86]'), 42 | (18, 'Paraná', 'PR', 41, 1, '[43,41,42,44,45,46]'), 43 | (19, 'Rio de Janeiro', 'RJ', 33, 1, '[24,22,21]'), 44 | (20, 'Rio Grande do Norte', 'RN', 24, 1, '[84]'), 45 | (21, 'Rondônia', 'RO', 11, 1, '[69]'), 46 | (22, 'Roraima', 'RR', 14, 1, '[95]'), 47 | (23, 'Rio Grande do Sul', 'RS', 43, 1, '[53,54,55,51]'), 48 | (24, 'Santa Catarina', 'SC', 42, 1, '[47,48,49]'), 49 | (25, 'Sergipe', 'SE', 28, 1, '[79]'), 50 | (26, 'São Paulo', 'SP', 35, 1, '[11,12,13,14,15,16,17,18,19]'), 51 | (27, 'Tocantins', 'TO', 17, 1, '[63]'), 52 | (99, 'Exterior', 'EX', 99, NULL, NULL); 53 | 54 | ALTER SEQUENCE estado_id_seq 55 | RESTART 99; 56 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/resources/db/migration/V4__enable_postgres_extentions.sql: -------------------------------------------------------------------------------- 1 | CREATE EXTENSION cube; 2 | CREATE EXTENSION earthdistance; -------------------------------------------------------------------------------- /cities-api-nearby-service/src/main/resources/db/migration/V5__delete_last_city_called_exterior.sql: -------------------------------------------------------------------------------- 1 | DELETE FROM cidade WHERE id=5610 AND lat_lon IS NULL; 2 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/test/java/com/github/andrelugomes/cities/resources/CityResourceTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.resources; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.web.client.TestRestTemplate; 9 | import org.springframework.boot.web.server.LocalServerPort; 10 | import org.springframework.test.context.ActiveProfiles; 11 | 12 | @ActiveProfiles("test") 13 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 14 | class CityResourceTest { 15 | 16 | @LocalServerPort 17 | private int port; 18 | 19 | @Autowired 20 | private TestRestTemplate restTemplate; 21 | 22 | @Test 23 | public void shouldReturnAPageOfCity() { 24 | String response = 25 | restTemplate.getForObject("http://localhost:" + port + "/cities", String.class); 26 | 27 | assertThat(response).contains("Ibaté"); 28 | assertThat(response).contains("São Carlos"); 29 | } 30 | } -------------------------------------------------------------------------------- /cities-api-nearby-service/src/test/java/com/github/andrelugomes/cities/service/DistanceServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.service; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.assertj.core.data.Offset.offset; 5 | import static org.mockito.ArgumentMatchers.anyList; 6 | import static org.mockito.BDDMockito.given; 7 | 8 | import com.github.andrelugomes.cities.entities.City; 9 | import com.github.andrelugomes.cities.repositories.CityRepository; 10 | import java.util.Arrays; 11 | import org.junit.jupiter.api.BeforeEach; 12 | import org.junit.jupiter.api.Test; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.boot.test.context.SpringBootTest; 15 | import org.springframework.boot.test.mock.mockito.MockBean; 16 | import org.springframework.data.geo.Point; 17 | 18 | @SpringBootTest 19 | class DistanceServiceTest { 20 | 21 | @Autowired 22 | private DistanceService service; 23 | 24 | @MockBean 25 | private CityRepository cityRepository; 26 | 27 | private City saoCarlos; 28 | private City ibate; 29 | 30 | @BeforeEach 31 | public void setUp() { 32 | ibate = new City(4929L, "Ibaté", 26, 3519303, "(-21.95840072631836,-47.98820114135742)", 33 | new Point(-21.95840072631836, -47.98820114135742)); 34 | saoCarlos = 35 | new City(5254L, "São Carlos", 26, 3548906, "(-22.01740074157715,-47.88600158691406)", 36 | new Point(-22.01740074157715, -47.88600158691406)); 37 | } 38 | 39 | @Test 40 | public void shouldCalculateInMetersUsingMath() { 41 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 42 | 43 | Double distance = service.distanceUsingMath(4929L, 5254L, EarthRadius.METERS); 44 | 45 | assertThat(distance).isEqualTo(12426.810463475855); 46 | } 47 | 48 | @Test 49 | public void shouldCalculateInKilometersUsingMath() { 50 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 51 | 52 | Double distance = service.distanceUsingMath(4929L, 5254L, EarthRadius.KILOMETERS); 53 | 54 | assertThat(distance).isCloseTo(12.426, offset(0.001d)); 55 | } 56 | 57 | @Test 58 | public void shouldCalculateInMilesUsingMath() { 59 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 60 | 61 | Double distance = service.distanceUsingMath(4929L, 5254L, EarthRadius.MILES); 62 | 63 | assertThat(distance).isCloseTo(7.71, offset(0.01d)); 64 | } 65 | 66 | @Test 67 | public void shouldCalculateInMetersUsingPoints() { 68 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 69 | 70 | Double distance = service.distanceUsingPoints(4929L, 5254L, EarthRadius.METERS); 71 | 72 | assertThat(distance).isEqualTo(12426.810463475855); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/test/java/com/github/andrelugomes/countries/resources/CountryResourceTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.countries.resources; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | 5 | import org.junit.jupiter.api.Test; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.boot.test.context.SpringBootTest; 8 | import org.springframework.boot.test.web.client.TestRestTemplate; 9 | import org.springframework.boot.web.server.LocalServerPort; 10 | 11 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 12 | class CountryResourceTest { 13 | 14 | public static final String URL = "http://localhost:"; 15 | 16 | @LocalServerPort 17 | private int port; 18 | 19 | @Autowired 20 | private TestRestTemplate restTemplate; 21 | 22 | @Test 23 | public void shouldReturnCountries() { 24 | String response = restTemplate.getForObject(URL + port + "/countries", String.class); 25 | 26 | assertThat(response).contains("Brasil"); 27 | assertThat(response).contains("Brazil"); 28 | } 29 | } -------------------------------------------------------------------------------- /cities-api-nearby-service/src/test/java/com/github/andrelugomes/states/resources/StateResourceTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.states.resources; 2 | 3 | import static java.util.Arrays.asList; 4 | import static org.hamcrest.Matchers.is; 5 | import static org.mockito.Mockito.when; 6 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 7 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 8 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 9 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 10 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 11 | 12 | import com.github.andrelugomes.countries.entities.Country; 13 | import com.github.andrelugomes.states.entities.State; 14 | import com.github.andrelugomes.states.repositories.StateRepository; 15 | import org.junit.jupiter.api.Test; 16 | import org.springframework.beans.factory.annotation.Autowired; 17 | import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 18 | import org.springframework.boot.test.mock.mockito.MockBean; 19 | import org.springframework.data.domain.PageImpl; 20 | import org.springframework.data.domain.PageRequest; 21 | import org.springframework.data.domain.Sort; 22 | import org.springframework.test.web.servlet.MockMvc; 23 | 24 | @WebMvcTest(StateResource.class) 25 | class StateResourceTest { 26 | 27 | @Autowired 28 | private MockMvc mockMvc; 29 | 30 | @MockBean 31 | private StateRepository repository; 32 | 33 | @Test 34 | public void shouldReturnStates() throws Exception { 35 | State state = new State(1L, "São Paulo", "SP", 35, new Country(), asList(1, 2, 3)); 36 | when(repository.findAll(PageRequest.of(0, 20, Sort.unsorted()))) 37 | .thenReturn(new PageImpl<>(asList(state))); 38 | 39 | mockMvc.perform(get("/states").accept("application/json;charset=UTF-8")) 40 | .andDo(print()) 41 | .andExpect(status().isOk()) 42 | .andExpect(content().contentType("application/json;charset=UTF-8")) 43 | .andExpect(jsonPath("$.content.[0].name", is("São Paulo"))) 44 | .andExpect(jsonPath("$.content.[0].uf", is("SP"))); 45 | } 46 | 47 | } -------------------------------------------------------------------------------- /cities-api-nearby-service/src/test/java/com/github/andrelugomes/utils/StringLocationUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.utils; 2 | 3 | import static org.junit.jupiter.api.Assertions.assertEquals; 4 | 5 | import org.junit.jupiter.api.Test; 6 | 7 | class StringLocationUtilsTest { 8 | 9 | @Test 10 | public void shouldExtractGeoLocationsFormString() { 11 | String geoLocation = "(123, 321)"; 12 | 13 | Double[] transform = StringLocationUtils.transform(geoLocation); 14 | 15 | assertEquals(123.0, transform[0], "Not equal"); 16 | assertEquals(321, transform[1], "Not equal"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /cities-api-nearby-service/src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.flyway.enabled=false 2 | 3 | spring.datasource.url=jdbc:h2:mem:cities-memory-db;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=TRUE 4 | spring.datasource.username=sa 5 | spring.datasource.password= 6 | spring.datasource.driverClassName=org.h2.Driver 7 | 8 | spring.jpa.hibernate.ddl-auto=none 9 | spring.jpa.database-platform=org.hibernate.dialect.H2Dialect 10 | spring.jpa.show-sql=true 11 | spring.jpa.properties.hibernate.format_sql=true 12 | 13 | #show sql statement 14 | logging.level.org.hibernate.SQL=debug 15 | 16 | #show sql values 17 | logging.level.org.hibernate.type.descriptor.sql=trace -------------------------------------------------------------------------------- /cities-api-nearby-service/src/test/resources/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO pais (id, nome, nome_pt, sigla, bacen) VALUES (1, 'Brazil', 'Brasil', 'BR', 1058); 2 | 3 | INSERT INTO estado (id, nome, uf, ibge, pais, ddd) VALUES (26, 'São Paulo', 'SP', 35, 1, '[11,12,13,14,15,16,17,18,19]'); 4 | 5 | INSERT INTO cidade (id, nome, uf, ibge, lat_lon) VALUES (4929, 'Ibaté', 26, 3519303, '(-21.958400726318359,-47.988201141357422)'); 6 | INSERT INTO cidade (id, nome, uf, ibge, lat_lon) VALUES (5254, 'São Carlos', 26, 3548906, '(-22.017400741577148,-47.886001586914063)'); -------------------------------------------------------------------------------- /cities-api-nearby-service/src/test/resources/schema.sql: -------------------------------------------------------------------------------- 1 | CREATE domain IF NOT EXISTS jsonb AS TEXT; 2 | CREATE domain IF NOT EXISTS POINT AS TEXT; 3 | 4 | DROP TABLE IF EXISTS pais; 5 | DROP TABLE IF EXISTS estado; 6 | DROP TABLE IF EXISTS cidade; 7 | 8 | CREATE TABLE pais ( 9 | id bigserial NOT NULL, 10 | nome varchar(60), 11 | nome_pt varchar(60), 12 | sigla varchar(2), 13 | bacen integer, 14 | /* Keys */ 15 | CONSTRAINT pais_pkey 16 | PRIMARY KEY (id) 17 | ); 18 | 19 | CREATE TABLE estado ( 20 | id bigserial NOT NULL, 21 | nome varchar(60), 22 | uf varchar(2), 23 | ibge integer, 24 | pais integer, 25 | ddd json, 26 | /* Keys */ 27 | CONSTRAINT estado_pkey 28 | PRIMARY KEY (id) 29 | ); 30 | 31 | CREATE TABLE cidade ( 32 | id bigint NOT NULL, 33 | nome varchar(120), 34 | uf integer, 35 | ibge integer, 36 | lat_lon varchar(120) 37 | ); -------------------------------------------------------------------------------- /cities-api/.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | !gradle/wrapper/gradle-wrapper.jar 4 | !**/src/main/** 5 | !**/src/test/** 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | out/ 22 | 23 | ### NetBeans ### 24 | /nbproject/private/ 25 | /nbbuild/ 26 | /dist/ 27 | /nbdist/ 28 | /.nb-gradle/ 29 | 30 | ### VS Code ### 31 | .vscode/ 32 | -------------------------------------------------------------------------------- /cities-api/Procfile: -------------------------------------------------------------------------------- 1 | web: java -jar -Dspring.profiles.active=heroku build/libs/cities-api-0.0.1-SNAPSHOT.jar -------------------------------------------------------------------------------- /cities-api/README.md: -------------------------------------------------------------------------------- 1 | # Cities API 2 | 3 | ## Requirements 4 | 5 | * Linux 6 | * Git 7 | * Java 8 8 | * Docker 9 | * IntelliJ Community 10 | * Heroku CLI 11 | 12 | ## DataBase 13 | 14 | ### Postgres 15 | 16 | * [Postgres Docker Hub](https://hub.docker.com/_/postgres) 17 | 18 | ```shell script 19 | docker run --name cities-db -d -p 5432:5432 -e POSTGRES_USER=postgres_user_city -e POSTGRES_PASSWORD=super_password -e POSTGRES_DB=cities postgres 20 | ``` 21 | 22 | ### Populate 23 | 24 | * [data](https://github.com/chinnonsantos/sql-paises-estados-cidades/tree/master/PostgreSQL) 25 | 26 | ```shell script 27 | cd ~/workspace/sql-paises-estados-cidades/PostgreSQL 28 | 29 | docker run -it --rm --net=host -v $PWD:/tmp postgres /bin/bash 30 | 31 | psql -h localhost -U postgres_user_city cities -f /tmp/pais.sql 32 | psql -h localhost -U postgres_user_city cities -f /tmp/estado.sql 33 | psql -h localhost -U postgres_user_city cities -f /tmp/cidade.sql 34 | 35 | psql -h localhost -U postgres_user_city cities 36 | 37 | CREATE EXTENSION cube; 38 | CREATE EXTENSION earthdistance; 39 | ``` 40 | 41 | * [Postgres Earth distance](https://www.postgresql.org/docs/current/earthdistance.html) 42 | * [earthdistance--1.0--1.1.sql](https://github.com/postgres/postgres/blob/master/contrib/earthdistance/earthdistance--1.0--1.1.sql) 43 | * [OPERATOR <@>](https://github.com/postgres/postgres/blob/master/contrib/earthdistance/earthdistance--1.1.sql) 44 | * [postgrescheatsheet](https://postgrescheatsheet.com/#/tables) 45 | * [datatype-geometric](https://www.postgresql.org/docs/current/datatype-geometric.html) 46 | 47 | ### Access 48 | 49 | ```shell script 50 | docker exec -it cities-db /bin/bash 51 | 52 | psql -U postgres_user_city cities 53 | ``` 54 | 55 | ### Query Earth Distance 56 | 57 | Point 58 | ```roomsql 59 | select ((select lat_lon from cidade where id = 4929) <@> (select lat_lon from cidade where id=5254)) as distance; 60 | ``` 61 | 62 | Cube 63 | ```roomsql 64 | select earth_distance( 65 | ll_to_earth(-21.95840072631836,-47.98820114135742), 66 | ll_to_earth(-22.01740074157715,-47.88600158691406) 67 | ) as distance; 68 | ``` 69 | 70 | ## Spring Boot 71 | 72 | * [https://start.spring.io/](https://start.spring.io/) 73 | 74 | + Java 8 75 | + Gradle Project 76 | + Jar 77 | + Spring Web 78 | + Spring Data JPA 79 | + PostgreSQL Driver 80 | 81 | ### Spring Data 82 | 83 | * [jpa.query-methods](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods) 84 | 85 | ### Properties 86 | 87 | * [appendix-application-properties](https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html) 88 | * [jdbc-database-connectio](https://www.codejava.net/java-se/jdbc/jdbc-database-connection-url-for-common-databases) 89 | 90 | ### Types 91 | 92 | * [JsonTypes](https://github.com/vladmihalcea/hibernate-types) 93 | * [UserType](https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/usertype/UserType.html) 94 | 95 | ## Heroku 96 | 97 | * [DevCenter](https://devcenter.heroku.com/articles/getting-started-with-gradle-on-heroku) 98 | 99 | ## Code Quality 100 | 101 | ### PMD 102 | 103 | + https://pmd.github.io/pmd-6.8.0/index.html 104 | 105 | ### Checkstyle 106 | 107 | + https://checkstyle.org/ 108 | 109 | + https://checkstyle.org/google_style.html 110 | 111 | + http://google.github.io/styleguide/javaguide.html 112 | 113 | ```shell script 114 | wget https://raw.githubusercontent.com/checkstyle/checkstyle/master/src/main/resources/google_checks.xml 115 | ``` 116 | -------------------------------------------------------------------------------- /cities-api/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'io.spring.dependency-management' version '1.0.9.RELEASE' 3 | id 'org.springframework.boot' version '2.2.6.RELEASE' 4 | id 'java' 5 | } 6 | 7 | group = 'com.github.andrelugomes' 8 | version = '0.0.1-SNAPSHOT' 9 | sourceCompatibility = '1.8' 10 | 11 | repositories { 12 | mavenCentral() 13 | } 14 | 15 | dependencies { 16 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 17 | implementation 'org.springframework.boot:spring-boot-starter-web' 18 | implementation 'com.vladmihalcea:hibernate-types-52:2.9.8' 19 | implementation 'org.postgresql:postgresql' 20 | 21 | testImplementation('org.springframework.boot:spring-boot-starter-test') { 22 | exclude group: 'org.junit.vintage', module: 'junit-vintage-engine' 23 | } 24 | testImplementation 'com.h2database:h2:1.4.200' 25 | 26 | } 27 | 28 | test { 29 | useJUnitPlatform() 30 | } 31 | -------------------------------------------------------------------------------- /cities-api/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andrelugomes/digital-innovation-one/31982544848f282a20f776efc7c8a64e4ba40560/cities-api/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /cities-api/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /cities-api/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | # Determine the Java command to use to start the JVM. 86 | if [ -n "$JAVA_HOME" ] ; then 87 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 88 | # IBM's JDK on AIX uses strange locations for the executables 89 | JAVACMD="$JAVA_HOME/jre/sh/java" 90 | else 91 | JAVACMD="$JAVA_HOME/bin/java" 92 | fi 93 | if [ ! -x "$JAVACMD" ] ; then 94 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 95 | 96 | Please set the JAVA_HOME variable in your environment to match the 97 | location of your Java installation." 98 | fi 99 | else 100 | JAVACMD="java" 101 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 102 | 103 | Please set the JAVA_HOME variable in your environment to match the 104 | location of your Java installation." 105 | fi 106 | 107 | # Increase the maximum file descriptors if we can. 108 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 109 | MAX_FD_LIMIT=`ulimit -H -n` 110 | if [ $? -eq 0 ] ; then 111 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 112 | MAX_FD="$MAX_FD_LIMIT" 113 | fi 114 | ulimit -n $MAX_FD 115 | if [ $? -ne 0 ] ; then 116 | warn "Could not set maximum file descriptor limit: $MAX_FD" 117 | fi 118 | else 119 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 120 | fi 121 | fi 122 | 123 | # For Darwin, add options to specify how the application appears in the dock 124 | if $darwin; then 125 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 126 | fi 127 | 128 | # For Cygwin or MSYS, switch paths to Windows format before running java 129 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 130 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 131 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 132 | JAVACMD=`cygpath --unix "$JAVACMD"` 133 | 134 | # We build the pattern for arguments to be converted via cygpath 135 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 136 | SEP="" 137 | for dir in $ROOTDIRSRAW ; do 138 | ROOTDIRS="$ROOTDIRS$SEP$dir" 139 | SEP="|" 140 | done 141 | OURCYGPATTERN="(^($ROOTDIRS))" 142 | # Add a user-defined pattern to the cygpath arguments 143 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 144 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 145 | fi 146 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 147 | i=0 148 | for arg in "$@" ; do 149 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 150 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 151 | 152 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 153 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 154 | else 155 | eval `echo args$i`="\"$arg\"" 156 | fi 157 | i=`expr $i + 1` 158 | done 159 | case $i in 160 | 0) set -- ;; 161 | 1) set -- "$args0" ;; 162 | 2) set -- "$args0" "$args1" ;; 163 | 3) set -- "$args0" "$args1" "$args2" ;; 164 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 165 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 166 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 167 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 168 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 169 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 170 | esac 171 | fi 172 | 173 | # Escape application args 174 | save () { 175 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 176 | echo " " 177 | } 178 | APP_ARGS=`save "$@"` 179 | 180 | # Collect all arguments for the java command, following the shell quoting and substitution rules 181 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 182 | 183 | exec "$JAVACMD" "$@" 184 | -------------------------------------------------------------------------------- /cities-api/gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto init 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto init 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :init 68 | @rem Get command-line arguments, handling Windows variants 69 | 70 | if not "%OS%" == "Windows_NT" goto win9xME_args 71 | 72 | :win9xME_args 73 | @rem Slurp the command line arguments. 74 | set CMD_LINE_ARGS= 75 | set _SKIP=2 76 | 77 | :win9xME_args_slurp 78 | if "x%~1" == "x" goto execute 79 | 80 | set CMD_LINE_ARGS=%* 81 | 82 | :execute 83 | @rem Setup the command line 84 | 85 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 86 | 87 | @rem Execute Gradle 88 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 89 | 90 | :end 91 | @rem End local scope for the variables with windows NT shell 92 | if "%ERRORLEVEL%"=="0" goto mainEnd 93 | 94 | :fail 95 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 96 | rem the _cmd.exe /c_ return code! 97 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 98 | exit /b 1 99 | 100 | :mainEnd 101 | if "%OS%"=="Windows_NT" endlocal 102 | 103 | :omega 104 | -------------------------------------------------------------------------------- /cities-api/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'cities-api' 2 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/CitiesApplication.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class CitiesApplication { 8 | 9 | public static void main(final String[] args) { 10 | SpringApplication.run(CitiesApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/cities/entities/City.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.entities; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.Id; 6 | import javax.persistence.Table; 7 | import org.hibernate.annotations.Type; 8 | import org.hibernate.annotations.TypeDef; 9 | import org.hibernate.annotations.TypeDefs; 10 | import org.springframework.data.geo.Point; 11 | 12 | 13 | @Entity 14 | @Table(name = "cidade") 15 | @TypeDefs(value = { 16 | @TypeDef(name = "point", typeClass = PointType.class) 17 | }) 18 | public class City { 19 | 20 | @Id 21 | private Long id; 22 | 23 | @Column(name = "nome") 24 | private String name; 25 | 26 | private Integer uf; 27 | 28 | private Integer ibge; 29 | 30 | // 1st 31 | @Column(name = "lat_lon") 32 | private String geolocation; 33 | 34 | // 2nd 35 | @Type(type = "point") 36 | @Column(name = "lat_lon", updatable = false, insertable = false) 37 | private Point location; 38 | 39 | public City() { 40 | } 41 | 42 | public City(final Long id, final String name, final Integer uf, final Integer ibge, 43 | final String geolocation, final Point location) { 44 | this.id = id; 45 | this.name = name; 46 | this.uf = uf; 47 | this.ibge = ibge; 48 | this.geolocation = geolocation; 49 | this.location = location; 50 | } 51 | 52 | public Long getId() { 53 | return id; 54 | } 55 | 56 | public String getName() { 57 | return name; 58 | } 59 | 60 | public Integer getUf() { 61 | return uf; 62 | } 63 | 64 | public Integer getIbge() { 65 | return ibge; 66 | } 67 | 68 | public String getGeolocation() { 69 | return geolocation; 70 | } 71 | 72 | public Point getLocation() { 73 | return location; 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/cities/entities/PointType.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.entities; 2 | 3 | import java.io.Serializable; 4 | import java.sql.PreparedStatement; 5 | import java.sql.ResultSet; 6 | import java.sql.SQLException; 7 | import org.hibernate.HibernateException; 8 | import org.hibernate.engine.spi.SharedSessionContractImplementor; 9 | import org.hibernate.usertype.UserType; 10 | import org.postgresql.geometric.PGpoint; 11 | import org.springframework.data.geo.Point; 12 | 13 | public class PointType implements UserType { 14 | 15 | @Override 16 | public int[] sqlTypes() { 17 | return new int[] {java.sql.Types.OTHER}; 18 | } 19 | 20 | @Override 21 | public Class returnedClass() { 22 | return Point.class; 23 | } 24 | 25 | @Override 26 | public boolean equals(Object x, Object y) throws HibernateException { 27 | return false; 28 | } 29 | 30 | @Override 31 | public int hashCode(Object x) throws HibernateException { 32 | return 0; 33 | } 34 | 35 | @Override 36 | public Object nullSafeGet(ResultSet rs, String[] names, SharedSessionContractImplementor session, 37 | Object owner) throws HibernateException, SQLException { 38 | /* 1st 39 | Object object = rs.getObject(names[0]); 40 | Double[] points = StringLocationUtils.transform(object.toString()); 41 | return new Point(points[0], points1);*/ 42 | 43 | /* 2nd */ 44 | PGpoint value = (PGpoint) rs.getObject(names[0]); 45 | return new Point(value.x, value.y); 46 | } 47 | 48 | @Override 49 | public void nullSafeSet(PreparedStatement st, Object value, int index, 50 | SharedSessionContractImplementor session) 51 | throws HibernateException, SQLException { 52 | 53 | } 54 | 55 | @Override 56 | public Object deepCopy(Object value) throws HibernateException { 57 | return null; 58 | } 59 | 60 | @Override 61 | public boolean isMutable() { 62 | return false; 63 | } 64 | 65 | @Override 66 | public Serializable disassemble(Object value) throws HibernateException { 67 | return null; 68 | } 69 | 70 | @Override 71 | public Object assemble(Serializable cached, Object owner) throws HibernateException { 72 | return null; 73 | } 74 | 75 | @Override 76 | public Object replace(Object original, Object target, Object owner) throws HibernateException { 77 | return null; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/cities/repositories/CityRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.repositories; 2 | 3 | import com.github.andrelugomes.cities.entities.City; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | import org.springframework.data.jpa.repository.Query; 6 | 7 | public interface CityRepository extends JpaRepository { 8 | 9 | @Query(value = "SELECT ((SELECT lat_lon FROM cidade WHERE id=?1) <@> (SELECT lat_lon FROM cidade WHERE id=?2)) as distance", nativeQuery = true) 10 | Double distanceByPoints(final Long cityId1, final Long cityId2); 11 | 12 | @Query(value = "SELECT earth_distance(ll_to_earth(?1,?2), ll_to_earth(?3,?4)) as distance", nativeQuery = true) 13 | Double distanceByCube(final Double lat1, final Double lon1, final Double lat2, final Double lon2); 14 | } 15 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/cities/resources/CityResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.resources; 2 | 3 | import com.github.andrelugomes.cities.entities.City; 4 | import com.github.andrelugomes.cities.repositories.CityRepository; 5 | import org.springframework.data.domain.Page; 6 | import org.springframework.data.domain.Pageable; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RestController; 10 | 11 | @RestController 12 | @RequestMapping("cities") 13 | public class CityResource { 14 | 15 | private final CityRepository repository; 16 | 17 | public CityResource(final CityRepository repository) { 18 | this.repository = repository; 19 | } 20 | 21 | /* 1st 22 | @GetMapping 23 | public List cities() { 24 | return repository.findAll(); 25 | }*/ 26 | 27 | // 2nd - Pageable 28 | @GetMapping 29 | public Page cities(final Pageable page) { 30 | return repository.findAll(page); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/cities/resources/DistanceResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.resources; 2 | 3 | import com.github.andrelugomes.cities.service.DistanceService; 4 | import com.github.andrelugomes.cities.service.EarthRadius; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.web.bind.annotation.GetMapping; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestParam; 10 | import org.springframework.web.bind.annotation.RestController; 11 | 12 | @RestController 13 | @RequestMapping("/distances") 14 | public class DistanceResource { 15 | 16 | private final DistanceService service; 17 | Logger log = LoggerFactory.getLogger(DistanceResource.class); 18 | 19 | public DistanceResource(DistanceService service) { 20 | this.service = service; 21 | } 22 | 23 | @GetMapping("/by-points") 24 | public Double byPoints(@RequestParam(name = "from") final Long city1, 25 | @RequestParam(name = "to") final Long city2) { 26 | log.info("byPoints"); 27 | return service.distanceByPointsInMiles(city1, city2); 28 | } 29 | 30 | @GetMapping("/by-cube") 31 | public Double byCube(@RequestParam(name = "from") final Long city1, 32 | @RequestParam(name = "to") final Long city2) { 33 | log.info("byCube"); 34 | return service.distanceByCubeInMeters(city1, city2); 35 | } 36 | 37 | @GetMapping("/by-math") 38 | public Double byMath(@RequestParam(name = "from") final Long city1, 39 | @RequestParam(name = "to") final Long city2, 40 | @RequestParam final EarthRadius unit) { 41 | log.info("byMath"); 42 | return service.distanceUsingMath(city1, city2, unit); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/cities/service/DistanceService.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.service; 2 | 3 | import static java.lang.Math.atan2; 4 | import static java.lang.Math.cos; 5 | import static java.lang.Math.sin; 6 | import static java.lang.Math.sqrt; 7 | import static java.lang.Math.toRadians; 8 | 9 | 10 | import com.github.andrelugomes.cities.entities.City; 11 | import com.github.andrelugomes.cities.repositories.CityRepository; 12 | import com.github.andrelugomes.utils.StringLocationUtils; 13 | import java.util.Arrays; 14 | import java.util.List; 15 | import org.slf4j.Logger; 16 | import org.slf4j.LoggerFactory; 17 | import org.springframework.data.geo.Point; 18 | import org.springframework.stereotype.Service; 19 | 20 | @Service 21 | public class DistanceService { 22 | 23 | private final CityRepository cityRepository; 24 | Logger log = LoggerFactory.getLogger(DistanceService.class); 25 | 26 | public DistanceService(final CityRepository cityRepository) { 27 | this.cityRepository = cityRepository; 28 | } 29 | 30 | /** 31 | * 1st option 32 | * 33 | * @param city1 34 | * @param city2 35 | * @param unit 36 | * @return 37 | */ 38 | public Double distanceUsingMath(final Long city1, final Long city2, final EarthRadius unit) { 39 | log.info("distanceUsingMath({}, {}, {})", city1, city2, unit); 40 | final List cities = cityRepository.findAllById((Arrays.asList(city1, city2))); 41 | 42 | final Double[] location1 = StringLocationUtils.transform(cities.get(0).getGeolocation()); 43 | final Double[] location2 = StringLocationUtils.transform(cities.get(1).getGeolocation()); 44 | 45 | return doCalculation(location1[0], location1[1], location2[0], location2[1], unit); 46 | } 47 | 48 | /** 49 | * 2nd option 50 | * 51 | * @param city1 52 | * @param city2 53 | * @return 54 | */ 55 | public Double distanceByPointsInMiles(final Long city1, final Long city2) { 56 | log.info("nativePostgresInMiles({}, {})", city1, city2); 57 | return cityRepository.distanceByPoints(city1, city2); 58 | } 59 | 60 | /** 61 | * 3rd option 62 | * 63 | * @param city1 64 | * @param city2 65 | * @param unit 66 | * @return 67 | */ 68 | public Double distanceUsingPoints(final Long city1, final Long city2, final EarthRadius unit) { 69 | log.info("distanceUsingPoints({}, {}, {})", city1, city2, unit); 70 | final List cities = cityRepository.findAllById((Arrays.asList(city1, city2))); 71 | 72 | Point p1 = cities.get(0).getLocation(); 73 | Point p2 = cities.get(1).getLocation(); 74 | 75 | return doCalculation(p1.getX(), p1.getY(), p2.getX(), p2.getY(), unit); 76 | } 77 | 78 | /** 79 | * 4th option 80 | * 81 | * @param city1 82 | * @param city2 83 | * @return 84 | */ 85 | public Double distanceByCubeInMeters(Long city1, Long city2) { 86 | log.info("distanceByCubeInMeters({}, {})", city1, city2); 87 | final List cities = cityRepository.findAllById((Arrays.asList(city1, city2))); 88 | 89 | Point p1 = cities.get(0).getLocation(); 90 | Point p2 = cities.get(1).getLocation(); 91 | 92 | return cityRepository.distanceByCube(p1.getX(), p1.getY(), p2.getX(), p2.getY()); 93 | } 94 | 95 | private double doCalculation(final double lat1, final double lon1, final double lat2, 96 | final double lng2, final EarthRadius earthRadius) { 97 | double lat = toRadians(lat2 - lat1); 98 | double lon = toRadians(lng2 - lon1); 99 | double a = sin(lat / 2) * sin(lat / 2) + 100 | cos(toRadians(lat1)) * cos(toRadians(lat2)) * sin(lon / 2) * sin(lon / 2); 101 | double c = 2 * atan2(sqrt(a), sqrt(1 - a)); 102 | 103 | return earthRadius.getValue() * c; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/cities/service/EarthRadius.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.service; 2 | 3 | public enum EarthRadius { 4 | METERS("m", 6378168), 5 | KILOMETERS("km", 6378.168f), 6 | MILES("mi", 3958.747716f); 7 | 8 | private final String unit; 9 | private final float value; 10 | 11 | EarthRadius(final String unit, final float value) { 12 | this.unit = unit; 13 | this.value = value; 14 | } 15 | 16 | public float getValue() { 17 | return value; 18 | } 19 | 20 | public String getUnit() { 21 | return unit; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/countries/entities/Country.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.countries.entities; 2 | 3 | import javax.persistence.Column; 4 | import javax.persistence.Entity; 5 | import javax.persistence.Id; 6 | import javax.persistence.Table; 7 | 8 | @Entity(name = "Country") 9 | @Table(name = "pais") 10 | public class Country { 11 | 12 | @Id 13 | private Long id; 14 | 15 | @Column(name = "nome") 16 | private String name; 17 | 18 | @Column(name = "nome_pt") 19 | private String portugueseName; 20 | 21 | @Column(name = "sigla") 22 | private String code; 23 | 24 | private Integer bacen; 25 | 26 | public Country() { 27 | } 28 | 29 | public Long getId() { 30 | return id; 31 | } 32 | 33 | public String getName() { 34 | return name; 35 | } 36 | 37 | public String getPortugueseName() { 38 | return portugueseName; 39 | } 40 | 41 | public String getCode() { 42 | return code; 43 | } 44 | 45 | public Integer getBacen() { 46 | return bacen; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/countries/repositories/CountryRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.countries.repositories; 2 | 3 | import com.github.andrelugomes.countries.entities.Country; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface CountryRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/countries/resources/CountryResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.countries.resources; 2 | 3 | import com.github.andrelugomes.countries.entities.Country; 4 | import com.github.andrelugomes.countries.repositories.CountryRepository; 5 | import java.util.List; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RestController; 8 | 9 | @RestController 10 | public class CountryResource { 11 | 12 | private final CountryRepository repository; 13 | 14 | public CountryResource(final CountryRepository repository) { 15 | this.repository = repository; 16 | } 17 | 18 | @GetMapping("/countries") 19 | public List cities() { 20 | 21 | return repository.findAll(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/staties/entities/State.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.staties.entities; 2 | 3 | import com.github.andrelugomes.countries.entities.Country; 4 | import com.vladmihalcea.hibernate.type.json.JsonBinaryType; 5 | import java.util.List; 6 | import javax.persistence.Basic; 7 | import javax.persistence.Column; 8 | import javax.persistence.Entity; 9 | import javax.persistence.FetchType; 10 | import javax.persistence.Id; 11 | import javax.persistence.JoinColumn; 12 | import javax.persistence.ManyToOne; 13 | import javax.persistence.Table; 14 | import org.hibernate.annotations.Type; 15 | import org.hibernate.annotations.TypeDef; 16 | import org.hibernate.annotations.TypeDefs; 17 | 18 | @Entity(name = "State") 19 | @Table(name = "estado") 20 | @TypeDefs({ 21 | @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class) 22 | }) 23 | public class State { 24 | 25 | @Id 26 | private Long id; 27 | 28 | @Column(name = "nome") 29 | private String name; 30 | 31 | private String uf; 32 | 33 | private Integer ibge; 34 | 35 | /* 1st 36 | @Column(name = "pais") 37 | private Integer countryId;*/ 38 | 39 | // 2nd - @ManyToOne 40 | @ManyToOne 41 | @JoinColumn(name = "pais", referencedColumnName = "id") 42 | private Country country; 43 | 44 | @Type(type = "jsonb") 45 | @Basic(fetch = FetchType.LAZY) 46 | @Column(name = "ddd", columnDefinition = "jsonb") 47 | private List ddd; 48 | 49 | public State() { 50 | } 51 | 52 | public Long getId() { 53 | return id; 54 | } 55 | 56 | public String getName() { 57 | return name; 58 | } 59 | 60 | public String getUf() { 61 | return uf; 62 | } 63 | 64 | public Integer getIbge() { 65 | return ibge; 66 | } 67 | 68 | public List getDdd() { 69 | return ddd; 70 | } 71 | 72 | public Country getCountry() { 73 | return country; 74 | } 75 | 76 | /*public Integer getCountryId() { 77 | return countryId; 78 | }*/ 79 | } 80 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/staties/repositories/StateRepository.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.staties.repositories; 2 | 3 | import com.github.andrelugomes.staties.entities.State; 4 | import org.springframework.data.jpa.repository.JpaRepository; 5 | 6 | public interface StateRepository extends JpaRepository { 7 | } 8 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/staties/resources/StateResource.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.staties.resources; 2 | 3 | import com.github.andrelugomes.staties.entities.State; 4 | import com.github.andrelugomes.staties.repositories.StateRepository; 5 | import java.util.List; 6 | import org.springframework.web.bind.annotation.GetMapping; 7 | import org.springframework.web.bind.annotation.RequestMapping; 8 | import org.springframework.web.bind.annotation.RestController; 9 | 10 | @RestController 11 | @RequestMapping("/staties") 12 | public class StateResource { 13 | 14 | private final StateRepository repository; 15 | 16 | public StateResource(final StateRepository repository) { 17 | this.repository = repository; 18 | } 19 | 20 | @GetMapping 21 | public List staties() { 22 | return repository.findAll(); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /cities-api/src/main/java/com/github/andrelugomes/utils/StringLocationUtils.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.utils; 2 | 3 | public class StringLocationUtils { 4 | public static Double[] transform(String geolocation) { 5 | String result = geolocation.replace("(", "").replace(")", ""); 6 | String[] strings = result.trim().split(","); 7 | return new Double[] {Double.valueOf(strings[0]), Double.valueOf(strings[1])}; 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /cities-api/src/main/resources/application-heroku.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=${DATABASE_URL} 2 | 3 | spring.jpa.show-sql=false 4 | -------------------------------------------------------------------------------- /cities-api/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port=${PORT:8080} 2 | 3 | spring.datasource.url=jdbc:postgresql://localhost:5432/cities 4 | spring.datasource.username=postgres_user_city 5 | spring.datasource.password=super_password 6 | 7 | spring.jpa.show-sql=true 8 | 9 | spring.jpa.properties.hibernate.format_sql=true 10 | 11 | #show sql statement 12 | #logging.level.org.hibernate.SQL=debug 13 | 14 | #show sql values 15 | #logging.level.org.hibernate.type.descriptor.sql=trace -------------------------------------------------------------------------------- /cities-api/src/test/java/com/github/andrelugomes/cities/service/DistanceServiceTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.cities.service; 2 | 3 | import static org.assertj.core.api.Assertions.assertThat; 4 | import static org.assertj.core.data.Offset.offset; 5 | import static org.mockito.ArgumentMatchers.anyList; 6 | import static org.mockito.BDDMockito.given; 7 | 8 | import com.github.andrelugomes.cities.entities.City; 9 | import com.github.andrelugomes.cities.repositories.CityRepository; 10 | import java.util.Arrays; 11 | import org.junit.jupiter.api.BeforeEach; 12 | import org.junit.jupiter.api.Test; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.boot.test.context.SpringBootTest; 15 | import org.springframework.boot.test.mock.mockito.MockBean; 16 | import org.springframework.data.geo.Point; 17 | 18 | @SpringBootTest 19 | class DistanceServiceTest { 20 | 21 | @Autowired 22 | private DistanceService service; 23 | 24 | @MockBean 25 | private CityRepository cityRepository; 26 | 27 | private City saoCarlos; 28 | private City ibate; 29 | 30 | @BeforeEach 31 | public void setUp() { 32 | ibate = new City(4929L, "Ibaté", 26, 3519303, "(-21.95840072631836,-47.98820114135742)", 33 | new Point(-21.95840072631836, -47.98820114135742)); 34 | saoCarlos = 35 | new City(5254L, "São Carlos", 26, 3548906, "(-22.01740074157715,-47.88600158691406)", 36 | new Point(-22.01740074157715, -47.88600158691406)); 37 | } 38 | 39 | @Test 40 | public void shouldCalculateInMetersUsingMath() { 41 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 42 | 43 | Double distance = service.distanceUsingMath(4929L, 5254L, EarthRadius.METERS); 44 | 45 | assertThat(distance).isEqualTo(12426.810463475855); 46 | } 47 | 48 | @Test 49 | public void shouldCalculateInKilometersUsingMath() { 50 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 51 | 52 | Double distance = service.distanceUsingMath(4929L, 5254L, EarthRadius.KILOMETERS); 53 | 54 | assertThat(distance).isCloseTo(12.426, offset(0.001d)); 55 | } 56 | 57 | @Test 58 | public void shouldCalculateInMilesUsingMath() { 59 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 60 | 61 | Double distance = service.distanceUsingMath(4929L, 5254L, EarthRadius.MILES); 62 | 63 | assertThat(distance).isCloseTo(7.71, offset(0.01d)); 64 | } 65 | 66 | @Test 67 | public void shouldCalculateInMetersUsingPoints() { 68 | given(cityRepository.findAllById(anyList())).willReturn(Arrays.asList(ibate, saoCarlos)); 69 | 70 | Double distance = service.distanceUsingPoints(4929L, 5254L, EarthRadius.METERS); 71 | 72 | assertThat(distance).isEqualTo(12426.810463475855); 73 | } 74 | 75 | } -------------------------------------------------------------------------------- /cities-api/src/test/java/com/github/andrelugomes/utils/StringLocationUtilsTest.java: -------------------------------------------------------------------------------- 1 | package com.github.andrelugomes.utils; 2 | 3 | import static org.junit.jupiter.api.Assertions.*; 4 | 5 | 6 | import org.junit.jupiter.api.Test; 7 | 8 | class StringLocationUtilsTest { 9 | 10 | @Test 11 | public void shouldExtractGeoLocationsFormString() { 12 | String geoLocation = "(123, 321)"; 13 | 14 | Double[] transform = StringLocationUtils.transform(geoLocation); 15 | 16 | assertEquals(123.0, transform[0], "Not equal"); 17 | assertEquals(321, transform[1], "Not equal"); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /cities-api/src/test/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.datasource.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE 2 | spring.datasource.username=sa 3 | spring.datasource.password= 4 | spring.datasource.driverClassName= org.h2.Driver 5 | 6 | spring.jpa.database-platform=org.hibernate.dialect.H2Dialect 7 | spring.jpa.show-sql=true 8 | spring.jpa.properties.hibernate.format_sql=true 9 | 10 | #show sql statement 11 | logging.level.org.hibernate.SQL=debug 12 | 13 | #show sql values 14 | logging.level.org.hibernate.type.descriptor.sql=trace -------------------------------------------------------------------------------- /debug-de-codigo/.gitignore: -------------------------------------------------------------------------------- 1 | # IntelliJ project files 2 | .idea 3 | *.iml 4 | out 5 | gen 6 | build 7 | .gradle 8 | 9 | -------------------------------------------------------------------------------- /debug-de-codigo/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'java' 3 | } 4 | 5 | group 'one.innovation.digital' 6 | version '1.0-SNAPSHOT' 7 | 8 | sourceCompatibility = 1.11 9 | 10 | repositories { 11 | mavenCentral() 12 | } 13 | 14 | dependencies { 15 | testCompile group: 'junit', name: 'junit', version: '4.12' 16 | } 17 | -------------------------------------------------------------------------------- /debug-de-codigo/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andrelugomes/digital-innovation-one/31982544848f282a20f776efc7c8a64e4ba40560/debug-de-codigo/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /debug-de-codigo/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /debug-de-codigo/gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /debug-de-codigo/gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /debug-de-codigo/settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'debug-de-codigo' 2 | 3 | -------------------------------------------------------------------------------- /debug-de-codigo/src/main/java/one/innovation/digital/Programa.java: -------------------------------------------------------------------------------- 1 | package one.innovation.digital; 2 | 3 | import one.innovation.digital.imc.CalculadorDeImc; 4 | import one.innovation.digital.pessoa.Pessoa; 5 | 6 | public class Programa { 7 | 8 | public static void main(String[] args) { 9 | final Pessoa pessoa = new Pessoa("André", 1.9, 100.00); 10 | 11 | final var calculadorDeImc = new CalculadorDeImc(); 12 | final var imc = calculadorDeImc.calcula(pessoa); 13 | 14 | System.out.printf("IMC = %.2f", imc); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /debug-de-codigo/src/main/java/one/innovation/digital/imc/CalculadorDeImc.java: -------------------------------------------------------------------------------- 1 | package one.innovation.digital.imc; 2 | 3 | import one.innovation.digital.pessoa.Pessoa; 4 | 5 | public class CalculadorDeImc { 6 | 7 | /** 8 | * MENOR QUE 18,5 MAGREZA 0 9 | * ENTRE 18,5 E 24,9 NORMAL 0 10 | * ENTRE 25,0 E 29,9 SOBREPESO I 11 | * ENTRE 30,0 E 39,9 OBESIDADE II 12 | * MAIOR QUE 40,0 OBESIDADE GRAVE III 13 | */ 14 | public Double calcula(final Pessoa pessoa) { 15 | final var altura = pessoa.getAltura(); 16 | final var imc = pessoa.getPeso() / (altura * altura); 17 | 18 | return imc; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /debug-de-codigo/src/main/java/one/innovation/digital/pessoa/Pessoa.java: -------------------------------------------------------------------------------- 1 | package one.innovation.digital.pessoa; 2 | 3 | public class Pessoa { 4 | 5 | private String nome; 6 | private Double altura; 7 | private Double peso; 8 | 9 | public Pessoa(final String nome, final Double altura, final Double peso) { 10 | this.nome = nome; 11 | this.altura = altura; 12 | this.peso = peso; 13 | } 14 | 15 | public String getNome() { 16 | return nome; 17 | } 18 | 19 | public Double getAltura() { 20 | return altura; 21 | } 22 | 23 | public Double getPeso() { 24 | return peso; 25 | } 26 | } 27 | 28 | --------------------------------------------------------------------------------