domingo, 8 de diciembre de 2019

Reactive Spring 2018 Reservation MongoDB

Reactive Spring 2018 Reservation MongoDB




Generate Reservation on MongoDB


After second running the records are appended.


Console:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.2.RELEASE)

2019-12-08 18:14:39.866  INFO 7464 --- [           main] c.b.r.ReservationServiceApplication      : Starting ReservationServiceApplication on DESKTOP-NLF0058 with PID 7464 (D:\proy\reservation-service\target\classes started by bext in D:\proy\reservation-service)
2019-12-08 18:14:39.867  INFO 7464 --- [           main] c.b.r.ReservationServiceApplication      : No active profile set, falling back to default profiles: default
2019-12-08 18:14:40.181  INFO 7464 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Reactive MongoDB repositories in DEFAULT mode.
2019-12-08 18:14:40.210  INFO 7464 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 26ms. Found 1 Reactive MongoDB repository interfaces.
2019-12-08 18:14:40.215  INFO 7464 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2019-12-08 18:14:40.216  INFO 7464 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 1ms. Found 0 MongoDB repository interfaces.
2019-12-08 18:14:40.466  INFO 7464 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-12-08 18:14:40.549  INFO 7464 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-12-08 18:14:40.562  INFO 7464 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:609}] to localhost:27017
2019-12-08 18:14:40.565  INFO 7464 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2, 1]}, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1674700}
2019-12-08 18:14:40.927  INFO 7464 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:610}] to localhost:27017
2019-12-08 18:14:40.928  INFO 7464 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2, 1]}, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1249600}
2019-12-08 18:14:40.932  INFO 7464 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2019-12-08 18:14:40.934  INFO 7464 --- [           main] c.b.r.ReservationServiceApplication      : Started ReservationServiceApplication in 1.268 seconds (JVM running for 1.83)
2019-12-08 18:14:41.026  INFO 7464 --- [ntLoopGroup-2-3] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:4, serverValue:612}] to localhost:27017
2019-12-08 18:14:41.026  INFO 7464 --- [ntLoopGroup-2-2] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:3, serverValue:611}] to localhost:27017
2019-12-08 18:14:41.026  INFO 7464 --- [ntLoopGroup-2-4] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:5, serverValue:613}] to localhost:27017
2019-12-08 18:14:41.026  INFO 7464 --- [ntLoopGroup-2-6] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:7, serverValue:615}] to localhost:27017
2019-12-08 18:14:41.034  INFO 7464 --- [ntLoopGroup-2-5] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:6, serverValue:614}] to localhost:27017
2019-12-08 18:14:41.035  INFO 7464 --- [ntLoopGroup-2-7] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:8, serverValue:616}] to localhost:27017
2019-12-08 18:14:41.036  INFO 7464 --- [ntLoopGroup-2-8] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:9, serverValue:617}] to localhost:27017
2019-12-08 18:14:41.043  INFO 7464 --- [ntLoopGroup-2-9] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:10, serverValue:618}] to localhost:27017

Process finished with exit code -1


Deleting All records before the work


Add Logging


On Console the log on save is showed.

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.2.RELEASE)

