├── Ejemplos
├── Eventos-Culturales
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── gradle.xml
│ │ ├── inspectionProfiles
│ │ │ └── Project_Default.xml
│ │ ├── kotlinc.xml
│ │ ├── misc.xml
│ │ └── vcs.xml
│ ├── build.gradle.kts
│ ├── gradle.properties
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ ├── settings.gradle.kts
│ └── src
│ │ └── main
│ │ ├── kotlin
│ │ ├── Main.kt
│ │ └── models
│ │ │ ├── Address.kt
│ │ │ ├── Area.kt
│ │ │ ├── Context.kt
│ │ │ ├── District.kt
│ │ │ ├── Evento.kt
│ │ │ ├── EventoData.kt
│ │ │ ├── Location.kt
│ │ │ ├── Organization.kt
│ │ │ ├── Recurrence.kt
│ │ │ ├── References.kt
│ │ │ └── Relation.kt
│ │ └── resources
│ │ ├── 206974-0-agenda-eventos-culturales-100.csv
│ │ ├── 206974-0-agenda-eventos-culturales-100.json
│ │ ├── 206974-0-agenda-eventos-culturales-100.xml
│ │ └── Estructura_DS_eventos_wwwmadrid.pdf
├── Ficheros-Java
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── encodings.xml
│ │ ├── misc.xml
│ │ ├── uiDesigner.xml
│ │ ├── vcs.xml
│ │ └── workspace-foxhound.xml
│ ├── data
│ │ ├── coches.csv
│ │ ├── enteros.dat
│ │ ├── fichero-texto-2.txt
│ │ ├── fichero-texto-copy.txt
│ │ ├── fichero-texto.txt
│ │ ├── paciente.json
│ │ ├── pacientes.json
│ │ ├── perro-foxhound.xml
│ │ ├── perro.xml
│ │ ├── perros-foxhound.xml
│ │ ├── perros.xml
│ │ ├── personas.dat
│ │ └── texto.txt
│ ├── enteros.dat
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ └── java
│ │ └── es
│ │ └── joseluisgs
│ │ ├── Main.java
│ │ ├── aleatorio
│ │ └── Aleatorio.java
│ │ ├── binario
│ │ └── Binario.java
│ │ ├── csv
│ │ ├── Coche.java
│ │ └── CsvFile.java
│ │ ├── json
│ │ ├── Paciente.java
│ │ ├── PacienteJson.java
│ │ └── utils
│ │ │ ├── LocalDateTimeAdapter.java
│ │ │ └── UuidAdapter.java
│ │ ├── serializable
│ │ └── Serializable.java
│ │ ├── texto
│ │ └── Texto.java
│ │ └── xml
│ │ ├── PerroXml.java
│ │ ├── dto
│ │ ├── PerroDto-foxhound.java
│ │ ├── PerroDto.java
│ │ ├── PerroListDto-foxhound.java
│ │ └── PerroListDto.java
│ │ ├── mappers
│ │ └── PerroMapper.java
│ │ └── model
│ │ └── Perro.java
├── Ficheros-Kotlin
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── gradle.xml
│ │ ├── inspectionProfiles
│ │ │ └── Project_Default.xml
│ │ ├── kotlinc.xml
│ │ ├── misc.xml
│ │ ├── uiDesigner.xml
│ │ ├── vcs.xml
│ │ └── workspace-foxhound.xml
│ ├── build.gradle-foxhound.kts
│ ├── build.gradle.kts
│ ├── data
│ │ ├── alumnos-serializable.dat
│ │ ├── alumnos.dat
│ │ ├── alumnos.txt
│ │ ├── coches.csv
│ │ ├── enteros.dat
│ │ ├── fichero-serializable.dat
│ │ ├── fichero-texto-2.txt
│ │ ├── fichero-texto-copy.txt
│ │ ├── fichero-texto.txt
│ │ ├── paciente-foxhound.json
│ │ ├── paciente-foxhound.xml
│ │ ├── paciente.json
│ │ ├── paciente.xml
│ │ ├── pacientes-foxhound.json
│ │ ├── pacientes-foxhound.xml
│ │ ├── pacientes.json
│ │ ├── pacientes.xml
│ │ └── texto.txt
│ ├── gradle.properties
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ ├── settings.gradle.kts
│ └── src
│ │ └── main
│ │ ├── kotlin
│ │ ├── Main.kt
│ │ ├── aleatorio
│ │ │ ├── Aleatorio.kt
│ │ │ └── AlumnosAleatorio.kt
│ │ ├── binario
│ │ │ ├── AlumnosBinario.kt
│ │ │ └── Binario.kt
│ │ ├── csv
│ │ │ ├── Coche.kt
│ │ │ └── Csv.kt
│ │ ├── json
│ │ │ ├── MoshiAdapters-foxhound.kt
│ │ │ ├── MoshiAdapters.kt
│ │ │ ├── PacientesJson-foxhound.kt
│ │ │ └── PacientesJson.kt
│ │ ├── serializable
│ │ │ ├── AlumnosSerializable.kt
│ │ │ └── Serializable.kt
│ │ ├── texto
│ │ │ ├── AlumnosTexto.kt
│ │ │ └── Texto.kt
│ │ ├── utils
│ │ │ └── Utils.kt
│ │ └── xml
│ │ │ ├── PacientesXml-foxhound.kt
│ │ │ └── PacientesXml.kt
│ │ └── resources
│ │ ├── coches.csv
│ │ ├── config.properties
│ │ └── data
│ │ └── fichero-texto.txt
├── FicherosDirectorios
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ ├── project-template.xml
│ │ ├── runConfigurations.xml
│ │ └── vcs.xml
│ ├── 06-FicherosDirectorios.iml
│ └── src
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ └── Main.java
├── Pokedex-Java
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── compiler.xml
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── jarRepositories.xml
│ │ ├── libraries
│ │ │ └── Maven__com_google_code_gson_gson_2_9_0.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ └── project-template.xml
│ ├── Pokedex.iml
│ ├── data
│ │ └── pokemon.json
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ └── java
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ ├── Main.java
│ │ ├── controllers
│ │ └── PokemonController.java
│ │ └── models
│ │ ├── NextEvolution.java
│ │ ├── Pokedex.java
│ │ ├── Pokemon.java
│ │ └── PrevEvolution.java
├── Pokedex-Kotlin
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── gradle.xml
│ │ ├── inspectionProfiles
│ │ │ └── Project_Default.xml
│ │ ├── kotlinc.xml
│ │ ├── misc.xml
│ │ ├── vcs.xml
│ │ └── workspace-foxhound.xml
│ ├── build.gradle.kts
│ ├── gradle.properties
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ ├── settings.gradle.kts
│ └── src
│ │ └── main
│ │ ├── kotlin
│ │ ├── Exceptions
│ │ │ └── PokemonException.kt
│ │ ├── Main.kt
│ │ ├── models
│ │ │ ├── NextEvolution.kt
│ │ │ ├── Pokedex.kt
│ │ │ ├── Pokemon.kt
│ │ │ └── PrevEvolution.kt
│ │ └── repositories
│ │ │ └── PokedexRepository.kt
│ │ └── resources
│ │ └── pokemon.json
├── Productos-Ventas-Ficheros
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── .name
│ │ ├── gradle.xml
│ │ ├── inspectionProfiles
│ │ │ └── Project_Default.xml
│ │ ├── kotlinc.xml
│ │ ├── misc.xml
│ │ ├── uiDesigner.xml
│ │ └── workspace-foxhound.xml
│ ├── build.gradle.kts
│ ├── data
│ │ ├── productos.bin
│ │ ├── productos.csv
│ │ ├── productos.dat
│ │ ├── productos.json
│ │ ├── productos.ser
│ │ ├── productos.txt
│ │ ├── productos.xml
│ │ ├── ventas.csv
│ │ ├── ventas.json
│ │ ├── ventas.ser
│ │ └── ventas.xml
│ ├── gradle.properties
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ ├── settings.gradle.kts
│ └── src
│ │ └── main
│ │ ├── kotlin
│ │ ├── Main.kt
│ │ ├── config
│ │ │ └── AppConfig.kt
│ │ ├── controllers
│ │ │ ├── ProductosController.kt
│ │ │ └── VentasController.kt
│ │ ├── dto
│ │ │ ├── LineaVentaDto.kt
│ │ │ ├── ProductoDto-foxhound.kt
│ │ │ ├── ProductoDto.kt
│ │ │ ├── VentaDto-foxhound.kt
│ │ │ └── VentaDto.kt
│ │ ├── exceptions
│ │ │ ├── ProductoException.kt
│ │ │ └── VentaException.kt
│ │ ├── factories
│ │ │ └── ProductosFactory.kt
│ │ ├── locale
│ │ │ └── Locale.kt
│ │ ├── mappers
│ │ │ ├── ProductoMapper.kt
│ │ │ └── VentaMapper.kt
│ │ ├── models
│ │ │ ├── LineaVenta.kt
│ │ │ ├── Producto.kt
│ │ │ ├── User.kt
│ │ │ └── Venta.kt
│ │ ├── repositories
│ │ │ ├── base
│ │ │ │ └── CrudRepository.kt
│ │ │ ├── productos
│ │ │ │ ├── ProductosRepository.kt
│ │ │ │ └── ProductosRepositoryMap.kt
│ │ │ └── ventas
│ │ │ │ ├── VentasRepository.kt
│ │ │ │ └── VentasRepositoryList.kt
│ │ ├── services
│ │ │ └── storage
│ │ │ │ ├── base
│ │ │ │ └── StorageService.kt
│ │ │ │ ├── productos
│ │ │ │ ├── ProductosFicheroAleatorioService.kt
│ │ │ │ ├── ProductosFicheroBinarioService.kt
│ │ │ │ ├── ProductosFicheroCsvService.kt
│ │ │ │ ├── ProductosFicheroJsonService.kt
│ │ │ │ ├── ProductosFicheroSerializableService.kt
│ │ │ │ ├── ProductosFicheroTextoService.kt
│ │ │ │ ├── ProductosFicheroXmlService.kt
│ │ │ │ └── ProductosStorageService.kt
│ │ │ │ └── ventas
│ │ │ │ ├── VentasFicheroCsvService.kt
│ │ │ │ ├── VentasFicheroJsonService.kt
│ │ │ │ ├── VentasFicheroSerializableService.kt
│ │ │ │ ├── VentasFicheroXmlService.kt
│ │ │ │ └── VentasStorageService.kt
│ │ ├── utils
│ │ │ └── MoshiAdapters.kt
│ │ └── validators
│ │ │ ├── ProductoValidator.kt
│ │ │ └── VentaValidator.kt
│ │ └── resources
│ │ └── config.properties
├── StreamAccidentes
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── compiler.xml
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── jarRepositories.xml
│ │ ├── libraries
│ │ │ └── Maven__org_projectlombok_lombok_1_18_22.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ └── project-template.xml
│ ├── AccidentesStream.iml
│ ├── data
│ │ └── accidentes.csv
│ ├── pom.xml
│ └── src
│ │ └── main
│ │ └── java
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ ├── Accidente.java
│ │ ├── AccidentesController.java
│ │ └── Main.java
├── StreamEjemplos-csv
│ ├── .gitignore
│ ├── .idea
│ │ ├── .gitignore
│ │ ├── description.html
│ │ ├── encodings.xml
│ │ ├── misc.xml
│ │ ├── modules.xml
│ │ ├── project-template.xml
│ │ └── vcs.xml
│ ├── 02-Stream.iml
│ ├── data
│ │ └── products.csv
│ └── src
│ │ └── es
│ │ └── joseluisgs
│ │ └── dam
│ │ ├── ConsultasAlumnos.java
│ │ ├── ConsultasCanciones.java
│ │ ├── ConsultasProductos.java
│ │ ├── Main.java
│ │ ├── model
│ │ ├── Alumno.java
│ │ ├── Cancion.java
│ │ └── Product.java
│ │ └── utils
│ │ └── Util.java
└── ZipAndTemp
│ ├── .gitignore
│ ├── .idea
│ ├── .gitignore
│ ├── gradle.xml
│ ├── inspectionProfiles
│ │ └── Project_Default.xml
│ ├── kotlinc.xml
│ └── misc.xml
│ ├── build.gradle.kts
│ ├── gradle.properties
│ ├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ ├── settings.gradle.kts
│ └── src
│ └── main
│ └── kotlin
│ └── Main.kt
├── Practicas
├── accidentes
│ ├── Estructura_DS_Accidentes_trafico_desde_2019.pdf
│ ├── README.md
│ └── accidentes.csv
├── aemet
│ ├── Aemet20171029.csv
│ ├── Aemet20171030.csv
│ ├── Aemet20171031.csv
│ └── README.md
├── buerguer-pig
│ └── README.md
└── herencia-dto
│ └── README.md
├── README.md
├── images
├── file.png
├── java-io-vs-nio.png
└── jeraquia.png
└── upload.sh
/Ejemplos/Eventos-Culturales/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | build/
3 | !gradle/wrapper/gradle-wrapper.jar
4 | !**/src/main/**/build/
5 | !**/src/test/**/build/
6 |
7 | ### IntelliJ IDEA ###
8 | .idea/modules.xml
9 | .idea/jarRepositories.xml
10 | .idea/compiler.xml
11 | .idea/libraries/
12 | *.iws
13 | *.iml
14 | *.ipr
15 | out/
16 | !**/src/main/**/out/
17 | !**/src/test/**/out/
18 |
19 | ### Eclipse ###
20 | .apt_generated
21 | .classpath
22 | .factorypath
23 | .project
24 | .settings
25 | .springBeans
26 | .sts4-cache
27 | bin/
28 | !**/src/main/**/bin/
29 | !**/src/test/**/bin/
30 |
31 | ### NetBeans ###
32 | /nbproject/private/
33 | /nbbuild/
34 | /dist/
35 | /nbdist/
36 | /.nb-gradle/
37 |
38 | ### VS Code ###
39 | .vscode/
40 |
41 | ### Mac OS ###
42 | .DS_Store
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | kotlin("jvm") version "1.8.0"
3 | application
4 | }
5 |
6 | group = "es.joseluisgs"
7 | version = "1.0-SNAPSHOT"
8 |
9 | repositories {
10 | mavenCentral()
11 | }
12 |
13 | dependencies {
14 | testImplementation(kotlin("test"))
15 |
16 | // Moshi
17 | // implementation("com.squareup.moshi:moshi:1.14.0")
18 | implementation("com.squareup.moshi:moshi-kotlin:1.14.0")
19 | // implementation("com.squareup.moshi:moshi-adapters:1.14.0")
20 | }
21 |
22 | tasks.test {
23 | useJUnitPlatform()
24 | }
25 |
26 | kotlin {
27 | jvmToolchain(8)
28 | }
29 |
30 | application {
31 | mainClass.set("MainKt")
32 | }
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
2 |
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Eventos-Culturales/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/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 execute
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 execute
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 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/settings.gradle.kts:
--------------------------------------------------------------------------------
1 |
2 | rootProject.name = "Eventos-Culturales"
3 |
4 |
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/kotlin/models/Address.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class Address(
7 | @Json(name = "district")
8 | val district: District = District(),
9 | @Json(name = "area")
10 | val area: Area? = null
11 | )
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/kotlin/models/Area.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class Area(
7 | @Json(name = "@id")
8 | val id: String = "",
9 | @Json(name = "locality")
10 | val locality: String = "",
11 | @Json(name = "postal-code")
12 | val postalCode: String = "",
13 | @Json(name = "street-address")
14 | val streetAddress: String = ""
15 | )
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/kotlin/models/Context.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class Context(
7 | @Json(name = "c")
8 | val c: String = "",
9 | @Json(name = "dcterms")
10 | val dcterms: String = "",
11 | @Json(name = "geo")
12 | val geo: String = "",
13 | @Json(name = "loc")
14 | val loc: String = "",
15 | @Json(name = "org")
16 | val org: String = "",
17 | @Json(name = "vcard")
18 | val vcard: String = "",
19 | @Json(name = "schema")
20 | val schema: String = "",
21 | @Json(name = "title")
22 | val title: String = "",
23 | @Json(name = "id")
24 | val id: String = "",
25 | @Json(name = "relation")
26 | val relation: String = "",
27 | @Json(name = "references")
28 | val references: String = "",
29 | @Json(name = "address")
30 | val address: String = "",
31 | @Json(name = "area")
32 | val area: String = "",
33 | @Json(name = "district")
34 | val district: String = "",
35 | @Json(name = "locality")
36 | val locality: String = "",
37 | @Json(name = "postal-code")
38 | val postalCode: String = "",
39 | @Json(name = "street-address")
40 | val streetAddress: String = "",
41 | @Json(name = "location")
42 | val location: String = "",
43 | @Json(name = "latitude")
44 | val latitude: String = "",
45 | @Json(name = "longitude")
46 | val longitude: String = "",
47 | @Json(name = "organization")
48 | val organization: String = "",
49 | @Json(name = "organization-desc")
50 | val organizationDesc: String = "",
51 | @Json(name = "accesibility")
52 | val accesibility: String = "",
53 | @Json(name = "services")
54 | val services: String = "",
55 | @Json(name = "schedule")
56 | val schedule: String = "",
57 | @Json(name = "organization-name")
58 | val organizationName: String = "",
59 | @Json(name = "description")
60 | val description: String = "",
61 | @Json(name = "link")
62 | val link: String = "",
63 | @Json(name = "uid")
64 | val uid: String = "",
65 | @Json(name = "dtstart")
66 | val dtstart: String = "",
67 | @Json(name = "dtend")
68 | val dtend: String = "",
69 | @Json(name = "time")
70 | val time: String = "",
71 | @Json(name = "excluded-days")
72 | val excludedDays: String = "",
73 | @Json(name = "event-location")
74 | val eventLocation: String = "",
75 | @Json(name = "free")
76 | val free: String = "",
77 | @Json(name = "price")
78 | val price: String = "",
79 | @Json(name = "recurrence")
80 | val recurrence: String = "",
81 | @Json(name = "days")
82 | val days: String = "",
83 | @Json(name = "frequency")
84 | val frequency: String = "",
85 | @Json(name = "interval")
86 | val interval: String = "",
87 | @Json(name = "audience")
88 | val audience: String = ""
89 | )
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/kotlin/models/District.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class District(
7 | @Json(name = "@id")
8 | val id: String = ""
9 | )
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/kotlin/models/Evento.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class Evento(
7 | @Json(name = "@context")
8 | val context: Context = Context(),
9 | @Json(name = "@graph")
10 | val eventoData: List = listOf()
11 | )
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/kotlin/models/EventoData.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class EventoData(
7 | @Json(name = "@id")
8 | val idUrl: String = "",
9 | @Json(name = "@type")
10 | val typeUrl: String? = null,
11 | @Json(name = "id")
12 | val id: String = "",
13 | @Json(name = "title")
14 | val title: String = "",
15 | @Json(name = "description")
16 | val description: String = "",
17 | @Json(name = "free")
18 | val free: Int = 0,
19 | @Json(name = "price")
20 | val price: String = "",
21 | @Json(name = "dtstart")
22 | val dtstart: String = "",
23 | @Json(name = "dtend")
24 | val dtend: String = "",
25 | @Json(name = "time")
26 | val time: String = "",
27 | @Json(name = "excluded-days")
28 | val excludedDays: String = "",
29 | @Json(name = "uid")
30 | val uid: String = "",
31 | @Json(name = "link")
32 | val link: String = "",
33 | @Json(name = "event-location")
34 | val eventLocation: String = "",
35 | @Json(name = "references")
36 | val references: References = References(),
37 | @Json(name = "relation")
38 | val relation: Relation? = null,
39 | @Json(name = "address")
40 | val address: Address? = null,
41 | @Json(name = "location")
42 | val location: Location? = null,
43 | @Json(name = "organization")
44 | val organization: Organization? = null,
45 | @Json(name = "audience")
46 | val audience: String? = null,
47 | @Json(name = "recurrence")
48 | val recurrence: Recurrence? = null
49 | )
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/kotlin/models/Location.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class Location(
7 | @Json(name = "latitude")
8 | val latitude: Double = 0.0,
9 | @Json(name = "longitude")
10 | val longitude: Double = 0.0
11 | )
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/kotlin/models/Organization.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class Organization(
7 | @Json(name = "organization-name")
8 | val organizationName: String = "",
9 | @Json(name = "accesibility")
10 | val accesibility: String = ""
11 | )
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/kotlin/models/Recurrence.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class Recurrence(
7 | @Json(name = "days")
8 | val days: String = "",
9 | @Json(name = "frequency")
10 | val frequency: String = "",
11 | @Json(name = "interval")
12 | val interval: Int = 0
13 | )
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/kotlin/models/References.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class References(
7 | @Json(name = "@id")
8 | val id: String = ""
9 | )
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/kotlin/models/Relation.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class Relation(
7 | @Json(name = "@id")
8 | val id: String = ""
9 | )
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/resources/206974-0-agenda-eventos-culturales-100.csv:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Eventos-Culturales/src/main/resources/206974-0-agenda-eventos-culturales-100.csv
--------------------------------------------------------------------------------
/Ejemplos/Eventos-Culturales/src/main/resources/Estructura_DS_eventos_wwwmadrid.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Eventos-Culturales/src/main/resources/Estructura_DS_eventos_wwwmadrid.pdf
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | !.mvn/wrapper/maven-wrapper.jar
3 | !**/src/main/**/target/
4 | !**/src/test/**/target/
5 |
6 | ### IntelliJ IDEA ###
7 | .idea/modules.xml
8 | .idea/jarRepositories.xml
9 | .idea/compiler.xml
10 | .idea/libraries/
11 | *.iws
12 | *.iml
13 | *.ipr
14 |
15 | ### Eclipse ###
16 | .apt_generated
17 | .classpath
18 | .factorypath
19 | .project
20 | .settings
21 | .springBeans
22 | .sts4-cache
23 |
24 | ### NetBeans ###
25 | /nbproject/private/
26 | /nbbuild/
27 | /dist/
28 | /nbdist/
29 | /.nb-gradle/
30 | build/
31 | !**/src/main/**/build/
32 | !**/src/test/**/build/
33 |
34 | ### VS Code ###
35 | .vscode/
36 |
37 | ### Mac OS ###
38 | .DS_Store
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/coches.csv:
--------------------------------------------------------------------------------
1 | id,modelo,precio,fecha_lanzamiento
2 | 1,Modelo 29,3861.165857832617,2023-03-14
3 | 2,Modelo 22,5717.061647216174,2023-03-14
4 | 3,Modelo 99,1601.1521085677073,2023-03-14
5 | 4,Modelo 34,6632.670094478061,2023-03-14
6 | 5,Modelo 10,7580.407089072447,2023-03-14
7 | 6,Modelo 62,113.49702316114984,2023-03-14
8 | 7,Modelo 36,2880.438772807673,2023-03-14
9 | 8,Modelo 68,3798.3322447961523,2023-03-14
10 | 9,Modelo 56,4115.162942058071,2023-03-14
11 | 10,Modelo 42,7271.168756253871,2023-03-14
12 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/enteros.dat:
--------------------------------------------------------------------------------
1 | - 8 D F X f H
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/fichero-texto-2.txt:
--------------------------------------------------------------------------------
1 | Hola mundo
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/fichero-texto-copy.txt:
--------------------------------------------------------------------------------
1 | Hola
2 | Esto es
3 | un fichero de texto
4 |
5 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/fichero-texto.txt:
--------------------------------------------------------------------------------
1 | Hola
2 | Esto es
3 | un fichero de texto
4 |
5 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/paciente.json:
--------------------------------------------------------------------------------
1 | {
2 | "createdAt": "2023-03-21T13:11:51.195243557",
3 | "edad": 45,
4 | "nombre": "José Luis",
5 | "uuid": "e656a1b6-b9c3-432d-991f-c40ef80249a3"
6 | }
7 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/pacientes.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "createdAt": "2023-03-21T13:11:51.406530035",
4 | "edad": 45,
5 | "nombre": "José Luis",
6 | "uuid": "5cc2b11b-78c9-4bf0-86fe-bf3e722422b2"
7 | },
8 | {
9 | "createdAt": "2023-03-21T13:11:51.406617049",
10 | "edad": 25,
11 | "nombre": "María",
12 | "uuid": "8fe3eb65-68a6-4bae-acd7-0ba3d63e7bca"
13 | },
14 | {
15 | "createdAt": "2023-03-21T13:11:51.406635092",
16 | "edad": 35,
17 | "nombre": "Juan",
18 | "uuid": "bd21dbfb-4dec-4a20-aad1-23b04b7eb30c"
19 | }
20 | ]
21 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/perro-foxhound.xml:
--------------------------------------------------------------------------------
1 |
2 | Firulais
3 | 5
4 | 2023-03-23T09:55:47.052414558
5 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/perro.xml:
--------------------------------------------------------------------------------
1 |
2 | Firulais
3 | 5
4 | 2023-03-23T09:55:47.052414558
5 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/perros-foxhound.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Firulais
4 | 5
5 | 2023-03-23T09:55:47.263106119
6 |
7 |
8 | Salchichon
9 | 6
10 | 2023-03-23T09:55:47.263189510
11 |
12 |
13 | Chispas
14 | 7
15 | 2023-03-23T09:55:47.263210224
16 |
17 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/perros.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Firulais
4 | 5
5 | 2023-03-23T09:55:47.263106119
6 |
7 |
8 | Salchichon
9 | 6
10 | 2023-03-23T09:55:47.263189510
11 |
12 |
13 | Chispas
14 | 7
15 | 2023-03-23T09:55:47.263210224
16 |
17 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/personas.dat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Ficheros-Java/data/personas.dat
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/data/texto.txt:
--------------------------------------------------------------------------------
1 | Pepe se va a comprar, CON
2 | pedro.
3 | Pero Pepe se ENCUENTRA, CON PABLO
4 | DAM, ESTUDIAR programacion
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/enteros.dat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Ficheros-Java/enteros.dat
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | es.joseluisgs
8 | Ficheros-Java
9 | 1.0-SNAPSHOT
10 |
11 |
12 | 17
13 | 17
14 | UTF-8
15 |
16 |
17 |
18 |
19 |
20 | com.squareup.moshi
21 | moshi
22 | 1.14.0
23 |
24 |
25 | com.squareup.moshi
26 | moshi-adapters
27 | 1.14.0
28 |
29 |
30 |
31 | org.projectlombok
32 | lombok
33 | 1.18.26
34 | provided
35 |
36 |
37 |
38 | ch.qos.logback
39 | logback-classic
40 | 1.4.6
41 |
42 |
43 |
44 | org.simpleframework
45 | simple-xml
46 | 2.7.1
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/Main.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs;
2 |
3 | public class Main {
4 | public static void main(String[] args) {
5 | System.out.println("Hello world!");
6 | }
7 | }
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/binario/Binario.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.binario;
2 |
3 | import java.io.*;
4 |
5 | public class Binario {
6 | public static void main(String[] args) {
7 | leerFichero();
8 | escribirFichero();
9 | }
10 |
11 | private static void escribirFichero() {
12 | String myPath = System.getProperty("user.dir");
13 | String myFile = myPath + File.separator + "data" + File.separator + "fichero-texto-2.txt";
14 | System.out.println(myFile);
15 | // Existe y podemos leerlo?
16 | File fDestino = new File(myFile);
17 |
18 | try (FileOutputStream fileOutputStream = new FileOutputStream(fDestino)) {
19 | String texto = "Hola mundo";
20 | fileOutputStream.write(texto.getBytes());
21 | } catch (IOException e) {
22 | e.printStackTrace();
23 | }
24 |
25 | try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(fDestino))) {
26 | String texto = "Hola mundo";
27 | bufferedOutputStream.write(texto.getBytes());
28 | } catch (IOException e) {
29 | e.printStackTrace();
30 | }
31 | }
32 |
33 | private static void leerFichero() {
34 | String myPath = System.getProperty("user.dir");
35 | String myFile = myPath + File.separator + "data" + File.separator + "fichero-texto.txt";
36 | System.out.println(myFile);
37 | // Existe y podemos leerlo?
38 | File fOrigen = new File(myFile);
39 |
40 | try (FileInputStream fileInputStream = new FileInputStream(fOrigen)) {
41 | int singleCharInt;
42 | char singleChar;
43 |
44 | while((singleCharInt = fileInputStream.read()) != -1) {
45 | singleChar = (char) singleCharInt;
46 | System.out.print(singleChar);
47 | }
48 | } catch (IOException e) {
49 | e.printStackTrace();
50 | }
51 |
52 | try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(fOrigen))) {
53 | int singleCharInt;
54 | char singleChar;
55 | while((singleCharInt = bufferedInputStream.read()) != -1) {
56 | singleChar = (char) singleCharInt;
57 | System.out.print(singleChar);
58 | }
59 | } catch (IOException e) {
60 | e.printStackTrace();
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/csv/Coche.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.csv;
2 |
3 | import java.time.LocalDate;
4 |
5 | public class Coche {
6 |
7 | private static int contador = 0;
8 | private final int id;
9 | private String modelo;
10 | private double precio;
11 | private LocalDate fechaLanzamiento;
12 |
13 | public Coche(String modelo, double precio, LocalDate fechaLanzamiento) {
14 | this.id = ++contador;
15 | this.modelo = modelo;
16 | this.precio = precio;
17 | this.fechaLanzamiento = fechaLanzamiento;
18 | }
19 |
20 | public Coche(int id, String modelo, double precio, LocalDate fechaLanzamiento) {
21 | this.id = id;
22 | this.modelo = modelo;
23 | this.precio = precio;
24 | this.fechaLanzamiento = fechaLanzamiento;
25 | }
26 |
27 | public static int getContador() {
28 | return contador;
29 | }
30 |
31 | public static void setContador(int contador) {
32 | Coche.contador = contador;
33 | }
34 |
35 | public static Coche randomCoche() {
36 | return new Coche("Modelo " + (int) (Math.random() * 100), Math.random() * 10000, LocalDate.now());
37 | }
38 |
39 | public int getId() {
40 | return id;
41 | }
42 |
43 | public String getModelo() {
44 | return modelo;
45 | }
46 |
47 | public void setModelo(String modelo) {
48 | this.modelo = modelo;
49 | }
50 |
51 | public double getPrecio() {
52 | return precio;
53 | }
54 |
55 | public void setPrecio(double precio) {
56 | this.precio = precio;
57 | }
58 |
59 | public LocalDate getFechaLanzamiento() {
60 | return fechaLanzamiento;
61 | }
62 |
63 | public void setFechaLanzamiento(LocalDate fechaLanzamiento) {
64 | this.fechaLanzamiento = fechaLanzamiento;
65 | }
66 |
67 | @Override
68 | public String toString() {
69 | return "Coche{" +
70 | "id=" + id +
71 | ", modelo='" + modelo + '\'' +
72 | ", precio=" + precio +
73 | ", fechaLanzamiento=" + fechaLanzamiento +
74 | '}';
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/json/Paciente.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.json;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | import java.time.LocalDateTime;
8 | import java.util.UUID;
9 |
10 | @Data
11 | @AllArgsConstructor // Constructor con los final
12 | @NoArgsConstructor // Necesario para Jackson y Lombok Es el constrcutor vacío
13 | public class Paciente {
14 | private final LocalDateTime createdAt = LocalDateTime.now();
15 | private final UUID uuid = UUID.randomUUID();
16 | private String nombre;
17 | private int edad;
18 |
19 | }
20 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/json/utils/LocalDateTimeAdapter.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.json.utils;
2 |
3 | import com.squareup.moshi.*;
4 |
5 | import java.io.IOException;
6 | import java.time.LocalDateTime;
7 |
8 |
9 | public class LocalDateTimeAdapter extends JsonAdapter {
10 | @FromJson
11 | @Override
12 | public LocalDateTime fromJson(JsonReader jsonReader) throws IOException {
13 | return LocalDateTime.parse(jsonReader.readJsonValue().toString());
14 | }
15 |
16 | @ToJson
17 | @Override
18 | public void toJson(JsonWriter jsonWriter, LocalDateTime localDateTime) throws IOException {
19 | jsonWriter.value(localDateTime.toString());
20 | }
21 | }
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/json/utils/UuidAdapter.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.json.utils;
2 |
3 | import com.squareup.moshi.*;
4 |
5 | import java.io.IOException;
6 | import java.util.UUID;
7 |
8 | public class UuidAdapter extends JsonAdapter {
9 | @Override
10 | @FromJson
11 | public UUID fromJson(JsonReader jsonReader) throws IOException {
12 | return UUID.fromString(jsonReader.nextString());
13 | }
14 |
15 |
16 | @Override
17 | @ToJson
18 | public void toJson(JsonWriter jsonWriter, UUID uuid) throws IOException {
19 | jsonWriter.value(uuid.toString());
20 | }
21 |
22 | }
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/xml/PerroXml.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.xml;
2 |
3 | import es.joseluisgs.xml.dto.PerroDto;
4 | import es.joseluisgs.xml.dto.PerroListDto;
5 | import es.joseluisgs.xml.mappers.PerroMapper;
6 | import es.joseluisgs.xml.model.Perro;
7 | import org.simpleframework.xml.Serializer;
8 | import org.simpleframework.xml.core.Persister;
9 |
10 | import java.io.File;
11 | import java.util.List;
12 |
13 | public class PerroXml {
14 | public static void main(String[] args) {
15 | System.out.println("Hola XML");
16 | String path = System.getProperty("user.dir") + File.separator + "data" + File.separator + "perro.xml";
17 |
18 | var perro = new Perro("Firulais", 5);
19 | System.out.println(perro);
20 |
21 | Serializer serializer = new Persister();
22 | try {
23 | serializer.write(PerroMapper.toPerroDto(perro), new File(path));
24 | } catch (Exception e) {
25 | System.out.println(e.getMessage());
26 | }
27 |
28 |
29 | try {
30 | var dto = serializer.read(PerroDto.class, new File(path));
31 | System.out.println(dto);
32 | var perro2 = PerroMapper.toPerro(dto);
33 | System.out.println(perro2);
34 | } catch (Exception e) {
35 | System.out.println(e.getMessage());
36 | }
37 |
38 | path = System.getProperty("user.dir") + File.separator + "data" + File.separator + "perros.xml";
39 |
40 | var perros = List.of(new Perro("Firulais", 5), new Perro("Salchichon", 6), new Perro("Chispas", 7));
41 |
42 | try {
43 | serializer.write(PerroMapper.toPerroListDto(perros), new File(path));
44 | } catch (Exception e) {
45 | System.out.println(e.getMessage());
46 | }
47 |
48 | try {
49 | var dtoList = serializer.read(PerroListDto.class, new File(path));
50 | var perros2 = PerroMapper.toPerroList(dtoList);
51 | System.out.println(perros2);
52 | } catch (Exception e) {
53 | System.out.println(e.getMessage());
54 | }
55 |
56 |
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/xml/dto/PerroDto-foxhound.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.xml.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 | import org.simpleframework.xml.Attribute;
7 | import org.simpleframework.xml.Element;
8 | import org.simpleframework.xml.Root;
9 |
10 | @Data
11 | @AllArgsConstructor
12 | @NoArgsConstructor
13 | @Root(name = "perro")
14 | public class PerroDto {
15 | @Attribute
16 | private String uuid;
17 | @Element
18 | private String nombre;
19 | @Element
20 | private String edad;
21 | @Element(name = "created_at", required = false)
22 | private String createdAt;
23 | }
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/xml/dto/PerroDto.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.xml.dto;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 | import org.simpleframework.xml.Attribute;
7 | import org.simpleframework.xml.Element;
8 | import org.simpleframework.xml.Root;
9 |
10 | @Data
11 | @AllArgsConstructor
12 | @NoArgsConstructor
13 | @Root(name = "perro")
14 | public class PerroDto {
15 | @Attribute
16 | private String uuid;
17 | @Element
18 | private String nombre;
19 | @Element
20 | private String edad;
21 | @Element(name = "created_at", required = false)
22 | private String createdAt;
23 | }
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/xml/dto/PerroListDto-foxhound.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.xml.dto;
2 |
3 | // Para la lista
4 | // Para las listas, necesitamos una clase contenedora
5 |
6 | import org.simpleframework.xml.ElementList;
7 | import org.simpleframework.xml.Root;
8 |
9 | import java.util.List;
10 |
11 | @Root(name = "perros")
12 | public class PerroListDto {
13 | @ElementList(name = "perros", inline = true) // inline para que no se cree un elemento contenedor
14 | public List perros;
15 | }
16 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/xml/dto/PerroListDto.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.xml.dto;
2 |
3 | // Para la lista
4 | // Para las listas, necesitamos una clase contenedora
5 |
6 | import org.simpleframework.xml.ElementList;
7 | import org.simpleframework.xml.Root;
8 |
9 | import java.util.List;
10 |
11 | @Root(name = "perros")
12 | public class PerroListDto {
13 | @ElementList(name = "perros", inline = true) // inline para que no se cree un elemento contenedor
14 | public List perros;
15 | }
16 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/xml/mappers/PerroMapper.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.xml.mappers;
2 |
3 | import es.joseluisgs.xml.dto.PerroDto;
4 | import es.joseluisgs.xml.dto.PerroListDto;
5 | import es.joseluisgs.xml.model.Perro;
6 |
7 | import java.time.LocalDateTime;
8 | import java.util.List;
9 | import java.util.UUID;
10 |
11 | public class PerroMapper {
12 | public static PerroDto toPerroDto(Perro perro) {
13 | return new PerroDto(
14 | perro.getUuid().toString(),
15 | perro.getNombre(),
16 | String.valueOf(perro.getEdad()),
17 | perro.getCreatedAt().toString()
18 | );
19 | }
20 |
21 | public static Perro toPerro(PerroDto perroDto) {
22 | return new Perro(
23 | UUID.fromString(perroDto.getUuid()),
24 | perroDto.getNombre(),
25 | Integer.parseInt(perroDto.getEdad()),
26 | LocalDateTime.parse(perroDto.getCreatedAt())
27 | );
28 | }
29 |
30 | public static List toPerroList(PerroListDto perroDtoList) {
31 | return perroDtoList.perros.stream().map(PerroMapper::toPerro).toList();
32 | }
33 |
34 | public static PerroListDto toPerroListDto(List perroList) {
35 | PerroListDto perroListDto = new PerroListDto();
36 | perroListDto.perros = perroList.stream().map(PerroMapper::toPerroDto).toList();
37 | return perroListDto;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Java/src/main/java/es/joseluisgs/xml/model/Perro.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.xml.model;
2 |
3 | import lombok.AllArgsConstructor;
4 | import lombok.Data;
5 | import lombok.NoArgsConstructor;
6 |
7 | import java.time.LocalDateTime;
8 | import java.util.UUID;
9 |
10 | @Data
11 | @AllArgsConstructor // Constructor con los final
12 | @NoArgsConstructor // Necesario para Jackson y Lombok Es el constrcutor vacío
13 | public class Perro {
14 | private UUID uuid = UUID.randomUUID();
15 | private String nombre;
16 | private int edad;
17 | private LocalDateTime createdAt = LocalDateTime.now();
18 |
19 | public Perro(String nombre, int edad) {
20 | this.nombre = nombre;
21 | this.edad = edad;
22 | }
23 | }
24 |
25 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | build/
3 | !gradle/wrapper/gradle-wrapper.jar
4 | !**/src/main/**/build/
5 | !**/src/test/**/build/
6 |
7 | ### IntelliJ IDEA ###
8 | .idea/modules.xml
9 | .idea/jarRepositories.xml
10 | .idea/compiler.xml
11 | .idea/libraries/
12 | *.iws
13 | *.iml
14 | *.ipr
15 | out/
16 | !**/src/main/**/out/
17 | !**/src/test/**/out/
18 |
19 | ### Eclipse ###
20 | .apt_generated
21 | .classpath
22 | .factorypath
23 | .project
24 | .settings
25 | .springBeans
26 | .sts4-cache
27 | bin/
28 | !**/src/main/**/bin/
29 | !**/src/test/**/bin/
30 |
31 | ### NetBeans ###
32 | /nbproject/private/
33 | /nbbuild/
34 | /dist/
35 | /nbdist/
36 | /.nb-gradle/
37 |
38 | ### VS Code ###
39 | .vscode/
40 |
41 | ### Mac OS ###
42 | .DS_Store
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/build.gradle-foxhound.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | kotlin("jvm") version "1.8.0"
3 | application
4 | }
5 |
6 | group = "es.joseluisgs"
7 | version = "1.0-SNAPSHOT"
8 |
9 | repositories {
10 | mavenCentral()
11 | }
12 |
13 | dependencies {
14 | testImplementation(kotlin("test"))
15 |
16 | // Moshi
17 | //implementation("com.squareup.moshi:moshi:1.14.0")
18 | implementation("com.squareup.moshi:moshi-kotlin:1.14.0")
19 | //implementation("com.squareup.moshi:moshi-adapters:1.14.0")
20 |
21 | // Simple XML
22 | implementation("org.simpleframework:simple-xml:2.7.1")
23 | }
24 |
25 | tasks.test {
26 | useJUnitPlatform()
27 | }
28 |
29 | kotlin {
30 | jvmToolchain(8)
31 | }
32 |
33 | application {
34 | mainClass.set("MainKt")
35 | }
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | kotlin("jvm") version "1.8.0"
3 | application
4 | }
5 |
6 | group = "es.joseluisgs"
7 | version = "1.0-SNAPSHOT"
8 |
9 | repositories {
10 | mavenCentral()
11 | }
12 |
13 | dependencies {
14 | testImplementation(kotlin("test"))
15 |
16 | // Moshi
17 | //implementation("com.squareup.moshi:moshi:1.14.0")
18 | implementation("com.squareup.moshi:moshi-kotlin:1.14.0")
19 | //implementation("com.squareup.moshi:moshi-adapters:1.14.0")
20 |
21 | // Simple XML
22 | implementation("org.simpleframework:simple-xml:2.7.1")
23 | }
24 |
25 | tasks.test {
26 | useJUnitPlatform()
27 | }
28 |
29 | kotlin {
30 | jvmToolchain(8)
31 | }
32 |
33 | application {
34 | mainClass.set("MainKt")
35 | }
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/alumnos-serializable.dat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Ficheros-Kotlin/data/alumnos-serializable.dat
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/alumnos.dat:
--------------------------------------------------------------------------------
1 | Juan Ana Luis María Pedro Lucía Marta Javier Sara
2 | Pablo
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/alumnos.txt:
--------------------------------------------------------------------------------
1 | 1
2 | Juan
3 | false
4 | 2
5 | Ana
6 | true
7 | 3
8 | Luis
9 | false
10 | 4
11 | María
12 | true
13 | 5
14 | Pedro
15 | false
16 | 6
17 | Lucía
18 | true
19 | 7
20 | Marta
21 | false
22 | 8
23 | Javier
24 | true
25 | 9
26 | Sara
27 | false
28 | 10
29 | Pablo
30 | true
31 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/coches.csv:
--------------------------------------------------------------------------------
1 | id,marca,precio,fechaLanzamiento
2 | 1,Marca 1,3956.3799242029186,2023-03-14
3 | 2,Marca 2,5281.058070697928,2023-03-14
4 | 3,Marca 3,3464.772376265057,2023-03-14
5 | 4,Marca 4,8808.790763612342,2023-03-14
6 | 5,Marca 5,1845.0260261751116,2023-03-14
7 | 6,Marca 6,6173.856935227333,2023-03-14
8 | 7,Marca 7,7742.885506468388,2023-03-14
9 | 8,Marca 8,8476.202324504715,2023-03-14
10 | 9,Marca 9,3059.4700354963657,2023-03-14
11 | 10,Marca 10,4538.066571470171,2023-03-14
12 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/enteros.dat:
--------------------------------------------------------------------------------
1 | - 8 E F X
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/fichero-serializable.dat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Ficheros-Kotlin/data/fichero-serializable.dat
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/fichero-texto-2.txt:
--------------------------------------------------------------------------------
1 | Hola mundo!
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/fichero-texto-copy.txt:
--------------------------------------------------------------------------------
1 | Hola
2 | Esto es
3 | un fichero de texto
4 |
5 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/fichero-texto.txt:
--------------------------------------------------------------------------------
1 | Hola
2 | Esto es
3 | un fichero de texto
4 |
5 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/paciente-foxhound.json:
--------------------------------------------------------------------------------
1 | {
2 | "uuid": "53a2df3d-6a22-459e-be08-a58efb411e9f",
3 | "nombre": "Juan",
4 | "edad": 30,
5 | "created_at": "2023-03-23T09:20:15.397186241"
6 | }
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/paciente-foxhound.xml:
--------------------------------------------------------------------------------
1 |
2 | Juan
3 | 30
4 | 2023-03-23T10:01:45.063908891
5 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/paciente.json:
--------------------------------------------------------------------------------
1 | {
2 | "uuid": "53a2df3d-6a22-459e-be08-a58efb411e9f",
3 | "nombre": "Juan",
4 | "edad": 30,
5 | "created_at": "2023-03-23T09:20:15.397186241"
6 | }
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/paciente.xml:
--------------------------------------------------------------------------------
1 |
2 | Juan
3 | 30
4 | 2023-03-23T10:01:45.063908891
5 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/pacientes-foxhound.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "uuid": "fb66a094-6859-484a-8b83-2e12f63d1e30",
4 | "nombre": "Juan",
5 | "edad": 30,
6 | "created_at": "2023-03-23T09:20:15.827271570"
7 | },
8 | {
9 | "uuid": "eb01a878-7a48-4b40-9c3f-679377fd14b9",
10 | "nombre": "Ana",
11 | "edad": 25,
12 | "created_at": "2023-03-23T09:20:15.827332108"
13 | },
14 | {
15 | "uuid": "399275c8-6870-4837-a5d4-2addb63cfb97",
16 | "nombre": "Luis",
17 | "edad": 40,
18 | "created_at": "2023-03-23T09:20:15.827381573"
19 | },
20 | {
21 | "uuid": "288244f0-8c0b-4e46-9c66-47b62ce83107",
22 | "nombre": "María",
23 | "edad": 35,
24 | "created_at": "2023-03-23T09:20:15.827397678"
25 | }
26 | ]
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/pacientes-foxhound.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Juan
4 | 30
5 | 2023-03-23T10:01:45.408870089
6 |
7 |
8 | Ana
9 | 25
10 | 2023-03-23T10:01:45.408961221
11 |
12 |
13 | Luis
14 | 40
15 | 2023-03-23T10:01:45.409341162
16 |
17 |
18 | María
19 | 35
20 | 2023-03-23T10:01:45.409354702
21 |
22 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/pacientes.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "uuid": "fb66a094-6859-484a-8b83-2e12f63d1e30",
4 | "nombre": "Juan",
5 | "edad": 30,
6 | "created_at": "2023-03-23T09:20:15.827271570"
7 | },
8 | {
9 | "uuid": "eb01a878-7a48-4b40-9c3f-679377fd14b9",
10 | "nombre": "Ana",
11 | "edad": 25,
12 | "created_at": "2023-03-23T09:20:15.827332108"
13 | },
14 | {
15 | "uuid": "399275c8-6870-4837-a5d4-2addb63cfb97",
16 | "nombre": "Luis",
17 | "edad": 40,
18 | "created_at": "2023-03-23T09:20:15.827381573"
19 | },
20 | {
21 | "uuid": "288244f0-8c0b-4e46-9c66-47b62ce83107",
22 | "nombre": "María",
23 | "edad": 35,
24 | "created_at": "2023-03-23T09:20:15.827397678"
25 | }
26 | ]
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/pacientes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Juan
4 | 30
5 | 2023-03-23T10:01:45.408870089
6 |
7 |
8 | Ana
9 | 25
10 | 2023-03-23T10:01:45.408961221
11 |
12 |
13 | Luis
14 | 40
15 | 2023-03-23T10:01:45.409341162
16 |
17 |
18 | María
19 | 35
20 | 2023-03-23T10:01:45.409354702
21 |
22 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/data/texto.txt:
--------------------------------------------------------------------------------
1 | Pepe se va a comprar, con
2 | PEDRO.Pero Pepe se ENCUENTRA, CON PABLO
3 | dam, ESTUDIAR programacion
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
2 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Ficheros-Kotlin/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/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 execute
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 execute
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 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/settings.gradle.kts:
--------------------------------------------------------------------------------
1 |
2 | rootProject.name = "Ficheros-Kotlin"
3 |
4 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/Main.kt:
--------------------------------------------------------------------------------
1 | fun main(args: Array) {
2 | }
3 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/aleatorio/AlumnosAleatorio.kt:
--------------------------------------------------------------------------------
1 | package aleatorio
2 |
3 | import java.io.File
4 | import java.io.RandomAccessFile
5 |
6 | private data class Alumno(val numero: Int, val nombre: String, val repetidor: Boolean)
7 |
8 | val programPath = System.getProperty("user.dir")
9 | val fileOrigen = "$programPath${File.separator}data${File.separator}alumnos.dat"
10 | fun main() {
11 | escribirAlumnosInit()
12 | mostrarAlumnos()
13 | }
14 |
15 | private fun mostrarAlumnos() {
16 | val fileRandom = RandomAccessFile(fileOrigen, "r")
17 | val alumnos = mutableListOf()
18 | fileRandom.use {
19 | // fileRandom.seek(0)
20 | while (it.filePointer < it.length()) {
21 | val numero = it.readInt() // 4 bytes
22 | val nombre = it.readUTF() // 2 bytes + longitud
23 | val repetidor = it.readBoolean() // 1 byte
24 | alumnos.add(Alumno(numero, nombre, repetidor))
25 | }
26 | }
27 | println("Alumnos: " + alumnos.size)
28 | alumnos.forEach { println(it) }
29 | }
30 |
31 | private fun escribirAlumnosInit() {
32 | val alumnos = listOf(
33 | Alumno(1, "Juan", false),
34 | Alumno(2, "Ana", true),
35 | Alumno(3, "Luis", false),
36 | Alumno(4, "María", true),
37 | Alumno(5, "Pedro", false),
38 | Alumno(6, "Lucía", true),
39 | Alumno(7, "Marta", false),
40 | Alumno(8, "Javier", true),
41 | Alumno(9, "Sara", false),
42 | Alumno(10, "Pablo", true),
43 | )
44 | val fileRandom = RandomAccessFile(fileOrigen, "rw")
45 | fileRandom.use {
46 | // fileRandom.seek(it.length()) // Posiciona el puntero al final del fichero
47 | // fileRandom.seek(0) // Posiciona el puntero al principio del fichero
48 | for (alumno in alumnos) {
49 | it.writeInt(alumno.numero)
50 | it.writeUTF(alumno.nombre)
51 | it.writeBoolean(alumno.repetidor)
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/binario/AlumnosBinario.kt:
--------------------------------------------------------------------------------
1 | package binario
2 |
3 | import java.io.File
4 |
5 | private data class Alumno(val numero: Int, val nombre: String, val repetidor: Boolean)
6 |
7 | val programPath = System.getProperty("user.dir")
8 | val fileOrigen = "$programPath${File.separator}data${File.separator}alumnos.txt"
9 | fun main() {
10 | escribirAlumnosInit()
11 | mostrarAlumnos()
12 | }
13 |
14 | private fun mostrarAlumnos() {
15 | val file = File(fileOrigen)
16 | val alumnos = mutableListOf()
17 | file.inputStream().buffered().use {
18 | while (it.available() > 0) {
19 | // Recorremos caracter a caracter hasta encontrar un salto de línea
20 | val numeroString = StringBuilder()
21 | var char = it.read().toChar()
22 | while (char != '\n') {
23 | numeroString.append(char)
24 | char = it.read().toChar()
25 | }
26 | val numero = numeroString.toString().toInt()
27 | // println("Número: $numero")
28 | // lee un nombre
29 | val nombreString = StringBuilder()
30 | char = it.read().toChar()
31 | while (char != '\n') {
32 | nombreString.append(char)
33 | char = it.read().toChar()
34 | }
35 | val nombre = nombreString.toString()
36 | // println("Nombre: $nombre")
37 | // lee un booleano
38 | val repetidorString = StringBuilder()
39 | char = it.read().toChar()
40 | while (char != '\n') {
41 | repetidorString.append(char)
42 | char = it.read().toChar()
43 | }
44 | val repetidor = repetidorString.toString().toBoolean()
45 | // println("Repetidor: $repetidor")
46 | alumnos.add(Alumno(numero, nombre, repetidor))
47 | }
48 | }
49 | println("Alumnos: " + alumnos.size)
50 | alumnos.forEach { println(it) }
51 | }
52 |
53 | private fun escribirAlumnosInit() {
54 | val alumnos = listOf(
55 | Alumno(1, "Juan", false),
56 | Alumno(2, "Ana", true),
57 | Alumno(3, "Luis", false),
58 | Alumno(4, "María", true),
59 | Alumno(5, "Pedro", false),
60 | Alumno(6, "Lucía", true),
61 | Alumno(7, "Marta", false),
62 | Alumno(8, "Javier", true),
63 | Alumno(9, "Sara", false),
64 | Alumno(10, "Pablo", true),
65 | )
66 | // fichero de texto
67 | val fileText = File(texto.fileOrigen)
68 | fileText.outputStream().buffered().use {
69 | for (alumno in alumnos) {
70 | it.write(alumno.numero.toString().toByteArray())
71 | it.write("\n".toByteArray())
72 | it.write(alumno.nombre.toByteArray())
73 | it.write("\n".toByteArray())
74 | it.write(alumno.repetidor.toString().toByteArray())
75 | it.write("\n".toByteArray())
76 | }
77 | }
78 | }
79 |
80 |
81 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/binario/Binario.kt:
--------------------------------------------------------------------------------
1 | package binario
2 |
3 | import java.io.File
4 |
5 | fun main() {
6 | leerFichero()
7 | escribirFichero()
8 | }
9 |
10 | fun escribirFichero() {
11 | val programPath = System.getProperty("user.dir")
12 | val filePath = "$programPath${File.separator}data${File.separator}fichero-texto-2.txt"
13 | println("Escribiendo fichero: $filePath")
14 |
15 | val fileDestino = File(filePath)
16 |
17 | // writeBytes
18 | fileDestino.writeBytes("Hola mundo!".toByteArray())
19 |
20 | // outputStream
21 | fileDestino.outputStream().use { it.write("Hola mundo!".toByteArray()) }
22 |
23 | // bufferedOutputStream
24 | fileDestino.outputStream().buffered().use { it.write("Hola mundo!".toByteArray()) }
25 |
26 | // con bufferedWriter
27 | fileDestino.bufferedWriter().use { it.write("Hola mundo!") }
28 | }
29 |
30 | fun leerFichero() {
31 | val programPath = System.getProperty("user.dir")
32 | val filePath = "$programPath${File.separator}data${File.separator}fichero-texto.txt"
33 | println("Leyendo fichero: $filePath")
34 |
35 | val fileOrigen = File(filePath)
36 |
37 | // readBytes
38 | val bytes = fileOrigen.readBytes().toString(Charsets.UTF_8)
39 | println(bytes)
40 | println()
41 | // con un inputStream
42 | fileOrigen.inputStream().use { println(it.readBytes().toString(Charsets.UTF_8)) }
43 | println()
44 | // con buffered
45 | fileOrigen.inputStream().buffered().use { println(it.readBytes().toString(Charsets.UTF_8)) }
46 | }
47 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/csv/Coche.kt:
--------------------------------------------------------------------------------
1 | package csv
2 |
3 | import java.time.LocalDate
4 |
5 | data class Coche(val id: Int = contador++, val marca: String, val precio: Double, val fechaLanzamiento: LocalDate) {
6 |
7 | companion object {
8 | var contador = 1
9 | fun randomCoche() =
10 | Coche(marca = "Marca $contador", precio = Math.random() * 10000, fechaLanzamiento = LocalDate.now())
11 | }
12 |
13 | override fun toString() = "Coche(id=$id, marca='$marca', precio=$precio, fechaLanzamiento=$fechaLanzamiento)"
14 | }
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/csv/Csv.kt:
--------------------------------------------------------------------------------
1 | package csv
2 |
3 | import java.io.File
4 | import java.time.LocalDate
5 |
6 | fun main() {
7 | println("Hola Csv")
8 |
9 | val coches = List(10) { Coche.randomCoche() }
10 | coches.forEach { println(it) }
11 |
12 | println("Escribiendo en CSV")
13 | escribirCsv(coches)
14 |
15 | println("Leyendo de CSV")
16 | val cochesLeidos = leerCsv()
17 | cochesLeidos.forEach { println(it) }
18 | }
19 |
20 | fun leerCsv(): List {
21 | val path = "${System.getProperty("user.dir")}${File.separator}data${File.separator}coches.csv"
22 | val fichero = File(path)
23 |
24 | // De esta manera lo procesamos todo en memoria, como colección
25 | return fichero.readLines()
26 | // ignoro la primera porque es el encabezado
27 | .drop(1)
28 | // separo por comas
29 | .map { linea -> linea.split(",") }
30 | // convierto a coche
31 | .map { columnas ->
32 | Coche(
33 | columnas[0].toInt(), // id
34 | columnas[1], // marca
35 | columnas[2].toDouble(), // precio
36 | LocalDate.parse(columnas[3]) // fechaLanzamiento
37 | )
38 | }
39 |
40 | // De esta manera lo procesamos línea a línea, como secuencia
41 | /*fichero.useLines { lines ->
42 | return lines
43 | // ignoro la primera porque es el encabezado
44 | .drop(1)
45 | // separo por comas
46 | .map { linea -> linea.split(",") }
47 | // convierto a coche
48 | .map { columnas ->
49 | Coche(
50 | columnas[0].toInt(), // id
51 | columnas[1], // marca
52 | columnas[2].toDouble(), // precio
53 | LocalDate.parse(columnas[3]) // fechaLanzamiento
54 | )
55 | }.toList()
56 | }*/
57 | }
58 |
59 | fun escribirCsv(coches: List) {
60 | val path = "${System.getProperty("user.dir")}${File.separator}data${File.separator}coches.csv"
61 | val fichero = File(path)
62 |
63 | // Escribimos el encabezado, separados por comas
64 | fichero.writeText("id,marca,precio,fechaLanzamiento\n")
65 | coches.forEach {
66 | fichero.appendText("${it.id},${it.marca},${it.precio},${it.fechaLanzamiento}\n")
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/json/MoshiAdapters-foxhound.kt:
--------------------------------------------------------------------------------
1 | package json
2 |
3 | import com.squareup.moshi.*
4 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
5 | import java.time.LocalDate
6 | import java.time.LocalDateTime
7 | import java.util.*
8 |
9 | class UuidAdapter : JsonAdapter() {
10 | @FromJson
11 | override fun fromJson(reader: JsonReader): UUID? = UUID.fromString(reader.readJsonValue().toString())
12 |
13 | @ToJson
14 | override fun toJson(writer: JsonWriter, value: UUID?) {
15 | writer.jsonValue(value.toString())
16 | }
17 | }
18 |
19 | class LocalDateAdapter : JsonAdapter() {
20 | @FromJson
21 | override fun fromJson(reader: JsonReader): LocalDate? = LocalDate.parse(reader.readJsonValue().toString())
22 |
23 | @ToJson
24 | override fun toJson(writer: JsonWriter, value: LocalDate?) {
25 | writer.jsonValue(value.toString())
26 | }
27 | }
28 |
29 | class LocalDateTimeAdapter : JsonAdapter() {
30 | @FromJson
31 | override fun fromJson(reader: JsonReader): LocalDateTime? = LocalDateTime.parse(reader.readJsonValue().toString())
32 |
33 | @ToJson
34 | override fun toJson(writer: JsonWriter, value: LocalDateTime?) {
35 | writer.jsonValue(value.toString())
36 | }
37 | }
38 |
39 | inline fun JsonAdapter.toPrettyJson(value: T) = this.indent(" ").toJson(value)
40 |
41 | object MoshiParser {
42 | private val moshi = Moshi.Builder()
43 | .add(UuidAdapter())
44 | .add(LocalDateAdapter())
45 | .addLast(KotlinJsonAdapterFactory())
46 | .build()
47 |
48 | fun newInstance(): Moshi = moshi
49 | }
50 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/json/MoshiAdapters.kt:
--------------------------------------------------------------------------------
1 | package json
2 |
3 | import com.squareup.moshi.*
4 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
5 | import java.time.LocalDate
6 | import java.time.LocalDateTime
7 | import java.util.*
8 |
9 | class UuidAdapter : JsonAdapter() {
10 | @FromJson
11 | override fun fromJson(reader: JsonReader): UUID? = UUID.fromString(reader.readJsonValue().toString())
12 |
13 | @ToJson
14 | override fun toJson(writer: JsonWriter, value: UUID?) {
15 | writer.jsonValue(value.toString())
16 | }
17 | }
18 |
19 | class LocalDateAdapter : JsonAdapter() {
20 | @FromJson
21 | override fun fromJson(reader: JsonReader): LocalDate? = LocalDate.parse(reader.readJsonValue().toString())
22 |
23 | @ToJson
24 | override fun toJson(writer: JsonWriter, value: LocalDate?) {
25 | writer.jsonValue(value.toString())
26 | }
27 | }
28 |
29 | class LocalDateTimeAdapter : JsonAdapter() {
30 | @FromJson
31 | override fun fromJson(reader: JsonReader): LocalDateTime? = LocalDateTime.parse(reader.readJsonValue().toString())
32 |
33 | @ToJson
34 | override fun toJson(writer: JsonWriter, value: LocalDateTime?) {
35 | writer.jsonValue(value.toString())
36 | }
37 | }
38 |
39 | inline fun JsonAdapter.toPrettyJson(value: T) = this.indent(" ").toJson(value)
40 |
41 | object MoshiParser {
42 | private val moshi = Moshi.Builder()
43 | .add(UuidAdapter())
44 | .add(LocalDateAdapter())
45 | .addLast(KotlinJsonAdapterFactory())
46 | .build()
47 |
48 | fun newInstance(): Moshi = moshi
49 | }
50 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/json/PacientesJson-foxhound.kt:
--------------------------------------------------------------------------------
1 | package json
2 |
3 | import com.squareup.moshi.Json
4 | import com.squareup.moshi.Moshi
5 | import com.squareup.moshi.adapter
6 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
7 | import okio.buffer
8 | import okio.source
9 | import java.io.File
10 | import java.time.LocalDateTime
11 | import java.util.*
12 |
13 | private data class Paciente(
14 | val uuid: UUID = UUID.randomUUID(),
15 | val nombre: String,
16 | val edad: Int,
17 | @Json(name = "created_at")
18 | val createdAt: LocalDateTime = LocalDateTime.now(),
19 | )
20 |
21 | @ExperimentalStdlibApi // Para usar el método DE adapter con enlazado de Kotlin
22 | fun main(args: Array) {
23 | val paciente = Paciente(nombre = "Juan", edad = 30)
24 | println(paciente)
25 |
26 | //val moshi = MoshiParser.newInstance()
27 |
28 | val moshi = Moshi.Builder()
29 | .add(UuidAdapter())
30 | .add(LocalDateTimeAdapter())
31 | .addLast(KotlinJsonAdapterFactory())
32 | .build()
33 |
34 |
35 | val jsonAdapter = moshi.adapter()
36 | var json = jsonAdapter.indent(" ").toJson(paciente)
37 | println(json)
38 | // Con mi función de extensión
39 | json = jsonAdapter.toPrettyJson(paciente)
40 | println(json)
41 |
42 | val paciente2 = jsonAdapter.fromJson(json)
43 | println(paciente2)
44 |
45 | // Escribir en un fichero
46 | val programPath = System.getProperty("user.dir")
47 | val fichero = "$programPath${File.separator}data${File.separator}paciente.json"
48 |
49 | File(fichero).writeText(json)
50 |
51 | // Leer de un fichero
52 | val paciente3 = jsonAdapter.fromJson(File(fichero).readText())
53 | println(paciente3)
54 |
55 | // Lista de pacientes
56 | val pacientes = listOf(
57 | Paciente(nombre = "Juan", edad = 30),
58 | Paciente(nombre = "Ana", edad = 25),
59 | Paciente(nombre = "Luis", edad = 40),
60 | Paciente(nombre = "María", edad = 35),
61 | )
62 |
63 | val jsonAdapter2 = moshi.adapter>()
64 | json = jsonAdapter2.indent(" ").toJson(pacientes)
65 | println(json)
66 | // Con mi función de extensión
67 | json = jsonAdapter2.toPrettyJson(pacientes)
68 | println(json)
69 |
70 | val pacientes2 = jsonAdapter2.fromJson(json)
71 | println(pacientes2)
72 |
73 | // Escribir en un fichero
74 | val fichero2 = "$programPath${File.separator}data${File.separator}pacientes.json"
75 | File(fichero2).writeText(json)
76 |
77 | // Leer de un fichero
78 | val pacientes3 = jsonAdapter2.fromJson(File(fichero2).readText())
79 | println(pacientes3)
80 |
81 | // Si el fichero es grande, usar un buffer
82 | val pacientes4 = jsonAdapter2.fromJson(File(fichero2).inputStream().source().buffer())
83 | println(pacientes4)
84 | }
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/json/PacientesJson.kt:
--------------------------------------------------------------------------------
1 | package json
2 |
3 | import com.squareup.moshi.Json
4 | import com.squareup.moshi.Moshi
5 | import com.squareup.moshi.adapter
6 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
7 | import okio.buffer
8 | import okio.source
9 | import java.io.File
10 | import java.time.LocalDateTime
11 | import java.util.*
12 |
13 | private data class Paciente(
14 | val uuid: UUID = UUID.randomUUID(),
15 | val nombre: String,
16 | val edad: Int,
17 | @Json(name = "created_at")
18 | val createdAt: LocalDateTime = LocalDateTime.now(),
19 | )
20 |
21 | @ExperimentalStdlibApi // Para usar el método DE adapter con enlazado de Kotlin
22 | fun main(args: Array) {
23 | val paciente = Paciente(nombre = "Juan", edad = 30)
24 | println(paciente)
25 |
26 | //val moshi = MoshiParser.newInstance()
27 |
28 | val moshi = Moshi.Builder()
29 | .add(UuidAdapter())
30 | .add(LocalDateTimeAdapter())
31 | .addLast(KotlinJsonAdapterFactory())
32 | .build()
33 |
34 |
35 | val jsonAdapter = moshi.adapter()
36 | var json = jsonAdapter.indent(" ").toJson(paciente)
37 | println(json)
38 | // Con mi función de extensión
39 | json = jsonAdapter.toPrettyJson(paciente)
40 | println(json)
41 |
42 | val paciente2 = jsonAdapter.fromJson(json)
43 | println(paciente2)
44 |
45 | // Escribir en un fichero
46 | val programPath = System.getProperty("user.dir")
47 | val fichero = "$programPath${File.separator}data${File.separator}paciente.json"
48 |
49 | File(fichero).writeText(json)
50 |
51 | // Leer de un fichero
52 | val paciente3 = jsonAdapter.fromJson(File(fichero).readText())
53 | println(paciente3)
54 |
55 | // Lista de pacientes
56 | val pacientes = listOf(
57 | Paciente(nombre = "Juan", edad = 30),
58 | Paciente(nombre = "Ana", edad = 25),
59 | Paciente(nombre = "Luis", edad = 40),
60 | Paciente(nombre = "María", edad = 35),
61 | )
62 |
63 | val jsonAdapter2 = moshi.adapter>()
64 | json = jsonAdapter2.indent(" ").toJson(pacientes)
65 | println(json)
66 | // Con mi función de extensión
67 | json = jsonAdapter2.toPrettyJson(pacientes)
68 | println(json)
69 |
70 | val pacientes2 = jsonAdapter2.fromJson(json)
71 | println(pacientes2)
72 |
73 | // Escribir en un fichero
74 | val fichero2 = "$programPath${File.separator}data${File.separator}pacientes.json"
75 | File(fichero2).writeText(json)
76 |
77 | // Leer de un fichero
78 | val pacientes3 = jsonAdapter2.fromJson(File(fichero2).readText())
79 | println(pacientes3)
80 |
81 | // Si el fichero es grande, usar un buffer
82 | val pacientes4 = jsonAdapter2.fromJson(File(fichero2).inputStream().source().buffer())
83 | println(pacientes4)
84 | }
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/serializable/AlumnosSerializable.kt:
--------------------------------------------------------------------------------
1 | package serializable
2 |
3 |
4 | import java.io.File
5 | import java.io.ObjectInputStream
6 | import java.io.ObjectOutputStream
7 | import java.io.Serializable
8 |
9 | private data class Alumno(val numero: Int, val nombre: String, val repetidor: Boolean) : Serializable
10 |
11 | val programPath = System.getProperty("user.dir")
12 | val fileOrigen = "$programPath${File.separator}data${File.separator}alumnos.dat"
13 | fun main() {
14 | escribirAlumnosInit()
15 | mostrarAlumnos()
16 | }
17 |
18 | private fun mostrarAlumnos() {
19 | val programPath = System.getProperty("user.dir")
20 | val filePath = "$programPath${File.separator}data${File.separator}alumnos-serializable.dat"
21 | println("Leyendo fichero: $filePath")
22 |
23 | val alumnos = mutableListOf()
24 |
25 | val input = ObjectInputStream(File(filePath).inputStream())
26 | input.use {
27 | // Podemos leer cualquier objeto serializable, ya sea un objeto o una colección
28 | val alumnosLeidos = it.readObject() as List
29 | alumnos.addAll(alumnosLeidos)
30 | // podría leer uno a uno
31 | // while (it.available() > 0) {
32 | // val alumno = it.readObject() as Alumno
33 | // alumnos.add(alumno)
34 | // }
35 | }
36 | println("Alumnos: " + alumnos.size)
37 | alumnos.forEach { println(it) }
38 | }
39 |
40 | private fun escribirAlumnosInit() {
41 | val programPath = System.getProperty("user.dir")
42 | val filePath = "$programPath${File.separator}data${File.separator}alumnos-serializable.dat"
43 | println("Escribiendo fichero: $filePath")
44 |
45 | val alumnos = listOf(
46 | Alumno(1, "Juan", false),
47 | Alumno(2, "Ana", true),
48 | Alumno(3, "Luis", false),
49 | Alumno(4, "María", true),
50 | Alumno(5, "Pedro", false),
51 | Alumno(6, "Lucía", true),
52 | Alumno(7, "Marta", false),
53 | Alumno(8, "Javier", true),
54 | Alumno(9, "Sara", false),
55 | Alumno(10, "Pablo", true),
56 | )
57 | val output = ObjectOutputStream(File(filePath).outputStream())
58 | output.use {
59 | // Podemos escribir cualquier objeto serializable, ya sea un objeto o una colección
60 | it.writeObject(alumnos)
61 | // podría escribir uno a uno
62 | // alumnos.forEach { alumno -> it.writeObject(alumno) }
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/serializable/Serializable.kt:
--------------------------------------------------------------------------------
1 | package serializable
2 |
3 | import java.io.*
4 |
5 |
6 | // Para ser serializable todas las propiedades deben ser serializables (sublases incluídas)
7 | private data class Persona(val nombre: String, val edad: Int) : Serializable
8 |
9 | fun main() {
10 | escribirFicheroSerializable()
11 | leerFicheroSerializable()
12 | }
13 |
14 | fun leerFicheroSerializable() {
15 | val programPath = System.getProperty("user.dir")
16 | val filePath = "$programPath${File.separator}data${File.separator}fichero-serializable.dat"
17 | println("Leyendo fichero: $filePath")
18 |
19 | val file = File(filePath)
20 |
21 | val input = ObjectInputStream(FileInputStream(file))
22 | input.use {
23 | // Podemos leer cualquier objeto serializable, ya sea un objeto o una colección
24 | val persona = it.readObject() as Persona
25 | val lista = it.readObject() as List
26 | println(persona)
27 | println(lista)
28 | }
29 | }
30 |
31 | fun escribirFicheroSerializable() {
32 | val programPath = System.getProperty("user.dir")
33 | val filePath = "$programPath${File.separator}data${File.separator}fichero-serializable.dat"
34 | println("Escribiendo fichero: $filePath")
35 |
36 | val file = File(filePath)
37 | val persona = Persona("Antonio", 34)
38 | val lista = listOf(
39 | Persona("Pepe", 23),
40 | Persona("Juan", 34),
41 | Persona("Ana", 45)
42 | )
43 | val output = ObjectOutputStream(FileOutputStream(file))
44 | output.use {
45 | // Podemos escribir cualquier objeto serializable, ya sea un objeto o una colección
46 | it.writeObject(persona)
47 | it.writeObject(lista)
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/kotlin/texto/AlumnosTexto.kt:
--------------------------------------------------------------------------------
1 | package texto
2 |
3 | import java.io.File
4 |
5 | private data class Alumno(val numero: Int, val nombre: String, val repetidor: Boolean)
6 |
7 | val programPath = System.getProperty("user.dir")
8 | val fileOrigen = "$programPath${File.separator}data${File.separator}alumnos.txt"
9 | fun main() {
10 | escribirAlumnosInit()
11 | mostrarAlumnos()
12 | }
13 |
14 | private fun mostrarAlumnos() {
15 | val fileText = File(fileOrigen)
16 | val alumnos = mutableListOf()
17 | // Esta vez lo debemos hacer con un while y bufferedReader
18 | fileText.bufferedReader().use {
19 | // De esta manera sabemos si hay más líneas que leer
20 | while (it.ready()) {
21 | val numero = it.readLine().toInt()
22 | val nombre = it.readLine().trim()
23 | val repetidor = it.readLine().toBoolean()
24 | alumnos.add(Alumno(numero, nombre, repetidor))
25 | }
26 | }
27 | println("Alumnos: " + alumnos.size)
28 | alumnos.forEach { println(it) }
29 | }
30 |
31 | private fun escribirAlumnosInit() {
32 | val alumnos = listOf(
33 | Alumno(1, "Juan", false),
34 | Alumno(2, "Ana", true),
35 | Alumno(3, "Luis", false),
36 | Alumno(4, "María", true),
37 | Alumno(5, "Pedro", false),
38 | Alumno(6, "Lucía", true),
39 | Alumno(7, "Marta", false),
40 | Alumno(8, "Javier", true),
41 | Alumno(9, "Sara", false),
42 | Alumno(10, "Pablo", true),
43 | )
44 | // fichero de texto
45 | val fileText = File(fileOrigen)
46 | fileText.writeText("")
47 | alumnos.forEach {
48 | fileText.appendText(it.numero.toString() + "\n")
49 | fileText.appendText(it.nombre + "\n")
50 | fileText.appendText(it.repetidor.toString() + "\n")
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/resources/coches.csv:
--------------------------------------------------------------------------------
1 | id,marca,precio,fechaLanzamiento
2 | 1,Marca 1,3956.3799242029186,2023-03-14
3 | 2,Marca 2,5281.058070697928,2023-03-14
4 | 3,Marca 3,3464.772376265057,2023-03-14
5 | 4,Marca 4,8808.790763612342,2023-03-14
6 | 5,Marca 5,1845.0260261751116,2023-03-14
7 | 6,Marca 6,6173.856935227333,2023-03-14
8 | 7,Marca 7,7742.885506468388,2023-03-14
9 | 8,Marca 8,8476.202324504715,2023-03-14
10 | 9,Marca 9,3059.4700354963657,2023-03-14
11 | 10,Marca 10,4538.066571470171,2023-03-14
12 |
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/resources/config.properties:
--------------------------------------------------------------------------------
1 | nombre=Pepe
2 | edad=20
3 | curso.modulo=Programacion
--------------------------------------------------------------------------------
/Ejemplos/Ficheros-Kotlin/src/main/resources/data/fichero-texto.txt:
--------------------------------------------------------------------------------
1 | Hola
2 | Esto es
3 | un fichero de texto
4 |
5 |
--------------------------------------------------------------------------------
/Ejemplos/FicherosDirectorios/.gitignore:
--------------------------------------------------------------------------------
1 | /out
2 | /fichero.txt
--------------------------------------------------------------------------------
/Ejemplos/FicherosDirectorios/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/Ejemplos/FicherosDirectorios/.idea/description.html:
--------------------------------------------------------------------------------
1 | Simple Java application that includes a class with main()
method
--------------------------------------------------------------------------------
/Ejemplos/FicherosDirectorios/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/FicherosDirectorios/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Ejemplos/FicherosDirectorios/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Ejemplos/FicherosDirectorios/.idea/project-template.xml:
--------------------------------------------------------------------------------
1 |
2 | IJ_BASE_PACKAGE
3 |
--------------------------------------------------------------------------------
/Ejemplos/FicherosDirectorios/.idea/runConfigurations.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/Ejemplos/FicherosDirectorios/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/FicherosDirectorios/06-FicherosDirectorios.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/.idea/description.html:
--------------------------------------------------------------------------------
1 | Simple Java application that includes a class with main()
method
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/.idea/libraries/Maven__com_google_code_gson_gson_2_9_0.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/.idea/project-template.xml:
--------------------------------------------------------------------------------
1 |
2 | IJ_BASE_PACKAGE
3 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/Pokedex.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | groupId
8 | Pokedex
9 | 1.0-SNAPSHOT
10 |
11 |
12 | 11
13 | 11
14 |
15 |
16 |
17 |
18 |
19 | com.google.code.gson
20 | gson
21 | 2.9.0
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/src/main/java/es/joseluisgs/dam/Main.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.GsonBuilder;
5 | import es.joseluisgs.dam.controllers.PokemonController;
6 | import es.joseluisgs.dam.models.Pokemon;
7 |
8 | /**
9 | * https://freecodegenerators.com/code-converters/json-to-pojo
10 | */
11 | public class Main {
12 |
13 | public static void main(String[] args) {
14 | System.out.println("Hello Pokedex!");
15 | var pokeController = PokemonController.getInstance();
16 | var pokemon = pokeController.getPokemon(24);
17 | printPokemon(pokemon);
18 | printPokemonJson(pokemon);
19 | }
20 |
21 | private static void printPokemon(Pokemon pokemon) {
22 | System.out.println(pokemon);
23 | }
24 |
25 | private static void printPokemonJson(Pokemon pokemon) {
26 | Gson gson = new GsonBuilder().setPrettyPrinting().create();
27 | System.out.println(gson.toJson(pokemon));
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/src/main/java/es/joseluisgs/dam/controllers/PokemonController.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.controllers;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.GsonBuilder;
5 | import com.google.gson.reflect.TypeToken;
6 | import es.joseluisgs.dam.models.Pokedex;
7 | import es.joseluisgs.dam.models.Pokemon;
8 |
9 | import java.io.File;
10 | import java.io.IOException;
11 | import java.io.Reader;
12 | import java.nio.file.Files;
13 | import java.nio.file.Path;
14 | import java.nio.file.Paths;
15 |
16 | public class PokemonController {
17 | private static PokemonController instance;
18 | private Pokedex pokedex;
19 |
20 | private PokemonController() {
21 | loadPokedex();
22 | }
23 |
24 | public static PokemonController getInstance() {
25 | if (instance == null) {
26 | instance = new PokemonController();
27 | }
28 | return instance;
29 | }
30 |
31 | private void loadPokedex() {
32 | Path currentRelativePath = Paths.get("");
33 | String ruta = currentRelativePath.toAbsolutePath().toString();
34 | String dir = ruta + File.separator + "data";
35 | String paisesFile = dir + File.separator + "pokemon.json";
36 | Gson gson = new GsonBuilder().setPrettyPrinting().create();
37 |
38 | Reader reader = null;
39 | try {
40 | reader = Files.newBufferedReader(Paths.get(paisesFile));
41 | this.pokedex = gson.fromJson(reader, new TypeToken() {
42 | }.getType());
43 | System.out.println("Pokedex loaded! There are: " + pokedex.pokemon.size());
44 | } catch (Exception e) {
45 | System.out.println("Error loading Pokedex!");
46 | System.out.println("Error: " + e.getMessage());
47 | } finally {
48 | if (reader != null) {
49 | try {
50 | reader.close();
51 | } catch (IOException e) {
52 | System.out.println("Error: " + e.getMessage());
53 | }
54 | }
55 | }
56 | }
57 |
58 | public Pokemon getPokemon(int index) {
59 | return pokedex.pokemon.get(index);
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/src/main/java/es/joseluisgs/dam/models/NextEvolution.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.models;
2 |
3 | public class NextEvolution {
4 | public String num;
5 | public String name;
6 |
7 | @Override
8 | public String toString() {
9 | return "NextEvolution{" +
10 | "num='" + num + '\'' +
11 | ", name='" + name + '\'' +
12 | '}';
13 | }
14 | }
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/src/main/java/es/joseluisgs/dam/models/Pokedex.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.models;
2 |
3 | import java.util.ArrayList;
4 |
5 | public class Pokedex {
6 | public ArrayList pokemon;
7 | }
8 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/src/main/java/es/joseluisgs/dam/models/Pokemon.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.models;
2 |
3 |
4 | import java.util.ArrayList;
5 |
6 | public class Pokemon {
7 | public int id;
8 | public String num;
9 | public String name;
10 | public String img;
11 | public ArrayList type;
12 | public String height;
13 | public String weight;
14 | public String candy;
15 | public int candy_count;
16 | public String egg;
17 | public double spawn_chance;
18 | public double avg_spawns;
19 | public String spawn_time;
20 | public ArrayList multipliers;
21 | public ArrayList weaknesses;
22 | public ArrayList next_evolution;
23 | public ArrayList prev_evolution;
24 |
25 | @Override
26 | public String toString() {
27 | return "Pokemon{" +
28 | "id=" + id +
29 | ", num='" + num + '\'' +
30 | ", name='" + name + '\'' +
31 | ", img='" + img + '\'' +
32 | ", type=" + type +
33 | ", height='" + height + '\'' +
34 | ", weight='" + weight + '\'' +
35 | ", candy='" + candy + '\'' +
36 | ", candy_count=" + candy_count +
37 | ", egg='" + egg + '\'' +
38 | ", spawn_chance=" + spawn_chance +
39 | ", avg_spawns=" + avg_spawns +
40 | ", spawn_time='" + spawn_time + '\'' +
41 | ", multipliers=" + multipliers +
42 | ", weaknesses=" + weaknesses +
43 | ", next_evolution=" + next_evolution +
44 | ", prev_evolution=" + prev_evolution +
45 | '}';
46 | }
47 | }
48 |
49 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Java/src/main/java/es/joseluisgs/dam/models/PrevEvolution.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.models;
2 |
3 | public class PrevEvolution {
4 | public String num;
5 | public String name;
6 |
7 | @Override
8 | public String toString() {
9 | return "PrevEvolution{" + "num=" + num + ", name=" + name + '}';
10 | }
11 | }
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | build/
3 | !gradle/wrapper/gradle-wrapper.jar
4 | !**/src/main/**/build/
5 | !**/src/test/**/build/
6 |
7 | ### IntelliJ IDEA ###
8 | .idea/modules.xml
9 | .idea/jarRepositories.xml
10 | .idea/compiler.xml
11 | .idea/libraries/
12 | *.iws
13 | *.iml
14 | *.ipr
15 | out/
16 | !**/src/main/**/out/
17 | !**/src/test/**/out/
18 |
19 | ### Eclipse ###
20 | .apt_generated
21 | .classpath
22 | .factorypath
23 | .project
24 | .settings
25 | .springBeans
26 | .sts4-cache
27 | bin/
28 | !**/src/main/**/bin/
29 | !**/src/test/**/bin/
30 |
31 | ### NetBeans ###
32 | /nbproject/private/
33 | /nbbuild/
34 | /dist/
35 | /nbdist/
36 | /.nb-gradle/
37 |
38 | ### VS Code ###
39 | .vscode/
40 |
41 | ### Mac OS ###
42 | .DS_Store
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | kotlin("jvm") version "1.8.0"
3 | application
4 | }
5 |
6 | group = "es.joseluisgs"
7 | version = "1.0-SNAPSHOT"
8 |
9 | repositories {
10 | mavenCentral()
11 | }
12 |
13 | dependencies {
14 | // Logger
15 | implementation("ch.qos.logback:logback-classic:1.4.5")
16 | implementation("io.github.microutils:kotlin-logging-jvm:3.0.4")
17 |
18 | // Moshi
19 | implementation("com.squareup.moshi:moshi:1.14.0")
20 | implementation("com.squareup.moshi:moshi-kotlin:1.14.0")
21 | implementation("com.squareup.moshi:moshi-adapters:1.14.0")
22 |
23 | // test
24 | testImplementation(kotlin("test"))
25 | }
26 |
27 | tasks.test {
28 | useJUnitPlatform()
29 | }
30 |
31 | kotlin {
32 | jvmToolchain(8)
33 | }
34 |
35 | application {
36 | mainClass.set("MainKt")
37 | }
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
2 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Pokedex-Kotlin/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/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 execute
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 execute
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 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/settings.gradle.kts:
--------------------------------------------------------------------------------
1 |
2 | rootProject.name = "Pokedex-Kotlin"
3 |
4 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/src/main/kotlin/Exceptions/PokemonException.kt:
--------------------------------------------------------------------------------
1 | package Exceptions
2 |
3 | sealed class PokedexException(message: String) : Exception(message)
4 | class PokemonNotFound(message: String) : PokedexException(message)
5 | class PokemonAlreadyExists(message: String) : PokedexException(message)
6 | class PokemonNotValid(message: String) : PokedexException(message)
7 | class PokemonInvalid(message: String) : PokedexException(message)
8 |
9 | class PokedexFileNotFound(message: String) : PokedexException(message)
10 | class PokedexParserError(message: String) : PokedexException(message)
11 |
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/src/main/kotlin/models/NextEvolution.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class NextEvolution(
7 | @Json(name = "name")
8 | val name: String = "",
9 | @Json(name = "num")
10 | val num: String = ""
11 | )
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/src/main/kotlin/models/Pokedex.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class Pokedex(
7 | @Json(name = "pokemon")
8 | val pokemon: List = listOf()
9 | )
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/src/main/kotlin/models/Pokemon.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class Pokemon(
7 | @Json(name = "avg_spawns")
8 | val avgSpawns: Double = 0.0,
9 | @Json(name = "candy")
10 | val candy: String = "",
11 | @Json(name = "candy_count")
12 | val candyCount: Int? = null,
13 | @Json(name = "egg")
14 | val egg: String = "",
15 | @Json(name = "height")
16 | val height: String = "",
17 | @Json(name = "id")
18 | val id: Int = 0,
19 | @Json(name = "img")
20 | val img: String = "",
21 | @Json(name = "multipliers")
22 | val multipliers: List? = null,
23 | @Json(name = "name")
24 | val name: String = "",
25 | @Json(name = "next_evolution")
26 | val nextEvolution: List? = null,
27 | @Json(name = "num")
28 | val num: String = "",
29 | @Json(name = "prev_evolution")
30 | val prevEvolution: List? = null,
31 | @Json(name = "spawn_chance")
32 | val spawnChance: Double = 0.0,
33 | @Json(name = "spawn_time")
34 | val spawnTime: String = "",
35 | @Json(name = "type")
36 | val type: List = listOf(),
37 | @Json(name = "weaknesses")
38 | val weaknesses: List = listOf(),
39 | @Json(name = "weight")
40 | val weight: String = ""
41 | )
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/src/main/kotlin/models/PrevEvolution.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 |
4 | import com.squareup.moshi.Json
5 |
6 | data class PrevEvolution(
7 | @Json(name = "name")
8 | val name: String = "",
9 | @Json(name = "num")
10 | val num: String = ""
11 | )
--------------------------------------------------------------------------------
/Ejemplos/Pokedex-Kotlin/src/main/kotlin/repositories/PokedexRepository.kt:
--------------------------------------------------------------------------------
1 | package repositories
2 |
3 | import Exceptions.PokedexFileNotFound
4 | import Exceptions.PokedexParserError
5 | import com.squareup.moshi.Moshi
6 | import com.squareup.moshi.adapter
7 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
8 | import models.Pokedex
9 | import models.Pokemon
10 | import mu.KotlinLogging
11 |
12 | private val logger = KotlinLogging.logger {}
13 |
14 | @OptIn(ExperimentalStdlibApi::class)
15 | class PokedexRepository {
16 | // Lista de pokemons
17 |
18 | // Backin properties: https://kotlinlang.org/docs/properties.html#backing-properties
19 | private val _pokemons = mutableListOf()
20 | val pokemons: List get() = _pokemons
21 |
22 | init {
23 | logger.debug { "Inicializando Pokedex" }
24 |
25 | // Fichero JSON de Resources
26 | val pokemonFile = PokedexRepository::class.java.getResourceAsStream("/pokemon.json")
27 | ?: throw PokedexFileNotFound("Error al cargar el JSON o el fichero no existe")
28 |
29 | // Cargamos Moshi
30 | val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
31 | val jsonAdapter = moshi.adapter()
32 | val pokedex = jsonAdapter.fromJson(pokemonFile.bufferedReader().readText())
33 | ?: throw PokedexParserError("Error al parsear el JSON de Pokedex")
34 |
35 |
36 | // Cargamos los pokemons
37 | _pokemons.addAll(pokedex.pokemon)
38 |
39 | logger.debug { "Pokedex cargada con: ${pokemons.size} pokemons" }
40 |
41 | }
42 |
43 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | build/
3 | !gradle/wrapper/gradle-wrapper.jar
4 | !**/src/main/**/build/
5 | !**/src/test/**/build/
6 |
7 | ### IntelliJ IDEA ###
8 | .idea/modules.xml
9 | .idea/jarRepositories.xml
10 | .idea/compiler.xml
11 | .idea/libraries/
12 | *.iws
13 | *.iml
14 | *.ipr
15 | out/
16 | !**/src/main/**/out/
17 | !**/src/test/**/out/
18 |
19 | ### Eclipse ###
20 | .apt_generated
21 | .classpath
22 | .factorypath
23 | .project
24 | .settings
25 | .springBeans
26 | .sts4-cache
27 | bin/
28 | !**/src/main/**/bin/
29 | !**/src/test/**/bin/
30 |
31 | ### NetBeans ###
32 | /nbproject/private/
33 | /nbbuild/
34 | /dist/
35 | /nbdist/
36 | /.nb-gradle/
37 |
38 | ### VS Code ###
39 | .vscode/
40 |
41 | ### Mac OS ###
42 | .DS_Store
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/.idea/.name:
--------------------------------------------------------------------------------
1 | Productos-Carrito
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | kotlin("jvm") version "1.8.0"
3 | application
4 | }
5 |
6 | group = "es.joseluisgs"
7 | version = "1.0-SNAPSHOT"
8 |
9 | repositories {
10 | mavenCentral()
11 | }
12 |
13 | dependencies {
14 | // Logger
15 | implementation("ch.qos.logback:logback-classic:1.4.5")
16 | implementation("io.github.microutils:kotlin-logging-jvm:3.0.4")
17 |
18 | // Moshi
19 | implementation("com.squareup.moshi:moshi:1.14.0")
20 | implementation("com.squareup.moshi:moshi-kotlin:1.14.0")
21 | implementation("com.squareup.moshi:moshi-adapters:1.14.0")
22 |
23 | // Simple XML
24 | implementation("org.simpleframework:simple-xml:2.7.1")
25 |
26 | // Test con JUnit 5 básico
27 | testImplementation(kotlin("test"))
28 | }
29 |
30 | tasks.test {
31 | useJUnitPlatform()
32 | }
33 |
34 | kotlin {
35 | jvmToolchain(8)
36 | }
37 |
38 | application {
39 | mainClass.set("MainKt")
40 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/data/productos.bin:
--------------------------------------------------------------------------------
1 | 2
2 | Producto E
3 | 97.6058844458666
4 | 17
5 | 2023-03-09
6 | 2023-03-09
7 | true
8 | 3
9 | Producto W
10 | 98.77939052053726
11 | 20
12 | 2023-03-09
13 | 2023-03-09
14 | true
15 | 4
16 | Producto Q
17 | 3.0880581101567186
18 | 42
19 | 2023-03-09
20 | 2023-03-09
21 | true
22 | 5
23 | Producto K
24 | 38.42476422304463
25 | 39
26 | 2023-03-09
27 | 2023-03-09
28 | true
29 | 6
30 | Producto H
31 | 18.52944947904237
32 | 43
33 | 2023-03-09
34 | 2023-03-09
35 | true
36 | 7
37 | Producto X
38 | 66.76513105494699
39 | 36
40 | 2023-03-09
41 | 2023-03-09
42 | true
43 | 8
44 | Producto P
45 | 63.44182513564735
46 | 39
47 | 2023-03-09
48 | 2023-03-09
49 | true
50 | 9
51 | Producto Z
52 | 40.441615027928705
53 | 37
54 | 2023-03-09
55 | 2023-03-09
56 | true
57 | 10
58 | Producto T
59 | 90.51662397641229
60 | 26
61 | 2023-03-09
62 | 2023-03-09
63 | true
64 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/data/productos.csv:
--------------------------------------------------------------------------------
1 | id,nombre,precio,cantidad,createdAt,updatedAt,disponible
2 | 2,Producto M,37.45055810239127,26,2023-03-17,2023-03-17,true
3 | 3,Producto M,53.090393711411735,11,2023-03-17,2023-03-17,true
4 | 4,Producto O,10.293439461887663,43,2023-03-17,2023-03-17,true
5 | 5,Producto U,50.39657547369932,26,2023-03-17,2023-03-17,true
6 | 6,Producto Q,54.03556666011682,14,2023-03-17,2023-03-17,true
7 | 7,Producto E,58.1055733524528,17,2023-03-17,2023-03-17,true
8 | 8,Producto A,41.92715537853899,18,2023-03-17,2023-03-17,true
9 | 9,Producto Y,70.28438647300885,45,2023-03-17,2023-03-17,true
10 | 10,Producto R,77.43546348987675,11,2023-03-17,2023-03-17,true
11 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/data/productos.dat:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Productos-Ventas-Ficheros/data/productos.dat
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/data/productos.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": 2,
4 | "nombre": "Producto O",
5 | "precio": 58.462588110854064,
6 | "cantidad": 30,
7 | "created_at": "2023-03-23",
8 | "updated_at": "2023-03-23",
9 | "disponible": true
10 | },
11 | {
12 | "id": 3,
13 | "nombre": "Producto M",
14 | "precio": 83.14279873572501,
15 | "cantidad": 7,
16 | "created_at": "2023-03-23",
17 | "updated_at": "2023-03-23",
18 | "disponible": true
19 | },
20 | {
21 | "id": 4,
22 | "nombre": "Producto S",
23 | "precio": 81.77069338991755,
24 | "cantidad": 7,
25 | "created_at": "2023-03-23",
26 | "updated_at": "2023-03-23",
27 | "disponible": true
28 | },
29 | {
30 | "id": 5,
31 | "nombre": "Producto N",
32 | "precio": 35.71029288156706,
33 | "cantidad": 28,
34 | "created_at": "2023-03-23",
35 | "updated_at": "2023-03-23",
36 | "disponible": true
37 | },
38 | {
39 | "id": 6,
40 | "nombre": "Producto U",
41 | "precio": 60.16243092516715,
42 | "cantidad": 19,
43 | "created_at": "2023-03-23",
44 | "updated_at": "2023-03-23",
45 | "disponible": true
46 | },
47 | {
48 | "id": 7,
49 | "nombre": "Producto N",
50 | "precio": 17.192200465116983,
51 | "cantidad": 31,
52 | "created_at": "2023-03-23",
53 | "updated_at": "2023-03-23",
54 | "disponible": true
55 | },
56 | {
57 | "id": 8,
58 | "nombre": "Producto O",
59 | "precio": 49.070942609774285,
60 | "cantidad": 44,
61 | "created_at": "2023-03-23",
62 | "updated_at": "2023-03-23",
63 | "disponible": true
64 | },
65 | {
66 | "id": 9,
67 | "nombre": "Producto L",
68 | "precio": 27.959834133270366,
69 | "cantidad": 11,
70 | "created_at": "2023-03-23",
71 | "updated_at": "2023-03-23",
72 | "disponible": true
73 | },
74 | {
75 | "id": 10,
76 | "nombre": "Producto R",
77 | "precio": 27.956989408326823,
78 | "cantidad": 19,
79 | "created_at": "2023-03-23",
80 | "updated_at": "2023-03-23",
81 | "disponible": true
82 | }
83 | ]
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/data/productos.ser:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Productos-Ventas-Ficheros/data/productos.ser
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/data/productos.txt:
--------------------------------------------------------------------------------
1 | 2
2 | Producto K
3 | 80.39567464332154
4 | 20
5 | 2023-03-09
6 | 2023-03-09
7 | true
8 | 3
9 | Producto Y
10 | 10.398909453724032
11 | 26
12 | 2023-03-09
13 | 2023-03-09
14 | true
15 | 4
16 | Producto O
17 | 93.91937099899799
18 | 37
19 | 2023-03-09
20 | 2023-03-09
21 | true
22 | 5
23 | Producto L
24 | 78.05922106006774
25 | 10
26 | 2023-03-09
27 | 2023-03-09
28 | true
29 | 6
30 | Producto K
31 | 76.50692381153938
32 | 24
33 | 2023-03-09
34 | 2023-03-09
35 | true
36 | 7
37 | Producto O
38 | 11.558869770369563
39 | 30
40 | 2023-03-09
41 | 2023-03-09
42 | true
43 | 8
44 | Producto M
45 | 96.23191080618167
46 | 16
47 | 2023-03-09
48 | 2023-03-09
49 | true
50 | 9
51 | Producto X
52 | 76.82975644026625
53 | 11
54 | 2023-03-09
55 | 2023-03-09
56 | true
57 | 10
58 | Producto R
59 | 32.08067097719504
60 | 31
61 | 2023-03-09
62 | 2023-03-09
63 | true
64 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/data/productos.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | Producto D
4 | 66.64001582446407
5 | 29
6 | 2023-03-23
7 | 2023-03-23
8 |
9 |
10 | Producto J
11 | 58.27697437577439
12 | 27
13 | 2023-03-23
14 | 2023-03-23
15 |
16 |
17 | Producto Z
18 | 26.205508826401104
19 | 42
20 | 2023-03-23
21 | 2023-03-23
22 |
23 |
24 | Producto W
25 | 22.756253195244412
26 | 50
27 | 2023-03-23
28 | 2023-03-23
29 |
30 |
31 | Producto Z
32 | 3.874355758178868
33 | 39
34 | 2023-03-23
35 | 2023-03-23
36 |
37 |
38 | Producto D
39 | 60.98566700580791
40 | 19
41 | 2023-03-23
42 | 2023-03-23
43 |
44 |
45 | Producto T
46 | 48.5607779863225
47 | 10
48 | 2023-03-23
49 | 2023-03-23
50 |
51 |
52 | Producto K
53 | 34.25139075415871
54 | 12
55 | 2023-03-23
56 | 2023-03-23
57 |
58 |
59 | Producto D
60 | 41.1937086395136
61 | 31
62 | 2023-03-23
63 | 2023-03-23
64 |
65 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/data/ventas.csv:
--------------------------------------------------------------------------------
1 | id,user_id,lineas,createdAt,updatedAt,total,total_items
2 | 1,1,[1;1;4;2;10.293439461887663;20.586878923775327|1;2;2;3;37.45055810239127;112.35167430717381|1;3;3;4;53.090393711411735;212.36157484564694],2023-03-17,2023-03-17,345.3001280765961,9
3 | 2,1,[2;1;4;2;10.293439461887663;20.586878923775327|2;2;2;3;37.45055810239127;112.35167430717381|2;3;3;4;53.090393711411735;212.36157484564694],2023-03-17,2023-03-17,345.3001280765961,9
4 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/data/ventas.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "id": 1,
4 | "userId": 1,
5 | "lineas": [
6 | {
7 | "idVenta": 1,
8 | "idLineaVenta": 1,
9 | "idProducto": 4,
10 | "cantidad": 2,
11 | "precioProducto": 81.77069338991755
12 | },
13 | {
14 | "idVenta": 1,
15 | "idLineaVenta": 2,
16 | "idProducto": 2,
17 | "cantidad": 3,
18 | "precioProducto": 58.462588110854064
19 | },
20 | {
21 | "idVenta": 1,
22 | "idLineaVenta": 3,
23 | "idProducto": 3,
24 | "cantidad": 4,
25 | "precioProducto": 83.14279873572501
26 | }
27 | ],
28 | "createdAt": "2023-03-23",
29 | "updatedAt": "2023-03-23"
30 | },
31 | {
32 | "id": 2,
33 | "userId": 1,
34 | "lineas": [
35 | {
36 | "idVenta": 2,
37 | "idLineaVenta": 1,
38 | "idProducto": 4,
39 | "cantidad": 2,
40 | "precioProducto": 81.77069338991755
41 | },
42 | {
43 | "idVenta": 2,
44 | "idLineaVenta": 2,
45 | "idProducto": 2,
46 | "cantidad": 3,
47 | "precioProducto": 58.462588110854064
48 | },
49 | {
50 | "idVenta": 2,
51 | "idLineaVenta": 3,
52 | "idProducto": 3,
53 | "cantidad": 4,
54 | "precioProducto": 83.14279873572501
55 | }
56 | ],
57 | "createdAt": "2023-03-23",
58 | "updatedAt": "2023-03-23"
59 | }
60 | ]
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/data/ventas.ser:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Productos-Ventas-Ficheros/data/ventas.ser
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/data/ventas.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
2 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Productos-Ventas-Ficheros/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/settings.gradle.kts:
--------------------------------------------------------------------------------
1 |
2 | rootProject.name = "Productos-Carrito"
3 |
4 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/Main.kt:
--------------------------------------------------------------------------------
1 | import config.AppConfig
2 | import controllers.ProductosController
3 | import controllers.VentasController
4 | import factories.productoRandom
5 | import models.User
6 | import mu.KotlinLogging
7 | import repositories.productos.ProductosRepositoryMap
8 | import repositories.ventas.VentasRepositoryMap
9 | import services.storage.productos.ProductosFicheroXmlService
10 | import services.storage.ventas.VentasFicheroXmlService
11 |
12 | private val logger = KotlinLogging.logger {}
13 |
14 | @ExperimentalStdlibApi
15 | fun main(args: Array) {
16 | println("Hola Carro de Compra")
17 |
18 | // Leemos la configuración de la aplicación
19 | println("APP_NAME: ${AppConfig.APP_NAME}")
20 |
21 | // Inyectamos dependencias
22 | val productosRepository = ProductosRepositoryMap(ProductosFicheroXmlService)
23 | val ventasRepository = VentasRepositoryMap(VentasFicheroXmlService)
24 |
25 | val productosController = ProductosController(productosRepository)
26 | val carritoController = VentasController(ventasRepository, productosRepository)
27 |
28 | repeat(10) {
29 | productosController.save(productoRandom())
30 | }
31 |
32 | println("Productos disponibles")
33 | productosController.findAll().forEach { println(it.toLocalString()) }
34 | println()
35 |
36 | println("Producto con id 1")
37 | productosController.findById(1).also { println(it.toLocalString()) }
38 | println()
39 |
40 | println("Producto con id 100")
41 | try {
42 | productosController.findById(100).also { println(it.toLocalString()) }
43 | } catch (e: Exception) {
44 | println("ERROR: ${e.message}")
45 | }
46 | println()
47 |
48 | println("Productos con nombre 'a'")
49 | productosController.findByNombre("a").forEach { println(it.toLocalString()) }
50 | println()
51 |
52 | println("Borrar producto con id 1")
53 | productosController.deleteById(1).also { println(it.toLocalString()) }
54 | println()
55 |
56 |
57 | println("Productos disponibles")
58 | println(productosController.findAll().count())
59 | println()
60 | productosController.findAll().forEach { println(it.toLocalString()) }
61 |
62 | println()
63 | println("Prueba Venta")
64 | val user = User(1, "Juan", "juan@juan.com", "123456")
65 | val items = mapOf(4 to 2, 2 to 3, 3 to 4)
66 | var venta = carritoController.save(user.id, items)
67 | println(venta.toLocalString())
68 | venta = carritoController.save(user.id, items)
69 | println()
70 | //println(venta.toLocalString())
71 | venta = carritoController.findById(2)
72 | println(venta.toLocalString())
73 |
74 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/config/AppConfig.kt:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import mu.KotlinLogging
4 | import java.io.File
5 | import java.nio.file.Files
6 | import java.nio.file.Paths
7 | import java.util.*
8 |
9 |
10 | private val logger = KotlinLogging.logger {}
11 |
12 | private val LOCAL_PATH = "${System.getProperty("user.dir")}${File.separator}"
13 |
14 | object AppConfig {
15 | val APP_NAME = "Kotlin Productos Ventas"
16 | val APP_VERSION = "1.0.0"
17 | lateinit var APP_AUTHOR: String
18 | lateinit var APP_DATA: String
19 |
20 |
21 | init {
22 | loadProperties()
23 | initStorage()
24 | }
25 |
26 | private fun initStorage() {
27 | // Crear el directorio data si no existe
28 | logger.debug { "Creando directorio data si no existe" }
29 | Files.createDirectories(Paths.get(APP_DATA))
30 | }
31 |
32 | private fun loadProperties() {
33 | logger.debug { "Cargando configuración de la aplicación" }
34 | val properties = Properties()
35 | properties.load(AppConfig::class.java.getResourceAsStream("/config.properties"))
36 | // properties.load(ClassLoader.getSystemResourceAsStream("/config.properties")) --> Aquí falla!!
37 | /*properties.forEach { (key, value) ->
38 | logger.debug { "Configuración: $key = $value" }
39 | }*/
40 | APP_AUTHOR = properties.getProperty("app.author") ?: "1DAM"
41 | APP_DATA = properties.getProperty("app.storage.dir") ?: "data"
42 | APP_DATA = "$LOCAL_PATH$APP_DATA"
43 |
44 | logger.debug { "Configuración: app.author = $APP_AUTHOR" }
45 | logger.debug { "Configuración: app.storage.dir = $APP_DATA" }
46 | }
47 |
48 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/controllers/ProductosController.kt:
--------------------------------------------------------------------------------
1 | package controllers
2 |
3 | import exceptions.ProductoNoEncontradoException
4 | import models.Producto
5 | import mu.KotlinLogging
6 | import repositories.productos.ProductosRepository
7 | import validators.validar
8 |
9 | private val logger = KotlinLogging.logger {}
10 |
11 | class ProductosController(
12 | private val productosRepository: ProductosRepository
13 | ) {
14 | fun findAll(disponible: Boolean = true): List {
15 | logger.info { "findAll: $disponible" }
16 | return productosRepository.findAllByDisponible(disponible)
17 | }
18 |
19 | fun findById(id: Int): Producto {
20 | logger.info { "findById: $id" }
21 | return productosRepository.findById(id)
22 | ?: throw ProductoNoEncontradoException("Producto con $id no existe en almacenamiento")
23 | }
24 |
25 | fun findByNombre(nombre: String): List {
26 | logger.info { "findByNombre: $nombre" }
27 | return productosRepository.findByNombre(nombre)
28 | }
29 |
30 | fun save(producto: Producto): Producto {
31 | logger.info { "save: $producto" }
32 | producto.validar() // Validar el producto
33 | return productosRepository.save(producto)
34 | }
35 |
36 | fun update(producto: Producto): Producto {
37 | logger.info { "update: $producto" }
38 | producto.validar() // Validar el producto
39 | return productosRepository.update(producto)
40 | ?: throw ProductoNoEncontradoException("Producto con ${producto.id} no existe en almacenamiento")
41 | }
42 |
43 | fun deleteById(id: Int): Producto {
44 | logger.info { "deleteById: $id" }
45 | return productosRepository.deleteById(id)
46 | ?: throw ProductoNoEncontradoException("Producto con $id no existe en almacenamiento")
47 | }
48 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/dto/LineaVentaDto.kt:
--------------------------------------------------------------------------------
1 | package dto
2 |
3 | import org.simpleframework.xml.Attribute
4 | import org.simpleframework.xml.Root
5 |
6 | @Root(name = "linea_venta")
7 | data class LineaVentaDto(
8 |
9 | @field:Attribute(name = "id_venta")
10 | @param:Attribute(name = "id_venta")
11 | val idVenta: Int,
12 |
13 | @field:Attribute(name = "id_linea_venta")
14 | @param:Attribute(name = "id_linea_venta")
15 | val idLineaVenta: Int,
16 |
17 | @field:Attribute(name = "id_producto")
18 | @param:Attribute(name = "id_producto")
19 | val idProducto: Int,
20 |
21 | @field:Attribute(name = "cantidad")
22 | @param:Attribute(name = "cantidad")
23 | val cantidad: Int,
24 |
25 | @field:Attribute(name = "precio_producto")
26 | @param:Attribute(name = "precio_producto")
27 | val precioProducto: Double
28 | )
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/dto/ProductoDto-foxhound.kt:
--------------------------------------------------------------------------------
1 | package dto
2 |
3 | import org.simpleframework.xml.Attribute
4 | import org.simpleframework.xml.Element
5 | import org.simpleframework.xml.ElementList
6 | import org.simpleframework.xml.Root
7 | import java.time.LocalDate
8 |
9 | @Root(name = "producto")
10 | data class ProductoDto(
11 | @field:Attribute(name = "id")
12 | @param:Attribute(name = "id")
13 | val id: Int = 0,
14 |
15 | @field:Element(name = "nombre")
16 | @param:Element(name = "nombre")
17 | val nombre: String = "",
18 |
19 | @field:Element(name = "precio")
20 | @param:Element(name = "precio")
21 | val precio: Double = 0.0,
22 |
23 | @field:Element(name = "cantidad")
24 | @param:Element(name = "cantidad")
25 | val cantidad: Int = 0,
26 |
27 | @field:Element(name = "created_at")
28 | @param:Element(name = "created_at")
29 | val createdAt: String = LocalDate.now().toString(),
30 |
31 | @field:Element(name = "updated_at")
32 | @param:Element(name = "updated_at")
33 | val updatedAt: String = LocalDate.now().toString(),
34 |
35 | @field:Attribute(name = "disponible")
36 | @param:Attribute(name = "disponible")
37 | val disponible: Boolean = true,
38 | )
39 |
40 | @Root(name = "productos")
41 | data class ProductosListDto(
42 | @field:ElementList(name = "productos", inline = true)
43 | @param:ElementList(name = "productos", inline = true)
44 | val productos: List
45 | )
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/dto/ProductoDto.kt:
--------------------------------------------------------------------------------
1 | package dto
2 |
3 | import org.simpleframework.xml.Attribute
4 | import org.simpleframework.xml.Element
5 | import org.simpleframework.xml.ElementList
6 | import org.simpleframework.xml.Root
7 | import java.time.LocalDate
8 |
9 | @Root(name = "producto")
10 | data class ProductoDto(
11 | @field:Attribute(name = "id")
12 | @param:Attribute(name = "id")
13 | val id: Int = 0,
14 |
15 | @field:Element(name = "nombre")
16 | @param:Element(name = "nombre")
17 | val nombre: String = "",
18 |
19 | @field:Element(name = "precio")
20 | @param:Element(name = "precio")
21 | val precio: Double = 0.0,
22 |
23 | @field:Element(name = "cantidad")
24 | @param:Element(name = "cantidad")
25 | val cantidad: Int = 0,
26 |
27 | @field:Element(name = "created_at")
28 | @param:Element(name = "created_at")
29 | val createdAt: String = LocalDate.now().toString(),
30 |
31 | @field:Element(name = "updated_at")
32 | @param:Element(name = "updated_at")
33 | val updatedAt: String = LocalDate.now().toString(),
34 |
35 | @field:Attribute(name = "disponible")
36 | @param:Attribute(name = "disponible")
37 | val disponible: Boolean = true,
38 | )
39 |
40 | @Root(name = "productos")
41 | data class ProductosListDto(
42 | @field:ElementList(name = "productos", inline = true)
43 | @param:ElementList(name = "productos", inline = true)
44 | val productos: List
45 | )
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/dto/VentaDto-foxhound.kt:
--------------------------------------------------------------------------------
1 | package dto
2 |
3 | import org.simpleframework.xml.Attribute
4 | import org.simpleframework.xml.ElementList
5 | import org.simpleframework.xml.Root
6 | import java.time.LocalDate
7 |
8 | @Root(name = "venta")
9 | data class VentaDto(
10 | @field:Attribute(name = "id")
11 | @param:Attribute(name = "id")
12 | val id: Int = 0,
13 |
14 | @field:Attribute(name = "user_id")
15 | @param:Attribute(name = "user_id")
16 | val userId: Int,
17 |
18 | @field:ElementList(name = "lineas", inline = true)
19 | @param:ElementList(name = "lineas", inline = true)
20 | val lineas: List = emptyList(),
21 |
22 | @field:Attribute(name = "created_at")
23 | @param:Attribute(name = "created_at")
24 | val createdAt: String = LocalDate.now().toString(),
25 |
26 | @field:Attribute(name = "updated_at")
27 | @param:Attribute(name = "updated_at")
28 | val updatedAt: String = LocalDate.now().toString()
29 | )
30 |
31 | @Root(name = "ventas")
32 | data class VentasListDto(
33 | @field:ElementList(name = "ventas", inline = true)
34 | @param:ElementList(name = "ventas", inline = true)
35 | val ventas: List
36 | )
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/dto/VentaDto.kt:
--------------------------------------------------------------------------------
1 | package dto
2 |
3 | import org.simpleframework.xml.Attribute
4 | import org.simpleframework.xml.ElementList
5 | import org.simpleframework.xml.Root
6 | import java.time.LocalDate
7 |
8 | @Root(name = "venta")
9 | data class VentaDto(
10 | @field:Attribute(name = "id")
11 | @param:Attribute(name = "id")
12 | val id: Int = 0,
13 |
14 | @field:Attribute(name = "user_id")
15 | @param:Attribute(name = "user_id")
16 | val userId: Int,
17 |
18 | @field:ElementList(name = "lineas", inline = true)
19 | @param:ElementList(name = "lineas", inline = true)
20 | val lineas: List = emptyList(),
21 |
22 | @field:Attribute(name = "created_at")
23 | @param:Attribute(name = "created_at")
24 | val createdAt: String = LocalDate.now().toString(),
25 |
26 | @field:Attribute(name = "updated_at")
27 | @param:Attribute(name = "updated_at")
28 | val updatedAt: String = LocalDate.now().toString()
29 | )
30 |
31 | @Root(name = "ventas")
32 | data class VentasListDto(
33 | @field:ElementList(name = "ventas", inline = true)
34 | @param:ElementList(name = "ventas", inline = true)
35 | val ventas: List
36 | )
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/exceptions/ProductoException.kt:
--------------------------------------------------------------------------------
1 | package exceptions
2 |
3 | sealed class ProductoException(message: String) : Exception(message)
4 | class ProductoNoEncontradoException(message: String) : ProductoException("Producto no encontrado: $message")
5 | class ProductoNoDisponibleException(message: String) : ProductoException("Producto no disponible: $message")
6 | class ProductoNoValidoException(message: String) : ProductoException("Producto no valido: $message")
7 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/exceptions/VentaException.kt:
--------------------------------------------------------------------------------
1 | package exceptions
2 |
3 | sealed class VentaException(message: String) : Exception(message)
4 | class CarritoNoExisteException(id: Int) : VentaException("Carrito con $id no existe en almacenamiento")
5 | class CarritoNoGuardadoException(message: String) : VentaException("Carrito no guardado: $message")
6 | class CarritoNoValidoException(message: String) : VentaException("Carrito no valido: $message")
7 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/factories/ProductosFactory.kt:
--------------------------------------------------------------------------------
1 | package factories
2 |
3 | import models.Producto
4 | import kotlin.random.Random
5 |
6 | fun productoRandom(): Producto {
7 | return Producto(
8 | nombre = "Producto ${('A'..'Z').random()}",
9 | precio = Random.nextDouble(1.0, 100.0),
10 | cantidad = (10..50).random()
11 | )
12 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/locale/Locale.kt:
--------------------------------------------------------------------------------
1 | package locale
2 |
3 | import java.text.NumberFormat
4 | import java.time.LocalDate
5 | import java.time.format.DateTimeFormatter
6 | import java.time.format.FormatStyle
7 | import java.util.*
8 |
9 | fun LocalDate.toLocalDate(): String {
10 | return this.format(
11 | DateTimeFormatter
12 | .ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale("es", "ES"))
13 | )
14 | }
15 |
16 | fun LocalDate.toLocalDateTime(): String {
17 | return this.format(
18 | DateTimeFormatter
19 | .ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale("es", "ES"))
20 | )
21 | }
22 |
23 | fun Double.toLocalMoney(): String {
24 | return NumberFormat.getCurrencyInstance(Locale("es", "ES")).format(this)
25 | }
26 |
27 | fun Double.toLocalNumber(): String {
28 | return NumberFormat.getNumberInstance(Locale("es", "ES")).format(this)
29 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/mappers/ProductoMapper.kt:
--------------------------------------------------------------------------------
1 | package mappers
2 |
3 | import dto.ProductoDto
4 | import dto.ProductosListDto
5 | import models.Producto
6 | import java.time.LocalDate
7 |
8 | fun ProductoDto.toProducto() = Producto(
9 | id = id,
10 | nombre = nombre,
11 | precio = precio,
12 | cantidad = cantidad,
13 | createdAt = LocalDate.parse(createdAt),
14 | updatedAt = LocalDate.parse(updatedAt),
15 | disponible = disponible,
16 | )
17 |
18 | fun Producto.toProductoDto() = ProductoDto(
19 | id = id,
20 | nombre = nombre,
21 | precio = precio,
22 | cantidad = cantidad,
23 | createdAt = createdAt.toString(),
24 | updatedAt = updatedAt.toString(),
25 | disponible = disponible,
26 | )
27 |
28 | fun List.toDto() = ProductosListDto(
29 | productos = map { it.toProductoDto() }
30 | )
31 |
32 | fun ProductosListDto.toProductosList() = productos.map { it.toProducto() }
33 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/mappers/VentaMapper.kt:
--------------------------------------------------------------------------------
1 | package mappers
2 |
3 | import dto.LineaVentaDto
4 | import dto.VentaDto
5 | import dto.VentasListDto
6 | import models.LineaVenta
7 | import models.Venta
8 | import java.time.LocalDate
9 |
10 | fun LineaVenta.toLineaVentaDto() = LineaVentaDto(
11 | idVenta = this.idVenta,
12 | idLineaVenta = this.idLineaVenta,
13 | idProducto = this.idProducto,
14 | cantidad = this.cantidad,
15 | precioProducto = this.precioProducto
16 | )
17 |
18 | fun LineaVentaDto.toLineaVenta() = LineaVenta(
19 | idVenta = this.idVenta,
20 | idLineaVenta = this.idLineaVenta,
21 | idProducto = this.idProducto,
22 | cantidad = this.cantidad,
23 | precioProducto = this.precioProducto
24 | )
25 |
26 | fun Venta.toDto() = VentaDto(
27 | id = this.id,
28 | userId = this.userId,
29 | lineas = this.lineas.map { it.toLineaVentaDto() }.toList(),
30 | createdAt = this.createdAt.toString(),
31 | updatedAt = this.updatedAt.toString(),
32 | )
33 |
34 | fun VentaDto.toVenta() = Venta(
35 | id = this.id,
36 | userId = this.userId,
37 | lineas = this.lineas.map { it.toLineaVenta() }.toMutableList(),
38 | createdAt = LocalDate.parse(this.createdAt),
39 | updatedAt = LocalDate.parse(this.updatedAt),
40 | )
41 |
42 | fun List.toDto() = VentasListDto(
43 | ventas = map { it.toDto() }
44 | )
45 |
46 | fun VentasListDto.toVentasList() = ventas.map { it.toVenta() }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/models/LineaVenta.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 | import locale.toLocalMoney
4 | import java.io.Serializable
5 |
6 | data class LineaVenta(
7 | val idVenta: Int, // No la necesitamos porque no estamos guardando la linea en la BD
8 | val idLineaVenta: Int,
9 | val idProducto: Int,
10 | val cantidad: Int,
11 | val precioProducto: Double
12 | ) : Serializable {
13 | val total: Double
14 | get() = precioProducto * cantidad
15 |
16 | fun toLocalString(): String {
17 | return "LineaVenta(idLineaVenta=$idLineaVenta, idProducto=$idProducto, cantidad=$cantidad, precioProducto=${precioProducto.toLocalMoney()}, total=${total.toLocalMoney()})"
18 | }
19 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/models/Producto.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 | import com.squareup.moshi.Json
4 | import locale.toLocalDate
5 | import locale.toLocalMoney
6 | import java.io.Serializable
7 | import java.time.LocalDate
8 |
9 | data class Producto(
10 | val id: Int = 0,
11 | val nombre: String = "",
12 | val precio: Double = 0.0,
13 | val cantidad: Int = 0,
14 | @Json(name = "created_at")
15 | val createdAt: LocalDate = LocalDate.now(),
16 | @Json(name = "updated_at")
17 | val updatedAt: LocalDate = LocalDate.now(),
18 | val disponible: Boolean = true,
19 | ) : Serializable {
20 | fun toLocalString(): String {
21 | return "Producto(id=$id, nombre='$nombre', precio=${precio.toLocalMoney()}, cantidad=$cantidad, , disponible=$disponible, createdAt=${createdAt.toLocalDate()}, updatedAt=${updatedAt.toLocalDate()})"
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/models/User.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 | import java.time.LocalDate
4 |
5 | data class User(
6 | val id: Int,
7 | val name: String,
8 | val email: String,
9 | val password: String,
10 | val createdAt: LocalDate = LocalDate.now(),
11 | val updatedAt: LocalDate = LocalDate.now(),
12 | val role: Role = Role.USER
13 | ) {
14 | enum class Role {
15 | ADMIN, USER
16 | }
17 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/models/Venta.kt:
--------------------------------------------------------------------------------
1 | package models
2 |
3 | import locale.toLocalDate
4 | import locale.toLocalMoney
5 | import java.io.Serializable
6 | import java.time.LocalDate
7 |
8 | data class Venta(
9 | val id: Int = 0,
10 | val userId: Int,
11 | val lineas: MutableList = mutableListOf(),
12 | val createdAt: LocalDate = LocalDate.now(),
13 | val updatedAt: LocalDate = LocalDate.now(),
14 | ) : Serializable {
15 | val total: Double
16 | get() = lineas.sumOf { it.total }
17 |
18 | val totalItems: Int
19 | get() = lineas.sumOf { it.cantidad }
20 |
21 | val nextLineaId: Int
22 | get() {
23 | val id = lineas.maxByOrNull { it.idLineaVenta }?.idLineaVenta ?: 0
24 | return id + 1
25 | }
26 |
27 | fun addLinea(linea: LineaVenta) {
28 | lineas.add(linea)
29 | }
30 |
31 | fun removeLinea(idLineaCarrito: Int) {
32 | lineas.removeIf { it.idLineaVenta == idLineaCarrito }
33 | }
34 |
35 | fun toLocalString(): String {
36 | return "Venta(id=$id, userId=$userId, totalItems=$totalItems, total=${total.toLocalMoney()}, lineas=${
37 | lineas.joinToString(
38 | prefix = "[",
39 | postfix = "]"
40 | ) { it.toLocalString() }
41 | } , createdAt=${createdAt.toLocalDate()}, updatedAt=${updatedAt.toLocalDate()})"
42 | }
43 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/repositories/base/CrudRepository.kt:
--------------------------------------------------------------------------------
1 | package repositories.base
2 |
3 | interface CrudRepository {
4 | fun findAll(): List
5 | fun findById(id: ID): T?
6 | fun save(entity: T): T
7 | fun update(entity: T): T?
8 | fun deleteById(id: ID): T?
9 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/repositories/productos/ProductosRepository.kt:
--------------------------------------------------------------------------------
1 | package repositories.productos
2 |
3 | import models.Producto
4 | import repositories.base.CrudRepository
5 |
6 | interface ProductosRepository : CrudRepository {
7 | fun findAllByDisponible(disponible: Boolean): List
8 | fun findByNombre(nombre: String): List
9 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/repositories/ventas/VentasRepository.kt:
--------------------------------------------------------------------------------
1 | package repositories.ventas
2 |
3 | import models.Venta
4 | import repositories.base.CrudRepository
5 |
6 | interface VentasRepository : CrudRepository {
7 | fun getNewId(): Int
8 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/repositories/ventas/VentasRepositoryList.kt:
--------------------------------------------------------------------------------
1 | package repositories.ventas
2 |
3 | import models.Venta
4 | import mu.KotlinLogging
5 | import services.storage.ventas.VentasStorageService
6 |
7 | private val logger = KotlinLogging.logger {}
8 |
9 | class VentasRepositoryMap(
10 | private val storageService: VentasStorageService
11 | ) : VentasRepository {
12 | private val ventas = mutableListOf()
13 | override fun getNewId(): Int {
14 | logger.debug { "getNewId" }
15 | val lastId = ventas.maxOfOrNull { it.id } ?: 0
16 | return lastId + 1
17 | }
18 |
19 | override fun findAll(): List {
20 | TODO("Not yet implemented")
21 | }
22 |
23 | override fun findById(id: Int): Venta? {
24 | logger.debug { "findById(${id})" }
25 |
26 | // leer del Storage
27 | loadAll()
28 |
29 | return ventas.find { it.id == id }
30 | }
31 |
32 | override fun save(entity: Venta): Venta {
33 | logger.debug { "save: $entity" }
34 | ventas.add(entity)
35 |
36 | // Guardar los cambios
37 | saveAll()
38 |
39 | return entity
40 | }
41 |
42 | override fun update(entity: Venta): Venta? {
43 | TODO("Not yet implemented")
44 | }
45 |
46 | override fun deleteById(id: Int): Venta? {
47 | TODO("Not yet implemented")
48 | }
49 |
50 | private fun saveAll() {
51 | logger.debug { "Ventas saveAll to Storage" }
52 | storageService.saveAll(ventas)
53 | }
54 |
55 | private fun loadAll() {
56 | logger.debug { "Ventas loadAll from Storage" }
57 | ventas.clear()
58 | storageService.loadAll().forEach {
59 | ventas.add(it)
60 | }
61 | }
62 |
63 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/base/StorageService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.base
2 |
3 | interface StorageService {
4 | fun saveAll(items: List)
5 | fun loadAll(): List
6 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/productos/ProductosFicheroAleatorioService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.productos
2 |
3 | import config.AppConfig
4 | import models.Producto
5 | import mu.KotlinLogging
6 | import java.io.File
7 | import java.io.RandomAccessFile
8 | import java.time.LocalDate
9 |
10 | private val logger = KotlinLogging.logger {}
11 |
12 | object ProductosFicheroAleatorioService : ProductosStorageService {
13 | private val localFile = "${AppConfig.APP_DATA}${File.separator}productos.dat"
14 |
15 |
16 | override fun saveAll(items: List) {
17 | logger.debug { "Guardando productos en fichero de aleatorio" }
18 | val file = RandomAccessFile(localFile, "rw")
19 | items.forEach {
20 | file.writeInt(it.id)
21 | file.writeUTF(it.nombre)
22 | file.writeDouble(it.precio)
23 | file.writeInt(it.cantidad)
24 | file.writeUTF(it.createdAt.toString())
25 | file.writeUTF(it.updatedAt.toString())
26 | file.writeBoolean(it.disponible)
27 | }
28 | }
29 |
30 | override fun loadAll(): List {
31 | logger.debug { "Cargando productos desde fichero de aleatorio" }
32 | val file = RandomAccessFile(localFile, "r")
33 | val productos = mutableListOf()
34 | // early return
35 | if (!File(localFile).exists()) return productos
36 | if (file.length() == 0L) return productos
37 |
38 | while (file.filePointer < file.length()) {
39 | val id = file.readInt()
40 | val nombre = file.readUTF()
41 | val precio = file.readDouble()
42 | val cantidad = file.readInt()
43 | val createdAt = LocalDate.parse(file.readUTF())
44 | val updatedAt = LocalDate.parse(file.readUTF())
45 | val disponible = file.readBoolean()
46 | productos.add(Producto(id, nombre, precio, cantidad, createdAt, updatedAt, disponible))
47 | }
48 | return productos
49 | }
50 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/productos/ProductosFicheroCsvService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.productos
2 |
3 | import config.AppConfig
4 | import models.Producto
5 | import mu.KotlinLogging
6 | import java.io.File
7 | import java.time.LocalDate
8 |
9 | private val logger = KotlinLogging.logger {}
10 |
11 | object ProductosFicheroCsvService : ProductosStorageService {
12 | private val localFile = "${AppConfig.APP_DATA}${File.separator}productos.csv"
13 |
14 | override fun saveAll(items: List) {
15 | logger.debug { "Guardando productos en fichero csv" }
16 | val file = File(localFile)
17 | // Escribir el encabezado
18 | file.writeText("id,nombre,precio,cantidad,createdAt,updatedAt,disponible" + "\n")
19 | items.forEach {
20 | file.appendText("${it.id},${it.nombre},${it.precio},${it.cantidad},${it.createdAt},${it.updatedAt},${it.disponible}" + "\n")
21 | }
22 | }
23 |
24 | override fun loadAll(): List {
25 | logger.debug { "Cargando productos desde fichero csv" }
26 | val file = File(localFile)
27 | // early return
28 | if (!file.exists()) return emptyList()
29 | // Leer el fichero
30 | return file.readLines()
31 | .drop(1)
32 | .map { linea -> linea.split(",") }
33 | .map { campos -> campos.map { it.trim() } } // trim() elimina espacios en blanco
34 | .map { campos ->
35 | Producto(
36 | id = campos[0].toInt(),
37 | nombre = campos[1],
38 | precio = campos[2].toDouble(),
39 | cantidad = campos[3].toInt(),
40 | createdAt = LocalDate.parse(campos[4]),
41 | updatedAt = LocalDate.parse(campos[5]),
42 | disponible = campos[6].toBoolean()
43 | )
44 |
45 | }
46 | }
47 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/productos/ProductosFicheroJsonService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.productos
2 |
3 | import com.squareup.moshi.Moshi
4 | import com.squareup.moshi.adapter
5 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
6 | import config.AppConfig
7 | import models.Producto
8 | import mu.KotlinLogging
9 | import utils.LocalDateAdapter
10 | import utils.LocalDateTimeAdapter
11 | import utils.UuidAdapter
12 | import utils.toPrettyJson
13 | import java.io.File
14 |
15 | private val logger = KotlinLogging.logger {}
16 |
17 | @ExperimentalStdlibApi // Para usar el método DE adapter con enlazado de Kotlin
18 | object ProductosFicheroJsonService : ProductosStorageService {
19 | private val localFile = "${AppConfig.APP_DATA}${File.separator}productos.json"
20 |
21 | private val moshi = Moshi.Builder()
22 | .add(UuidAdapter())
23 | .add(LocalDateTimeAdapter())
24 | .add(LocalDateAdapter())
25 | .addLast(KotlinJsonAdapterFactory())
26 | .build()
27 | private val jsonAdapter = moshi.adapter>()
28 |
29 |
30 | override fun saveAll(items: List) {
31 | logger.debug { "Guardando productos en fichero json" }
32 | val file = File(localFile)
33 | file.writeText(jsonAdapter.toPrettyJson(items))
34 | }
35 |
36 | override fun loadAll(): List {
37 | logger.debug { "Cargando productos desde fichero de json" }
38 | val file = File(localFile)
39 | return jsonAdapter.fromJson(file.readText()) ?: emptyList()
40 | }
41 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/productos/ProductosFicheroSerializableService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.productos
2 |
3 | import config.AppConfig
4 | import models.Producto
5 | import mu.KotlinLogging
6 | import java.io.*
7 |
8 | private val logger = KotlinLogging.logger {}
9 |
10 |
11 | object ProductosFicheroSerializableService : ProductosStorageService {
12 | private val localFile = "${AppConfig.APP_DATA}${File.separator}productos.ser"
13 |
14 |
15 | override fun saveAll(items: List) {
16 | logger.debug { "Guardando productos en fichero serializable" }
17 | val file = File(localFile)
18 |
19 | val output = ObjectOutputStream(FileOutputStream(file))
20 | output.use {
21 | // Podemos escribir cualquier objeto serializable, ya sea un objeto o una colección
22 | it.writeObject(items)
23 | }
24 | }
25 |
26 | override fun loadAll(): List {
27 | logger.debug { "Cargando productos desde fichero de serializable" }
28 | val file = File(localFile)
29 | var productos = mutableListOf()
30 | // early return
31 | if (!file.exists()) return productos
32 | val input = ObjectInputStream(FileInputStream(file)).use {
33 | // Podemos leer cualquier objeto serializable, ya sea un objeto o una colección
34 | productos = it.readObject() as MutableList
35 | }
36 |
37 | return productos
38 | }
39 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/productos/ProductosFicheroTextoService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.productos
2 |
3 | import config.AppConfig
4 | import models.Producto
5 | import mu.KotlinLogging
6 | import java.io.File
7 | import java.time.LocalDate
8 |
9 | private val logger = KotlinLogging.logger {}
10 |
11 | object ProductosFicheroTextoService : ProductosStorageService {
12 | private val localFile = "${AppConfig.APP_DATA}${File.separator}productos.txt"
13 |
14 | override fun saveAll(items: List) {
15 | logger.debug { "Guardando productos en fichero de texto" }
16 | val file = File(localFile)
17 | file.writeText("")
18 | items.forEach {
19 | file.appendText(it.id.toString() + "\n")
20 | file.appendText(it.nombre + "\n")
21 | file.appendText(it.precio.toString() + "\n")
22 | file.appendText(it.cantidad.toString() + "\n")
23 | file.appendText(it.createdAt.toString() + "\n")
24 | file.appendText(it.updatedAt.toString() + "\n")
25 | file.appendText(it.disponible.toString() + "\n")
26 | }
27 | }
28 |
29 | override fun loadAll(): List {
30 | logger.debug { "Cargando productos desde fichero de texto" }
31 | val file = File(localFile)
32 | val productos = mutableListOf()
33 | // early return
34 | if (!file.exists()) return productos
35 |
36 | file.bufferedReader().use {
37 | while (it.ready()) {
38 | val id = it.readLine().toInt()
39 | val nombre = it.readLine().trim()
40 | val precio = it.readLine().toDouble()
41 | val cantidad = it.readLine().toInt()
42 | val createdAt = LocalDate.parse(it.readLine().trim())
43 | val updatedAt = LocalDate.parse(it.readLine().trim())
44 | val disponible = it.readLine().toBoolean()
45 | productos.add(Producto(id, nombre, precio, cantidad, createdAt, updatedAt, disponible))
46 | }
47 | }
48 | return productos
49 | }
50 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/productos/ProductosFicheroXmlService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.productos
2 |
3 | import config.AppConfig
4 | import mappers.toDto
5 | import mappers.toProductosList
6 | import models.Producto
7 | import mu.KotlinLogging
8 | import org.simpleframework.xml.core.Persister
9 | import java.io.File
10 |
11 | private val logger = KotlinLogging.logger {}
12 |
13 | object ProductosFicheroXmlService : ProductosStorageService {
14 | private val localFile = "${AppConfig.APP_DATA}${File.separator}productos.xml"
15 |
16 | private val serializer = Persister()
17 |
18 |
19 | override fun saveAll(items: List) {
20 | logger.debug { "Guardando productos en fichero xml" }
21 | val file = File(localFile)
22 | serializer.write(items.toDto(), file)
23 | }
24 |
25 | override fun loadAll(): List {
26 | logger.debug { "Cargando productos desde fichero de xml" }
27 | val file = File(localFile)
28 | return serializer.read(dto.ProductosListDto::class.java, file).toProductosList()
29 | }
30 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/productos/ProductosStorageService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.productos
2 |
3 | import models.Producto
4 | import services.storage.base.StorageService
5 |
6 | interface ProductosStorageService : StorageService
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/ventas/VentasFicheroCsvService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.ventas
2 |
3 | import config.AppConfig
4 | import models.LineaVenta
5 | import models.Venta
6 | import mu.KotlinLogging
7 | import java.io.File
8 | import java.time.LocalDate
9 |
10 | private val logger = KotlinLogging.logger {}
11 |
12 | object VentasFicheroCsvService : VentasStorageService {
13 |
14 | val localFile = "${AppConfig.APP_DATA}${File.separator}ventas.csv"
15 |
16 |
17 | override fun saveAll(items: List) {
18 | logger.debug { "Guardando ventas en fichero csv" }
19 | val file = File(localFile)
20 | // Escribir el encabezado
21 | file.writeText("id,user_id,lineas,createdAt,updatedAt,total,total_items" + "\n")
22 | items.forEach {
23 | file.appendText("${it.id},${it.userId},${fromLineaVentasListToCsvColumn(it.lineas)},${it.createdAt},${it.updatedAt},${it.total},${it.totalItems}" + "\n")
24 | }
25 | }
26 |
27 | private fun fromLineaVentasListToCsvColumn(lineas: List): String {
28 | return lineas.joinToString(separator = "|", prefix = "[", postfix = "]") {
29 | "${it.idVenta};${it.idLineaVenta};${it.idProducto};${it.cantidad};${it.precioProducto};${it.total}"
30 | }
31 | }
32 |
33 | override fun loadAll(): List {
34 | logger.debug { "Cargando ventas desde fichero csv" }
35 | val file = File(localFile)
36 | // early return
37 | if (!file.exists()) return emptyList()
38 | // Leer el fichero
39 | return file.readLines()
40 | .drop(1)
41 | .map { linea -> linea.split(",") }
42 | .map { campos -> campos.map { it.trim() } } // trim() elimina espacios en blanco
43 | .map { campos ->
44 | Venta(
45 | id = campos[0].toInt(),
46 | userId = campos[1].toInt(),
47 | lineas = fromCsvColumnToLineaVentaList(campos[2]).toMutableList(),
48 | createdAt = LocalDate.parse(campos[3]),
49 | updatedAt = LocalDate.parse(campos[4]),
50 | )
51 | }
52 | }
53 |
54 | private fun fromCsvColumnToLineaVentaList(columna: String): List {
55 | return columna
56 | .replace("[", "")
57 | .replace("]", "")
58 | .split("|")
59 | .map { it.split(";") }
60 | .map {
61 | LineaVenta(
62 | idVenta = it[0].toInt(),
63 | idLineaVenta = it[1].toInt(),
64 | idProducto = it[2].toInt(),
65 | cantidad = it[3].toInt(),
66 | precioProducto = it[4].toDouble(),
67 | )
68 | }
69 |
70 | }
71 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/ventas/VentasFicheroJsonService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.ventas
2 |
3 | import com.squareup.moshi.Moshi
4 | import com.squareup.moshi.adapter
5 | import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
6 | import config.AppConfig
7 | import models.Venta
8 | import mu.KotlinLogging
9 | import utils.LocalDateAdapter
10 | import utils.LocalDateTimeAdapter
11 | import utils.UuidAdapter
12 | import utils.toPrettyJson
13 | import java.io.File
14 |
15 | private val logger = KotlinLogging.logger {}
16 |
17 | @ExperimentalStdlibApi // Para usar el método DE adapter con enlazado de Kotlin
18 | object VentasFicheroJsonService : VentasStorageService {
19 |
20 | private val localFile = "${AppConfig.APP_DATA}${File.separator}ventas.json"
21 |
22 | private val moshi = Moshi.Builder()
23 | .add(UuidAdapter())
24 | .add(LocalDateTimeAdapter())
25 | .add(LocalDateAdapter())
26 | .addLast(KotlinJsonAdapterFactory())
27 | .build()
28 | private val jsonAdapter = moshi.adapter>()
29 |
30 |
31 | override fun saveAll(items: List) {
32 | logger.debug { "Guardando ventas en fichero json" }
33 |
34 | val file = File(localFile)
35 | file.writeText(jsonAdapter.toPrettyJson(items))
36 | }
37 |
38 | override fun loadAll(): List {
39 | logger.debug { "Cargando ventas desde fichero de json" }
40 | val file = File(localFile)
41 | return jsonAdapter.fromJson(file.readText()) ?: emptyList()
42 | }
43 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/ventas/VentasFicheroSerializableService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.ventas
2 |
3 | import config.AppConfig
4 | import models.Venta
5 | import mu.KotlinLogging
6 | import java.io.*
7 |
8 | private val logger = KotlinLogging.logger {}
9 |
10 | object VentasFicheroSerializableService : VentasStorageService {
11 |
12 | private val localFile = "${AppConfig.APP_DATA}${File.separator}ventas.ser"
13 |
14 |
15 | override fun saveAll(items: List) {
16 | logger.debug { "Guardando ventas en fichero serializable" }
17 | val file = File(localFile)
18 |
19 | val output = ObjectOutputStream(FileOutputStream(file))
20 | output.use {
21 | // Podemos escribir cualquier objeto serializable, ya sea un objeto o una colección
22 | it.writeObject(items)
23 | }
24 | }
25 |
26 | override fun loadAll(): List {
27 | logger.debug { "Cargando ventas desde fichero de serializable" }
28 | val file = File(localFile)
29 | var ventas = mutableListOf()
30 | // early return
31 | if (!file.exists()) return ventas
32 | val input = ObjectInputStream(FileInputStream(file)).use {
33 | // Podemos leer cualquier objeto serializable, ya sea un objeto o una colección
34 | ventas = it.readObject() as MutableList
35 | }
36 |
37 | return ventas
38 | }
39 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/ventas/VentasFicheroXmlService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.ventas
2 |
3 | import config.AppConfig
4 | import mappers.toDto
5 | import mappers.toVentasList
6 | import models.Venta
7 | import mu.KotlinLogging
8 | import org.simpleframework.xml.core.Persister
9 | import java.io.File
10 |
11 | private val logger = KotlinLogging.logger {}
12 |
13 | object VentasFicheroXmlService : VentasStorageService {
14 |
15 | private val localFile = "${AppConfig.APP_DATA}${File.separator}ventas.xml"
16 |
17 | private val serializer = Persister()
18 |
19 |
20 | override fun saveAll(items: List) {
21 | logger.debug { "Guardando ventas en fichero xml" }
22 |
23 | val file = File(localFile)
24 | serializer.write(items.toDto(), file)
25 | }
26 |
27 | override fun loadAll(): List {
28 | logger.debug { "Cargando ventas desde fichero de xml" }
29 | val file = File(localFile)
30 | return serializer.read(dto.VentasListDto::class.java, file).toVentasList()
31 | }
32 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/services/storage/ventas/VentasStorageService.kt:
--------------------------------------------------------------------------------
1 | package services.storage.ventas
2 |
3 | import models.Venta
4 | import services.storage.base.StorageService
5 |
6 | interface VentasStorageService : StorageService
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/utils/MoshiAdapters.kt:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import com.squareup.moshi.*
4 | import java.time.LocalDate
5 | import java.time.LocalDateTime
6 | import java.util.*
7 |
8 | class UuidAdapter : JsonAdapter() {
9 | @FromJson
10 | override fun fromJson(reader: JsonReader): UUID? = UUID.fromString(reader.readJsonValue().toString())
11 |
12 | @ToJson
13 | override fun toJson(writer: JsonWriter, value: UUID?) {
14 | writer.jsonValue(value.toString())
15 | }
16 | }
17 |
18 | class LocalDateAdapter : JsonAdapter() {
19 | @FromJson
20 | override fun fromJson(reader: JsonReader): LocalDate? = LocalDate.parse(reader.readJsonValue().toString())
21 |
22 | @ToJson
23 | override fun toJson(writer: JsonWriter, value: LocalDate?) {
24 | writer.jsonValue(value.toString())
25 | }
26 | }
27 |
28 | class LocalDateTimeAdapter : JsonAdapter() {
29 | @FromJson
30 | override fun fromJson(reader: JsonReader): LocalDateTime? = LocalDateTime.parse(reader.readJsonValue().toString())
31 |
32 | @ToJson
33 | override fun toJson(writer: JsonWriter, value: LocalDateTime?) {
34 | writer.jsonValue(value.toString())
35 | }
36 | }
37 |
38 |
39 | fun JsonAdapter.toPrettyJson(value: T) = this.indent(" ").toJson(value)
40 |
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/validators/ProductoValidator.kt:
--------------------------------------------------------------------------------
1 | package validators
2 |
3 | import exceptions.ProductoNoValidoException
4 | import models.Producto
5 | import mu.KotlinLogging
6 |
7 | private val logger = KotlinLogging.logger {}
8 | fun Producto.validar() {
9 | logger.debug { "validar: $this" }
10 | require(nombre.isNotBlank()) { throw ProductoNoValidoException("Nombre no puede estar vacio") }
11 | require(precio > 0) { throw ProductoNoValidoException("Precio debe ser mayor a 0") }
12 | require(cantidad >= 0) { throw ProductoNoValidoException("Cantidad debe ser mayor o igual a 0") }
13 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/kotlin/validators/VentaValidator.kt:
--------------------------------------------------------------------------------
1 | package validators
2 |
3 | import exceptions.CarritoNoValidoException
4 | import models.Venta
5 | import mu.KotlinLogging
6 |
7 | private val logger = KotlinLogging.logger {}
8 | fun Venta.validar() {
9 | logger.debug { "validar: $this" }
10 | require(userId > 0) { throw CarritoNoValidoException("userId debe ser mayor a 0") }
11 | //require(lineas.isNotEmpty()) { throw CarritoNoValidoException("Carrito debe tener al menos un producto") }
12 | }
--------------------------------------------------------------------------------
/Ejemplos/Productos-Ventas-Ficheros/src/main/resources/config.properties:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/Productos-Ventas-Ficheros/src/main/resources/config.properties
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/.idea/description.html:
--------------------------------------------------------------------------------
1 | Simple Java application that includes a class with main()
method
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/.idea/libraries/Maven__org_projectlombok_lombok_1_18_22.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/.idea/project-template.xml:
--------------------------------------------------------------------------------
1 |
2 | IJ_BASE_PACKAGE
3 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/AccidentesStream.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 | 4.0.0
6 |
7 | groupId
8 | AccidentesStream
9 | 1.0-SNAPSHOT
10 |
11 |
12 | org.projectlombok
13 | lombok
14 | RELEASE
15 | compile
16 |
17 |
18 |
19 |
20 | 11
21 | 11
22 |
23 |
24 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/src/main/java/es/joseluisgs/dam/Accidente.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | import lombok.Data;
4 |
5 | import java.time.LocalDate;
6 | import java.time.LocalTime;
7 |
8 | @Data
9 | public class Accidente {
10 | private final String numExpediente;
11 | private final LocalDate fecha;
12 | private final LocalTime hora;
13 | private final String localizacion;
14 | private final String distrito;
15 | private final String tipoAccidente;
16 | private final String meteorologia;
17 | private final String tipoVehiculo;
18 | private final String tipoPersona;
19 | private final String sexo;
20 | private final boolean positivoAlcohol;
21 | private final boolean positivoDrogas;
22 | }
23 |
--------------------------------------------------------------------------------
/Ejemplos/StreamAccidentes/src/main/java/es/joseluisgs/dam/Main.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | public class Main {
4 |
5 | public static void main(String[] args) {
6 | System.out.println("Accidentes Madrid");
7 | System.out.println("==================");
8 | AccidentesController controller = new AccidentesController();
9 | controller.run();
10 |
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/.gitignore:
--------------------------------------------------------------------------------
1 | /out
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/.idea/description.html:
--------------------------------------------------------------------------------
1 | Simple Java application that includes a class with main()
method
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/.idea/project-template.xml:
--------------------------------------------------------------------------------
1 |
2 | IJ_BASE_PACKAGE
3 |
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/02-Stream.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/src/es/joseluisgs/dam/Main.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam;
2 |
3 | public class Main {
4 | public static void main(String[] args) {
5 | // ConsultasAlumnos alumnos = new ConsultasAlumnos();
6 | ConsultasCanciones canciones = new ConsultasCanciones();
7 | // ConsultasProductos productos = new ConsultasProductos();
8 | }
9 |
10 |
11 | }
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/src/es/joseluisgs/dam/model/Alumno.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.model;
2 |
3 | public class Alumno {
4 | private int id;
5 | private String dni;
6 | private String nombre;
7 | private String apellidos;
8 | private String nombreCurso;
9 | private double nota;
10 | private int edad;
11 |
12 | public Alumno() {
13 |
14 | }
15 |
16 | public Alumno(int id, String dni, String nombre, String apellidos, String nombreCurso, double nota, int edad) {
17 | this.id = id;
18 | this.dni = dni;
19 | this.nombre = nombre;
20 | this.apellidos = apellidos;
21 | this.nombreCurso = nombreCurso;
22 | this.nota = nota;
23 | this.edad = edad;
24 | }
25 |
26 | public int getId() {
27 | return id;
28 | }
29 |
30 | public void setId(int id) {
31 | this.id = id;
32 | }
33 |
34 | public String getDni() {
35 | return dni;
36 | }
37 |
38 | public void setDni(String dni) {
39 | this.dni = dni;
40 | }
41 |
42 | public String getNombre() {
43 | return nombre;
44 | }
45 |
46 | public void setNombre(String nombre) {
47 | this.nombre = nombre;
48 | }
49 |
50 | public String getApellidos() {
51 | return apellidos;
52 | }
53 |
54 | public void setApellidos(String apellidos) {
55 | this.apellidos = apellidos;
56 | }
57 |
58 | public String getNombreCurso() {
59 | return nombreCurso;
60 | }
61 |
62 | public void setNombreCurso(String nombreCurso) {
63 | this.nombreCurso = nombreCurso;
64 | }
65 |
66 | public double getNota() {
67 | return nota;
68 | }
69 |
70 | public void setNota(double nota) {
71 | this.nota = nota;
72 | }
73 |
74 | public int getEdad() {
75 | return edad;
76 | }
77 |
78 | public void setEdad(int edad) {
79 | this.edad = edad;
80 | }
81 |
82 | @Override
83 | public String toString() {
84 | return id+" | "+dni+" | "+ nombre +" | "+apellidos+" | Curso: "+nombreCurso+" | Nota: "+nota+" | Edad: "+edad;
85 | }
86 | }
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/src/es/joseluisgs/dam/model/Cancion.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.model;
2 |
3 | public class Cancion {
4 | String titulo;
5 | String cantante;
6 |
7 | public Cancion(String titulo, String cantante) {
8 | this.titulo = titulo;
9 | this.cantante = cantante;
10 | }
11 |
12 | public String getTitulo() {
13 | return titulo;
14 | }
15 |
16 | public void setTitulo(String titulo) {
17 | this.titulo = titulo;
18 | }
19 |
20 | public String getCantante() {
21 | return cantante;
22 | }
23 |
24 | public void setCantante(String cantante) {
25 | this.cantante = cantante;
26 | }
27 |
28 | @Override
29 | public String toString() {
30 | return "Cancion{" +
31 | "titulo='" + titulo + '\'' +
32 | ", cantante='" + cantante + '\'' +
33 | '}';
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/src/es/joseluisgs/dam/model/Product.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.model;
2 |
3 | public class Product implements Comparable {
4 | private int id;
5 | private String name;
6 | private int supplier;
7 | private int category;
8 | private double unitPrice;
9 | private int unitsInStock;
10 |
11 | public int getId() {
12 | return id;
13 | }
14 |
15 | public void setId(int id) {
16 | this.id = id;
17 | }
18 |
19 | public String getName() {
20 | return name;
21 | }
22 |
23 | public void setName(String name) {
24 | this.name = name;
25 | }
26 |
27 | public int getSupplier() {
28 | return supplier;
29 | }
30 |
31 | public void setSupplier(int supplier) {
32 | this.supplier = supplier;
33 | }
34 |
35 | public int getCategory() {
36 | return category;
37 | }
38 |
39 | public void setCategory(int category) {
40 | this.category = category;
41 | }
42 |
43 | public double getUnitPrice() {
44 | return unitPrice;
45 | }
46 |
47 | public void setUnitPrice(double unitPrice) {
48 | this.unitPrice = unitPrice;
49 | }
50 |
51 | public int getUnitsInStock() {
52 | return unitsInStock;
53 | }
54 |
55 | public void setUnitsInStock(int unitsInStock) {
56 | this.unitsInStock = unitsInStock;
57 | }
58 |
59 | @Override
60 | public String toString() {
61 | return "Product{" +
62 | "id=" + id +
63 | ", name='" + name + '\'' +
64 | ", supplier=" + supplier +
65 | ", category=" + category +
66 | ", unitPrice=" + unitPrice +
67 | ", unitsInStock=" + unitsInStock +
68 | '}';
69 | }
70 |
71 |
72 | @Override
73 | public int compareTo(Product p) {
74 | if (this.getUnitsInStock() < p.getUnitsInStock())
75 | return -1;
76 | else if (this.getUnitsInStock() > p.getUnitsInStock())
77 | return 1;
78 | else
79 | return 0;
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/Ejemplos/StreamEjemplos-csv/src/es/joseluisgs/dam/utils/Util.java:
--------------------------------------------------------------------------------
1 | package es.joseluisgs.dam.utils;
2 |
3 | import es.joseluisgs.dam.model.Product;
4 |
5 | import java.io.File;
6 | import java.io.IOException;
7 | import java.nio.charset.StandardCharsets;
8 | import java.nio.file.Files;
9 | import java.nio.file.Path;
10 | import java.nio.file.Paths;
11 | import java.util.ArrayList;
12 | import java.util.List;
13 | import java.util.StringTokenizer;
14 | import java.util.stream.Collectors;
15 |
16 | public class Util {
17 |
18 | public static List getProducts() throws IOException {
19 | // Cargamos el archivo ubicado en la carpeta data
20 | String DATA_FILE = "products.csv";
21 | String WORKING_DIRECTORY = System.getProperty("user.dir");
22 | Path path = Paths.get(WORKING_DIRECTORY + File.separator + "data" + File.separator + DATA_FILE);
23 | // Puedo leer todo el fichero del tiron. Cuidado si no es muy grande!!
24 | final List lineas = Files.readAllLines(path, StandardCharsets.UTF_8);
25 | // lines.forEach(System.out::println);
26 | // List products = new ArrayList<>();
27 | // Me he saltado la primera línea del archivo, porque es la cabecera
28 | /*for (int i = 1; i < lineas.size(); i++) {
29 | Product product = parseProduct(lineas.get(i));
30 | products.add(product);
31 | }*/
32 | // Mapeando cada línea a un objeto Product
33 | // Usamos Skip para saltarnos la primera línea
34 | return lineas.stream().skip(1).map(Util::parseProduct).collect(Collectors.toList());
35 |
36 | }
37 |
38 | public static List getProducts2() throws IOException {
39 | // Cargamos el archivo ubicado en la carpeta data
40 | String DATA_FILE = "products.csv";
41 | String WORKING_DIRECTORY = System.getProperty("user.dir");
42 | Path path = Paths.get(WORKING_DIRECTORY + File.separator + "data" + File.separator + DATA_FILE);
43 | // Puedo leer todo el fichero liena a linea usando API Stream y Programación Funcional
44 | // Mapeando cada línea a un objeto Product
45 | // Usamos Skip para saltarnos la primera línea
46 | return Files.lines(path, StandardCharsets.UTF_8)
47 | .skip(1).map(Util::parseProduct).collect(Collectors.toList());
48 |
49 | }
50 |
51 | private static Product parseProduct(String linea) {
52 | String[] campos = linea.split(",");
53 | Product product = new Product();
54 | product.setId(Integer.parseInt(campos[0]));
55 | product.setName(campos[1]);
56 | product.setSupplier(Integer.parseInt(campos[2]));
57 | product.setCategory(Integer.parseInt(campos[3]));
58 | product.setUnitPrice(Double.parseDouble(campos[5]));
59 | product.setUnitsInStock(Integer.parseInt(campos[6]));
60 | return product;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/.gitignore:
--------------------------------------------------------------------------------
1 | .gradle
2 | build/
3 | !gradle/wrapper/gradle-wrapper.jar
4 | !**/src/main/**/build/
5 | !**/src/test/**/build/
6 |
7 | ### IntelliJ IDEA ###
8 | .idea/modules.xml
9 | .idea/jarRepositories.xml
10 | .idea/compiler.xml
11 | .idea/libraries/
12 | *.iws
13 | *.iml
14 | *.ipr
15 | out/
16 | !**/src/main/**/out/
17 | !**/src/test/**/out/
18 |
19 | ### Eclipse ###
20 | .apt_generated
21 | .classpath
22 | .factorypath
23 | .project
24 | .settings
25 | .springBeans
26 | .sts4-cache
27 | bin/
28 | !**/src/main/**/bin/
29 | !**/src/test/**/bin/
30 |
31 | ### NetBeans ###
32 | /nbproject/private/
33 | /nbbuild/
34 | /dist/
35 | /nbdist/
36 | /.nb-gradle/
37 |
38 | ### VS Code ###
39 | .vscode/
40 |
41 | ### Mac OS ###
42 | .DS_Store
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Editor-based HTTP Client requests
5 | /httpRequests/
6 | # Datasource local storage ignored files
7 | /dataSources/
8 | /dataSources.local.xml
9 |
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/build.gradle.kts:
--------------------------------------------------------------------------------
1 | plugins {
2 | kotlin("jvm") version "1.8.20"
3 | application
4 | }
5 |
6 | group = "dev.joseluisgs"
7 | version = "1.0-SNAPSHOT"
8 |
9 | repositories {
10 | mavenCentral()
11 | }
12 |
13 | dependencies {
14 | testImplementation(kotlin("test"))
15 | }
16 |
17 | tasks.test {
18 | useJUnitPlatform()
19 | }
20 |
21 | kotlin {
22 | jvmToolchain(11)
23 | }
24 |
25 | application {
26 | mainClass.set("MainKt")
27 | }
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
2 |
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Ejemplos/ZipAndTemp/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/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 execute
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 execute
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 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/Ejemplos/ZipAndTemp/settings.gradle.kts:
--------------------------------------------------------------------------------
1 |
2 | rootProject.name = "ZipAndTemp"
3 |
4 |
--------------------------------------------------------------------------------
/Practicas/accidentes/Estructura_DS_Accidentes_trafico_desde_2019.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Practicas/accidentes/Estructura_DS_Accidentes_trafico_desde_2019.pdf
--------------------------------------------------------------------------------
/Practicas/accidentes/README.md:
--------------------------------------------------------------------------------
1 | # Accidentes de Madrid
2 |
3 | Dado el fichero de accidentes CSV, leerlo pasarlo a JSON y XML. Volver a leer ambos.
4 |
5 | Realizar las siguientes consultas:
6 |
7 | - Accidentes en los que estan implicados alcohol o drogas.
8 | - Numero de accidentes que han dado positivo en alcohol y drogas.
9 | - Accidentes agrupados por sexo.
10 | - Accidentes agrupados por meses.
11 | - Accidentes agrupados por tipos de vehiculos.
12 | - Accidentes ocurridos en la calle de leganes.
13 | - Numero de accidentes por distrito.
14 | - Estadisticas por distrito.
15 | - Accidentes por distrito ordenadas de manera descendente.
16 | - Listado de accidentes que se produzcan en fin de semana y de noche (a partir de las 8 de la tarde hasta las 6 de la mañana)
17 | - Listado de accidentes que se produzcan en fin de semana y de noche donde se haya dado positivo en alcohol
18 | - Accidentes donde haya mas de un fallecido.
19 | - Comprobar si el distrito con mas accidentes coincide con el distrito donde hay más accidentes en fin de semana.
20 | - Numero de accidentes donde ha habido (alcohol o drogas) y victimas mortales.
21 | - Numero de accidentes donde ha habido atropellos a personas.
22 | - Accidentes agrupados por estado metereológio.
23 | - Lista de accidentes donde haya habido un atropello animal.
24 |
--------------------------------------------------------------------------------
/Practicas/aemet/Aemet20171029.csv:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Practicas/aemet/Aemet20171029.csv
--------------------------------------------------------------------------------
/Practicas/aemet/Aemet20171030.csv:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Practicas/aemet/Aemet20171030.csv
--------------------------------------------------------------------------------
/Practicas/aemet/Aemet20171031.csv:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/Practicas/aemet/Aemet20171031.csv
--------------------------------------------------------------------------------
/Practicas/aemet/README.md:
--------------------------------------------------------------------------------
1 | # Servicio meteorológico
2 |
3 | 1. Leer los tres ficheros y combinarlos en uno solo completando los datos e incluyendo el campo fecha
4 | 2. Exportar el resultado a Json y XML
5 | 3. Realizar las siguientes consultas:
6 | - Temperatura máxima por día y lugar
7 | - Temperatura mínima por día y lugar
8 | - Temperatura máxima por provincia (día, lugar, valor y momento)
9 | - Temperatura mínima por provincia (día, lugar, valor y valor)
10 | - Temperatura media por provincia (día, lugar y valor)
11 | - Listado de precipitación media por día y provincia
12 | - Numero de lugares en el que llovío por día y provincia
13 | - Temperatura média de la provincia de Madrid
14 | - Media de temperatura máxima total
15 | - Media de temprratura minima total
16 | - Lugares donde la máxima ha sido antes de las 15:00 por día
17 | - Lugares donde la mínima ha sido después de las 17:30 por día
18 |
19 | 4.- Para la privincia de Madid exportar en JSON y XML el siguiente informe
20 | - Por cada día:
21 | - Temperatura media
22 | - Temperatura máxima (Lugar y momento)
23 | - Temperatura mínima (Lugar y momento
24 | - Si hubo precipitación (sí/no) y valor de la misma.
25 |
--------------------------------------------------------------------------------
/Practicas/buerguer-pig/README.md:
--------------------------------------------------------------------------------
1 | # Burguer Pig
2 |
3 | Crear repositorios y almacenamiento para:
4 | - Hamburguesa (id: UUID, nombre: String, List>, precio: calculado desde ingredientes))
5 | - Ingrediente (id: Autonumerico, nombre: String, precio: Double)
6 |
7 | Crear almacenamiento y repositorio para leer y escribir Ingredientes y Hambuguesas:
8 | - Ficheros de texto
9 | - Ficheros binarios
10 | - Ficheros serializados
11 | - Ficheros CSV
12 | - Ficheros JSON
13 | - Ficheros XML
14 |
15 | Adems obtener:
16 |
17 | - Hambuguesa más cara
18 | - Hambuguesa con más ingredientes
19 | - Número de Hambuguesas por ingrediente
20 | - Hambuguesaas agrupadas por total de ingredientes
21 | - Precio medio de las hambuguesas
22 | - Precio medio de los ingredientes.
23 |
--------------------------------------------------------------------------------
/Practicas/herencia-dto/README.md:
--------------------------------------------------------------------------------
1 | # Herencia, DTO y Ficheros
2 |
3 | Data esta estructura:
4 | - Persona(nombre: String)
5 | - Profesor(modulo: String): Persona
6 | - Alumno(edad: Int): Persona
7 |
8 | Crear DTO y la estructura necesaria para pocesar información den CSV, JSON y XML
9 |
10 | Para ello deberás crear 20 personas donde 10% son profesores y el resto alumnos. Los módulos puedeo ser "Programación" y "Entornos" y la edad va de los 18 a los 40.
11 |
12 | Probar lectura y escritura de ficheros CSV, JSON y XML para estos ejemplo
13 |
14 | Consultas:
15 | - Profesor más mayor
16 | - Alumno más joven
17 | - Media de edad de alumnos
18 | - Media de longitud de nombre
19 | - Listado de agrupados por tipo
20 |
--------------------------------------------------------------------------------
/images/file.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/images/file.png
--------------------------------------------------------------------------------
/images/java-io-vs-nio.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/images/java-io-vs-nio.png
--------------------------------------------------------------------------------
/images/jeraquia.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/joseluisgs/Programacion-07-2022-2023/2aa9db372f7f44925bfe881f01017d25bfe0d180/images/jeraquia.png
--------------------------------------------------------------------------------
/upload.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | # Este es un script para subir el repositorio eliminado la historia
3 | # debido a que solo subo PDFs y cada cambio y mantenerlos hace que el repositorio aumente
4 | # considerablemente
5 | echo Borrando repositorio local...
6 | rm -rf .git
7 |
8 | # Iniciamos un nuevo repositorio
9 | git init
10 | # Añadimos los ficheros y hacemos comit en main
11 | git add -A
12 | date=`date +%Y-%m-%d_%H:%M:%S`
13 | git commit -m "deploy ${date}"
14 | git branch -M master
15 |
16 | # Nos conectamos a remoto y subimos
17 | echo Subiendo contenidos a GitHub...
18 | git remote add origin https://github.com/joseluisgs/Programacion-07-2022-2023.git
19 | git push -u -f origin master
20 |
21 | rm -rf .git
22 |
23 | echo Fin :D
--------------------------------------------------------------------------------