2019-12-08 18:26:19.044  INFO 13212 --- [           main] c.b.r.ReservationServiceApplication      : Starting ReservationServiceApplication on DESKTOP-NLF0058 with PID 13212 (D:\proy\reservation-service\target\classes started by bext in D:\proy\reservation-service)
2019-12-08 18:26:19.047  INFO 13212 --- [           main] c.b.r.ReservationServiceApplication      : No active profile set, falling back to default profiles: default
2019-12-08 18:26:19.351  INFO 13212 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Reactive MongoDB repositories in DEFAULT mode.
2019-12-08 18:26:19.384  INFO 13212 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 29ms. Found 1 Reactive MongoDB repository interfaces.
2019-12-08 18:26:19.387  INFO 13212 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2019-12-08 18:26:19.388  INFO 13212 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 1ms. Found 0 MongoDB repository interfaces.
2019-12-08 18:26:19.642  INFO 13212 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-12-08 18:26:19.727  INFO 13212 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-12-08 18:26:19.739  INFO 13212 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:642}] to localhost:27017
2019-12-08 18:26:19.742  INFO 13212 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2, 1]}, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1610800}
2019-12-08 18:26:20.099  INFO 13212 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:644}] to localhost:27017
2019-12-08 18:26:20.100  INFO 13212 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2, 1]}, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1308100}
2019-12-08 18:26:20.110  INFO 13212 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2019-12-08 18:26:20.112  INFO 13212 --- [           main] c.b.r.ReservationServiceApplication      : Started ReservationServiceApplication in 1.261 seconds (JVM running for 1.813)
2019-12-08 18:26:20.163  INFO 13212 --- [ntLoopGroup-2-2] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:3, serverValue:645}] to localhost:27017
2019-12-08 18:26:20.194  INFO 13212 --- [ntLoopGroup-2-3] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:4, serverValue:646}] to localhost:27017
2019-12-08 18:26:20.195  INFO 13212 --- [ntLoopGroup-2-4] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:5, serverValue:647}] to localhost:27017
2019-12-08 18:26:20.201  INFO 13212 --- [ntLoopGroup-2-5] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:6, serverValue:648}] to localhost:27017
2019-12-08 18:26:20.205  INFO 13212 --- [ntLoopGroup-2-5] c.b.r.SamplaDataInitializr               : Reservation(id=5ded94ace4f1762422e2950b, nombre=Luis)
2019-12-08 18:26:20.206  INFO 13212 --- [ntLoopGroup-2-5] c.b.r.SamplaDataInitializr               : Reservation(id=5ded94ace4f1762422e2950c, nombre=Daisy)
2019-12-08 18:26:20.206  INFO 13212 --- [ntLoopGroup-2-5] c.b.r.SamplaDataInitializr               : Reservation(id=5ded94ace4f1762422e2950d, nombre=McPato)
2019-12-08 18:26:20.206  INFO 13212 --- [ntLoopGroup-2-5] c.b.r.SamplaDataInitializr               : Reservation(id=5ded94ace4f1762422e29509, nombre=Hugo)
2019-12-08 18:26:20.206  INFO 13212 --- [ntLoopGroup-2-5] c.b.r.SamplaDataInitializr               : Reservation(id=5ded94ace4f1762422e2950a, nombre=Paco)
2019-12-08 18:26:20.207  INFO 13212 --- [ntLoopGroup-2-5] c.b.r.SamplaDataInitializr               : Reservation(id=5ded94ace4f1762422e2950e, nombre=Beto)
2019-12-08 18:26:20.208  INFO 13212 --- [ntLoopGroup-2-5] c.b.r.SamplaDataInitializr               : Reservation(id=5ded94ace4f1762422e2950f, nombre=Guille)
2019-12-08 18:26:20.208  INFO 13212 --- [ntLoopGroup-2-4] c.b.r.SamplaDataInitializr               : Reservation(id=5ded94ace4f1762422e29510, nombre=Juan)


Adding logging on different steps of the Fluxes, just ilustrative.


On Console the logging for the respective Fluxes.
...
2019-12-08 18:31:29.945  INFO 16072 --- [ntLoopGroup-2-3] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:4, serverValue:661}] to localhost:27017
2019-12-08 18:31:29.947  INFO 16072 --- [ntLoopGroup-2-2] c.b.r.SamplaDataInitializr               : Reservation(id=5ded95e13880f842320efd8e, nombre=Paco)
2019-12-08 18:31:29.947  INFO 16072 --- [ntLoopGroup-2-2] c.b.r.SamplaDataInitializr               : Reservation(id=5ded95e13880f842320efd8d, nombre=Hugo)
2019-12-08 18:31:29.954  INFO 16072 --- [ntLoopGroup-2-2] c.b.r.SamplaDataInitializr               : Reservation(id=5ded95e13880f842320efd8f, nombre=Luis)
2019-12-08 18:31:29.955  INFO 16072 --- [ntLoopGroup-2-2] c.b.r.SamplaDataInitializr               : Reservation(id=5ded95e13880f842320efd91, nombre=McPato)
2019-12-08 18:31:29.956  INFO 16072 --- [ntLoopGroup-2-3] c.b.r.SamplaDataInitializr               : Reservation(id=5ded95e13880f842320efd92, nombre=Beto)
2019-12-08 18:31:29.956  INFO 16072 --- [ntLoopGroup-2-4] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:5, serverValue:662}] to localhost:27017
2019-12-08 18:31:29.957  INFO 16072 --- [ntLoopGroup-2-3] c.b.r.SamplaDataInitializr               : Reservation(id=5ded95e13880f842320efd93, nombre=Guille)
2019-12-08 18:31:29.958  INFO 16072 --- [ntLoopGroup-2-4] c.b.r.SamplaDataInitializr               : Reservation(id=5ded95e13880f842320efd90, nombre=Daisy)
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : null
2019-12-08 18:31:29.959  INFO 16072 --- [ntLoopGroup-2-2] c.b.r.SamplaDataInitializr               : Reservation(id=5ded95e13880f842320efd94, nombre=Juan)
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : null
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : null
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : null
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : null
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : null
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : null
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : null
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : Hugo
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : Paco
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : Luis
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : Daisy
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : McPato
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : Beto
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : Guille
2019-12-08 18:31:29.959  INFO 16072 --- [           main] c.b.r.SamplaDataInitializr               : Juan

Optimizing the code for java 11, using var and compacting


Console

...
2019-12-08 18:34:26.080  INFO 3024 --- [ntLoopGroup-2-7] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:8, serverValue:675}] to localhost:27017
2019-12-08 18:34:26.095  INFO 3024 --- [ntLoopGroup-2-7] c.b.r.SamplaDataInitializr               : Reservation(id=5ded969205c528360d969eda, nombre=Hugo)
2019-12-08 18:34:26.095  INFO 3024 --- [ntLoopGroup-2-7] c.b.r.SamplaDataInitializr               : Reservation(id=5ded969205c528360d969edb, nombre=Paco)
2019-12-08 18:34:26.095  INFO 3024 --- [ntLoopGroup-2-7] c.b.r.SamplaDataInitializr               : Reservation(id=5ded969205c528360d969edc, nombre=Luis)
2019-12-08 18:34:26.095  INFO 3024 --- [ntLoopGroup-2-7] c.b.r.SamplaDataInitializr               : Reservation(id=5ded969205c528360d969edf, nombre=Beto)
2019-12-08 18:34:26.096  INFO 3024 --- [ntLoopGroup-2-7] c.b.r.SamplaDataInitializr               : Reservation(id=5ded969205c528360d969edd, nombre=Daisy)
2019-12-08 18:34:26.096  INFO 3024 --- [ntLoopGroup-2-7] c.b.r.SamplaDataInitializr               : Reservation(id=5ded969205c528360d969ee1, nombre=Juan)
2019-12-08 18:34:26.096  INFO 3024 --- [ntLoopGroup-2-7] c.b.r.SamplaDataInitializr               : Reservation(id=5ded969205c528360d969ede, nombre=McPato)
2019-12-08 18:34:26.096  INFO 3024 --- [ntLoopGroup-2-7] c.b.r.SamplaDataInitializr               : Reservation(id=5ded969205c528360d969ee0, nombre=Guille)



eot

sábado, 7 de diciembre de 2019

Reactive Spring MongoDB flux-flix-service

Spring Reactive MongoDB flux-flix-service


package com.bext.fluxflixservice;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import reactor.core.publisher.Mono;

import java.util.Random;
import java.util.UUID;
import java.util.stream.Stream;

@SpringBootApplication
public class FluxFlixServiceApplication {


        public static void main(String[] args) {
        SpringApplication.run(FluxFlixServiceApplication.class, args);
    }

    @Bean
    CommandLineRunner demo(PeliculaRepository peliculaRepository) {
        return args -> {
            //Mono mono = Mono.just("peliculaRepository.count(): " );
            peliculaRepository.count().map(x->"Numero de Registros de Pelicula: "+ x ).subscribe(System.out::println);

            peliculaRepository.deleteAll().subscribe(null, null, () ->
                    Stream.of("Buscando a Nemo", "Ciudad de Dios", "Hable con ella",
                            "El Señor de los Anilllos", "Kandahar (2001)", "La mirada de Ulises", "Pulp Fiction", "Matrix")
                            .map( nombre -> new Pelicula(UUID.randomUUID().toString(), nombre, generoRandom()))
                            .forEach( peli -> peliculaRepository.save(peli).subscribe(System.out::println))
            );

        };
    }

    private String generoRandom() {
        String[] generos = "accion,terror,comedia,documental,arte".split(",");
        return generos[new Random().nextInt(generos.length)];
    }

}

interface PeliculaRepository extends ReactiveMongoRepository<Pelicula, String> {

}

@Document
@AllArgsConstructor
@ToString
@NoArgsConstructor
@Data
class Pelicula {
    @Id
    private String id;
    private String titulo , genero;
}

Run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.0.RELEASE)

2019-12-07 19:49:42.338  INFO 24896 --- [           main] c.b.f.FluxFlixServiceApplication         : Starting FluxFlixServiceApplication on DESKTOP-NLF0058 with PID 24896 (D:\proy\flux-flix-service\target\classes started by bext in D:\proy\flux-flix-service)
2019-12-07 19:49:42.339  INFO 24896 --- [           main] c.b.f.FluxFlixServiceApplication         : No active profile set, falling back to default profiles: default
2019-12-07 19:49:42.710  INFO 24896 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-12-07 19:49:42.749  INFO 24896 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 36ms. Found 1 repository interfaces.
2019-12-07 19:49:42.755  INFO 24896 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-12-07 19:49:42.758  INFO 24896 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 2ms. Found 0 repository interfaces.
2019-12-07 19:49:43.011  INFO 24896 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-12-07 19:49:43.107  INFO 24896 --- [           main] org.mongodb.driver.cluster               : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2019-12-07 19:49:43.122  INFO 24896 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:63}] to localhost:27017
2019-12-07 19:49:43.126  INFO 24896 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2, 1]}, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1876100}
2019-12-07 19:49:43.156  WARN 24896 --- [           main] o.s.data.convert.CustomConversions       : Registering converter from class java.time.LocalDateTime to class java.time.Instant as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
2019-12-07 19:49:43.156  WARN 24896 --- [           main] o.s.data.convert.CustomConversions       : Registering converter from class java.time.Instant to class java.time.LocalDateTime as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
2019-12-07 19:49:43.197  WARN 24896 --- [           main] o.s.data.convert.CustomConversions       : Registering converter from class java.time.LocalDateTime to class java.time.Instant as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
2019-12-07 19:49:43.197  WARN 24896 --- [           main] o.s.data.convert.CustomConversions       : Registering converter from class java.time.Instant to class java.time.LocalDateTime as reading converter although it doesn't convert from a store-supported type! You might wanna check you annotation setup at the converter implementation.
2019-12-07 19:49:43.459  INFO 24896 --- [localhost:27017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:64}] to localhost:27017
2019-12-07 19:49:43.461  INFO 24896 --- [localhost:27017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[4, 2, 1]}, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=1322099}
2019-12-07 19:49:43.472  INFO 24896 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2019-12-07 19:49:43.475  INFO 24896 --- [           main] c.b.f.FluxFlixServiceApplication         : Started FluxFlixServiceApplication in 1.331 seconds (JVM running for 1.903)
2019-12-07 19:49:43.534  INFO 24896 --- [ntLoopGroup-2-2] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:3, serverValue:65}] to localhost:27017
Numero de Registros de Pelicula: 0
2019-12-07 19:49:43.541  INFO 24896 --- [ntLoopGroup-2-3] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:4, serverValue:66}] to localhost:27017
2019-12-07 19:49:43.583  INFO 24896 --- [ntLoopGroup-2-4] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:5, serverValue:67}] to localhost:27017
2019-12-07 19:49:43.591  INFO 24896 --- [ntLoopGroup-2-5] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:6, serverValue:68}] to localhost:27017
2019-12-07 19:49:43.598  INFO 24896 --- [ntLoopGroup-2-6] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:7, serverValue:69}] to localhost:27017
2019-12-07 19:49:43.600  INFO 24896 --- [ntLoopGroup-2-7] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:8, serverValue:70}] to localhost:27017
2019-12-07 19:49:43.607  INFO 24896 --- [ntLoopGroup-2-8] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:9, serverValue:71}] to localhost:27017
2019-12-07 19:49:43.614  INFO 24896 --- [ntLoopGroup-2-9] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:10, serverValue:72}] to localhost:27017
Pelicula(id=37516675-5439-4a9e-89d1-402f3a781a55, titulo=Kandahar (2001), genero=documental)
Pelicula(id=b045c87e-7a58-430a-9212-30bce5a1aa28, titulo=Pulp Fiction, genero=terror)
Pelicula(id=a251905e-30e9-4820-af74-b887615bd2f5, titulo=Matrix, genero=accion)
Pelicula(id=91203906-658a-49d1-991b-89e643e78c2c, titulo=Hable con ella, genero=documental)
Pelicula(id=3424fd82-d2c7-46bf-aa92-7425c4be06a4, titulo=La mirada de Ulises, genero=accion)
Pelicula(id=21b663d6-cc8b-4c6b-8057-b35162fd7a0b, titulo=Buscando a Nemo, genero=accion)
Pelicula(id=bfbf8ab7-3e2e-417b-a15e-dc6c465e7362, titulo=Ciudad de Dios, genero=documental)
Pelicula(id=68b655e9-7ae5-4c8d-8b72-ea32e501240a, titulo=El Señor de los Anilllos, genero=terror)


Exploring the content of MongoDB with Compass tool, the records are created





eot

Simple Spring Reactive 2018 Mono, Flux

Simple Spring Reactive 2018 demo Mono, Flux




Using Mono

package com.bext;
import org.springframework.boot.CommandLineRunner; 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean; 
import reactor.core.publisher.Mono; 
 
 @SpringBootApplicationpublic class SpringReactive2018Application {

   public static void main(String[] args) {
      SpringApplication.run(SpringReactive2018Application.class, args);    
   }

   @Bean   CommandLineRunner demo() {
      return args -> {
         Mono<String> miMono = Mono.just("Mono maneja un solo dato"); 
         miMono.subscribe(System.out::println);      }; 
     }
}

Run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.2.RELEASE)

2019-12-07 18:58:46.769  INFO 20348 --- [           main] com.bext.SpringReactive2018Application   : Starting SpringReactive2018Application on DESKTOP-NLF0058 with PID 20348 (D:\Descargas\SpringReactive2018\target\classes started by bext in D:\Descargas\SpringReactive2018)
2019-12-07 18:58:46.770  INFO 20348 --- [           main] com.bext.SpringReactive2018Application   : No active profile set, falling back to default profiles: default
2019-12-07 18:58:47.780  INFO 20348 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2019-12-07 18:58:47.783  INFO 20348 --- [           main] com.bext.SpringReactive2018Application   : Started SpringReactive2018Application in 1.208 seconds (JVM running for 1.808)
Mono maneja un solo dato


Using Flux

package com.bext;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean; 
import reactor.core.publisher.Flux; 
 
@SpringBootApplication 
public class SpringReactive2018Application {

   public static void main(String[] args) {
      SpringApplication.run(SpringReactive2018Application.class, args);    
   }

   @Bean   CommandLineRunner demo() {
      return args -> {
         Flux<String> miFlux = Flux.fromArray("1,2,3,4,5,6".split(",")); 
         miFlux.map(Integer::parseInt)
                    .filter(i -> i % 2 == 0)
                    .subscribe(System.out::println, null, null); 
      }; 
   }
}

Run

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.2.RELEASE)

2019-12-07 19:22:39.436  INFO 27864 --- [           main] com.bext.SpringReactive2018Application   : Starting SpringReactive2018Application on DESKTOP-NLF0058 with PID 27864 (D:\Descargas\SpringReactive2018\target\classes started by bext in D:\Descargas\SpringReactive2018)
2019-12-07 19:22:39.438  INFO 27864 --- [           main] com.bext.SpringReactive2018Application   : No active profile set, falling back to default profiles: default
2019-12-07 19:22:40.455  INFO 27864 --- [           main] o.s.b.web.embedded.netty.NettyWebServer  : Netty started on port(s): 8080
2019-12-07 19:22:40.458  INFO 27864 --- [           main] com.bext.SpringReactive2018Application   : Started SpringReactive2018Application in 1.206 seconds (JVM running for 1.821)
2
4
6



eot

Dependency Injection, IoC (Inversion of Control)

https://github.com/jalbertomr/SimpleDependencyInjectionIoC.git

Without IoC

package com.bext;
public class IoC {

    public static void main(String[] args) {
        IoC container = new IoC(); 
        User user = container.new User(); 
        user.add( "Info to persist"); 
    }

    public class User {
        MySqlDatabase database;
 
        public User() {
            this.database = new MySqlDatabase();         
        }

        void add( String data) {
            database.persist( data);         
        }
    }

    public class MySqlDatabase {
        public void persist(String data) {
            System.out.println("MySqlDatabase persisted [" + data + "]");         
        }
    }

}



Implementing Inversion of Control (IoC) , Now instance of database can be accessed for use for tests.

package com.bext;
public class IoC {

    public static void main(String[] args) {
        IoC container = new IoC(); 
        User user = container.new User( container.new MySqlDatabase()); 
        user.add( "Info to persist"); 
    }

    public class User {
        MySqlDatabase database;
 
        public User( MySqlDatabase database) {
            this.database = database; 
        }

        void add( String data) {
            database.persist( data); 
        }
    }

    public class MySqlDatabase {
        public void persist(String data) {
            System.out.println("MySqlDatabase persisted [" + data + "]"); 
        }
    }

}


Loosely coupled Architecture to define de database to use, in this case MySqlDatabase

package com.bext;
public class IoC {

    public static void main(String[] args) {
        IoC container = new IoC(); 
        User user = container.new User( container.new MySqlDatabase()); 
        user.add( "Info to persist");    }

    public class User {
        Database database; 
        public User( Database database) {
            this.database = database;         
        }

        void add( String data) {
            database.persist( data);         
        }
    }

    interface Database {
        public void persist(String data);     
    }

    public class MySqlDatabase implements Database {
        public void persist(String data) {
            System.out.println("MySqlDatabase persisted [" + data + "]"); 
        }
    }

    public class OracleDatabase implements Database {
        public void persist(String data) {
            System.out.println("OracleDatabase persisted [" + data + "]"); 
        }
    }
}



The Run shows:

MySqlDatabase persisted [Info to persist]

The same  but now for use Oracle Database

package com.bext;
public class IoC {

    public static void main(String[] args) {
        IoC container = new IoC();         
        User user = container.new User( container.new OracleDatabase()); 
        user.add( "Info to persist"); 
    }

    public class User {
        Database database;
        public User( Database database) {
            this.database = database;        }

        void add( String data) {
            database.persist( data);        }
    }

    interface Database {
        public void persist(String data);    }

    public class MySqlDatabase implements Database {
        public void persist(String data) {
            System.out.println("MySqlDatabase persisted [" + data + "]");        }
    }

    public class OracleDatabase implements Database {
        public void persist(String data) {
            System.out.println("OracleDatabase persisted [" + data + "]");        }
    }
}


The Run shows:

OracleDatabase persisted [Info to persist]

eot

viernes, 6 de diciembre de 2019

Dependency Injection Types [Spring]

Dependency Injection

Reference https://medium.com/@ilyailin7777/all-dependency-injection-types-spring-336da7baf51b

Types of Dependency Injection:

- Constructor.
- Setter.
- Field.
- lookup method.


1.- Constructor Injection (Immutable)


package com.bext
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
class ServiceA {
    void method() {
        System.out.println("ServiceA"); 
    }
}

class ServiceB {
    void method() {
        System.out.println("ServiceB");     
    }
}

class DependentService {
    private final ServiceA serviceA; 
    private final ServiceB serviceB;
    public DependentService(ServiceA serviceA, ServiceB serviceB) {
        this.serviceA = serviceA; 
        this.serviceB = serviceB; 
    }

    void method() {
        service1.method();         
        service2.method();     
    }

}

public class Main {
    public static void main(String[] args) {
        ApplicationContext container = new ClassPathXmlApplicationContext("spring.xml");
        ((DependentService) container.getBean("dependentService")).method();    }
}

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <bean id="serviceA" class="com.bext.ServiceA"/> 
    <bean id="serviceB" class="com.bext.ServiceB"/>
 
    <bean id="dependentService" class="com.bext.DependentService"> 
        <constructor-arg type="com.bext.ServiceA" ref="serviceA"/> 
        <constructor-arg type="com.bext.ServiceB" ref="serviceB"/> 
    </bean>
</beans>

Using Annotations

package com.bext;
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;
 
@Service
class ServiceA {
    void method() {
        System.out.println("ServiceA"); 
    }
}

@Service
class ServiceB {
    void method() {
        System.out.println("ServiceB"); 
    }
}

@Service
class DependentService {
    private final ServiceA serviceA; 
    private final ServiceB serviceB;
     
    @Autowired
    public DependentService(ServiceA serviceA, ServiceB serviceB) {
        this.serviceA = serviceA; 
        this.serviceB = serviceB; 
    }

    void method() {
        serviceA.method(); 
        serviceB.method(); 
    }

}

public class Main {
    public static void main(String[] args) {
        ApplicationContext container = new ClassPathXmlApplicationContext("spring.xml");         
        ((DependentService) container.getBean("dependentService")).method(); 
   }
}

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.bext"/>

</beans>


  Advantages
      - Constructed objects are immutable and returned initialized.
      - More dependencies bigger the constructor.
      - can be combined with  setter injection of field injector, constructor parameters indicate
        required dependencies.
   Disadvantages
      - No possiblitiy to change object's dependencies later.
      - Higher change to have circular dependencies.

2.- Setter Injection ( mutability )

class DependentService {
    private ServiceA serviceA; 
    private ServiceB serviceB;
 
    public void setServiceA(ServiceA serviceA) {
        this.serviceA = serviceA; 
    }

    public void setServiceB(ServiceB serviceB) {
        this.serviceB = serviceB; 
    }

    void method() {
        serviceA.method();        serviceB.method(); 
    }
}


<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
    <bean id="serviceA" class="com.bext.ServiceA"/> 
    <bean id="serviceB" class="com.bext.ServiceB"/>
 
    <bean id="dependentService" class="com.bext.DependentService"> 
       <property name="serviceA" ref="serviceA"/> 
       <property name="serviceB" ref="serviceB"/> 
    </bean>
</beans>

Using Annotations


@Service
class DependentService {
    private ServiceA serviceA; 
    private ServiceB serviceB;
     
    @Autowired
    public void setServiceA(ServiceA serviceA) {
        this.serviceA = serviceA; 
    }

    @Autowired
    public void setServiceB(ServiceB serviceB) {
        this.serviceB = serviceB; 
    }

    void method() {
        serviceA.method(); 
        serviceB.method(); 
    }
}

with mandatory dependency (ServiceA final property)

@Service
class DependentService {
    private final ServiceA serviceA; 
    private ServiceB serviceB;
     
    @Autowired
    public void DependentService(ServiceA serviceA) {
        this.serviceA = serviceA; 
    }

    @Autowired
    public void setServiceB(ServiceB serviceB) {
        this.serviceB = serviceB; 
    }

    void method() {
        serviceA.method(); 
        serviceB.method(); 
    }
}

  Advantages
   - Flexibility in dependency resolution or object reconfiguration, at any time.
   Disadvantages
     - Null checks are required.
     - Potentially more error prone and less secure than constructor injection. (by overriding dependencies).

3.- Field Injection

@Service
class DependentService {
    @Autowired
    private ServiceA serviceA;    
    @Autowired
    private ServiceB serviceB;
    void method() { 
     serviceA.method();        serviceB.method();    }
}

Spring Uses reflection to set these values

  Advantages
   - Easy to use, no constructors or setters required.
   - Can be easily combined with the constructor and/or setter approach.
  Disadvantages
   - Less control over object instantiation.
   - A number of dependencies can reach dozens until realize that something went wrong.
   - mutability.

4.- Lookup Method Injection

  Each time method is called, a new ServiceA is created, so the scope is prototype. the default is singleton. 

abstract class DependentService {
    private ServiceB serviceB; 
 
    public void setServiceB(ServiceB serviceB) {
        this.serviceB = serviceB; 
    }

    void method() {
        createServiceA().method(); 
        serviceB.method(); 
    }

    protected abstract ServiceA createService1(); 
}

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> 
 
    <bean id="serviceA" class="com.bext.ServiceA" scope="prototype"/> 
    <bean id="serviceB" class="com.bext.ServiceB"/>
    <bean id="dependentService" class="com.bext.DependentService"> 
      <lookup-method name="createServiceA" bean="serviceA"/> 
      <property name="serviceB" ref="serviceB"/> 
    </bean>
</beans>

Using Annotations

@Service
@Scope(value = "prototype")
class ServiceA {
    void method() {
        System.out.println("ServiceA");     
    }
}

@Service
abstract class DependentService {
    private ServiceB serviceB;
     
    @Autowired
    public void setServiceB(ServiceB serviceB) {
        this.serviceB = serviceB; 
    }

    void method() {
        createServiceA().method(); 
        serviceB.method();     
    }

    @Lookup
    protected abstract ServiceA createServiceA(); 
}