├── BibliotecaVaadin ├── .gitignore ├── .springBeans ├── pom.xml └── src │ ├── main │ ├── java │ │ └── es │ │ │ └── ejercicio │ │ │ └── microservicios │ │ │ ├── BibliotecaVaadinApplication.java │ │ │ ├── application.css │ │ │ ├── rest │ │ │ ├── AppConfiguration.java │ │ │ └── RestClient.java │ │ │ ├── screen │ │ │ ├── AbstractBibliotecaScreen.java │ │ │ ├── BibliotecaMenuBar.java │ │ │ ├── IndexScreen.java │ │ │ ├── autores │ │ │ │ └── AutoresScreen.java │ │ │ ├── categorias │ │ │ │ └── CategoriasScreen.java │ │ │ ├── editoriales │ │ │ │ └── EditorialesScreen.java │ │ │ └── libros │ │ │ │ ├── LibrosFavoritosScreen.java │ │ │ │ └── LibrosScreen.java │ │ │ └── ui │ │ │ └── BilbliotecaUI.java │ ├── resources │ │ └── bootstrap.properties │ └── webapp │ │ └── VAADIN │ │ └── themes │ │ └── ejercicio │ │ ├── addons.scss │ │ ├── banner.png │ │ ├── favicon.ico │ │ └── styles.css │ └── test │ └── java │ └── es │ └── ejercicio │ └── microservicios │ └── BibliotecaVaadinApplicationTests.java ├── README.md ├── ServicioZuul ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── es │ │ │ └── ejercicio │ │ │ └── microservicios │ │ │ └── zuul │ │ │ ├── ServicioZuulApplication.java │ │ │ ├── config │ │ │ └── SecurityConfiguration.java │ │ │ └── filters │ │ │ └── SimpleFilter.java │ └── resources │ │ └── bootstrap.properties │ └── test │ └── java │ └── es │ └── ejercicio │ └── microservicios │ └── zuul │ └── ServicioZuulApplicationTests.java ├── ServidorAutorizacion ├── .gitignore ├── WebContent │ └── META-INF │ │ └── MANIFEST.MF ├── pom.xml └── src │ └── main │ ├── java │ └── es │ │ └── ejercicio │ │ └── microservicios │ │ └── oauth │ │ ├── ServidorAutorizacionApplication.java │ │ ├── config │ │ └── OAuth2Config.java │ │ ├── controller │ │ └── AuthorizationController.java │ │ ├── repository │ │ └── UserRepository.java │ │ └── service │ │ ├── entity │ │ └── User.java │ │ └── impl │ │ └── UserService.java │ └── resources │ ├── bootstrap.properties │ ├── data.sql │ └── schema.sql ├── ServidorConfiguracion ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── es │ │ │ └── ejercicio │ │ │ └── microservicios │ │ │ └── gestionconfiguracion │ │ │ └── GestionConfiguracionApplication.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── es │ └── ejercicio │ └── microservicios │ └── gestionconfiguracion │ └── GestionConfiguracionApplicationTests.java ├── ServidorHystrix ├── .gitignore ├── .mvn │ └── wrapper │ │ ├── maven-wrapper.jar │ │ └── maven-wrapper.properties ├── mvnw ├── mvnw.cmd ├── pom.xml └── src │ ├── main │ ├── java │ │ └── es │ │ │ └── ejercicio │ │ │ └── microservicio │ │ │ └── hystrix │ │ │ └── ServidorHystrixApplication.java │ └── resources │ │ └── application.properties │ └── test │ └── java │ └── es │ └── ejercicio │ └── microservicio │ └── hystrix │ └── DemoApplicationTests.java ├── ServidorRegistro ├── .gitignore ├── pom.xml └── src │ ├── main │ ├── java │ │ └── es │ │ │ └── ejercicio │ │ │ └── microservicios │ │ │ └── eureka │ │ │ └── ServidorEurekaApplication.java │ └── resources │ │ └── application.yml │ └── test │ └── java │ └── es │ └── ejercicio │ └── microservicios │ └── eureka │ └── ServidorEurekaApplicationApplicationTests.java ├── ServidorZipkin ├── .gitignore ├── pom.xml └── src │ └── main │ ├── java │ └── es │ │ └── ejercicio │ │ └── microservicios │ │ └── zipkin │ │ └── ServidorZipkinApplication.java │ └── resources │ └── bootstrap.properties ├── autores ├── .gitignore ├── .springBeans ├── pom.xml └── src │ ├── main │ ├── java │ │ └── es │ │ │ └── ejercicio │ │ │ └── microservicios │ │ │ └── autores │ │ │ ├── AutoresApplication.java │ │ │ ├── config │ │ │ └── AutoresResourceServerConfig.java │ │ │ ├── controller │ │ │ └── AutorController.java │ │ │ ├── entity │ │ │ └── Autor.java │ │ │ ├── repository │ │ │ └── AutorRepository.java │ │ │ ├── service │ │ │ ├── AutorService.java │ │ │ └── impl │ │ │ │ └── AutorServiceImpl.java │ │ │ └── swager │ │ │ └── SwaggerConfig.java │ └── resources │ │ ├── bootstrap.properties │ │ └── data.sql │ └── test │ └── java │ └── es │ └── ejercicio │ └── microservicios │ └── autores │ └── controller │ ├── AutorControllerTest.java │ └── AutoresControllerTestIT.java ├── biblioteca ├── .gitignore ├── .springBeans ├── pom.xml └── src │ └── main │ ├── java │ └── es │ │ └── ejercicio │ │ └── microservicios │ │ └── biblioteca │ │ ├── BibliotecaApplication.java │ │ ├── configuration │ │ └── BibliotecaConfig.java │ │ ├── controller │ │ └── BibliotecaController.java │ │ └── swager │ │ └── SwaggerConfig.java │ └── resources │ └── bootstrap.properties ├── bibliotecaCliente ├── .gitignore ├── pom.xml └── src │ └── main │ └── java │ └── es │ └── ejercicio │ └── microservicios │ └── biblioteca │ ├── cliente │ ├── ClienteAutores.java │ ├── ClienteCategorias.java │ ├── ClienteEditoriales.java │ └── ClienteLibros.java │ ├── config │ ├── FeignAutoConfiguration.java │ ├── OAuth2FeignAutoConfiguration.java │ ├── OAuth2FeignRequestInterceptor.java │ ├── Oauth2ClientConfig.java │ └── properties │ │ └── Oauth2ClientProperties.java │ └── control │ ├── ControlAutores.java │ ├── ControlCategorias.java │ ├── ControlEditoriales.java │ └── ControlLibros.java ├── categorias ├── .gitignore ├── .springBeans ├── pom.xml └── src │ ├── main │ ├── java │ │ └── es │ │ │ └── ejercicio │ │ │ └── microservicios │ │ │ └── categorias │ │ │ ├── CategoriasApplication.java │ │ │ ├── config │ │ │ └── CategoriasResourceServerConfig.java │ │ │ ├── controller │ │ │ └── CategoriaController.java │ │ │ ├── entity │ │ │ └── Categoria.java │ │ │ ├── repository │ │ │ └── CategoriaRepository.java │ │ │ ├── service │ │ │ ├── CategoriaService.java │ │ │ └── impl │ │ │ │ └── CategoriaServiceImpl.java │ │ │ └── swager │ │ │ └── SwaggerConfig.java │ └── resources │ │ ├── bootstrap.properties │ │ └── data.sql │ └── test │ └── java │ └── es │ └── ejercicio │ └── microservicios │ └── categorias │ └── controller │ ├── CategoriaControllerTest.java │ └── CategoriasControllerTestIT.java ├── editoriales ├── .gitignore ├── .springBeans ├── pom.xml └── src │ ├── main │ ├── java │ │ └── es │ │ │ └── ejercicio │ │ │ └── microservicios │ │ │ └── editoriales │ │ │ ├── EditorialesApplication.java │ │ │ ├── config │ │ │ └── EditorialResourceServerConfig.java │ │ │ ├── controller │ │ │ └── EditorialController.java │ │ │ ├── entity │ │ │ └── Editorial.java │ │ │ ├── repository │ │ │ └── EditorialRepository.java │ │ │ ├── service │ │ │ ├── EditorialService.java │ │ │ └── impl │ │ │ │ └── EditorialServiceImpl.java │ │ │ └── swager │ │ │ └── SwaggerConfig.java │ └── resources │ │ ├── bootstrap.properties │ │ └── data.sql │ └── test │ └── java │ └── es │ └── ejercicio │ └── microservicios │ └── editoriales │ └── controller │ ├── EditorialControllerTest.java │ └── EditorialControllerTestIT.java ├── ejercicio-dto ├── .gitignore ├── pom.xml └── src │ └── main │ └── java │ └── es │ └── ejercicio │ └── microservicios │ └── dto │ ├── AutorDTO.java │ ├── CategoriaDTO.java │ ├── EditorialDTO.java │ ├── LibroBibliotecaDTO.java │ ├── LibroDTO.java │ └── OAuthDTO.java └── libros ├── .gitignore ├── .springBeans ├── pom.xml └── src ├── main ├── java │ └── es │ │ └── ejercicio │ │ └── microservicios │ │ └── libros │ │ ├── LibrosApplication.java │ │ ├── config │ │ └── LibrosResourceServerConfig.java │ │ ├── controller │ │ └── LibroController.java │ │ ├── entity │ │ └── Libro.java │ │ ├── repository │ │ └── LibroRepository.java │ │ ├── service │ │ ├── LibroService.java │ │ └── impl │ │ │ └── LibroServiceImpl.java │ │ └── swager │ │ └── SwaggerConfig.java └── resources │ ├── bootstrap.properties │ └── data.sql └── test └── java └── es └── ejercicio └── microservicios └── libros └── controller ├── LibrosControllerTest.java └── LibrosControllerTestIT.java /BibliotecaVaadin/.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | .classpath 3 | .settings 4 | .project 5 | -------------------------------------------------------------------------------- /BibliotecaVaadin/.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /BibliotecaVaadin/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | es.ejercicio.microservicios 6 | BibliotecaVaadin 7 | 0.0.1-SNAPSHOT 8 | jar 9 | 10 | bibliotecavaadin 11 | Aplicacion Biblioteca Vaadin 12 | 13 | 14 | org.springframework.boot 15 | spring-boot-starter-parent 16 | 1.5.8.RELEASE 17 | 18 | 19 | 20 | 21 | UTF-8 22 | UTF-8 23 | 1.8 24 | 8.1.0 25 | 0.0.1-SNAPSHOT 26 | Dalston.SR4 27 | jar 28 | 0.23.0 29 | Dalston.SR4 30 | 31 | 32 | 33 | 34 | org.springframework.cloud 35 | spring-cloud-starter-sleuth 36 | 37 | 38 | org.springframework.cloud 39 | spring-cloud-starter-zipkin 40 | 41 | 42 | com.vaadin 43 | vaadin-spring-boot-starter 44 | 45 | 46 | org.springframework.cloud 47 | spring-cloud-starter-config 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-test 52 | test 53 | 54 | 55 | 56 | 57 | javax.ws.rs 58 | javax.ws.rs-api 59 | 2.0.1 60 | 61 | 62 | org.glassfish.jersey.core 63 | jersey-client 64 | 65 | 66 | org.glassfish.jersey.media 67 | jersey-media-jaxb 68 | 69 | 70 | com.google.code.gson 71 | gson 72 | 73 | 74 | org.projectlombok 75 | lombok 76 | 77 | 78 | es.ejercicio.microservicios 79 | ejercicio-dto 80 | ${ejercicio-dto.version} 81 | 82 | 83 | 84 | 85 | 86 | 87 | org.springframework.cloud 88 | spring-cloud-dependencies 89 | ${spring-cloud.version} 90 | pom 91 | import 92 | 93 | 94 | com.vaadin 95 | vaadin-bom 96 | ${vaadin.version} 97 | pom 98 | import 99 | 100 | 101 | 102 | 103 | 104 | local 105 | 106 | true 107 | 108 | 109 | 110 | docker 111 | 112 | 113 | 114 | io.fabric8 115 | docker-maven-plugin 116 | ${maven-docker-fabric8.version} 117 | 118 | medium 119 | 120 | 121 | ${project.name}:${project.version} 122 | ${project.name} 123 | 124 | java:8u40 125 | 126 | artifact-with-dependencies 127 | 128 | java -Djava.security.egd=file:/dev/./urandom -jar -Xdebug /maven/${project.build.finalName}.${artifact.extension} 129 | 130 | 131 | 132 | 133 | 134 | 135 | build-image 136 | package 137 | 138 | build 139 | 140 | 141 | 142 | start 143 | pre-integration-test 144 | 145 | build 146 | start 147 | 148 | 149 | 150 | stop 151 | post-integration-test 152 | 153 | stop 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | src/main/java 164 | 165 | 166 | src/main/java 167 | 168 | **/*.java 169 | 170 | 171 | 172 | src/main/resources 173 | 174 | 175 | src/main/webapp 176 | 177 | 178 | 179 | 180 | org.springframework.boot 181 | spring-boot-maven-plugin 182 | 183 | 184 | 185 | 186 | 187 | 188 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/BibliotecaVaadinApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class BibliotecaVaadinApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(BibliotecaVaadinApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/application.css: -------------------------------------------------------------------------------- 1 | .v-caption-inline-label{ 2 | display: inline-block; 3 | } -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/rest/AppConfiguration.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.rest; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.web.client.RestTemplate; 6 | 7 | @Configuration 8 | public class AppConfiguration { 9 | 10 | @Bean 11 | public RestTemplate restTemplate() { 12 | return new RestTemplate(); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/rest/RestClient.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.rest; 2 | 3 | import java.util.Arrays; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.stereotype.Component; 9 | 10 | import es.ejercicio.microservicios.dto.AutorDTO; 11 | import es.ejercicio.microservicios.dto.CategoriaDTO; 12 | import es.ejercicio.microservicios.dto.EditorialDTO; 13 | import es.ejercicio.microservicios.dto.LibroBibliotecaDTO; 14 | import lombok.extern.slf4j.Slf4j; 15 | 16 | @Slf4j 17 | @Component 18 | public class RestClient { 19 | 20 | @Value("${endpoint.LibrosBiblioteca}") 21 | private String WS_URI_LIST_LIBROS; 22 | 23 | @Value("${endpoint.LibrosFavoritosBiblioteca}") 24 | private String WS_URI_LIST_LIBROS_FAVORITOS; 25 | 26 | @Value("${endpoint.AutoresBiblioteca}") 27 | private String WS_URI_LIST_AUTORES; 28 | 29 | @Value("${endpoint.EditorialesBiblioteca}") 30 | private String WS_URI_LIST_EDITORIALES; 31 | 32 | @Value("${endpoint.CategoriasBiblioteca}") 33 | private String WS_URI_LIST_CATEGORIAS; 34 | 35 | @Autowired 36 | AppConfiguration config; 37 | 38 | public List obtenerLibrosBiblioteca() throws RuntimeException { 39 | log.debug("Inicio obtenerLibrosBiblioteca"); 40 | LibroBibliotecaDTO[] mensaje = config.restTemplate().getForObject(WS_URI_LIST_LIBROS, LibroBibliotecaDTO[].class); 41 | return Arrays.asList(mensaje); 42 | } 43 | 44 | public List obtenerLibrosFavoritosBiblioteca() throws RuntimeException { 45 | log.debug("Inicio obtenerLibrosFavoritosBiblioteca"); 46 | LibroBibliotecaDTO[] mensaje = config.restTemplate().getForObject(WS_URI_LIST_LIBROS_FAVORITOS, LibroBibliotecaDTO[].class); 47 | return Arrays.asList(mensaje); 48 | } 49 | 50 | public List obtenerAutoresBiblioteca() throws RuntimeException { 51 | log.debug("Inicio obtenerAutoresBiblioteca"); 52 | AutorDTO[] mensaje = config.restTemplate().getForObject(WS_URI_LIST_AUTORES, AutorDTO[].class); 53 | return Arrays.asList(mensaje); 54 | } 55 | 56 | public List obtenerCategoriasBiblioteca() throws RuntimeException { 57 | log.debug("Inicio obtenerAutoresBiblioteca"); 58 | CategoriaDTO[] mensaje = config.restTemplate().getForObject(WS_URI_LIST_CATEGORIAS, CategoriaDTO[].class); 59 | return Arrays.asList(mensaje); 60 | } 61 | 62 | public List obtenerEditorialesBiblioteca() throws RuntimeException { 63 | log.debug("Inicio obtenerAutoresBiblioteca"); 64 | EditorialDTO[] mensaje = config.restTemplate().getForObject(WS_URI_LIST_EDITORIALES, EditorialDTO[].class); 65 | return Arrays.asList(mensaje); 66 | } 67 | 68 | 69 | } 70 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/screen/AbstractBibliotecaScreen.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.screen; 2 | 3 | import java.util.Iterator; 4 | import java.util.Optional; 5 | 6 | import javax.annotation.PostConstruct; 7 | 8 | import org.springframework.stereotype.Component; 9 | 10 | import com.vaadin.ui.HasComponents; 11 | import com.vaadin.ui.VerticalLayout; 12 | 13 | import lombok.extern.slf4j.Slf4j; 14 | 15 | @Component 16 | @Slf4j 17 | public abstract class AbstractBibliotecaScreen extends VerticalLayout { 18 | 19 | private static final long serialVersionUID = -46212438974612614L; 20 | 21 | @PostConstruct 22 | public void init() { 23 | log.info("Inicio {}", this.getClass().getName()); 24 | 25 | this.removeAllComponents(); 26 | 27 | this.addComponent(new BibliotecaMenuBar()); 28 | 29 | initScreen(); 30 | 31 | log.info("Fin {}", this.getClass().getName()); 32 | 33 | } 34 | 35 | public abstract void initScreen(); 36 | 37 | protected Optional getComponentById(String id, 38 | Iterator itComponent) { 39 | 40 | while (itComponent.hasNext()) { 41 | com.vaadin.ui.Component component = itComponent.next(); 42 | if (id.equals(component.getId())) { 43 | return Optional.of(component); 44 | } else if (component instanceof HasComponents) { 45 | return getComponentById(id, ((HasComponents) component).iterator()); 46 | } 47 | } 48 | 49 | return Optional.empty(); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/screen/BibliotecaMenuBar.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.screen; 2 | 3 | import com.vaadin.ui.MenuBar; 4 | 5 | import es.ejercicio.microservicios.screen.autores.AutoresScreen; 6 | import es.ejercicio.microservicios.screen.categorias.CategoriasScreen; 7 | import es.ejercicio.microservicios.screen.editoriales.EditorialesScreen; 8 | import es.ejercicio.microservicios.screen.libros.LibrosFavoritosScreen; 9 | import es.ejercicio.microservicios.screen.libros.LibrosScreen; 10 | import lombok.extern.slf4j.Slf4j; 11 | 12 | @Slf4j 13 | public class BibliotecaMenuBar extends MenuBar { 14 | 15 | private static final long serialVersionUID = 4570934148969606674L; 16 | 17 | private MenuItem itemLibros; 18 | private MenuItem itemLibrosFavoritos; 19 | private MenuItem itemLibrosTodos; 20 | private MenuItem itemAutores; 21 | private MenuItem itemListadoAutores; 22 | private MenuItem itemCategorias; 23 | private MenuItem itemListadoCategorias; 24 | private MenuItem itemEditoriales; 25 | private MenuItem itemListadoEditoriales; 26 | private MenuItem itemSalir; 27 | 28 | public BibliotecaMenuBar() { 29 | super(); 30 | 31 | itemLibros = this.addItem("Libros", null, null); 32 | itemLibrosTodos = itemLibros.addItem("Libros", null, selectedItem -> menuSelected(selectedItem)); 33 | itemLibrosFavoritos = itemLibros.addItem("Libros Favoritos", null, selectedItem -> menuSelected(selectedItem)); 34 | itemAutores = this.addItem("Autores", null, null); 35 | itemListadoAutores = itemAutores.addItem("Listado Autores", null, selectedItem -> menuSelected(selectedItem)); 36 | itemCategorias = this.addItem("Categorias", null, null); 37 | itemListadoCategorias = itemCategorias.addItem("Listado Categorias", null, selectedItem -> menuSelected(selectedItem)); 38 | itemEditoriales = this.addItem("Editoriales", null, null); 39 | itemListadoEditoriales = itemEditoriales.addItem("Listado Editoriales", null, selectedItem -> menuSelected(selectedItem)); 40 | itemSalir = this.addItem("Salir", null, selectedItem -> menuSelected(selectedItem)); 41 | 42 | } 43 | 44 | private void menuSelected(MenuItem selectedItem) { 45 | log.info("Selected item: " + selectedItem.getId()); 46 | 47 | final int itemLibrosId = itemLibrosTodos != null ? itemLibrosTodos.getId() : -1; 48 | final int itemLibrosFavId = itemLibrosFavoritos != null ? itemLibrosFavoritos.getId() : -1; 49 | final int itemListadoAutoresId = itemListadoAutores != null ? itemListadoAutores.getId() : -1; 50 | final int itemListadoCategoriasId = itemListadoCategorias != null ? itemListadoCategorias.getId() : -1; 51 | final int itemListadoEditorialesId = itemListadoEditoriales != null ? itemListadoEditoriales.getId() : -1; 52 | final int itemSalirId= itemSalir != null ? itemSalir.getId() : -1; 53 | 54 | 55 | if (selectedItem != null && selectedItem.getId() != -1) { 56 | 57 | if (itemLibrosId == selectedItem.getId()) { 58 | getUI().getNavigator().navigateTo(LibrosScreen.VIEW_NAME); 59 | } else if (itemLibrosFavId == selectedItem.getId()) { 60 | getUI().getNavigator().navigateTo(LibrosFavoritosScreen.VIEW_NAME); 61 | } else if (itemListadoAutoresId == selectedItem.getId()) { 62 | getUI().getNavigator().navigateTo(AutoresScreen.VIEW_NAME); 63 | } else if (itemListadoEditorialesId == selectedItem.getId()) { 64 | getUI().getNavigator().navigateTo(EditorialesScreen.VIEW_NAME); 65 | } else if (itemListadoCategoriasId == selectedItem.getId()) { 66 | getUI().getNavigator().navigateTo(CategoriasScreen.VIEW_NAME); 67 | } else if (itemSalirId == selectedItem.getId()) { 68 | getUI().getNavigator().navigateTo(IndexScreen.VIEW_NAME); 69 | } 70 | } 71 | 72 | 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/screen/IndexScreen.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.screen; 2 | 3 | import com.vaadin.navigator.View; 4 | import com.vaadin.spring.annotation.SpringView; 5 | 6 | 7 | @SpringView(name = IndexScreen.VIEW_NAME) 8 | public class IndexScreen extends AbstractBibliotecaScreen implements View { 9 | 10 | public static final String VIEW_NAME = ""; 11 | 12 | private static final long serialVersionUID = 6092429507520923718L; 13 | 14 | public void initScreen() { 15 | 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/screen/autores/AutoresScreen.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.screen.autores; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | 7 | import com.vaadin.navigator.View; 8 | import com.vaadin.spring.annotation.SpringView; 9 | import com.vaadin.ui.Grid; 10 | import com.vaadin.ui.Grid.SelectionMode; 11 | 12 | import es.ejercicio.microservicios.dto.AutorDTO; 13 | import es.ejercicio.microservicios.rest.RestClient; 14 | import es.ejercicio.microservicios.screen.AbstractBibliotecaScreen; 15 | import lombok.extern.slf4j.Slf4j; 16 | 17 | @Slf4j 18 | @SpringView(name = AutoresScreen.VIEW_NAME) 19 | public class AutoresScreen extends AbstractBibliotecaScreen implements View { 20 | 21 | public static final String VIEW_NAME = "autores"; 22 | 23 | private static final long serialVersionUID = 2851204137357460687L; 24 | 25 | private Grid gridAutores; 26 | private List listaAutores; 27 | 28 | @Autowired 29 | RestClient restClient; 30 | 31 | 32 | @Override 33 | public void initScreen() { 34 | log.debug("Inicio Autores"); 35 | listaAutores = restClient.obtenerAutoresBiblioteca(); 36 | gridAutores = initLibrosGrid(); 37 | 38 | this.addComponents(gridAutores); 39 | 40 | } 41 | 42 | private Grid initLibrosGrid() { 43 | 44 | gridAutores = new Grid(); 45 | 46 | gridAutores.addColumn(AutorDTO::getId).setCaption("Id"); 47 | gridAutores.addColumn(AutorDTO::getNombre).setCaption("Nombre"); 48 | 49 | gridAutores.setEnabled(true); 50 | gridAutores.setSelectionMode(SelectionMode.SINGLE); 51 | gridAutores.setSizeFull(); 52 | 53 | gridAutores.setItems(this.listaAutores); 54 | 55 | return gridAutores; 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/screen/categorias/CategoriasScreen.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.screen.categorias; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | 7 | import com.vaadin.navigator.View; 8 | import com.vaadin.spring.annotation.SpringView; 9 | import com.vaadin.ui.Grid; 10 | import com.vaadin.ui.Grid.SelectionMode; 11 | 12 | import es.ejercicio.microservicios.dto.CategoriaDTO; 13 | import es.ejercicio.microservicios.rest.RestClient; 14 | import es.ejercicio.microservicios.screen.AbstractBibliotecaScreen; 15 | import lombok.extern.slf4j.Slf4j; 16 | 17 | @Slf4j 18 | @SpringView(name = CategoriasScreen.VIEW_NAME) 19 | public class CategoriasScreen extends AbstractBibliotecaScreen implements View { 20 | 21 | public static final String VIEW_NAME = "categorias"; 22 | 23 | private static final long serialVersionUID = 2851204137357460687L; 24 | 25 | private Grid gridCategoria; 26 | private List listaCategorias; 27 | 28 | @Autowired 29 | RestClient restClient; 30 | 31 | 32 | @Override 33 | public void initScreen() { 34 | log.debug("Inicio Editoriales"); 35 | listaCategorias = restClient.obtenerCategoriasBiblioteca(); 36 | gridCategoria = initLibrosGrid(); 37 | 38 | this.addComponents(gridCategoria); 39 | 40 | } 41 | 42 | private Grid initLibrosGrid() { 43 | 44 | gridCategoria = new Grid(); 45 | 46 | gridCategoria.addColumn(CategoriaDTO::getId).setCaption("Id"); 47 | gridCategoria.addColumn(CategoriaDTO::getNombre).setCaption("Nombre"); 48 | 49 | gridCategoria.setEnabled(true); 50 | gridCategoria.setSelectionMode(SelectionMode.SINGLE); 51 | gridCategoria.setSizeFull(); 52 | 53 | gridCategoria.setItems(this.listaCategorias); 54 | 55 | return gridCategoria; 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/screen/editoriales/EditorialesScreen.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.screen.editoriales; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | 7 | import com.vaadin.navigator.View; 8 | import com.vaadin.spring.annotation.SpringView; 9 | import com.vaadin.ui.Grid; 10 | import com.vaadin.ui.Grid.SelectionMode; 11 | 12 | import es.ejercicio.microservicios.dto.EditorialDTO; 13 | import es.ejercicio.microservicios.rest.RestClient; 14 | import es.ejercicio.microservicios.screen.AbstractBibliotecaScreen; 15 | import lombok.extern.slf4j.Slf4j; 16 | 17 | @Slf4j 18 | @SpringView(name = EditorialesScreen.VIEW_NAME) 19 | public class EditorialesScreen extends AbstractBibliotecaScreen implements View { 20 | 21 | public static final String VIEW_NAME = "editoriales"; 22 | 23 | private static final long serialVersionUID = 2851204137357460687L; 24 | 25 | private Grid gridEditorial; 26 | private List listaEditorial; 27 | 28 | @Autowired 29 | RestClient restClient; 30 | 31 | 32 | @Override 33 | public void initScreen() { 34 | log.debug("Inicio Editoriales"); 35 | listaEditorial = restClient.obtenerEditorialesBiblioteca(); 36 | gridEditorial = initLibrosGrid(); 37 | 38 | this.addComponents(gridEditorial); 39 | 40 | } 41 | 42 | private Grid initLibrosGrid() { 43 | 44 | gridEditorial = new Grid(); 45 | 46 | gridEditorial.addColumn(EditorialDTO::getId).setCaption("Id"); 47 | gridEditorial.addColumn(EditorialDTO::getNombre).setCaption("Nombre"); 48 | 49 | gridEditorial.setEnabled(true); 50 | gridEditorial.setSelectionMode(SelectionMode.SINGLE); 51 | gridEditorial.setSizeFull(); 52 | 53 | gridEditorial.setItems(this.listaEditorial); 54 | 55 | return gridEditorial; 56 | 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/screen/libros/LibrosFavoritosScreen.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.screen.libros; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | 7 | import com.vaadin.navigator.View; 8 | import com.vaadin.spring.annotation.SpringView; 9 | import com.vaadin.ui.Grid; 10 | import com.vaadin.ui.Grid.SelectionMode; 11 | 12 | import es.ejercicio.microservicios.dto.LibroBibliotecaDTO; 13 | import es.ejercicio.microservicios.rest.RestClient; 14 | import es.ejercicio.microservicios.screen.AbstractBibliotecaScreen; 15 | import lombok.extern.slf4j.Slf4j; 16 | 17 | @Slf4j 18 | @SpringView(name = LibrosFavoritosScreen.VIEW_NAME) 19 | public class LibrosFavoritosScreen extends AbstractBibliotecaScreen implements View { 20 | 21 | public static final String VIEW_NAME = "librosfavoritos"; 22 | 23 | private static final long serialVersionUID = 2851204137357460687L; 24 | 25 | private Grid gridLibros; 26 | private List listaLibros; 27 | 28 | @Autowired 29 | RestClient restClient; 30 | 31 | 32 | @Override 33 | public void initScreen() { 34 | log.debug("Inicio Biblioteca Libros"); 35 | listaLibros = restClient.obtenerLibrosFavoritosBiblioteca(); 36 | gridLibros = initLibrosGrid(); 37 | 38 | this.addComponents(gridLibros); 39 | 40 | } 41 | 42 | private Grid initLibrosGrid() { 43 | 44 | gridLibros = new Grid(); 45 | 46 | gridLibros.addColumn(LibroBibliotecaDTO::getId).setCaption("Id"); 47 | gridLibros.addColumn(LibroBibliotecaDTO::getTitulo).setCaption("Título"); 48 | gridLibros.addColumn(LibroBibliotecaDTO::getDescripcion).setCaption("Descripción"); 49 | gridLibros.addColumn(LibroBibliotecaDTO::getAutor).setCaption("Autor"); 50 | gridLibros.addColumn(LibroBibliotecaDTO::getCategoria).setCaption("Categoria"); 51 | gridLibros.addColumn(LibroBibliotecaDTO::getEditorial).setCaption("Editorial"); 52 | 53 | 54 | gridLibros.setEnabled(true); 55 | gridLibros.setSelectionMode(SelectionMode.SINGLE); 56 | gridLibros.setSizeFull(); 57 | 58 | gridLibros.setItems(this.listaLibros); 59 | 60 | return gridLibros; 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/screen/libros/LibrosScreen.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.screen.libros; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | 7 | import com.vaadin.navigator.View; 8 | import com.vaadin.spring.annotation.SpringView; 9 | import com.vaadin.ui.Grid; 10 | import com.vaadin.ui.Grid.SelectionMode; 11 | 12 | import es.ejercicio.microservicios.dto.LibroBibliotecaDTO; 13 | import es.ejercicio.microservicios.rest.RestClient; 14 | import es.ejercicio.microservicios.screen.AbstractBibliotecaScreen; 15 | import lombok.extern.slf4j.Slf4j; 16 | 17 | @Slf4j 18 | @SpringView(name = LibrosScreen.VIEW_NAME) 19 | public class LibrosScreen extends AbstractBibliotecaScreen implements View { 20 | 21 | public static final String VIEW_NAME = "libros"; 22 | 23 | private static final long serialVersionUID = 2851204137357460687L; 24 | 25 | private Grid gridLibros; 26 | private List listaLibros; 27 | 28 | @Autowired 29 | RestClient restClient; 30 | 31 | 32 | @Override 33 | public void initScreen() { 34 | log.debug("Inicio Biblioteca Libros"); 35 | listaLibros = restClient.obtenerLibrosBiblioteca(); 36 | gridLibros = initLibrosGrid(); 37 | 38 | this.addComponents(gridLibros); 39 | 40 | } 41 | 42 | private Grid initLibrosGrid() { 43 | 44 | gridLibros = new Grid(); 45 | 46 | gridLibros.addColumn(LibroBibliotecaDTO::getId).setCaption("Id"); 47 | gridLibros.addColumn(LibroBibliotecaDTO::getTitulo).setCaption("Título"); 48 | gridLibros.addColumn(LibroBibliotecaDTO::getDescripcion).setCaption("Descripción"); 49 | gridLibros.addColumn(LibroBibliotecaDTO::getAutor).setCaption("Autor"); 50 | gridLibros.addColumn(LibroBibliotecaDTO::getCategoria).setCaption("Categoria"); 51 | gridLibros.addColumn(LibroBibliotecaDTO::getEditorial).setCaption("Editorial"); 52 | 53 | 54 | gridLibros.setEnabled(true); 55 | gridLibros.setSelectionMode(SelectionMode.SINGLE); 56 | gridLibros.setSizeFull(); 57 | 58 | gridLibros.setItems(this.listaLibros); 59 | 60 | return gridLibros; 61 | 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/java/es/ejercicio/microservicios/ui/BilbliotecaUI.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.ui; 2 | 3 | import com.vaadin.navigator.Navigator; 4 | import com.vaadin.navigator.View; 5 | import com.vaadin.navigator.ViewDisplay; 6 | import com.vaadin.server.Page; 7 | import com.vaadin.server.VaadinRequest; 8 | import com.vaadin.spring.annotation.SpringUI; 9 | import com.vaadin.spring.annotation.SpringViewDisplay; 10 | import com.vaadin.ui.Component; 11 | import com.vaadin.ui.Panel; 12 | import com.vaadin.ui.UI; 13 | import com.vaadin.ui.VerticalLayout; 14 | 15 | 16 | @SpringUI 17 | @SpringViewDisplay 18 | public class BilbliotecaUI extends UI implements ViewDisplay { 19 | 20 | private static final long serialVersionUID = -5510796932223511405L; 21 | 22 | Navigator navigator; 23 | 24 | private Panel springViewDisplay; 25 | 26 | @Override 27 | protected void init(VaadinRequest request) { 28 | Page.getCurrent().setTitle("Biblioteca"); 29 | 30 | final VerticalLayout root = new VerticalLayout(); 31 | root.setSizeFull(); 32 | setContent(root); 33 | 34 | VerticalLayout banner = new VerticalLayout(); 35 | banner.addStyleNames("banner"); 36 | banner.setId("banner"); 37 | banner.setWidth(100, Unit.PERCENTAGE); 38 | banner.setSpacing(false); 39 | 40 | root.addComponent(banner); 41 | 42 | springViewDisplay = new Panel(); 43 | springViewDisplay.setSizeFull(); 44 | root.addComponent(springViewDisplay); 45 | root.setExpandRatio(springViewDisplay, 1.0f); 46 | 47 | } 48 | 49 | @Override 50 | public void showView(View view) { 51 | springViewDisplay.setContent((Component) view); 52 | 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/resources/bootstrap.properties: -------------------------------------------------------------------------------- 1 | spring.cloud.config.uri=http://${CONFIG_HOST:localhost}:${CONFIG_PORT:8888} 2 | spring.application.name=bibliotecavaadin 3 | spring.profiles.active=${PROFILE:default} 4 | endpoints.refresh.sensitive=false -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/webapp/VAADIN/themes/ejercicio/addons.scss: -------------------------------------------------------------------------------- 1 | /* This file is automatically managed and will be overwritten from time to time. */ 2 | /* Do not manually edit this file. */ 3 | 4 | /* Import and include this mixin into your project theme to include the addon themes */ 5 | @mixin addons { 6 | } 7 | 8 | -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/webapp/VAADIN/themes/ejercicio/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/juanmacintas/ejercicioMicroserviciosSpringCloud/f6b85413042051955217df14bb46ccc3cbeb4ce9/BibliotecaVaadin/src/main/webapp/VAADIN/themes/ejercicio/banner.png -------------------------------------------------------------------------------- /BibliotecaVaadin/src/main/webapp/VAADIN/themes/ejercicio/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/juanmacintas/ejercicioMicroserviciosSpringCloud/f6b85413042051955217df14bb46ccc3cbeb4ce9/BibliotecaVaadin/src/main/webapp/VAADIN/themes/ejercicio/favicon.ico -------------------------------------------------------------------------------- /BibliotecaVaadin/src/test/java/es/ejercicio/microservicios/BibliotecaVaadinApplicationTests.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class BibliotecaVaadinApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ejercicioMircroserviciosSpringCloud 2 | Microservices demo using Spring Boot, Spring Cloud Config, Eureka, Feign, Hystrix and Zipkin. 3 | 4 | # Ejercicio Microservicios Spring Cloud 5 | 6 | * Contiene 12 microservicios distintos. 7 | * Servidor Configuración (Spring Cloud Config) Microservicio encargado de proveer los ficheros de configuración al resto de microservicios. 8 | * Servidor Registro (Eureka) Servicio donde se registra el resto de microservicios. Su url de acceso es http://localhost:8084/ 9 | * Servidor Autorización (Oauth2 Authorization Server). Servidor que valida los accesos a los microservicios. Contiene una base de datos 10 | con los credenciales permitidos. 11 | * Servidor Hystrix - (Hystrix Dashboard) - Servicio de información de las distintas ejecuciones de llamadas entre microservicios. 12 | Su url de acceso es http://localhost:8072/hystrix 13 | * Servidor Zipkin - (Zipkin Dahsboard) - Servicio de Log distribuido. Permite visualizar la ejecución y llamadas entre los microservicios. 14 | Su url de acceso es http://localhost:9411 15 | * Libros - Microservicio mantenimiento entidad libros. 16 | * Categorias - Microservicio mantenimiento entidad categorias. 17 | * Editoriales - Microservicio mantenimiento entidad editoriales. 18 | * Autores - Microservicio mantenimiento entidad autores. 19 | * Biblioteca - Microservicio biblioteca.(Microservicio Edge que accede al resto de microservicios) 20 | * ServicioZuul - Proxy Inverso con entrada a la aplicación. Tiene parametrizado el microservicio Biblioteca. 21 | * BibliotecaVaadin - Frontal Web Vaadin para visualizar la información. Hace uso del servidio Edge de Bilioteca para el acceso a datos. Su url de acceso es http://localhost:8086/ 22 | 23 | * Contiene 2 librerías de utilidades. 24 | * ejercicio-dto - Contiene todos los contratos de entrada/salida de los distintos REST usados. Todos los microservicios de la biblioteca 25 | lo importan. 26 | * BibliotecaCliente - Interfaz Feing y Controlador de error con Hystrix implementado para las distintas llamadas a los microservicios. 27 | Este cliente es usado por Biblioteca para obtener la información de las disintas entidades. 28 | 29 | * La entrada para obtener la información será a traves del puerto 8080 de Zuul. 30 | * Para obtener todos los libros -> http://localhost:8080/biblioteca/biblioteca/getAll 31 | * Para obtener los libros favoritos -> http://localhost:8080/biblioteca/biblioteca/getAllFavoritos 32 | * Para obtener un libro por su id -> http://localhost:8080/biblioteca/biblioteca/getLibro/1 33 | 34 | 35 | 36 | 37 | # Actualización Docker 38 | * Para generar imagen docker 39 | * mvn package -P docker 40 | * mvn -DCONFIG_HOST=192.168.99.100 package -P docker 41 | 42 | 43 | 44 | Para establecer valor de variable de entorno al iniciar contenedor incluir -e VARIABLE = VALOR 45 | * Para arrancar servicio configuracion: 46 | docker run -p 8888:8888 -d --name servidorconfiguracion servidorconfiguracion:0.0.1-SNAPSHOT 47 | * Para arrancar servicio eureka 48 | docker run -p 8084:8084 -d --name servidorregistro servidorregistro:0.0.1-SNAPSHOT 49 | * Para arrancar servidor zipkin 50 | docker run -e CONFIG_HOST=192.168.99.100 -e PROFILE=docker -p 9411:9411 -d --name servidorzipkin servidorzipkin:0.0.1-SNAPSHOT 51 | * Para arrancar servidor autotizacion 52 | docker run -e CONFIG_HOST=192.168.99.100 -e PROFILE=docker -p 9000:9000 -d --name servidorautorizacion servidorautorizacion:0.0.1-SNAPSHOT 53 | * Para arrancar servicio zuul 54 | docker run -e CONFIG_HOST=192.168.99.100 -e PROFILE=docker -p 8080:8080 -d --name serviciozuul serviciozuul:0.0.1-SNAPSHOT 55 | * Para arrancar autores 56 | docker run -e CONFIG_HOST=192.168.99.100 -e PROFILE=docker -d --name autores autores:0.0.1-SNAPSHOT 57 | * Para arrancar categorias 58 | docker run -e CONFIG_HOST=192.168.99.100 -e PROFILE=docker -d --name categorias categorias:0.0.1-SNAPSHOT 59 | * Para arrancar editoriales 60 | docker run -e CONFIG_HOST=192.168.99.100 -e PROFILE=docker -d --name editoriales editoriales:0.0.1-SNAPSHOT 61 | * Para arrancar libros 62 | docker run -e CONFIG_HOST=192.168.99.100 -e PROFILE=docker -d --name libros libros:0.0.1-SNAPSHOT 63 | * Para arrancar biblioteca 64 | docker run -e CONFIG_HOST=192.168.99.100 -e PROFILE=docker -d --name biblioteca biblioteca:0.0.1-SNAPSHOT 65 | * Para arrancar bibliotecavaadin 66 | docker run -e CONFIG_HOST=192.168.99.100 -e PROFILE=docker -p 8086:8086 -d --name bibliotecavaadin bibliotecavaadin:0.0.1-SNAPSHOT 67 | 68 | 69 | La url de acceso es http://192.168.99.100:8086/ 70 | 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /ServicioZuul/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ 25 | 26 | 27 | ### Maven ### 28 | .mvn/ 29 | mvnw 30 | mvnw.cmd 31 | -------------------------------------------------------------------------------- /ServicioZuul/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | es.ejercicio.microservicios 7 | ServicioZuul 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | serviciozuul 12 | Zuul is an edge service that provides dynamic routing, monitoring, resiliency, security, and more. 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.8.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Dalston.SR4 26 | ${project.name} 27 | 0.23.0 28 | jar 29 | 30 | 31 | 32 | 33 | org.springframework.cloud 34 | spring-cloud-starter-eureka 35 | 36 | 37 | org.springframework.cloud 38 | spring-cloud-starter-zuul 39 | 40 | 41 | org.springframework.cloud 42 | spring-cloud-starter-config 43 | 44 | 45 | org.springframework.cloud 46 | spring-cloud-starter-oauth2 47 | 48 | 49 | org.springframework.cloud 50 | spring-cloud-starter-security 51 | 52 | 53 | org.springframework.boot 54 | spring-boot-starter-test 55 | test 56 | 57 | 58 | org.projectlombok 59 | lombok 60 | 61 | 62 | 63 | 64 | 65 | 66 | org.springframework.cloud 67 | spring-cloud-dependencies 68 | ${spring-cloud.version} 69 | pom 70 | import 71 | 72 | 73 | 74 | 75 | 76 | local 77 | 78 | true 79 | 80 | 81 | 82 | docker 83 | 84 | 85 | 86 | io.fabric8 87 | docker-maven-plugin 88 | ${maven-docker-fabric8.version} 89 | 90 | medium 91 | 92 | 93 | ${project.name}:${project.version} 94 | ${project.name} 95 | 96 | java:8u40 97 | 98 | artifact-with-dependencies 99 | 100 | java -Djava.security.egd=file:/dev/./urandom -jar -Xdebug /maven/${project.build.finalName}.${artifact.extension} 101 | 102 | 103 | 104 | 105 | 106 | 107 | build-image 108 | package 109 | 110 | build 111 | 112 | 113 | 114 | start 115 | pre-integration-test 116 | 117 | build 118 | start 119 | 120 | 121 | 122 | stop 123 | post-integration-test 124 | 125 | stop 126 | 127 | 128 | 129 | 130 | 131 | maven-failsafe-plugin 132 | 2.17 133 | 134 | 135 | integration-test 136 | 137 | integration-test 138 | 139 | 140 | 141 | verify 142 | 143 | verify 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | org.springframework.boot 156 | spring-boot-maven-plugin 157 | 158 | 159 | 160 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /ServicioZuul/src/main/java/es/ejercicio/microservicios/zuul/ServicioZuulApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.zuul; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso; 6 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 7 | import org.springframework.cloud.netflix.zuul.EnableZuulProxy; 8 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 9 | 10 | @EnableDiscoveryClient 11 | @EnableZuulProxy 12 | @EnableOAuth2Sso 13 | @EnableResourceServer 14 | @SpringBootApplication 15 | public class ServicioZuulApplication { 16 | 17 | public static void main(String[] args) { 18 | 19 | SpringApplication.run(ServicioZuulApplication.class, args); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /ServicioZuul/src/main/java/es/ejercicio/microservicios/zuul/config/SecurityConfiguration.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.zuul.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.core.annotation.Order; 5 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 7 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 8 | 9 | @Configuration 10 | @EnableWebSecurity 11 | @Order(value = -1) 12 | public class SecurityConfiguration 13 | extends WebSecurityConfigurerAdapter { 14 | 15 | @Override 16 | public void configure(HttpSecurity http) throws Exception { 17 | 18 | http.authorizeRequests().antMatchers("/uaa/**", "/biblioteca/**").permitAll().and() 19 | .authorizeRequests().anyRequest().authenticated(); 20 | http.csrf().disable(); 21 | http.httpBasic().disable(); 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /ServicioZuul/src/main/java/es/ejercicio/microservicios/zuul/filters/SimpleFilter.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.zuul.filters; 2 | 3 | import javax.servlet.http.HttpServletRequest; 4 | 5 | import com.netflix.zuul.ZuulFilter; 6 | import com.netflix.zuul.context.RequestContext; 7 | 8 | import lombok.extern.slf4j.Slf4j; 9 | 10 | @Slf4j 11 | public class SimpleFilter extends ZuulFilter { 12 | 13 | @Override 14 | public Object run() { 15 | RequestContext ctx = RequestContext.getCurrentContext(); 16 | HttpServletRequest request = ctx.getRequest(); 17 | 18 | log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString())); 19 | 20 | return null; 21 | } 22 | 23 | @Override 24 | public boolean shouldFilter() { 25 | return true; 26 | } 27 | 28 | @Override 29 | public int filterOrder() { 30 | return 1; 31 | } 32 | 33 | @Override 34 | public String filterType() { 35 | return "pre"; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /ServicioZuul/src/main/resources/bootstrap.properties: -------------------------------------------------------------------------------- 1 | spring.cloud.config.uri=http://${CONFIG_HOST:localhost}:${CONFIG_PORT:8888} 2 | spring.application.name=zuul 3 | spring.jmx.default-domain=zuul 4 | spring.profiles.active=${PROFILE:default} 5 | endpoints.refresh.sensitive=false -------------------------------------------------------------------------------- /ServicioZuul/src/test/java/es/ejercicio/microservicios/zuul/ServicioZuulApplicationTests.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.zuul; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ServicioZuulApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /ServidorAutorizacion/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ 25 | 26 | ### Maven ### 27 | .mvn/ 28 | mvnw 29 | mvnw.cmd 30 | -------------------------------------------------------------------------------- /ServidorAutorizacion/WebContent/META-INF/MANIFEST.MF: -------------------------------------------------------------------------------- 1 | Manifest-Version: 1.0 2 | Class-Path: 3 | 4 | -------------------------------------------------------------------------------- /ServidorAutorizacion/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | es.ejercicio.microservicios.oauth 7 | ServidorAutorizacion 8 | 0.0.1-SNAPSHOT 9 | 10 | servidorautorizacion 11 | OAuth2 authorization server using Spring Security 12 | 13 | 18 | 19 | 20 | org.springframework.boot 21 | spring-boot-starter-parent 22 | 1.5.7.RELEASE 23 | 24 | 25 | 26 | 27 | Dalston.RELEASE 28 | 1.8 29 | ${project.name} 30 | 0.23.0 31 | jar 32 | 33 | 34 | 35 | 36 | org.springframework.cloud 37 | spring-cloud-starter-oauth2 38 | 39 | 40 | org.springframework.boot 41 | spring-boot-starter-security 42 | 43 | 44 | org.springframework.cloud 45 | spring-cloud-starter-eureka 46 | 47 | 48 | org.springframework.boot 49 | spring-boot-starter-test 50 | test 51 | 52 | 53 | org.springframework.security 54 | spring-security-test 55 | test 56 | 57 | 58 | com.h2database 59 | h2 60 | runtime 61 | 62 | 63 | org.springframework.boot 64 | spring-boot-starter-data-jpa 65 | 66 | 67 | org.springframework.cloud 68 | spring-cloud-starter-config 69 | 70 | 71 | javax.servlet 72 | javax.servlet-api 73 | provided 74 | 75 | 76 | org.springframework.cloud 77 | spring-cloud-starter-zipkin 78 | 79 | 80 | org.projectlombok 81 | lombok 82 | true 83 | 84 | 85 | 86 | 87 | 88 | 89 | org.springframework.cloud 90 | spring-cloud-dependencies 91 | ${spring-cloud.version} 92 | pom 93 | import 94 | 95 | 96 | 97 | 98 | 99 | local 100 | 101 | true 102 | 103 | 104 | 105 | docker 106 | 107 | 108 | 109 | io.fabric8 110 | docker-maven-plugin 111 | ${maven-docker-fabric8.version} 112 | 113 | medium 114 | 115 | 116 | ${project.name}:${project.version} 117 | ${project.name} 118 | 119 | java:8u40 120 | 121 | artifact-with-dependencies 122 | 123 | java -Djava.security.egd=file:/dev/./urandom -jar -Xdebug /maven/${project.build.finalName}.${artifact.extension} 124 | 125 | 126 | 127 | 128 | 129 | 130 | build-image 131 | package 132 | 133 | build 134 | 135 | 136 | 137 | start 138 | pre-integration-test 139 | 140 | build 141 | start 142 | 143 | 144 | 145 | stop 146 | post-integration-test 147 | 148 | stop 149 | 150 | 151 | 152 | 153 | 154 | maven-failsafe-plugin 155 | 2.17 156 | 157 | 158 | integration-test 159 | 160 | integration-test 161 | 162 | 163 | 164 | verify 165 | 166 | verify 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | org.springframework.boot 179 | spring-boot-maven-plugin 180 | 181 | 182 | org.apache.maven.plugins 183 | maven-war-plugin 184 | 185 | authorization-service 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | -------------------------------------------------------------------------------- /ServidorAutorizacion/src/main/java/es/ejercicio/microservicios/oauth/ServidorAutorizacionApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.oauth; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.boot.builder.SpringApplicationBuilder; 6 | import org.springframework.boot.web.support.SpringBootServletInitializer; 7 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 8 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; 9 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 10 | 11 | @SpringBootApplication 12 | @EnableAuthorizationServer 13 | @EnableResourceServer 14 | @EnableDiscoveryClient 15 | public class ServidorAutorizacionApplication extends SpringBootServletInitializer { 16 | 17 | public static void main(String[] args) { 18 | SpringApplication.run(ServidorAutorizacionApplication.class, args); 19 | } 20 | 21 | @Override 22 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 23 | return application.sources(applicationClass); 24 | } 25 | 26 | private static Class applicationClass = ServidorAutorizacionApplication.class; 27 | } 28 | -------------------------------------------------------------------------------- /ServidorAutorizacion/src/main/java/es/ejercicio/microservicios/oauth/config/OAuth2Config.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.oauth.config; 2 | 3 | import javax.sql.DataSource; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.beans.factory.annotation.Qualifier; 7 | import org.springframework.beans.factory.annotation.Value; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.jdbc.datasource.DriverManagerDataSource; 11 | import org.springframework.security.authentication.AuthenticationManager; 12 | import org.springframework.security.core.userdetails.UserDetailsService; 13 | import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 14 | import org.springframework.security.crypto.password.PasswordEncoder; 15 | import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; 16 | import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; 17 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; 18 | import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; 19 | import org.springframework.security.oauth2.provider.token.TokenStore; 20 | import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; 21 | 22 | import lombok.extern.slf4j.Slf4j; 23 | 24 | @Slf4j 25 | @Configuration 26 | public class OAuth2Config 27 | extends AuthorizationServerConfigurerAdapter { 28 | 29 | @Value("${spring.datasource.driver-class-name}") 30 | private String dbDriver; 31 | 32 | @Value("${spring.datasource.url}") 33 | private String dbUrl; 34 | 35 | @Value("${spring.datasource.username}") 36 | private String dbUsername; 37 | 38 | @Value("${spring.datasource.password}") 39 | private String dbPassword; 40 | 41 | @Autowired 42 | @Qualifier("userDetailsService") 43 | private UserDetailsService userDetailsService; 44 | 45 | @Autowired 46 | private AuthenticationManager authenticationManager; 47 | 48 | @Bean 49 | public PasswordEncoder passwordEncoder() { 50 | 51 | return new BCryptPasswordEncoder(); 52 | } 53 | 54 | @Override 55 | public void configure(AuthorizationServerEndpointsConfigurer endpoints) 56 | throws Exception { 57 | 58 | log.info("Start {} :: endpoints -> {}", this.getClass().getName(), 59 | endpoints.toString()); 60 | 61 | endpoints.tokenStore(tokenStore()) 62 | .authenticationManager(authenticationManager); 63 | 64 | endpoints.userDetailsService(userDetailsService); 65 | } 66 | 67 | @Override 68 | public void configure(ClientDetailsServiceConfigurer clients) 69 | throws Exception { 70 | 71 | log.info("Start {} :: clients -> {}", this.getClass().getName(), 72 | clients.toString()); 73 | 74 | clients.jdbc(dataSource()); 75 | 76 | } 77 | 78 | @Override 79 | public void configure(AuthorizationServerSecurityConfigurer oauthServer) { 80 | 81 | log.info("Start {} :: oauth server -> {}", this.getClass().getName(), 82 | oauthServer.toString()); 83 | 84 | // oauthServer.tokenKeyAccess("permitAll()") 85 | // .checkTokenAccess("isAuthenticated()"); 86 | 87 | oauthServer.allowFormAuthenticationForClients(); 88 | } 89 | 90 | @Bean 91 | public TokenStore tokenStore() { 92 | 93 | return new JdbcTokenStore(dataSource()); 94 | } 95 | 96 | @Bean 97 | public DataSource dataSource() { 98 | 99 | DriverManagerDataSource dataSource = new DriverManagerDataSource(); 100 | dataSource.setDriverClassName(dbDriver); 101 | dataSource.setUrl(dbUrl); 102 | dataSource.setUsername(dbUsername); 103 | dataSource.setPassword(dbPassword); 104 | 105 | return dataSource; 106 | 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /ServidorAutorizacion/src/main/java/es/ejercicio/microservicios/oauth/controller/AuthorizationController.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.oauth.controller; 2 | 3 | import java.security.Principal; 4 | 5 | import org.springframework.web.bind.annotation.RequestMapping; 6 | import org.springframework.web.bind.annotation.RestController; 7 | 8 | import lombok.extern.slf4j.Slf4j; 9 | 10 | @Slf4j 11 | @RestController 12 | public class AuthorizationController { 13 | 14 | @RequestMapping("/user") 15 | public Principal user(Principal user) { 16 | 17 | log.info("Start {} -> user :: {}", this.getClass().getSimpleName(), 18 | String.valueOf(user != null)); 19 | 20 | return user; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ServidorAutorizacion/src/main/java/es/ejercicio/microservicios/oauth/repository/UserRepository.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.oauth.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | 5 | import es.ejercicio.microservicios.oauth.service.entity.User; 6 | 7 | 8 | public interface UserRepository extends JpaRepository{ 9 | 10 | User findOneByUsername(String username); 11 | 12 | } 13 | -------------------------------------------------------------------------------- /ServidorAutorizacion/src/main/java/es/ejercicio/microservicios/oauth/service/entity/User.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.oauth.service.entity; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Entity; 8 | import javax.persistence.GeneratedValue; 9 | import javax.persistence.GenerationType; 10 | import javax.persistence.Id; 11 | import javax.persistence.Table; 12 | 13 | import org.springframework.security.core.GrantedAuthority; 14 | import org.springframework.security.core.userdetails.UserDetails; 15 | 16 | import lombok.Getter; 17 | import lombok.NoArgsConstructor; 18 | 19 | @Getter 20 | @NoArgsConstructor 21 | @Entity 22 | @Table(name = "users") 23 | public class User 24 | implements UserDetails { 25 | 26 | private static final long serialVersionUID = -3228481300736691975L; 27 | 28 | @Id 29 | @GeneratedValue(strategy = GenerationType.AUTO) 30 | @Column(name = "user_id", nullable = false, updatable = false) 31 | private Long id; 32 | 33 | @Column(name = "username", nullable = false, unique = true) 34 | private String username; 35 | 36 | @Column(name = "password", nullable = false) 37 | private String password; 38 | 39 | @Column(name = "enabled", nullable = false) 40 | private boolean enabled; 41 | 42 | @Override 43 | public Collection getAuthorities() { 44 | 45 | return new ArrayList<>(); 46 | } 47 | 48 | @Override 49 | public boolean isAccountNonExpired() { 50 | 51 | return true; 52 | } 53 | 54 | @Override 55 | public boolean isAccountNonLocked() { 56 | 57 | return true; 58 | } 59 | 60 | @Override 61 | public boolean isCredentialsNonExpired() { 62 | 63 | return true; 64 | } 65 | 66 | } 67 | -------------------------------------------------------------------------------- /ServidorAutorizacion/src/main/java/es/ejercicio/microservicios/oauth/service/impl/UserService.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.oauth.service.impl; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.context.annotation.Lazy; 5 | import org.springframework.security.core.userdetails.UserDetails; 6 | import org.springframework.security.core.userdetails.UserDetailsService; 7 | import org.springframework.security.core.userdetails.UsernameNotFoundException; 8 | import org.springframework.stereotype.Service; 9 | 10 | import es.ejercicio.microservicios.oauth.repository.UserRepository; 11 | 12 | @Service("userDetailsService") 13 | public class UserService 14 | implements UserDetailsService { 15 | 16 | @Autowired 17 | @Lazy 18 | private UserRepository userRepository; 19 | 20 | @Override 21 | public UserDetails loadUserByUsername(String username) 22 | throws UsernameNotFoundException { 23 | 24 | UserDetails user = userRepository.findOneByUsername(username); 25 | 26 | if (user == null) { 27 | throw new UsernameNotFoundException(username); 28 | } 29 | 30 | return user; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /ServidorAutorizacion/src/main/resources/bootstrap.properties: -------------------------------------------------------------------------------- 1 | spring.cloud.config.uri=http://${CONFIG_HOST:localhost}:${CONFIG_PORT:8888} 2 | spring.application.name=autorizacion 3 | spring.profiles.active=${PROFILE:default} 4 | endpoints.refresh.sensitive=false -------------------------------------------------------------------------------- /ServidorAutorizacion/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO oauth_client_details 2 | (client_id, client_secret, scope, authorized_grant_types, 3 | web_server_redirect_uri, authorities, access_token_validity, 4 | refresh_token_validity, additional_information, autoapprove) 5 | VALUES 6 | ('bibliotecaApp', 'secretBiblioteca', 'foo,read,write', 'password,authorization_code,refresh_token,client_credentials', null, null, 36000, 36000, null, true), 7 | ('editorialesApp', 'secretEditoriales', 'foo,read,write', 'password,authorization_code,refresh_token,client_credentials', null, null, 36000, 36000, null, true), 8 | ('autoresApp', 'secretAutores', 'foo,read,write', 'password,authorization_code,refresh_token,client_credentials', null, null, 36000, 36000, null, true), 9 | ('categoriasApp', 'secretCategorias', 'foo,read,write', 'password,authorization_code,refresh_token,client_credentials', null, null, 36000, 36000, null, true), 10 | ('librosApp', 'secretLibros', 'foo,read,write', 'password,authorization_code,refresh_token,client_credentials', null, null, 36000, 36000, null, true), 11 | ('zuulApp', 'secretZuul', 'foo,read,write', 'password,authorization_code,refresh_token,client_credentials', null, null, 36000, 36000, null, true), 12 | ('barClientIdPassword', 'secret', 'bar,read,write', 'password,authorization_code,refresh_token,client_credentials', null, null, 36000, 36000, null, true), 13 | ('foo', 'foosecret', 'openid', 'password,authorization_code,refresh_token,client_credentials', null, null, 36000, 36000, null, true); 14 | 15 | 16 | INSERT INTO users (username, password, enabled) 17 | VALUES 18 | ('peter@example.com', '$2a$10$D4OLKI6yy68crm.3imC9X.P2xqKHs5TloWUcr6z5XdOqnTrAK84ri', true), 19 | ('john@example.com', '$2a$10$D4OLKI6yy68crm.3imC9X.P2xqKHs5TloWUcr6z5XdOqnTrAK84ri', true), 20 | ('katie@example.com', '$2a$10$D4OLKI6yy68crm.3imC9X.P2xqKHs5TloWUcr6z5XdOqnTrAK84ri', true); -------------------------------------------------------------------------------- /ServidorAutorizacion/src/main/resources/schema.sql: -------------------------------------------------------------------------------- 1 | create table oauth_client_details ( 2 | client_id VARCHAR(256), 3 | resource_ids VARCHAR(256), 4 | client_secret VARCHAR(256), 5 | scope VARCHAR(256), 6 | authorized_grant_types VARCHAR(256), 7 | web_server_redirect_uri VARCHAR(256), 8 | authorities VARCHAR(256), 9 | access_token_validity INTEGER, 10 | refresh_token_validity INTEGER, 11 | additional_information VARCHAR(4096), 12 | autoapprove VARCHAR(256), 13 | primary key(client_id) 14 | ); 15 | 16 | create table oauth_client_token ( 17 | token_id VARCHAR(255), 18 | token VARBINARY, 19 | authentication_id VARCHAR(255), 20 | user_name VARCHAR(255), 21 | client_id VARCHAR(255), 22 | primary key(authentication_id) 23 | ); 24 | 25 | create table oauth_access_token ( 26 | token_id VARCHAR(255), 27 | token VARBINARY, 28 | authentication_id VARCHAR(255), 29 | user_name VARCHAR(255), 30 | client_id VARCHAR(255), 31 | authentication VARBINARY, 32 | refresh_token VARCHAR(255), 33 | primary key(authentication_id) 34 | ); 35 | 36 | create table oauth_refresh_token ( 37 | token_id VARCHAR(255), 38 | token VARBINARY, 39 | authentication VARBINARY 40 | ); 41 | 42 | create table users ( 43 | user_id BIGINT PRIMARY KEY auto_increment, 44 | username VARCHAR(128) UNIQUE, 45 | password VARCHAR(256), 46 | enabled BOOL, 47 | ); -------------------------------------------------------------------------------- /ServidorConfiguracion/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /ServidorConfiguracion/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | es.ejercicio.microservicios.gestionconfiguracion 7 | servidorconfiguracion 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | servidorconfiguracion 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.8.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Dalston.SR4 26 | ${project.name} 27 | 0.23.0 28 | jar 29 | 30 | 31 | 32 | 33 | org.springframework.cloud 34 | spring-cloud-config-server 35 | 36 | 37 | org.springframework.boot 38 | spring-boot-starter-test 39 | test 40 | 41 | 42 | 43 | 44 | local 45 | 46 | true 47 | 48 | 49 | 50 | docker 51 | 52 | 53 | 54 | io.fabric8 55 | docker-maven-plugin 56 | ${maven-docker-fabric8.version} 57 | 58 | medium 59 | 60 | 61 | ${project.name}:${project.version} 62 | ${project.name} 63 | 64 | java:8u40 65 | 66 | artifact-with-dependencies 67 | 68 | java -Djava.security.egd=file:/dev/./urandom -jar -Xdebug /maven/${project.build.finalName}.${artifact.extension} 69 | 70 | 71 | 72 | 73 | 74 | 75 | build-image 76 | package 77 | 78 | build 79 | 80 | 81 | 82 | start 83 | pre-integration-test 84 | 85 | build 86 | start 87 | 88 | 89 | 90 | stop 91 | post-integration-test 92 | 93 | stop 94 | 95 | 96 | 97 | 98 | 99 | maven-failsafe-plugin 100 | 2.17 101 | 102 | 103 | integration-test 104 | 105 | integration-test 106 | 107 | 108 | 109 | verify 110 | 111 | verify 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | org.springframework.cloud 124 | spring-cloud-dependencies 125 | ${spring-cloud.version} 126 | pom 127 | import 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | org.springframework.boot 136 | spring-boot-maven-plugin 137 | 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /ServidorConfiguracion/src/main/java/es/ejercicio/microservicios/gestionconfiguracion/GestionConfiguracionApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.gestionconfiguracion; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.config.server.EnableConfigServer; 6 | 7 | @SpringBootApplication 8 | @EnableConfigServer 9 | public class GestionConfiguracionApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(GestionConfiguracionApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ServidorConfiguracion/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8888 3 | 4 | spring: 5 | cloud: 6 | config: 7 | server: 8 | git: 9 | uri: https://github.com/juanmacintas/ejercicioMircroserviciosConfigRepo 10 | searchPaths: autores,autorizacion,biblioteca,bibliotecavaadin,libros,categorias,editoriales,zuul,zipkin* 11 | 12 | endpoints: 13 | beans: 14 | sensitive: false 15 | refresh: 16 | sensitive: false -------------------------------------------------------------------------------- /ServidorConfiguracion/src/test/java/es/ejercicio/microservicios/gestionconfiguracion/GestionConfiguracionApplicationTests.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.gestionconfiguracion; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class GestionConfiguracionApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /ServidorHystrix/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /ServidorHystrix/.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/juanmacintas/ejercicioMicroserviciosSpringCloud/f6b85413042051955217df14bb46ccc3cbeb4ce9/ServidorHystrix/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /ServidorHystrix/.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.2/apache-maven-3.5.2-bin.zip 2 | -------------------------------------------------------------------------------- /ServidorHystrix/mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /ServidorHystrix/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | es.ejercicio.microservicio 7 | ServidorHystrix 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | servidorhystrix 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.8.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 1.6.1.RELEASE 26 | Dalston.SR4 27 | ${project.name} 28 | 0.23.0 29 | jar 30 | 31 | 32 | 33 | 34 | io.pivotal.spring.cloud 35 | spring-cloud-services-starter-circuit-breaker 36 | 37 | 38 | org.springframework.cloud 39 | spring-cloud-starter-hystrix-dashboard 40 | 41 | 42 | org.springframework.boot 43 | spring-boot-starter-actuator 44 | 45 | 46 | org.springframework.cloud 47 | spring-cloud-starter-eureka 48 | 49 | 50 | org.springframework.boot 51 | spring-boot-starter-test 52 | test 53 | 54 | 55 | 56 | 57 | 58 | 59 | org.springframework.cloud 60 | spring-cloud-dependencies 61 | ${spring-cloud.version} 62 | pom 63 | import 64 | 65 | 66 | io.pivotal.spring.cloud 67 | spring-cloud-services-dependencies 68 | ${spring-cloud-services.version} 69 | pom 70 | import 71 | 72 | 73 | 74 | 75 | 76 | local 77 | 78 | true 79 | 80 | 81 | 82 | docker 83 | 84 | 85 | 86 | io.fabric8 87 | docker-maven-plugin 88 | ${maven-docker-fabric8.version} 89 | 90 | medium 91 | 92 | 93 | ${project.name}:${project.version} 94 | ${project.name} 95 | 96 | java:8u40 97 | 98 | artifact-with-dependencies 99 | 100 | java -Djava.security.egd=file:/dev/./urandom -jar -Xdebug /maven/${project.build.finalName}.${artifact.extension} 101 | 102 | 103 | 104 | 105 | 106 | 107 | build-image 108 | package 109 | 110 | build 111 | 112 | 113 | 114 | start 115 | pre-integration-test 116 | 117 | build 118 | start 119 | 120 | 121 | 122 | stop 123 | post-integration-test 124 | 125 | stop 126 | 127 | 128 | 129 | 130 | 131 | maven-failsafe-plugin 132 | 2.17 133 | 134 | 135 | integration-test 136 | 137 | integration-test 138 | 139 | 140 | 141 | verify 142 | 143 | verify 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | org.springframework.boot 156 | spring-boot-maven-plugin 157 | 158 | 159 | 160 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /ServidorHystrix/src/main/java/es/ejercicio/microservicio/hystrix/ServidorHystrixApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicio.hystrix; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; 7 | 8 | @SpringBootApplication 9 | @EnableHystrixDashboard 10 | @EnableDiscoveryClient 11 | public class ServidorHystrixApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(ServidorHystrixApplication.class, args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ServidorHystrix/src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | server.port = 8072 2 | spring.application.name=hystrixServer 3 | eureka.client.serviceUrl.defaultZone=http://localhost:8084/eureka/ 4 | turbine.appConfig= biblioteca -------------------------------------------------------------------------------- /ServidorHystrix/src/test/java/es/ejercicio/microservicio/hystrix/DemoApplicationTests.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicio.hystrix; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class DemoApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /ServidorRegistro/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /ServidorRegistro/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | es.ejercicio.microservicios.eureka 7 | ServidorRegistro 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | servidorregistro 12 | Servidor Eureka 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.8.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Dalston.SR4 26 | ${project.name} 27 | 0.23.0 28 | jar 29 | 30 | 31 | 32 | 33 | org.springframework.cloud 34 | spring-cloud-starter-eureka-server 35 | 36 | 37 | 38 | org.springframework.boot 39 | spring-boot-starter-test 40 | test 41 | 42 | 43 | 44 | 45 | 46 | 47 | org.springframework.cloud 48 | spring-cloud-dependencies 49 | ${spring-cloud.version} 50 | pom 51 | import 52 | 53 | 54 | 55 | 56 | 57 | local 58 | 59 | true 60 | 61 | 62 | 63 | docker 64 | 65 | 66 | 67 | io.fabric8 68 | docker-maven-plugin 69 | ${maven-docker-fabric8.version} 70 | 71 | medium 72 | 73 | 74 | ${project.name}:${project.version} 75 | ${project.name} 76 | 77 | java:8u40 78 | 79 | artifact-with-dependencies 80 | 81 | java -Djava.security.egd=file:/dev/./urandom -jar -Xdebug /maven/${project.build.finalName}.${artifact.extension} 82 | 83 | 84 | 85 | 86 | 87 | 88 | build-image 89 | package 90 | 91 | build 92 | 93 | 94 | 95 | start 96 | pre-integration-test 97 | 98 | build 99 | start 100 | 101 | 102 | 103 | stop 104 | post-integration-test 105 | 106 | stop 107 | 108 | 109 | 110 | 111 | 112 | maven-failsafe-plugin 113 | 2.17 114 | 115 | 116 | integration-test 117 | 118 | integration-test 119 | 120 | 121 | 122 | verify 123 | 124 | verify 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | org.springframework.boot 137 | spring-boot-maven-plugin 138 | 139 | 140 | 141 | 142 | -------------------------------------------------------------------------------- /ServidorRegistro/src/main/java/es/ejercicio/microservicios/eureka/ServidorEurekaApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.eureka; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; 6 | 7 | @SpringBootApplication 8 | @EnableEurekaServer 9 | public class ServidorEurekaApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(ServidorEurekaApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /ServidorRegistro/src/main/resources/application.yml: -------------------------------------------------------------------------------- 1 | server: 2 | port: 8084 3 | 4 | eureka: 5 | instance: 6 | hostname: localhost 7 | serviceUrl: 8 | defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ 9 | 10 | client: 11 | register-with-eureka: false 12 | fetch-registry: false -------------------------------------------------------------------------------- /ServidorRegistro/src/test/java/es/ejercicio/microservicios/eureka/ServidorEurekaApplicationApplicationTests.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.eureka; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class ServidorEurekaApplicationApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /ServidorZipkin/.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /ServidorZipkin/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | es.ejercicio.microservicios.zipkin 7 | ServidorZipkin 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | servidorzipkin 12 | Servidor ZipKin 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.8.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | Dalston.SR4 26 | ${project.name} 27 | jar 28 | 0.23.0 29 | 30 | 31 | 32 | 33 | org.springframework.boot 34 | spring-boot-starter-actuator 35 | 36 | 37 | 38 | io.zipkin.java 39 | zipkin-server 40 | 41 | 42 | io.zipkin.java 43 | zipkin-autoconfigure-ui 44 | runtime 45 | 46 | 47 | org.springframework.cloud 48 | spring-cloud-starter-eureka 49 | 50 | 51 | org.springframework.cloud 52 | spring-cloud-starter-config 53 | 54 | 55 | 56 | 57 | local 58 | 59 | true 60 | 61 | 62 | 63 | docker 64 | 65 | 66 | 67 | io.fabric8 68 | docker-maven-plugin 69 | ${maven-docker-fabric8.version} 70 | 71 | medium 72 | 73 | 74 | ${project.name}:${project.version} 75 | ${project.name} 76 | 77 | java:8u40 78 | 79 | artifact-with-dependencies 80 | 81 | java -Djava.security.egd=file:/dev/./urandom -jar -Xdebug /maven/${project.build.finalName}.${artifact.extension} 82 | 83 | 84 | 85 | 86 | 87 | 88 | build-image 89 | package 90 | 91 | build 92 | 93 | 94 | 95 | start 96 | pre-integration-test 97 | 98 | build 99 | start 100 | 101 | 102 | 103 | stop 104 | post-integration-test 105 | 106 | stop 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | org.springframework.cloud 120 | spring-cloud-dependencies 121 | ${spring-cloud.version} 122 | pom 123 | import 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | org.springframework.boot 132 | spring-boot-maven-plugin 133 | 134 | 135 | 136 | 137 | -------------------------------------------------------------------------------- /ServidorZipkin/src/main/java/es/ejercicio/microservicios/zipkin/ServidorZipkinApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.zipkin; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | 7 | import zipkin.server.EnableZipkinServer; 8 | 9 | @SpringBootApplication 10 | @EnableDiscoveryClient 11 | @EnableZipkinServer 12 | public class ServidorZipkinApplication { 13 | 14 | public static void main(String[] args) { 15 | SpringApplication.run(ServidorZipkinApplication.class, args); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /ServidorZipkin/src/main/resources/bootstrap.properties: -------------------------------------------------------------------------------- 1 | spring.cloud.config.uri=http://${CONFIG_HOST:localhost}:${CONFIG_PORT:8888} 2 | spring.application.name=zipkin 3 | spring.profiles.active=${PROFILE:default} 4 | endpoints.refresh.sensitive=false -------------------------------------------------------------------------------- /autores/.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings 4 | /target/ 5 | -------------------------------------------------------------------------------- /autores/.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | java:es.ejercicio.microservicios.autores.AutoresApplication 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /autores/src/main/java/es/ejercicio/microservicios/autores/AutoresApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.autores; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | 7 | @SpringBootApplication 8 | @EnableDiscoveryClient 9 | public class AutoresApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(AutoresApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /autores/src/main/java/es/ejercicio/microservicios/autores/config/AutoresResourceServerConfig.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.autores.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 7 | 8 | @Configuration 9 | @EnableResourceServer 10 | public class AutoresResourceServerConfig extends ResourceServerConfigurerAdapter { 11 | 12 | private static final String[] AUTH_WHITELIST = { 13 | // -- swagger ui 14 | "/v2/api-docs", 15 | "/swagger-resources", 16 | "/swagger-resources/**", 17 | "/configuration/ui", 18 | "/configuration/security", 19 | "/swagger-ui.html", 20 | "/webjars/**" 21 | }; 22 | 23 | 24 | @Override 25 | public void configure(HttpSecurity http) throws Exception { 26 | http.authorizeRequests(). 27 | antMatchers(AUTH_WHITELIST).permitAll(). 28 | and() 29 | .authorizeRequests(). 30 | antMatchers("/autores/**").authenticated(); 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /autores/src/main/java/es/ejercicio/microservicios/autores/entity/Autor.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.autores.entity; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.Id; 5 | 6 | import lombok.AllArgsConstructor; 7 | import lombok.Builder; 8 | import lombok.Data; 9 | import lombok.NoArgsConstructor; 10 | 11 | /** 12 | * @author Juan Manuel Cintas 13 | * 14 | */ 15 | @Entity 16 | @Data 17 | @Builder 18 | @NoArgsConstructor 19 | @AllArgsConstructor 20 | public class Autor { 21 | 22 | /** 23 | * Id. 24 | */ 25 | @Id 26 | private int id; 27 | 28 | /** 29 | * Nombre del autor. 30 | */ 31 | private String nombre; 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /autores/src/main/java/es/ejercicio/microservicios/autores/repository/AutorRepository.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.autores.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import es.ejercicio.microservicios.autores.entity.Autor; 7 | 8 | 9 | 10 | @Repository 11 | public interface AutorRepository extends JpaRepository { 12 | 13 | 14 | } -------------------------------------------------------------------------------- /autores/src/main/java/es/ejercicio/microservicios/autores/service/AutorService.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.autores.service; 2 | 3 | import java.util.List; 4 | 5 | import es.ejercicio.microservicios.autores.entity.Autor; 6 | 7 | public interface AutorService { 8 | 9 | public List findAll(); 10 | 11 | public Autor findById(Integer id); 12 | 13 | public void deleteById(Integer id); 14 | 15 | public Autor nuevoAutor(Autor autor); 16 | } -------------------------------------------------------------------------------- /autores/src/main/java/es/ejercicio/microservicios/autores/service/impl/AutorServiceImpl.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.autores.service.impl; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | import es.ejercicio.microservicios.autores.entity.Autor; 9 | import es.ejercicio.microservicios.autores.repository.AutorRepository; 10 | import es.ejercicio.microservicios.autores.service.AutorService; 11 | import lombok.extern.slf4j.Slf4j; 12 | 13 | @Slf4j 14 | @Service 15 | public class AutorServiceImpl implements AutorService { 16 | 17 | @Autowired 18 | private AutorRepository autorRepository; 19 | 20 | 21 | @Override 22 | public List findAll() { 23 | log.debug("Se obtienen todos los autores."); 24 | 25 | return autorRepository.findAll(); 26 | } 27 | 28 | 29 | @Override 30 | public Autor findById(Integer id) { 31 | log.debug("Se obtiene el autor con id:" + id); 32 | return autorRepository.findOne(id); 33 | } 34 | 35 | 36 | @Override 37 | public void deleteById(Integer id) { 38 | log.debug("Se elimina el autor con id:" + id); 39 | autorRepository.delete(id); 40 | 41 | } 42 | 43 | 44 | @Override 45 | public Autor nuevoAutor(Autor autor) { 46 | log.debug("Se añade el autor:" + autor); 47 | return autorRepository.save(autor); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /autores/src/main/java/es/ejercicio/microservicios/autores/swager/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.autores.swager; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import com.google.common.base.Predicates; 7 | 8 | import springfox.documentation.builders.ApiInfoBuilder; 9 | import springfox.documentation.builders.PathSelectors; 10 | import springfox.documentation.service.ApiInfo; 11 | import springfox.documentation.service.Contact; 12 | import springfox.documentation.spi.DocumentationType; 13 | import springfox.documentation.spring.web.plugins.Docket; 14 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 15 | 16 | /** 17 | * @author Juan Manuel Cintas 18 | * 19 | */ 20 | @Configuration 21 | @EnableSwagger2 22 | public class SwaggerConfig { 23 | 24 | @Bean 25 | public Docket swaggerSpringMvcPlugin() { 26 | return new Docket(DocumentationType.SWAGGER_2) 27 | .useDefaultResponseMessages(false) 28 | .apiInfo(apiInfo()) 29 | .select() 30 | .paths(Predicates.not(PathSelectors.regex("/error.*"))) 31 | .build(); 32 | } 33 | 34 | private ApiInfo apiInfo() { 35 | return new ApiInfoBuilder() 36 | .title("Biblioteca - Autores") 37 | .description("API documentation for Autores Application") 38 | .contact(new Contact("Juan Manuel Cintas", "https://github.com/juanmacintas", "hurone@gmail.com")) 39 | .license("Apache License Version 2.0") 40 | .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE") 41 | .version("2.0") 42 | .build(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /autores/src/main/resources/bootstrap.properties: -------------------------------------------------------------------------------- 1 | spring.cloud.config.uri=http://${CONFIG_HOST:localhost}:${CONFIG_PORT:8888} 2 | spring.application.name=autores 3 | spring.profiles.active=${PROFILE:default} 4 | endpoints.refresh.sensitive=false -------------------------------------------------------------------------------- /autores/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO AUTOR (id, nombre) values (1,'Ken Follett'); 2 | INSERT INTO AUTOR (id, nombre) values (2,'Eva García Sáenz de Urturi'); 3 | INSERT INTO AUTOR (id, nombre) values (3,'Astrid Nilsen'); 4 | INSERT INTO AUTOR (id, nombre) values (4,'Bram Stoker'); 5 | INSERT INTO AUTOR (id, nombre) values (5,'Mary Shelley'); 6 | INSERT INTO AUTOR (id, nombre) values (6,'Andy Weir'); 7 | INSERT INTO AUTOR (id, nombre) values (7,'Stephen King'); 8 | INSERT INTO AUTOR (id, nombre) values (8,'Ernest Cline'); 9 | INSERT INTO AUTOR (id, nombre) values (9,'Juan Gómez-Jurado'); 10 | INSERT INTO AUTOR (id, nombre) values (10,'Umberto Eco'); 11 | INSERT INTO AUTOR (id, nombre) values (11, 'Ben Kane'); 12 | INSERT INTO AUTOR (id, nombre) values (12, 'Isaac Asimov'); 13 | INSERT INTO AUTOR (id, nombre) values (13, 'Robert Kirkman'); 14 | INSERT INTO AUTOR (id, nombre) values (14, 'J.R.R. Tolkien'); -------------------------------------------------------------------------------- /autores/src/test/java/es/ejercicio/microservicios/autores/controller/AutorControllerTest.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.autores.controller; 2 | 3 | import static org.hamcrest.Matchers.empty; 4 | import static org.hamcrest.Matchers.is; 5 | import static org.hamcrest.Matchers.not; 6 | import static org.junit.Assert.fail; 7 | import static org.mockito.Matchers.anyInt; 8 | import static org.mockito.Mockito.when; 9 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 10 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 11 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 12 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 13 | 14 | import java.nio.charset.Charset; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | import org.junit.Before; 19 | import org.junit.Test; 20 | import org.junit.runner.RunWith; 21 | import org.springframework.beans.factory.annotation.Autowired; 22 | import org.springframework.boot.test.context.SpringBootTest; 23 | import org.springframework.boot.test.mock.mockito.MockBean; 24 | import org.springframework.http.MediaType; 25 | import org.springframework.test.context.junit4.SpringRunner; 26 | import org.springframework.test.context.web.WebAppConfiguration; 27 | import org.springframework.test.web.servlet.MockMvc; 28 | import org.springframework.test.web.servlet.ResultActions; 29 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 30 | import org.springframework.web.context.WebApplicationContext; 31 | 32 | import com.fasterxml.jackson.core.JsonProcessingException; 33 | 34 | import es.ejercicio.microservicios.autores.AutoresApplication; 35 | import es.ejercicio.microservicios.autores.entity.Autor; 36 | import es.ejercicio.microservicios.autores.repository.AutorRepository; 37 | import es.ejercicio.microservicios.autores.service.AutorService; 38 | 39 | /** 40 | * @author Juan Manuel Cintas 41 | * 42 | */ 43 | @RunWith(SpringRunner.class) 44 | @SpringBootTest(classes = AutoresApplication.class) 45 | @WebAppConfiguration 46 | public class AutorControllerTest { 47 | private MockMvc mockMvc; 48 | 49 | private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), 50 | MediaType.APPLICATION_JSON.getSubtype(), 51 | Charset.forName("utf8")); 52 | 53 | @Autowired 54 | private WebApplicationContext webApplicationContext; 55 | 56 | @MockBean 57 | private AutorRepository autorRepository; 58 | 59 | @MockBean 60 | AutorService autorService; 61 | 62 | @Before 63 | public void setup() throws Exception { 64 | this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); 65 | } 66 | 67 | 68 | @Test 69 | public void testGetAllAutores() { 70 | 71 | Autor autor1 = Autor.builder().id(1).nombre("Autor 1").build(); 72 | Autor autor2 = Autor.builder().id(2).nombre("Autor 2").build(); 73 | 74 | List listAutores = new ArrayList(); 75 | listAutores.add(autor1); 76 | listAutores.add(autor2); 77 | 78 | 79 | when(autorRepository.findAll()).thenReturn(listAutores); 80 | when(autorService.findAll()).thenReturn(listAutores); 81 | try { 82 | ResultActions res = this.mockMvc.perform(get("/autores/getAll")) 83 | .andDo(print()) 84 | .andExpect(status().isOk()) 85 | .andExpect(jsonPath("$", not(empty()))) 86 | .andExpect(jsonPath("$.[0].id", is(1) )); 87 | } catch (JsonProcessingException e1) { 88 | fail(e1.getMessage()); 89 | } catch (Exception e) { 90 | fail(e.getMessage()); 91 | } 92 | 93 | } 94 | 95 | 96 | @Test 97 | public void testAutorPorId() { 98 | 99 | Autor autor1 = Autor.builder().id(1).nombre("Autor 1").build(); 100 | 101 | 102 | 103 | when(autorRepository.findOne(anyInt())).thenReturn(autor1); 104 | when(autorService.findById(anyInt())).thenReturn(autor1); 105 | try { 106 | ResultActions res = this.mockMvc.perform(get("/autores/getAutor/1")) 107 | .andDo(print()) 108 | .andExpect(status().isOk()) 109 | .andExpect(jsonPath("$", not(empty()))) 110 | .andExpect(jsonPath("$.id", is(1) )); 111 | } catch (JsonProcessingException e1) { 112 | fail(e1.getMessage()); 113 | } catch (Exception e) { 114 | fail(e.getMessage()); 115 | } 116 | 117 | } 118 | 119 | } 120 | -------------------------------------------------------------------------------- /biblioteca/.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings 4 | /target/ 5 | -------------------------------------------------------------------------------- /biblioteca/.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /biblioteca/src/main/java/es/ejercicio/microservicios/biblioteca/BibliotecaApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; 6 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 7 | import org.springframework.cloud.netflix.feign.EnableFeignClients; 8 | 9 | @SpringBootApplication 10 | @EnableDiscoveryClient 11 | @EnableFeignClients 12 | @EnableCircuitBreaker 13 | public class BibliotecaApplication { 14 | 15 | public static void main(String[] args) { 16 | SpringApplication.run(BibliotecaApplication.class, args); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /biblioteca/src/main/java/es/ejercicio/microservicios/biblioteca/configuration/BibliotecaConfig.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.configuration; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 6 | 7 | @Configuration 8 | public class BibliotecaConfig extends WebSecurityConfigurerAdapter { 9 | 10 | @Override 11 | protected void configure(HttpSecurity http) throws Exception { 12 | http. 13 | authorizeRequests(). 14 | antMatchers("/biblioteca/**").permitAll(); 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /biblioteca/src/main/java/es/ejercicio/microservicios/biblioteca/swager/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.swager; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import com.google.common.base.Predicates; 7 | 8 | import springfox.documentation.builders.ApiInfoBuilder; 9 | import springfox.documentation.builders.PathSelectors; 10 | import springfox.documentation.service.ApiInfo; 11 | import springfox.documentation.service.Contact; 12 | import springfox.documentation.spi.DocumentationType; 13 | import springfox.documentation.spring.web.plugins.Docket; 14 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 15 | 16 | /** 17 | * @author Juan Manuel Cintas 18 | * 19 | */ 20 | @Configuration 21 | @EnableSwagger2 22 | public class SwaggerConfig { 23 | 24 | @Bean 25 | public Docket swaggerSpringMvcPlugin() { 26 | return new Docket(DocumentationType.SWAGGER_2) 27 | .useDefaultResponseMessages(false) 28 | .apiInfo(apiInfo()) 29 | .select() 30 | .paths(Predicates.not(PathSelectors.regex("/error.*"))) 31 | .build(); 32 | } 33 | 34 | private ApiInfo apiInfo() { 35 | return new ApiInfoBuilder() 36 | .title("Biblioteca") 37 | .description("API documentation for Biblioteca Application") 38 | .contact(new Contact("Juan Manuel Cintas", "https://github.com/juanmacintas", "hurone@gmail.com")) 39 | .license("Apache License Version 2.0") 40 | .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE") 41 | .version("2.0") 42 | .build(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /biblioteca/src/main/resources/bootstrap.properties: -------------------------------------------------------------------------------- 1 | spring.cloud.config.uri=http://${CONFIG_HOST:localhost}:${CONFIG_PORT:8888} 2 | spring.application.name=biblioteca 3 | spring.profiles.active=${PROFILE:default} 4 | endpoints.refresh.sensitive=false -------------------------------------------------------------------------------- /bibliotecaCliente/.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings 4 | /target/ 5 | -------------------------------------------------------------------------------- /bibliotecaCliente/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | es.ejercicio.microservicios 5 | biblioteca-cliente 6 | 0.0.1-SNAPSHOT 7 | biblioteca-cliente 8 | Librería con cliente de comunicación entre microservicios mediante feign y hystrix. 9 | 10 | 11 | org.springframework.boot 12 | spring-boot-starter-parent 13 | 1.5.8.RELEASE 14 | 15 | 16 | 17 | 18 | UTF-8 19 | UTF-8 20 | 1.8 21 | 1.8 22 | 1.8 23 | 0.0.1-SNAPSHOT 24 | Dalston.SR4 25 | 26 | 27 | 28 | 29 | org.projectlombok 30 | lombok 31 | 32 | 33 | org.springframework.cloud 34 | spring-cloud-starter-feign 35 | 36 | 37 | org.springframework.cloud 38 | spring-cloud-starter-hystrix 39 | 40 | 41 | org.springframework.boot 42 | spring-boot-starter-security 43 | 44 | 45 | org.springframework.security.oauth 46 | spring-security-oauth2 47 | 48 | 49 | org.springframework.boot 50 | spring-boot-configuration-processor 51 | 52 | 53 | es.ejercicio.microservicios 54 | ejercicio-dto 55 | ${ejercicio-dto.version} 56 | 57 | 58 | 59 | 60 | 61 | org.springframework.cloud 62 | spring-cloud-dependencies 63 | ${spring-cloud.version} 64 | pom 65 | import 66 | 67 | 68 | 69 | 70 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/cliente/ClienteAutores.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.cliente; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.cloud.netflix.feign.FeignClient; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RequestMethod; 11 | 12 | import es.ejercicio.microservicios.biblioteca.config.OAuth2FeignAutoConfiguration; 13 | import es.ejercicio.microservicios.dto.AutorDTO; 14 | 15 | @FeignClient(name="autores", 16 | configuration = {OAuth2FeignAutoConfiguration.class}) 17 | public interface ClienteAutores { 18 | 19 | @RequestMapping(path = "/autores/getAll", 20 | method = RequestMethod.GET) 21 | public List obtenerAutores(); 22 | 23 | @RequestMapping(path = "/autores/getAutor/{id}", 24 | method = RequestMethod.GET) 25 | public ResponseEntity obtenerAutor(@PathVariable("id") String id); 26 | 27 | @RequestMapping(path = "/autores/nuevoAutor", 28 | method = RequestMethod.POST) 29 | public ResponseEntity nuevoAutor(@RequestBody AutorDTO input); 30 | 31 | 32 | @RequestMapping(path = "/autores/deleteAutor/{id}", 33 | method = RequestMethod.DELETE) 34 | public void eliminarAutor(@PathVariable("id") String id); 35 | 36 | } 37 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/cliente/ClienteCategorias.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.cliente; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.cloud.netflix.feign.FeignClient; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RequestMethod; 11 | 12 | import es.ejercicio.microservicios.biblioteca.config.OAuth2FeignAutoConfiguration; 13 | import es.ejercicio.microservicios.dto.CategoriaDTO; 14 | 15 | @FeignClient(name="categorias", 16 | configuration = {OAuth2FeignAutoConfiguration.class}) 17 | public interface ClienteCategorias { 18 | 19 | @RequestMapping(path = "/categorias/getAll", 20 | method = RequestMethod.GET) 21 | public List obtenerCategorias(); 22 | 23 | @RequestMapping(path = "/categorias/getCategoria/{id}", 24 | method = RequestMethod.GET) 25 | public CategoriaDTO obtenerCategoria(@PathVariable("id") String id); 26 | 27 | @RequestMapping(path = "/categorias/nuevaCategoria", 28 | method = RequestMethod.POST) 29 | public ResponseEntity nuevaCategoria(@RequestBody CategoriaDTO input); 30 | 31 | 32 | @RequestMapping(path = "/categorias/deleteCategoria/{id}", 33 | method = RequestMethod.DELETE) 34 | public void eliminarCategoria(@PathVariable("id") String id); 35 | 36 | } 37 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/cliente/ClienteEditoriales.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.cliente; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.cloud.netflix.feign.FeignClient; 6 | import org.springframework.http.ResponseEntity; 7 | import org.springframework.web.bind.annotation.PathVariable; 8 | import org.springframework.web.bind.annotation.RequestBody; 9 | import org.springframework.web.bind.annotation.RequestMapping; 10 | import org.springframework.web.bind.annotation.RequestMethod; 11 | 12 | import es.ejercicio.microservicios.biblioteca.config.OAuth2FeignAutoConfiguration; 13 | import es.ejercicio.microservicios.dto.EditorialDTO; 14 | 15 | @FeignClient(name="editoriales", 16 | configuration = {OAuth2FeignAutoConfiguration.class}) 17 | public interface ClienteEditoriales { 18 | 19 | @RequestMapping(path = "/editoriales/getAll", 20 | method = RequestMethod.GET) 21 | public List obtenerEditoriales(); 22 | 23 | @RequestMapping(path = "/editoriales/getEditorial/{id}", 24 | method = RequestMethod.GET) 25 | public EditorialDTO obtenerEditorial(@PathVariable("id") String id); 26 | 27 | @RequestMapping(path = "/editoriales/nuevaEditorial", 28 | method = RequestMethod.POST) 29 | public ResponseEntity nuevoEditorial(@RequestBody EditorialDTO input); 30 | 31 | 32 | @RequestMapping(path = "/editoriales/deleteEditorial/{id}", 33 | method = RequestMethod.DELETE) 34 | public void eliminarEditorial(@PathVariable("id") String id); 35 | 36 | } 37 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/cliente/ClienteLibros.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.cliente; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.cloud.netflix.feign.FeignClient; 6 | import org.springframework.web.bind.annotation.PathVariable; 7 | import org.springframework.web.bind.annotation.RequestBody; 8 | import org.springframework.web.bind.annotation.RequestMapping; 9 | import org.springframework.web.bind.annotation.RequestMethod; 10 | 11 | import es.ejercicio.microservicios.biblioteca.config.OAuth2FeignAutoConfiguration; 12 | import es.ejercicio.microservicios.dto.LibroDTO; 13 | 14 | @FeignClient(name="libros", 15 | configuration = {OAuth2FeignAutoConfiguration.class}) 16 | public interface ClienteLibros { 17 | 18 | @RequestMapping(path = "/libros/getAll", 19 | method = RequestMethod.GET) 20 | public List obtenerLibros(); 21 | 22 | @RequestMapping(path = "/libros/getFavoritos", 23 | method = RequestMethod.GET) 24 | public List obtenerLibrosFavoritos(); 25 | 26 | 27 | @RequestMapping(path = "/libros/getByExample", 28 | method = RequestMethod.POST) 29 | public List obtenerLibrosByExample(@RequestBody LibroDTO input); 30 | 31 | @RequestMapping(path = "/libros/getLibro/{id}", 32 | method = RequestMethod.GET) 33 | public LibroDTO obtenerLibro(@PathVariable("id") String id); 34 | 35 | } 36 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/config/FeignAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import feign.RequestInterceptor; 7 | import feign.RequestTemplate; 8 | import lombok.RequiredArgsConstructor; 9 | import lombok.extern.slf4j.Slf4j; 10 | 11 | @Slf4j 12 | @Configuration 13 | @RequiredArgsConstructor 14 | public class FeignAutoConfiguration { 15 | 16 | 17 | @Bean 18 | public RequestInterceptor feignRequestInterceptor() { 19 | 20 | return new RequestInterceptor() { 21 | 22 | @Override 23 | public void apply(RequestTemplate arg0) { 24 | log.debug("Llamada a :" + arg0.toString()); 25 | 26 | } 27 | }; 28 | 29 | 30 | 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/config/OAuth2FeignAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.config; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.security.oauth2.client.OAuth2RestTemplate; 6 | import org.springframework.security.oauth2.common.OAuth2AccessToken; 7 | 8 | import feign.RequestInterceptor; 9 | import lombok.RequiredArgsConstructor; 10 | import lombok.extern.slf4j.Slf4j; 11 | 12 | @Slf4j 13 | @Configuration 14 | @RequiredArgsConstructor 15 | public class OAuth2FeignAutoConfiguration { 16 | 17 | private final OAuth2RestTemplate oAuth2RestTemplate; 18 | 19 | private static final String AUTHORIZATION_HEADER = "Authorization"; 20 | 21 | private static final String BEARER_TOKEN = "Bearer"; 22 | 23 | @Bean 24 | public RequestInterceptor oauth2FeignRequestInterceptor() { 25 | // return new OAuth2FeignRequestInterceptor(oAuth2RestTemplate); 26 | return requestTemplate -> { 27 | final OAuth2AccessToken accessToken = this.oAuth2RestTemplate.getAccessToken(); 28 | final String accessTokenValue = accessToken.getValue(); 29 | log.info("Using access token {}.", accessTokenValue); 30 | log.info("Request {}.", requestTemplate.toString()); 31 | requestTemplate.header(AUTHORIZATION_HEADER, 32 | String.format("%s %s", 33 | BEARER_TOKEN, 34 | oAuth2RestTemplate.getAccessToken().toString())); 35 | }; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/config/OAuth2FeignRequestInterceptor.java: -------------------------------------------------------------------------------- 1 | //package es.ejercicio.microservicios.biblioteca.config; 2 | // 3 | //import org.springframework.security.oauth2.client.OAuth2RestTemplate; 4 | // 5 | //import feign.RequestInterceptor; 6 | //import feign.RequestTemplate; 7 | //import lombok.extern.slf4j.Slf4j; 8 | // 9 | //@Slf4j 10 | //public class OAuth2FeignRequestInterceptor implements RequestInterceptor { 11 | // 12 | // private static final String AUTHORIZATION_HEADER = "Authorization"; 13 | // 14 | // private static final String BEARER_TOKEN = "Bearer"; 15 | // 16 | // private final OAuth2RestTemplate oAuth2RestTemplate; 17 | // 18 | // public OAuth2FeignRequestInterceptor(OAuth2RestTemplate restTemplate) { 19 | // this.oAuth2RestTemplate = restTemplate; 20 | // } 21 | // 22 | // @Override 23 | // public void apply(RequestTemplate requestTemplate) { 24 | // log.debug("REQUEST:" + requestTemplate.toString()); 25 | // log.debug("Se aplica el token:" + oAuth2RestTemplate.getAccessToken().toString()); 26 | // requestTemplate.header(AUTHORIZATION_HEADER, 27 | // String.format("%s %s", 28 | // BEARER_TOKEN, 29 | // oAuth2RestTemplate.getAccessToken().toString())); 30 | // } 31 | // 32 | //} 33 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/config/Oauth2ClientConfig.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.config; 2 | 3 | import org.springframework.beans.factory.annotation.Autowired; 4 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import org.springframework.http.client.Netty4ClientHttpRequestFactory; 8 | import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext; 9 | import org.springframework.security.oauth2.client.OAuth2RestTemplate; 10 | import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; 11 | import org.springframework.security.oauth2.common.AuthenticationScheme; 12 | 13 | import es.ejercicio.microservicios.biblioteca.config.properties.Oauth2ClientProperties; 14 | 15 | @Configuration 16 | @EnableConfigurationProperties(Oauth2ClientProperties.class) 17 | public class Oauth2ClientConfig { 18 | 19 | @Autowired 20 | private Oauth2ClientProperties oauth2ClientProperties; 21 | 22 | @Bean(name = "ejercicioClientCredentialsResourceDetails") 23 | public ClientCredentialsResourceDetails resourceDetails() { 24 | ClientCredentialsResourceDetails resourceDetails = new ClientCredentialsResourceDetails(); 25 | resourceDetails.setId(oauth2ClientProperties.getId()); 26 | resourceDetails.setAccessTokenUri(oauth2ClientProperties.getAccessTokenUrl()); 27 | resourceDetails.setClientId(oauth2ClientProperties.getClientId()); 28 | resourceDetails.setClientSecret(oauth2ClientProperties.getClientSecret()); 29 | resourceDetails.setAuthenticationScheme(AuthenticationScheme.valueOf(oauth2ClientProperties.getClientAuthenticationScheme())); 30 | return resourceDetails; 31 | } 32 | 33 | @Bean(name = "ejercicioOAuth2RestTemplate") 34 | public OAuth2RestTemplate oAuth2RestTemplate() { 35 | final OAuth2RestTemplate oAuth2RestTemplate = 36 | new OAuth2RestTemplate(resourceDetails(), 37 | new DefaultOAuth2ClientContext()); 38 | oAuth2RestTemplate.setRequestFactory(new Netty4ClientHttpRequestFactory()); 39 | 40 | return oAuth2RestTemplate; 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/config/properties/Oauth2ClientProperties.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.config.properties; 2 | 3 | 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | 6 | import lombok.Data; 7 | 8 | @Data 9 | @ConfigurationProperties(prefix = "ejercicio.oauth2.client") 10 | public class Oauth2ClientProperties { 11 | 12 | private String id; 13 | private String accessTokenUrl; 14 | private String clientId; 15 | private String clientSecret; 16 | private String clientAuthenticationScheme; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/control/ControlAutores.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.control; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.stereotype.Component; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | 12 | import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; 13 | 14 | import es.ejercicio.microservicios.biblioteca.cliente.ClienteAutores; 15 | import es.ejercicio.microservicios.dto.AutorDTO; 16 | 17 | 18 | @Component 19 | public class ControlAutores { 20 | 21 | @Autowired 22 | ClienteAutores clienteAutores; 23 | 24 | @HystrixCommand(fallbackMethod="failObtenerAutores") 25 | public List obtenerAutores() { 26 | return clienteAutores.obtenerAutores(); 27 | } 28 | 29 | @HystrixCommand(fallbackMethod="failObtenerAutor") 30 | public ResponseEntity obtenerAutor(String id) { 31 | return clienteAutores.obtenerAutor(id); 32 | } 33 | 34 | 35 | @HystrixCommand(fallbackMethod="failNuevoAutor") 36 | public ResponseEntity nuevoAutor(@RequestBody AutorDTO input) { 37 | return clienteAutores.nuevoAutor(input); 38 | } 39 | 40 | @HystrixCommand(fallbackMethod="failEliminarAutor") 41 | public void eliminarAutor(String id) { 42 | clienteAutores.eliminarAutor(id); 43 | } 44 | 45 | public List failObtenerAutores(Throwable t) { 46 | return new ArrayList(); 47 | } 48 | 49 | 50 | public ResponseEntity failObtenerAutor(String id, Throwable t) { 51 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body( 52 | AutorDTO.builder().id(0).nombre("NO DISPONIBLE").build()); 53 | } 54 | 55 | public ResponseEntity failNuevoAutor(AutorDTO input, Throwable t) { 56 | return ResponseEntity 57 | .status(HttpStatus.NOT_FOUND) 58 | .body(AutorDTO.builder().id(0).nombre("NO DISPONIBLE").build()); 59 | } 60 | 61 | public void failEliminarAutor(String id, Throwable t) { 62 | t.printStackTrace(); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/control/ControlCategorias.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.control; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.stereotype.Component; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | 12 | import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; 13 | 14 | import es.ejercicio.microservicios.biblioteca.cliente.ClienteCategorias; 15 | import es.ejercicio.microservicios.dto.CategoriaDTO; 16 | 17 | 18 | @Component 19 | public class ControlCategorias { 20 | 21 | @Autowired 22 | ClienteCategorias clienteCategorias; 23 | 24 | @HystrixCommand(fallbackMethod="failObtenerCategorias") 25 | public List obtenerCategorias() { 26 | return clienteCategorias.obtenerCategorias(); 27 | } 28 | 29 | @HystrixCommand(fallbackMethod="failObtenerCategoria") 30 | public CategoriaDTO obtenerCategoria(String id) { 31 | return clienteCategorias.obtenerCategoria(id); 32 | } 33 | 34 | 35 | @HystrixCommand(fallbackMethod="failNuevaCategoria") 36 | public ResponseEntity nuevaCategoria(@RequestBody CategoriaDTO input) { 37 | return clienteCategorias.nuevaCategoria(input); 38 | } 39 | 40 | @HystrixCommand(fallbackMethod="failEliminarCategoria") 41 | public void eliminarCategoria(String id) { 42 | clienteCategorias.eliminarCategoria(id); 43 | } 44 | 45 | public List failObtenerCategorias(Throwable t) { 46 | return new ArrayList(); 47 | } 48 | 49 | public CategoriaDTO failObtenerCategoria(String id, Throwable t) { 50 | return CategoriaDTO.builder().id(0).nombre("NO DISPONIBLE").build(); 51 | } 52 | 53 | public ResponseEntity failNuevaCategoria(CategoriaDTO input, Throwable t) { 54 | return ResponseEntity 55 | .status(HttpStatus.NOT_FOUND) 56 | .body(CategoriaDTO.builder().id(0).nombre("NO DISPONIBLE").build()); 57 | } 58 | 59 | public void failEliminarCategoria(String id, Throwable t) { 60 | t.printStackTrace(); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/control/ControlEditoriales.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.control; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.http.HttpStatus; 8 | import org.springframework.http.ResponseEntity; 9 | import org.springframework.stereotype.Component; 10 | import org.springframework.web.bind.annotation.RequestBody; 11 | 12 | import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; 13 | 14 | import es.ejercicio.microservicios.biblioteca.cliente.ClienteEditoriales; 15 | import es.ejercicio.microservicios.dto.AutorDTO; 16 | import es.ejercicio.microservicios.dto.EditorialDTO; 17 | 18 | 19 | @Component 20 | public class ControlEditoriales { 21 | 22 | @Autowired 23 | ClienteEditoriales clienteEditoriales; 24 | 25 | @HystrixCommand(fallbackMethod="failObtenerEditoriales") 26 | public List obtenerEditoriales() { 27 | return clienteEditoriales.obtenerEditoriales(); 28 | } 29 | 30 | @HystrixCommand(fallbackMethod="failObtenerEditorial") 31 | public EditorialDTO obtenerEditorial(String id) { 32 | return clienteEditoriales.obtenerEditorial(id); 33 | } 34 | 35 | 36 | @HystrixCommand(fallbackMethod="failNuevaEditorial") 37 | public ResponseEntity nuevaEditorial(@RequestBody EditorialDTO input) { 38 | return clienteEditoriales.nuevoEditorial(input); 39 | } 40 | 41 | @HystrixCommand(fallbackMethod="failEliminarEditorial") 42 | public void eliminarEditorial(String id) { 43 | clienteEditoriales.eliminarEditorial(id); 44 | } 45 | 46 | public List failObtenerEditoriales(Throwable t) { 47 | return new ArrayList(); 48 | } 49 | 50 | public EditorialDTO failObtenerEditorial(String id, Throwable t) { 51 | t.printStackTrace(); 52 | return EditorialDTO.builder().id(0).nombre("NO DISPONIBLE").build(); 53 | } 54 | 55 | public ResponseEntity failNuevaEditorial(EditorialDTO input, Throwable t) { 56 | return ResponseEntity 57 | .status(HttpStatus.NOT_FOUND) 58 | .body(EditorialDTO.builder().id(0).nombre("NO DISPONIBLE").build()); 59 | } 60 | 61 | public void failEliminarEditorial(String id, Throwable t) { 62 | t.printStackTrace(); 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /bibliotecaCliente/src/main/java/es/ejercicio/microservicios/biblioteca/control/ControlLibros.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.biblioteca.control; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Component; 8 | 9 | import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; 10 | 11 | import es.ejercicio.microservicios.biblioteca.cliente.ClienteLibros; 12 | import es.ejercicio.microservicios.dto.EditorialDTO; 13 | import es.ejercicio.microservicios.dto.LibroDTO; 14 | 15 | 16 | @Component 17 | public class ControlLibros { 18 | 19 | @Autowired 20 | ClienteLibros clienteLibros; 21 | 22 | @HystrixCommand(fallbackMethod="failObtenerLibros") 23 | public List obtenerLibros() { 24 | return clienteLibros.obtenerLibros(); 25 | } 26 | 27 | 28 | @HystrixCommand(fallbackMethod="failObtenerLibrosFavoritos") 29 | public List obtenerLibrosFavoritos() { 30 | return clienteLibros.obtenerLibrosFavoritos(); 31 | } 32 | 33 | @HystrixCommand(fallbackMethod="failObtenerLibrosByExample") 34 | public List obtenerLibrosByExample(LibroDTO example) { 35 | return clienteLibros.obtenerLibrosByExample(example); 36 | } 37 | 38 | @HystrixCommand(fallbackMethod="failObtenerLibro") 39 | public LibroDTO obtenerLibro(String id) { 40 | return clienteLibros.obtenerLibro(id); 41 | } 42 | 43 | 44 | public List failObtenerLibros(Throwable t) { 45 | 46 | return new ArrayList() ; 47 | } 48 | 49 | public List failObtenerLibrosFavoritos(Throwable t) { 50 | 51 | return new ArrayList() ; 52 | } 53 | 54 | public List failObtenerLibrosByExample(LibroDTO input, Throwable t) { 55 | 56 | return new ArrayList() ; 57 | } 58 | 59 | public LibroDTO failObtenerLibro(String id, Throwable t) { 60 | return LibroDTO.builder().id(0).titulo("NO DISPONIBLE").build(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /categorias/.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings 4 | /target/ 5 | -------------------------------------------------------------------------------- /categorias/.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /categorias/src/main/java/es/ejercicio/microservicios/categorias/CategoriasApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.categorias; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cache.annotation.EnableCaching; 6 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 7 | 8 | @SpringBootApplication 9 | @EnableDiscoveryClient 10 | @EnableCaching 11 | public class CategoriasApplication { 12 | 13 | public static void main(String[] args) { 14 | SpringApplication.run(CategoriasApplication.class, args); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /categorias/src/main/java/es/ejercicio/microservicios/categorias/config/CategoriasResourceServerConfig.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.categorias.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 7 | 8 | @Configuration 9 | @EnableResourceServer 10 | public class CategoriasResourceServerConfig extends ResourceServerConfigurerAdapter { 11 | 12 | private static final String[] AUTH_WHITELIST = { 13 | // -- swagger ui 14 | "/v2/api-docs", 15 | "/swagger-resources", 16 | "/swagger-resources/**", 17 | "/configuration/ui", 18 | "/configuration/security", 19 | "/swagger-ui.html", 20 | "/webjars/**" 21 | }; 22 | 23 | 24 | @Override 25 | public void configure(HttpSecurity http) throws Exception { 26 | http.authorizeRequests(). 27 | antMatchers(AUTH_WHITELIST).permitAll(). 28 | and() 29 | .authorizeRequests(). 30 | antMatchers("/categorias/**").authenticated(); 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /categorias/src/main/java/es/ejercicio/microservicios/categorias/controller/CategoriaController.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.categorias.controller; 2 | 3 | import java.sql.SQLException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import org.dozer.DozerBeanMapper; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.RequestBody; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RequestMethod; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | import es.ejercicio.microservicios.categorias.entity.Categoria; 18 | import es.ejercicio.microservicios.categorias.service.CategoriaService; 19 | import es.ejercicio.microservicios.dto.AutorDTO; 20 | import es.ejercicio.microservicios.dto.CategoriaDTO; 21 | import io.swagger.annotations.Api; 22 | import io.swagger.annotations.ApiOperation; 23 | import io.swagger.annotations.ApiParam; 24 | import io.swagger.annotations.ApiResponse; 25 | import io.swagger.annotations.ApiResponses; 26 | import lombok.extern.slf4j.Slf4j; 27 | 28 | 29 | @Slf4j 30 | @RestController 31 | @Api(value = "CategoriaController", description="Operaciones sobre las Categorías de los libros de la Biblioteca") 32 | @RequestMapping(value = "/categorias/") 33 | public class CategoriaController { 34 | 35 | 36 | @Autowired 37 | private CategoriaService categoriaService; 38 | 39 | /** DozerMapper. */ 40 | DozerBeanMapper mapper = new DozerBeanMapper(); 41 | 42 | /** 43 | * Retorna todos las categorias 44 | * @return Listado de categorias 45 | * @throws SQLException 46 | */ 47 | @RequestMapping(value = "/getAll", method = RequestMethod.GET) 48 | @ApiOperation(value = "Retorna todas las categorías", 49 | notes = "Retorna todos las categorías almacenados en base de datos", 50 | response = CategoriaDTO.class, 51 | responseContainer = "List") 52 | @ApiResponses(value = {@ApiResponse(code = 200, message = "Categorías retornados correctamente")}) 53 | public List getAll() throws SQLException { 54 | 55 | List categorias = categoriaService.findAll(); 56 | List autoresDTO = new ArrayList(); 57 | if (categorias != null) 58 | { 59 | for (Categoria categoria : categorias) { 60 | CategoriaDTO categoriaDTO= (CategoriaDTO) mapper.map(categoria, CategoriaDTO.class); 61 | autoresDTO.add(categoriaDTO); 62 | } 63 | 64 | } 65 | return autoresDTO; 66 | 67 | } 68 | 69 | /** 70 | * Retorna la categoria del id 71 | * @return Categoria 72 | * @throws SQLException 73 | */ 74 | @RequestMapping(value = "/getCategoria/{id}", method = RequestMethod.GET) 75 | @ApiOperation(value = "Retorna una Categoría", 76 | notes = "Retorna la Categoría del id especificado", 77 | response = CategoriaDTO.class) 78 | @ApiResponses(value = {@ApiResponse(code = 404, message = "Categoría no encontrada"), 79 | @ApiResponse(code = 200, message = "Categoría encontrada")} 80 | ) 81 | public ResponseEntity getCategoria(@ApiParam(name = "id", value = "Id de la Categoría a buscar", required = true)@PathVariable("id") String id) throws SQLException { 82 | Integer idAutor = 0; 83 | try 84 | { 85 | idAutor = Integer.parseInt(id); 86 | } catch (NumberFormatException ex) { 87 | log.error("Se ha producido un error, el id no es un valor numerico:" + ex.getMessage()); 88 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new CategoriaDTO()); 89 | } 90 | Categoria categoria = categoriaService.findById(idAutor); 91 | 92 | if (categoria != null) 93 | { 94 | CategoriaDTO categoriaDTO= (CategoriaDTO) mapper.map(categoria, CategoriaDTO.class); 95 | 96 | return ResponseEntity.status(HttpStatus.OK).body(categoriaDTO); 97 | } else { 98 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new CategoriaDTO()); 99 | } 100 | 101 | } 102 | 103 | /** 104 | * Elimina la categoria del id 105 | * @throws SQLException 106 | */ 107 | @RequestMapping(value = "/deleteCategoria/{id}", method = RequestMethod.DELETE) 108 | @ApiOperation(value = "Elimina una Categoría", 109 | notes = "Elimina la Categoría del id especificado", 110 | response = HttpStatus.class) 111 | public HttpStatus deleteCategoria(@ApiParam(name = "id", value = "Id de la Categoría a eliminar", required = true) @PathVariable("id") String id) throws SQLException { 112 | Integer idCategoria = 0; 113 | try 114 | { 115 | idCategoria = Integer.parseInt(id); 116 | } catch (NumberFormatException ex) { 117 | log.error("Se ha producido un error, el id no es un valor numerico:" + ex.getMessage()); 118 | return HttpStatus.NOT_FOUND; 119 | } 120 | categoriaService.deleteById(idCategoria); 121 | 122 | return HttpStatus.OK; 123 | } 124 | 125 | /** 126 | * Añade una nueva categoria 127 | * @return Categoria 128 | * @throws SQLException 129 | */ 130 | @RequestMapping(value = "/nuevaCategoria", method = RequestMethod.POST) 131 | @ApiOperation("Inserta o actualiza en base de datos un Autor") 132 | public ResponseEntity nuevaCategoria(@ApiParam(name = "categoriaDTO", value = "Categoría a insertar/actualizar", required = true)@RequestBody CategoriaDTO input) throws SQLException { 133 | log.debug("Se intenta insertar la categoria:" + input); 134 | 135 | Categoria categoria = Categoria.builder().id(input.getId()) 136 | .nombre(input.getNombre()) 137 | .build(); 138 | 139 | Categoria nuevaCategoria = categoriaService.nuevaCategoria(categoria); 140 | CategoriaDTO categoriaDTO= (CategoriaDTO) mapper.map(nuevaCategoria, CategoriaDTO.class); 141 | 142 | return ResponseEntity.status(HttpStatus.OK).body(categoriaDTO); 143 | 144 | } 145 | 146 | } 147 | -------------------------------------------------------------------------------- /categorias/src/main/java/es/ejercicio/microservicios/categorias/entity/Categoria.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.categorias.entity; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.Id; 5 | 6 | import lombok.AllArgsConstructor; 7 | import lombok.Builder; 8 | import lombok.Data; 9 | import lombok.NoArgsConstructor; 10 | 11 | /** 12 | * @author Juan Manuel Cintas 13 | * 14 | */ 15 | @Entity 16 | @Data 17 | @Builder 18 | @NoArgsConstructor 19 | @AllArgsConstructor 20 | public class Categoria { 21 | 22 | /** 23 | * Id. 24 | */ 25 | @Id 26 | private int id; 27 | 28 | /** 29 | * Nombre del autor. 30 | */ 31 | private String nombre; 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /categorias/src/main/java/es/ejercicio/microservicios/categorias/repository/CategoriaRepository.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.categorias.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import es.ejercicio.microservicios.categorias.entity.Categoria; 7 | 8 | 9 | 10 | @Repository 11 | public interface CategoriaRepository extends JpaRepository { 12 | 13 | 14 | } -------------------------------------------------------------------------------- /categorias/src/main/java/es/ejercicio/microservicios/categorias/service/CategoriaService.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.categorias.service; 2 | 3 | import java.util.List; 4 | 5 | import es.ejercicio.microservicios.categorias.entity.Categoria; 6 | 7 | public interface CategoriaService { 8 | 9 | public List findAll(); 10 | 11 | public Categoria findById(Integer id); 12 | 13 | public void deleteById(Integer id); 14 | 15 | public Categoria nuevaCategoria(Categoria categoria); 16 | } -------------------------------------------------------------------------------- /categorias/src/main/java/es/ejercicio/microservicios/categorias/service/impl/CategoriaServiceImpl.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.categorias.service.impl; 2 | 3 | import java.util.List; 4 | 5 | 6 | 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.cache.annotation.Cacheable; 9 | import org.springframework.stereotype.Service; 10 | 11 | import es.ejercicio.microservicios.categorias.entity.Categoria; 12 | import es.ejercicio.microservicios.categorias.repository.CategoriaRepository; 13 | import es.ejercicio.microservicios.categorias.service.CategoriaService; 14 | import lombok.extern.slf4j.Slf4j; 15 | 16 | @Slf4j 17 | @Service 18 | public class CategoriaServiceImpl implements CategoriaService { 19 | 20 | @Autowired 21 | private CategoriaRepository categoriaRepository; 22 | 23 | 24 | @Override 25 | @Cacheable(value = "categorias") 26 | public List findAll() { 27 | log.debug("Se obtienen todas las categorias."); 28 | return categoriaRepository.findAll(); 29 | } 30 | 31 | 32 | @Override 33 | @Cacheable(value = "categoria", key = "#id") 34 | public Categoria findById(Integer id) { 35 | log.debug("Se obtiene la categoria con id:" + id); 36 | return categoriaRepository.findOne(id); 37 | } 38 | 39 | 40 | @Override 41 | public Categoria nuevaCategoria(Categoria categoria) { 42 | log.debug("Se añade la categoria:" + categoria); 43 | return categoriaRepository.save(categoria); 44 | 45 | } 46 | 47 | 48 | @Override 49 | public void deleteById(Integer id) { 50 | log.debug("Se elimina la categoria con id:" + id); 51 | categoriaRepository.delete(id); 52 | 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /categorias/src/main/java/es/ejercicio/microservicios/categorias/swager/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.categorias.swager; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import com.google.common.base.Predicates; 7 | 8 | import springfox.documentation.builders.ApiInfoBuilder; 9 | import springfox.documentation.builders.PathSelectors; 10 | import springfox.documentation.service.ApiInfo; 11 | import springfox.documentation.service.Contact; 12 | import springfox.documentation.spi.DocumentationType; 13 | import springfox.documentation.spring.web.plugins.Docket; 14 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 15 | 16 | /** 17 | * @author Juan Manuel Cintas 18 | * 19 | */ 20 | @Configuration 21 | @EnableSwagger2 22 | public class SwaggerConfig { 23 | 24 | @Bean 25 | public Docket swaggerSpringMvcPlugin() { 26 | return new Docket(DocumentationType.SWAGGER_2) 27 | .useDefaultResponseMessages(false) 28 | .apiInfo(apiInfo()) 29 | .select() 30 | .paths(Predicates.not(PathSelectors.regex("/error.*"))) 31 | .build(); 32 | } 33 | 34 | private ApiInfo apiInfo() { 35 | return new ApiInfoBuilder() 36 | .title("Biblioteca - Categorias") 37 | .description("API documentation for Categorias Application") 38 | .contact(new Contact("Juan Manuel Cintas", "https://github.com/juanmacintas", "hurone@gmail.com")) 39 | .license("Apache License Version 2.0") 40 | .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE") 41 | .version("2.0") 42 | .build(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /categorias/src/main/resources/bootstrap.properties: -------------------------------------------------------------------------------- 1 | spring.cloud.config.uri=http://${CONFIG_HOST:localhost}:${CONFIG_PORT:8888} 2 | spring.application.name=categorias 3 | spring.profiles.active=${PROFILE:default} 4 | endpoints.refresh.sensitive=false -------------------------------------------------------------------------------- /categorias/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO CATEGORIA (id, nombre) values (1,'Ciencia Ficción'); 2 | INSERT INTO CATEGORIA (id, nombre) values (2,'Novela Negra'); 3 | INSERT INTO CATEGORIA (id, nombre) values (3,'Terror'); 4 | INSERT INTO CATEGORIA (id, nombre) values (4,'Romántica'); 5 | INSERT INTO CATEGORIA (id, nombre) values (5,'Ensayo'); 6 | INSERT INTO CATEGORIA (id, nombre) values (6,'Cómic'); 7 | INSERT INTO CATEGORIA (id, nombre) values (7,'Suspense'); 8 | INSERT INTO CATEGORIA (id, nombre) values (8,'Policiaca'); 9 | INSERT INTO CATEGORIA (id, nombre) values (9,'Aventuras'); 10 | INSERT INTO CATEGORIA (id, nombre) values (10,'Ficción Histórica'); 11 | INSERT INTO CATEGORIA (id, nombre) values (11,'Fantasía'); -------------------------------------------------------------------------------- /categorias/src/test/java/es/ejercicio/microservicios/categorias/controller/CategoriaControllerTest.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.categorias.controller; 2 | 3 | import static org.hamcrest.Matchers.empty; 4 | import static org.hamcrest.Matchers.is; 5 | import static org.hamcrest.Matchers.not; 6 | import static org.junit.Assert.fail; 7 | import static org.mockito.Matchers.anyInt; 8 | import static org.mockito.Matchers.anyObject; 9 | import static org.mockito.Mockito.when; 10 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 11 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; 12 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 13 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 14 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 15 | 16 | import java.nio.charset.Charset; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | 20 | import org.junit.Before; 21 | import org.junit.Test; 22 | import org.junit.runner.RunWith; 23 | import org.springframework.beans.factory.annotation.Autowired; 24 | import org.springframework.boot.test.context.SpringBootTest; 25 | import org.springframework.boot.test.mock.mockito.MockBean; 26 | import org.springframework.http.MediaType; 27 | import org.springframework.test.context.junit4.SpringRunner; 28 | import org.springframework.test.context.web.WebAppConfiguration; 29 | import org.springframework.test.web.servlet.MockMvc; 30 | import org.springframework.test.web.servlet.ResultActions; 31 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 32 | import org.springframework.web.context.WebApplicationContext; 33 | 34 | import com.fasterxml.jackson.core.JsonProcessingException; 35 | import com.google.gson.Gson; 36 | 37 | import es.ejercicio.microservicios.categorias.CategoriasApplication; 38 | import es.ejercicio.microservicios.categorias.entity.Categoria; 39 | import es.ejercicio.microservicios.categorias.repository.CategoriaRepository; 40 | import es.ejercicio.microservicios.categorias.service.CategoriaService; 41 | import es.ejercicio.microservicios.dto.CategoriaDTO; 42 | 43 | /** 44 | * @author Juan Manuel Cintas 45 | * 46 | */ 47 | @RunWith(SpringRunner.class) 48 | @SpringBootTest(classes = CategoriasApplication.class) 49 | @WebAppConfiguration 50 | public class CategoriaControllerTest { 51 | private MockMvc mockMvc; 52 | 53 | private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), 54 | MediaType.APPLICATION_JSON.getSubtype(), 55 | Charset.forName("utf8")); 56 | 57 | @Autowired 58 | private WebApplicationContext webApplicationContext; 59 | 60 | @MockBean 61 | private CategoriaRepository categoriaRepository; 62 | 63 | @MockBean 64 | CategoriaService categoriaService; 65 | 66 | @Before 67 | public void setup() throws Exception { 68 | this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); 69 | } 70 | 71 | 72 | @Test 73 | public void testGetAllCategorias() { 74 | 75 | Categoria categoria1 = Categoria.builder().id(1).nombre("Categoria 1").build(); 76 | Categoria categoria2 = Categoria.builder().id(2).nombre("Categoria 2").build(); 77 | 78 | List listCategorias = new ArrayList(); 79 | listCategorias.add(categoria1); 80 | listCategorias.add(categoria2); 81 | 82 | 83 | when(categoriaRepository.findAll()).thenReturn(listCategorias); 84 | when(categoriaService.findAll()).thenReturn(listCategorias); 85 | try { 86 | ResultActions res = this.mockMvc.perform(get("/categorias/getAll")) 87 | .andDo(print()) 88 | .andExpect(status().isOk()) 89 | .andExpect(jsonPath("$", not(empty()))) 90 | .andExpect(jsonPath("$.[0].id", is(1) )); 91 | } catch (JsonProcessingException e1) { 92 | fail(e1.getMessage()); 93 | } catch (Exception e) { 94 | fail(e.getMessage()); 95 | } 96 | 97 | } 98 | 99 | 100 | @Test 101 | public void testCategoriaPorId() { 102 | 103 | Categoria categoria = Categoria.builder().id(1).nombre("Categoria 1").build(); 104 | 105 | when(categoriaRepository.findOne(anyInt())).thenReturn(categoria); 106 | when(categoriaService.findById(anyInt())).thenReturn(categoria); 107 | try { 108 | ResultActions res = this.mockMvc.perform(get("/categorias/getCategoria/1")) 109 | .andDo(print()) 110 | .andExpect(status().isOk()) 111 | .andExpect(jsonPath("$", not(empty()))) 112 | .andExpect(jsonPath("$.id", is(1) )); 113 | } catch (JsonProcessingException e1) { 114 | fail(e1.getMessage()); 115 | } catch (Exception e) { 116 | fail(e.getMessage()); 117 | } 118 | 119 | } 120 | 121 | @Test 122 | public void testNuevaCategoria() { 123 | 124 | Categoria categoria = Categoria.builder().id(1).nombre("Categoria 1").build(); 125 | 126 | CategoriaDTO categoriaDTO = CategoriaDTO.builder().id(1).build(); 127 | 128 | Gson gson = new Gson(); 129 | 130 | 131 | String json = gson.toJson(categoriaDTO); 132 | 133 | 134 | when(categoriaRepository.save(categoria)).thenReturn(categoria); 135 | when(categoriaService.nuevaCategoria(anyObject())).thenReturn(categoria); 136 | try { 137 | ResultActions res = this.mockMvc.perform(post("/categorias/nuevaCategoria/") 138 | .contentType(MediaType.APPLICATION_JSON).content(json)) 139 | .andDo(print()) 140 | .andExpect(status().isOk()) 141 | .andExpect(jsonPath("$", not(empty()))) 142 | .andExpect(jsonPath("$.id", is(1) )); 143 | } catch (JsonProcessingException e1) { 144 | fail(e1.getMessage()); 145 | } catch (Exception e) { 146 | fail(e.getMessage()); 147 | } 148 | 149 | } 150 | 151 | } 152 | -------------------------------------------------------------------------------- /editoriales/.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings 4 | /target/ 5 | -------------------------------------------------------------------------------- /editoriales/.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /editoriales/src/main/java/es/ejercicio/microservicios/editoriales/EditorialesApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.editoriales; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | 7 | @SpringBootApplication 8 | @EnableDiscoveryClient 9 | public class EditorialesApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(EditorialesApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /editoriales/src/main/java/es/ejercicio/microservicios/editoriales/config/EditorialResourceServerConfig.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.editoriales.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 7 | 8 | @Configuration 9 | @EnableResourceServer 10 | public class EditorialResourceServerConfig extends ResourceServerConfigurerAdapter { 11 | 12 | private static final String[] AUTH_WHITELIST = { 13 | // -- swagger ui 14 | "/v2/api-docs", 15 | "/swagger-resources", 16 | "/swagger-resources/**", 17 | "/configuration/ui", 18 | "/configuration/security", 19 | "/swagger-ui.html", 20 | "/webjars/**" 21 | }; 22 | 23 | 24 | @Override 25 | public void configure(HttpSecurity http) throws Exception { 26 | http.authorizeRequests(). 27 | antMatchers(AUTH_WHITELIST).permitAll(). 28 | and() 29 | .authorizeRequests(). 30 | antMatchers("/editoriales/**").authenticated(); 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /editoriales/src/main/java/es/ejercicio/microservicios/editoriales/controller/EditorialController.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.editoriales.controller; 2 | 3 | import java.sql.SQLException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import org.dozer.DozerBeanMapper; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.security.core.Authentication; 12 | import org.springframework.web.bind.annotation.PathVariable; 13 | import org.springframework.web.bind.annotation.RequestBody; 14 | import org.springframework.web.bind.annotation.RequestMapping; 15 | import org.springframework.web.bind.annotation.RequestMethod; 16 | import org.springframework.web.bind.annotation.RestController; 17 | 18 | import es.ejercicio.microservicios.dto.AutorDTO; 19 | import es.ejercicio.microservicios.dto.CategoriaDTO; 20 | import es.ejercicio.microservicios.dto.EditorialDTO; 21 | import es.ejercicio.microservicios.editoriales.entity.Editorial; 22 | import es.ejercicio.microservicios.editoriales.service.EditorialService; 23 | import io.swagger.annotations.Api; 24 | import io.swagger.annotations.ApiOperation; 25 | import io.swagger.annotations.ApiParam; 26 | import io.swagger.annotations.ApiResponse; 27 | import io.swagger.annotations.ApiResponses; 28 | import lombok.extern.slf4j.Slf4j; 29 | 30 | @Slf4j 31 | @RestController 32 | @RequestMapping(value = "/editoriales/") 33 | @Api(value = "EditorialController", description="Operaciones sobre las Editoriales de los libros de la Biblioteca") 34 | public class EditorialController { 35 | 36 | 37 | @Autowired 38 | private EditorialService editorialService; 39 | 40 | /** DozerMapper. */ 41 | DozerBeanMapper mapper = new DozerBeanMapper(); 42 | 43 | /** 44 | * Retorna todos las editoriales 45 | * @return Listado de editoriales 46 | * @throws SQLException 47 | */ 48 | @RequestMapping(value = "/getAll", method = RequestMethod.GET) 49 | @ApiOperation(value = "Retorna todos las editoriales", 50 | notes = "Retorna todos las editoriales almacenados en base de datos", 51 | response = EditorialDTO.class, 52 | responseContainer = "List") 53 | @ApiResponses(value = {@ApiResponse(code = 200, message = "Editoriales retornadas correctamente")}) 54 | public List getAll(Authentication authentication) throws SQLException { 55 | 56 | List editoriales = editorialService.findAll(); 57 | List editorialesDTO = new ArrayList(); 58 | if (editoriales != null) 59 | { 60 | for (Editorial editorial : editoriales) { 61 | EditorialDTO editorialDTO= (EditorialDTO) mapper.map(editorial, EditorialDTO.class); 62 | editorialesDTO.add(editorialDTO); 63 | } 64 | 65 | } 66 | return editorialesDTO; 67 | 68 | } 69 | 70 | /** 71 | * Retorna la editorial del id 72 | * @return Editorial 73 | * @throws SQLException 74 | */ 75 | @RequestMapping(value = "/getEditorial/{id}", method = RequestMethod.GET) 76 | @ApiOperation(value = "Retorna una Editorial", 77 | notes = "Retorna la Editorial del id especificado", 78 | response = AutorDTO.class) 79 | @ApiResponses(value = {@ApiResponse(code = 404, message = "Editorial no encontrada"), 80 | @ApiResponse(code = 200, message = "Editorial encontrada")} 81 | ) 82 | public ResponseEntity getEditorial(Authentication authentication,@ApiParam(name = "id", value = "Id del Autor a buscar", required = true)@PathVariable("id") String id) throws SQLException { 83 | Integer idEditorial = 0; 84 | try 85 | { 86 | idEditorial = Integer.parseInt(id); 87 | } catch (NumberFormatException ex) { 88 | log.error("Se ha producido un error, el id no es un valor numerico:" + ex.getMessage()); 89 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new EditorialDTO()); 90 | } 91 | Editorial editorial = editorialService.findById(idEditorial); 92 | 93 | if (editorial != null) 94 | { 95 | EditorialDTO editorialDTO= (EditorialDTO) mapper.map(editorial, EditorialDTO.class); 96 | 97 | return ResponseEntity.status(HttpStatus.OK).body(editorialDTO); 98 | } else { 99 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new EditorialDTO()); 100 | } 101 | 102 | 103 | } 104 | 105 | /** 106 | * Elimina la editorial del id 107 | * @throws SQLException 108 | */ 109 | @RequestMapping(value = "/deleteEditorial/{id}", method = RequestMethod.DELETE) 110 | @ApiOperation(value = "Elimina una Editorial", 111 | notes = "Elimina la Editorial del id especificado", 112 | response = HttpStatus.class) 113 | public HttpStatus deleteEditorial(@ApiParam(name = "id", value = "Id del Autor a eliminar", required = true)@PathVariable("id") String id) throws SQLException { 114 | Integer idEditorial = 0; 115 | try 116 | { 117 | idEditorial = Integer.parseInt(id); 118 | } catch (NumberFormatException ex) { 119 | log.error("Se ha producido un error, el id no es un valor numerico:" + ex.getMessage()); 120 | return HttpStatus.NOT_FOUND; 121 | } 122 | editorialService.deleteById(idEditorial); 123 | 124 | return HttpStatus.OK; 125 | } 126 | 127 | /** 128 | * Añade una nueva categoria 129 | * @return Categoria 130 | * @throws SQLException 131 | */ 132 | @RequestMapping(value = "/nuevaEditorial", method = RequestMethod.POST) 133 | @ApiOperation("Inserta o actualiza en base de datos una Editorial") 134 | public ResponseEntity nuevaEditorial(@ApiParam(name = "editorialDTO", value = "Editorial a insertar/actualizar", required = true)@RequestBody CategoriaDTO input) throws SQLException { 135 | log.debug("Se intenta insertar la editorial:" + input); 136 | 137 | Editorial editorial = Editorial.builder().id(input.getId()) 138 | .nombre(input.getNombre()) 139 | .build(); 140 | 141 | Editorial nuevaEditorial = editorialService.nuevaEditorial(editorial); 142 | EditorialDTO editorialDTO= (EditorialDTO) mapper.map(nuevaEditorial, EditorialDTO.class); 143 | 144 | return ResponseEntity.status(HttpStatus.OK).body(editorialDTO); 145 | 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /editoriales/src/main/java/es/ejercicio/microservicios/editoriales/entity/Editorial.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.editoriales.entity; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.Id; 5 | 6 | import lombok.AllArgsConstructor; 7 | import lombok.Builder; 8 | import lombok.Data; 9 | import lombok.NoArgsConstructor; 10 | 11 | /** 12 | * @author Juan Manuel Cintas 13 | * 14 | */ 15 | @Entity 16 | @Data 17 | @Builder 18 | @NoArgsConstructor 19 | @AllArgsConstructor 20 | public class Editorial { 21 | 22 | /** 23 | * Id. 24 | */ 25 | @Id 26 | private int id; 27 | 28 | /** 29 | * Nombre del autor. 30 | */ 31 | private String nombre; 32 | 33 | 34 | } 35 | -------------------------------------------------------------------------------- /editoriales/src/main/java/es/ejercicio/microservicios/editoriales/repository/EditorialRepository.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.editoriales.repository; 2 | 3 | import org.springframework.data.jpa.repository.JpaRepository; 4 | import org.springframework.stereotype.Repository; 5 | 6 | import es.ejercicio.microservicios.editoriales.entity.Editorial; 7 | 8 | 9 | 10 | @Repository 11 | public interface EditorialRepository extends JpaRepository { 12 | 13 | 14 | } -------------------------------------------------------------------------------- /editoriales/src/main/java/es/ejercicio/microservicios/editoriales/service/EditorialService.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.editoriales.service; 2 | 3 | import java.util.List; 4 | 5 | import es.ejercicio.microservicios.editoriales.entity.Editorial; 6 | 7 | public interface EditorialService { 8 | 9 | public List findAll(); 10 | 11 | public Editorial findById(Integer id); 12 | 13 | public void deleteById(Integer id); 14 | 15 | public Editorial nuevaEditorial(Editorial editorial); 16 | } -------------------------------------------------------------------------------- /editoriales/src/main/java/es/ejercicio/microservicios/editoriales/service/impl/EditorialServiceImpl.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.editoriales.service.impl; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.stereotype.Service; 7 | 8 | import es.ejercicio.microservicios.editoriales.entity.Editorial; 9 | import es.ejercicio.microservicios.editoriales.repository.EditorialRepository; 10 | import es.ejercicio.microservicios.editoriales.service.EditorialService; 11 | import lombok.extern.slf4j.Slf4j; 12 | 13 | @Slf4j 14 | @Service 15 | public class EditorialServiceImpl implements EditorialService { 16 | 17 | @Autowired 18 | private EditorialRepository editorialRepository; 19 | 20 | 21 | @Override 22 | public List findAll() { 23 | log.debug("Se obtienen todas las editoriales"); 24 | return editorialRepository.findAll(); 25 | } 26 | 27 | 28 | @Override 29 | public Editorial findById(Integer id) { 30 | log.debug("Se obtiene la editorial con id:" + id); 31 | return editorialRepository.findOne(id); 32 | } 33 | 34 | 35 | @Override 36 | public void deleteById(Integer id) { 37 | log.debug("Se elimina la editorial con id:" + id); 38 | editorialRepository.delete(id); 39 | 40 | } 41 | 42 | 43 | @Override 44 | public Editorial nuevaEditorial(Editorial editorial) { 45 | log.debug("Se añade la editorial:" + editorial); 46 | return editorialRepository.save(editorial); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /editoriales/src/main/java/es/ejercicio/microservicios/editoriales/swager/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.editoriales.swager; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import com.google.common.base.Predicates; 7 | 8 | import springfox.documentation.builders.ApiInfoBuilder; 9 | import springfox.documentation.builders.PathSelectors; 10 | import springfox.documentation.service.ApiInfo; 11 | import springfox.documentation.service.Contact; 12 | import springfox.documentation.spi.DocumentationType; 13 | import springfox.documentation.spring.web.plugins.Docket; 14 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 15 | 16 | /** 17 | * @author Juan Manuel Cintas 18 | * 19 | */ 20 | @Configuration 21 | @EnableSwagger2 22 | public class SwaggerConfig { 23 | 24 | @Bean 25 | public Docket swaggerSpringMvcPlugin() { 26 | return new Docket(DocumentationType.SWAGGER_2) 27 | .useDefaultResponseMessages(false) 28 | .apiInfo(apiInfo()) 29 | .select() 30 | .paths(Predicates.not(PathSelectors.regex("/error.*"))) 31 | .build(); 32 | } 33 | 34 | private ApiInfo apiInfo() { 35 | return new ApiInfoBuilder() 36 | .title("Biblioteca - Editorial") 37 | .description("API documentation for Editoriales Application") 38 | .contact(new Contact("Juan Manuel Cintas", "https://github.com/juanmacintas", "hurone@gmail.com")) 39 | .license("Apache License Version 2.0") 40 | .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE") 41 | .version("2.0") 42 | .build(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /editoriales/src/main/resources/bootstrap.properties: -------------------------------------------------------------------------------- 1 | spring.cloud.config.uri=http://${CONFIG_HOST:localhost}:${CONFIG_PORT:8888} 2 | spring.application.name=editoriales 3 | spring.profiles.active=${PROFILE:default} 4 | endpoints.refresh.sensitive=false -------------------------------------------------------------------------------- /editoriales/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO EDITORIAL (id, nombre) values (1,'Planeta'); 2 | INSERT INTO EDITORIAL (id, nombre) values (2,'B DE BOOKS'); 3 | INSERT INTO EDITORIAL (id, nombre) values (3,'DEBOLS!LLO'); 4 | INSERT INTO EDITORIAL (id, nombre) values (4,'ALFAGUARA'); 5 | INSERT INTO EDITORIAL (id, nombre) values (5,'Minotauro'); 6 | INSERT INTO EDITORIAL (id, nombre) values (6,'RESERVOIR BOOKS'); 7 | INSERT INTO EDITORIAL (id, nombre) values (7,'e-artnow'); 8 | INSERT INTO EDITORIAL (id, nombre) values (8,'Nova'); 9 | INSERT INTO EDITORIAL (id, nombre) values (9,'Booket'); 10 | INSERT INTO EDITORIAL (id, nombre) values (10,'EDHASA'); 11 | INSERT INTO EDITORIAL (id, nombre) values (11,'Planeta DeAgostini Cómics'); 12 | 13 | -------------------------------------------------------------------------------- /editoriales/src/test/java/es/ejercicio/microservicios/editoriales/controller/EditorialControllerTest.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.editoriales.controller; 2 | 3 | import static org.hamcrest.Matchers.empty; 4 | import static org.hamcrest.Matchers.is; 5 | import static org.hamcrest.Matchers.not; 6 | import static org.junit.Assert.fail; 7 | import static org.mockito.Matchers.anyInt; 8 | import static org.mockito.Mockito.when; 9 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 10 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 11 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 12 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 13 | 14 | import java.nio.charset.Charset; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | import org.junit.Before; 19 | import org.junit.Test; 20 | import org.junit.runner.RunWith; 21 | import org.springframework.beans.factory.annotation.Autowired; 22 | import org.springframework.boot.test.context.SpringBootTest; 23 | import org.springframework.boot.test.mock.mockito.MockBean; 24 | import org.springframework.http.MediaType; 25 | import org.springframework.test.context.junit4.SpringRunner; 26 | import org.springframework.test.context.web.WebAppConfiguration; 27 | import org.springframework.test.web.servlet.MockMvc; 28 | import org.springframework.test.web.servlet.ResultActions; 29 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 30 | import org.springframework.web.context.WebApplicationContext; 31 | 32 | import com.fasterxml.jackson.core.JsonProcessingException; 33 | 34 | import es.ejercicio.microservicios.editoriales.EditorialesApplication; 35 | import es.ejercicio.microservicios.editoriales.entity.Editorial; 36 | import es.ejercicio.microservicios.editoriales.repository.EditorialRepository; 37 | import es.ejercicio.microservicios.editoriales.service.EditorialService; 38 | 39 | /** 40 | * @author Juan Manuel Cintas 41 | * 42 | */ 43 | @RunWith(SpringRunner.class) 44 | @SpringBootTest(classes = EditorialesApplication.class) 45 | @WebAppConfiguration 46 | public class EditorialControllerTest { 47 | private MockMvc mockMvc; 48 | 49 | private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), 50 | MediaType.APPLICATION_JSON.getSubtype(), 51 | Charset.forName("utf8")); 52 | 53 | @Autowired 54 | private WebApplicationContext webApplicationContext; 55 | 56 | @MockBean 57 | private EditorialRepository editorialRepository; 58 | 59 | @MockBean 60 | EditorialService editorialService; 61 | 62 | @Before 63 | public void setup() throws Exception { 64 | this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); 65 | } 66 | 67 | 68 | @Test 69 | public void testGetAllEditoriales() { 70 | 71 | Editorial editorial1 = Editorial.builder().id(1).nombre("Editorial 1").build(); 72 | Editorial editorial2 = Editorial.builder().id(2).nombre("Editorial 2").build(); 73 | 74 | List listEditoriales = new ArrayList(); 75 | listEditoriales.add(editorial1); 76 | listEditoriales.add(editorial2); 77 | 78 | 79 | when(editorialRepository.findAll()).thenReturn(listEditoriales); 80 | when(editorialService.findAll()).thenReturn(listEditoriales); 81 | try { 82 | ResultActions res = this.mockMvc.perform(get("/editoriales/getAll")) 83 | .andDo(print()) 84 | .andExpect(status().isOk()) 85 | .andExpect(jsonPath("$", not(empty()))) 86 | .andExpect(jsonPath("$.[0].id", is(1) )); 87 | } catch (JsonProcessingException e1) { 88 | fail(e1.getMessage()); 89 | } catch (Exception e) { 90 | fail(e.getMessage()); 91 | } 92 | 93 | } 94 | 95 | @Test 96 | public void testEditorialPorId() { 97 | 98 | Editorial editorial = Editorial.builder().id(1).nombre("Editorial 1").build(); 99 | 100 | 101 | 102 | when(editorialRepository.findOne(anyInt())).thenReturn(editorial); 103 | when(editorialService.findById(anyInt())).thenReturn(editorial); 104 | try { 105 | ResultActions res = this.mockMvc.perform(get("/editoriales/getEditorial/1")) 106 | .andDo(print()) 107 | .andExpect(status().isOk()) 108 | .andExpect(jsonPath("$", not(empty()))) 109 | .andExpect(jsonPath("$.id", is(1) )); 110 | } catch (JsonProcessingException e1) { 111 | fail(e1.getMessage()); 112 | } catch (Exception e) { 113 | fail(e.getMessage()); 114 | } 115 | 116 | } 117 | 118 | } 119 | -------------------------------------------------------------------------------- /ejercicio-dto/.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings 4 | /target/ 5 | -------------------------------------------------------------------------------- /ejercicio-dto/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | es.ejercicio.microservicios 5 | ejercicio-dto 6 | 0.0.1-SNAPSHOT 7 | ejercicio-dto 8 | DTOs expuestos para el ejercicio 9 | 10 | UTF-8 11 | UTF-8 12 | 1.8 13 | 1.8 14 | 1.8 15 | 1.16.16 16 | 17 | 18 | 19 | org.projectlombok 20 | lombok 21 | ${lombok.version} 22 | 23 | 24 | io.springfox 25 | springfox-swagger2 26 | 2.6.1 27 | compile 28 | 29 | 30 | io.springfox 31 | springfox-swagger-ui 32 | 2.6.1 33 | compile 34 | 35 | 36 | -------------------------------------------------------------------------------- /ejercicio-dto/src/main/java/es/ejercicio/microservicios/dto/AutorDTO.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.dto; 2 | 3 | import io.swagger.annotations.ApiModel; 4 | import io.swagger.annotations.ApiModelProperty; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Builder; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | 10 | /** 11 | * @author Juan Manuel Cintas 12 | * 13 | */ 14 | 15 | @Data 16 | @Builder 17 | @NoArgsConstructor 18 | @AllArgsConstructor 19 | @ApiModel 20 | public class AutorDTO { 21 | 22 | 23 | @ApiModelProperty(notes = "ID del Autor. Clave primaria", required = true) 24 | private int id; 25 | 26 | @ApiModelProperty(notes = "Nombre del Autor") 27 | private String nombre; 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /ejercicio-dto/src/main/java/es/ejercicio/microservicios/dto/CategoriaDTO.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.dto; 2 | 3 | import io.swagger.annotations.ApiModelProperty; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | /** 10 | * @author Juan Manuel Cintas 11 | * 12 | */ 13 | 14 | @Data 15 | @Builder 16 | @NoArgsConstructor 17 | @AllArgsConstructor 18 | public class CategoriaDTO { 19 | 20 | @ApiModelProperty(notes = "ID de la Categoría. Clave primaria", required = true) 21 | private int id; 22 | 23 | @ApiModelProperty(notes = "Nombre de la Categoría") 24 | private String nombre; 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /ejercicio-dto/src/main/java/es/ejercicio/microservicios/dto/EditorialDTO.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.dto; 2 | 3 | import io.swagger.annotations.ApiModelProperty; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | /** 10 | * @author Juan Manuel Cintas 11 | * 12 | */ 13 | 14 | @Data 15 | @Builder 16 | @NoArgsConstructor 17 | @AllArgsConstructor 18 | public class EditorialDTO { 19 | 20 | @ApiModelProperty(notes = "ID de la Editorial. Clave primaria", required = true) 21 | private int id; 22 | 23 | @ApiModelProperty(notes = "Nombre de la Editorial") 24 | private String nombre; 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /ejercicio-dto/src/main/java/es/ejercicio/microservicios/dto/LibroBibliotecaDTO.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.dto; 2 | 3 | import io.swagger.annotations.ApiModelProperty; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | /** 10 | * @author Juan Manuel Cintas 11 | * 12 | */ 13 | 14 | @Data 15 | @Builder 16 | @NoArgsConstructor 17 | @AllArgsConstructor 18 | public class LibroBibliotecaDTO { 19 | 20 | @ApiModelProperty(notes = "ID del Libro. Clave primaria", required = true) 21 | private int id; 22 | 23 | @ApiModelProperty(notes = "Título del Libro") 24 | private String titulo; 25 | 26 | @ApiModelProperty(notes = "Descripción del Libro") 27 | private String descripcion; 28 | 29 | @ApiModelProperty(notes = "ID Categoría del Libro") 30 | private String categoria; 31 | 32 | @ApiModelProperty(notes = "ID Autor del Libro") 33 | private String autor; 34 | 35 | @ApiModelProperty(notes = "ID Editorial del Libro") 36 | private String editorial; 37 | 38 | } 39 | -------------------------------------------------------------------------------- /ejercicio-dto/src/main/java/es/ejercicio/microservicios/dto/LibroDTO.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.dto; 2 | 3 | import io.swagger.annotations.ApiModelProperty; 4 | import lombok.AllArgsConstructor; 5 | import lombok.Builder; 6 | import lombok.Data; 7 | import lombok.NoArgsConstructor; 8 | 9 | /** 10 | * @author Juan Manuel Cintas 11 | * 12 | */ 13 | 14 | @Data 15 | @Builder 16 | @NoArgsConstructor 17 | @AllArgsConstructor 18 | public class LibroDTO { 19 | 20 | @ApiModelProperty(notes = "ID del Libro. Clave primaria", required = true) 21 | private int id; 22 | 23 | @ApiModelProperty(notes = "Título del Libro") 24 | private String titulo; 25 | 26 | @ApiModelProperty(notes = "Descripción del Libro") 27 | private String descripcion; 28 | 29 | @ApiModelProperty(notes = "ID Categoría del Libro") 30 | private Integer categoria; 31 | 32 | @ApiModelProperty(notes = "ID Autor del Libro") 33 | private Integer autor; 34 | 35 | @ApiModelProperty(notes = "ID Editorial del Libro") 36 | private Integer editorial; 37 | 38 | @ApiModelProperty(notes = "Indicador Favorito") 39 | private Boolean favorite; 40 | 41 | } 42 | -------------------------------------------------------------------------------- /ejercicio-dto/src/main/java/es/ejercicio/microservicios/dto/OAuthDTO.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.dto; 2 | 3 | import io.swagger.annotations.ApiModel; 4 | import io.swagger.annotations.ApiModelProperty; 5 | import lombok.AllArgsConstructor; 6 | import lombok.Builder; 7 | import lombok.Data; 8 | import lombok.NoArgsConstructor; 9 | 10 | /** 11 | * @author Juan Manuel Cintas 12 | * 13 | */ 14 | 15 | @Data 16 | @Builder 17 | @NoArgsConstructor 18 | @AllArgsConstructor 19 | @ApiModel 20 | public class OAuthDTO { 21 | 22 | 23 | private String access_token; 24 | 25 | private String token_type; 26 | 27 | private Long expires_in; 28 | 29 | private String scope; 30 | } 31 | -------------------------------------------------------------------------------- /libros/.gitignore: -------------------------------------------------------------------------------- 1 | .classpath 2 | .project 3 | .settings 4 | /target/ 5 | -------------------------------------------------------------------------------- /libros/.springBeans: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /libros/src/main/java/es/ejercicio/microservicios/libros/LibrosApplication.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.libros; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 6 | 7 | @SpringBootApplication 8 | @EnableDiscoveryClient 9 | public class LibrosApplication { 10 | 11 | public static void main(String[] args) { 12 | SpringApplication.run(LibrosApplication.class, args); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /libros/src/main/java/es/ejercicio/microservicios/libros/config/LibrosResourceServerConfig.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.libros.config; 2 | 3 | import org.springframework.context.annotation.Configuration; 4 | import org.springframework.security.config.annotation.web.builders.HttpSecurity; 5 | import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; 6 | import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; 7 | 8 | @Configuration 9 | @EnableResourceServer 10 | public class LibrosResourceServerConfig extends ResourceServerConfigurerAdapter { 11 | 12 | private static final String[] AUTH_WHITELIST = { 13 | // -- swagger ui 14 | "/v2/api-docs", 15 | "/swagger-resources", 16 | "/swagger-resources/**", 17 | "/configuration/ui", 18 | "/configuration/security", 19 | "/swagger-ui.html", 20 | "/webjars/**" 21 | }; 22 | 23 | 24 | @Override 25 | public void configure(HttpSecurity http) throws Exception { 26 | http.authorizeRequests(). 27 | antMatchers(AUTH_WHITELIST).permitAll(). 28 | and() 29 | .authorizeRequests(). 30 | antMatchers("/libros/**").authenticated(); 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /libros/src/main/java/es/ejercicio/microservicios/libros/controller/LibroController.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.libros.controller; 2 | 3 | import java.sql.SQLException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import org.dozer.DozerBeanMapper; 8 | import org.springframework.beans.factory.annotation.Autowired; 9 | import org.springframework.http.HttpStatus; 10 | import org.springframework.http.ResponseEntity; 11 | import org.springframework.web.bind.annotation.PathVariable; 12 | import org.springframework.web.bind.annotation.RequestBody; 13 | import org.springframework.web.bind.annotation.RequestMapping; 14 | import org.springframework.web.bind.annotation.RequestMethod; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | import es.ejercicio.microservicios.dto.LibroDTO; 18 | import es.ejercicio.microservicios.libros.entity.Libro; 19 | import es.ejercicio.microservicios.libros.service.LibroService; 20 | import io.swagger.annotations.Api; 21 | import io.swagger.annotations.ApiOperation; 22 | import io.swagger.annotations.ApiParam; 23 | import io.swagger.annotations.ApiResponse; 24 | import io.swagger.annotations.ApiResponses; 25 | import lombok.extern.slf4j.Slf4j; 26 | 27 | 28 | @Slf4j 29 | @RestController 30 | @RequestMapping(value = "/libros/") 31 | @Api(value = "LibroController", description="Operaciones sobre los Libros de la Biblioteca") 32 | class LibroController { 33 | 34 | 35 | @Autowired 36 | private LibroService libroService; 37 | 38 | /** DozerMapper. */ 39 | DozerBeanMapper mapper = new DozerBeanMapper(); 40 | 41 | /** 42 | * Retorna todos los libros 43 | * @return Listado de libros 44 | * @throws SQLException 45 | */ 46 | @RequestMapping(value = "/getAll", method = RequestMethod.GET) 47 | @ApiOperation(value = "Retorna todos los libros", 48 | notes = "Retorna todos los libros almacenados en base de datos", 49 | response = LibroDTO.class, 50 | responseContainer = "List") 51 | @ApiResponses(value = {@ApiResponse(code = 200, message = "Libros retornadas correctamente")}) 52 | public List getAll() throws SQLException { 53 | 54 | List libros = libroService.findAll(); 55 | List librosDTO = new ArrayList(); 56 | if (libros != null) 57 | { 58 | for (Libro libro : libros) { 59 | LibroDTO libroDTO= (LibroDTO) mapper.map(libro, LibroDTO.class); 60 | librosDTO.add(libroDTO); 61 | } 62 | 63 | } 64 | return librosDTO; 65 | 66 | 67 | } 68 | 69 | 70 | /** 71 | * Retorna todos los libros favoritos 72 | * @return Lista de libros favoritos 73 | * @throws SQLException 74 | */ 75 | @RequestMapping(value = "/getFavoritos", method = RequestMethod.GET) 76 | @ApiOperation(value = "Retorna todos los libros favoritos", 77 | notes = "Retorna todos los libros favoritos almacenados en base de datos", 78 | response = LibroDTO.class, 79 | responseContainer = "List") 80 | @ApiResponses(value = {@ApiResponse(code = 200, message = "Libros retornadas correctamente")}) 81 | public List getFavoritos() throws SQLException { 82 | 83 | List libros = libroService.findByFavoriteTrue(); 84 | List librosDTO = new ArrayList(); 85 | if (libros != null) 86 | { 87 | for (Libro libro : libros) { 88 | LibroDTO libroDTO= (LibroDTO) mapper.map(libro, LibroDTO.class); 89 | librosDTO.add(libroDTO); 90 | } 91 | 92 | } 93 | return librosDTO; 94 | 95 | } 96 | 97 | 98 | /** 99 | * Retorna el libro del id 100 | * @return Editorial 101 | * @throws SQLException 102 | */ 103 | @RequestMapping(value = "/getLibro/{id}", method = RequestMethod.GET) 104 | @ApiOperation(value = "Retorna un Libro", 105 | notes = "Retorna el Libro del id especificado", 106 | response = LibroDTO.class) 107 | @ApiResponses(value = {@ApiResponse(code = 404, message = "Libro no encontrado"), 108 | @ApiResponse(code = 200, message = "Lirbo encontrado")} 109 | ) 110 | public ResponseEntity getLibro(@ApiParam(name = "id", value = "Id del Libro a buscar", required = true)@PathVariable("id") String id) throws SQLException { 111 | Integer idLibro = 0; 112 | try 113 | { 114 | idLibro = Integer.parseInt(id); 115 | } catch (NumberFormatException ex) { 116 | log.error("Se ha producido un error, el id no es un valor numerico:" + ex.getMessage()); 117 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new LibroDTO()); 118 | } 119 | Libro libro = libroService.findById(idLibro); 120 | 121 | if (libro != null) 122 | { 123 | LibroDTO libroDTO= (LibroDTO) mapper.map(libro, LibroDTO.class); 124 | 125 | return ResponseEntity.status(HttpStatus.OK).body(libroDTO); 126 | } else { 127 | return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new LibroDTO()); 128 | } 129 | 130 | 131 | } 132 | 133 | /** 134 | * Añade una nueva categoria 135 | * @return Categoria 136 | * @throws SQLException 137 | */ 138 | @RequestMapping(value = "/getByExample", method = RequestMethod.POST) 139 | @ApiOperation(value = "Retorna todos los libros que coinciden con el DTO de Ejemplo", 140 | notes = "Retorna todos los libros coincidentes con el ejemplo almacenados en base de datos", 141 | response = LibroDTO.class, 142 | responseContainer = "List") 143 | @ApiResponses(value = {@ApiResponse(code = 200, message = "Libros retornadas correctamente")}) 144 | public List librosByExample(@ApiParam(name = "libroDTO", value = "Libro ejemplo para la consulta", required = true)@RequestBody LibroDTO input) throws SQLException { 145 | log.debug("Se obtienen los libros coincidentes con:" + input); 146 | 147 | Libro libroInput = Libro.builder().id(null) 148 | .descripcion(input.getDescripcion()) 149 | .titulo(input.getTitulo()) 150 | .autor(input.getAutor()) 151 | .categoria(input.getCategoria()) 152 | .editorial(input.getEditorial()) 153 | .build(); 154 | 155 | List libros = libroService.findByExample(libroInput); 156 | List librosDTO = new ArrayList(); 157 | if (libros != null) 158 | { 159 | for (Libro libro : libros) { 160 | LibroDTO libroDTO= (LibroDTO) mapper.map(libro, LibroDTO.class); 161 | librosDTO.add(libroDTO); 162 | } 163 | 164 | } 165 | return librosDTO; 166 | 167 | } 168 | 169 | } 170 | -------------------------------------------------------------------------------- /libros/src/main/java/es/ejercicio/microservicios/libros/entity/Libro.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.libros.entity; 2 | 3 | import javax.persistence.Entity; 4 | import javax.persistence.Id; 5 | 6 | import lombok.AllArgsConstructor; 7 | import lombok.Builder; 8 | import lombok.Data; 9 | import lombok.NoArgsConstructor; 10 | 11 | /** 12 | * @author Juan Manuel Cintas 13 | * 14 | */ 15 | @Entity 16 | @Data 17 | @Builder 18 | @NoArgsConstructor 19 | @AllArgsConstructor 20 | public class Libro { 21 | 22 | /** 23 | * Id. 24 | */ 25 | @Id 26 | private Integer id; 27 | 28 | /** 29 | * Titulo del libro. 30 | */ 31 | private String titulo; 32 | 33 | /** 34 | * Descripcion. 35 | */ 36 | private String descripcion; 37 | 38 | /** 39 | * Categoria ID. 40 | */ 41 | private Integer categoria; 42 | 43 | /** 44 | * Autor ID. 45 | */ 46 | private Integer autor; 47 | 48 | /** 49 | * Editorial ID. 50 | */ 51 | private Integer editorial; 52 | 53 | /** 54 | * Favorite 55 | */ 56 | private Boolean favorite; 57 | 58 | } 59 | -------------------------------------------------------------------------------- /libros/src/main/java/es/ejercicio/microservicios/libros/repository/LibroRepository.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.libros.repository; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.data.jpa.repository.JpaRepository; 6 | import org.springframework.data.repository.query.QueryByExampleExecutor; 7 | import org.springframework.stereotype.Repository; 8 | 9 | import es.ejercicio.microservicios.libros.entity.Libro; 10 | 11 | 12 | //https://github.com/spring-projects/spring-data-examples/tree/master/jpa/query-by-example 13 | @Repository 14 | public interface LibroRepository extends JpaRepository, QueryByExampleExecutor { 15 | 16 | public List findByFavoriteTrue(); 17 | } -------------------------------------------------------------------------------- /libros/src/main/java/es/ejercicio/microservicios/libros/service/LibroService.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.libros.service; 2 | 3 | import java.util.List; 4 | 5 | import es.ejercicio.microservicios.libros.entity.Libro; 6 | 7 | public interface LibroService { 8 | 9 | public List findByFavoriteTrue(); 10 | 11 | public List findAll(); 12 | 13 | public List findByExample(Libro libro); 14 | 15 | public Libro findById(Integer id); 16 | } -------------------------------------------------------------------------------- /libros/src/main/java/es/ejercicio/microservicios/libros/service/impl/LibroServiceImpl.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.libros.service.impl; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.data.domain.Example; 7 | import org.springframework.stereotype.Service; 8 | 9 | import es.ejercicio.microservicios.libros.entity.Libro; 10 | import es.ejercicio.microservicios.libros.repository.LibroRepository; 11 | import es.ejercicio.microservicios.libros.service.LibroService; 12 | import lombok.extern.slf4j.Slf4j; 13 | 14 | @Slf4j 15 | @Service 16 | public class LibroServiceImpl implements LibroService { 17 | 18 | @Autowired 19 | private LibroRepository libroRepository; 20 | 21 | 22 | @Override 23 | public List findByFavoriteTrue() { 24 | log.debug("Se obtienen todos los libros favoritos"); 25 | return libroRepository.findByFavoriteTrue(); 26 | } 27 | 28 | 29 | @Override 30 | public List findAll() { 31 | log.debug("Se obtienen todos los libros"); 32 | return libroRepository.findAll(); 33 | } 34 | 35 | 36 | @Override 37 | public List findByExample(Libro libro) { 38 | log.debug("Se obtienen todos los libros coincidentes"); 39 | Example exLibro = Example.of(libro); 40 | return libroRepository.findAll(exLibro); 41 | } 42 | 43 | 44 | @Override 45 | public Libro findById(Integer id) { 46 | log.debug("Se busca el libro del id" + id); 47 | return libroRepository.findOne(id); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /libros/src/main/java/es/ejercicio/microservicios/libros/swager/SwaggerConfig.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.libros.swager; 2 | 3 | import org.springframework.context.annotation.Bean; 4 | import org.springframework.context.annotation.Configuration; 5 | 6 | import com.google.common.base.Predicates; 7 | 8 | import springfox.documentation.builders.ApiInfoBuilder; 9 | import springfox.documentation.builders.PathSelectors; 10 | import springfox.documentation.service.ApiInfo; 11 | import springfox.documentation.service.Contact; 12 | import springfox.documentation.spi.DocumentationType; 13 | import springfox.documentation.spring.web.plugins.Docket; 14 | import springfox.documentation.swagger2.annotations.EnableSwagger2; 15 | 16 | /** 17 | * @author Juan Manuel Cintas 18 | * 19 | */ 20 | @Configuration 21 | @EnableSwagger2 22 | public class SwaggerConfig { 23 | 24 | @Bean 25 | public Docket swaggerSpringMvcPlugin() { 26 | return new Docket(DocumentationType.SWAGGER_2) 27 | .useDefaultResponseMessages(false) 28 | .apiInfo(apiInfo()) 29 | .select() 30 | .paths(Predicates.not(PathSelectors.regex("/error.*"))) 31 | .build(); 32 | } 33 | 34 | private ApiInfo apiInfo() { 35 | return new ApiInfoBuilder() 36 | .title("Biblioteca - Libros") 37 | .description("API documentation for Libros Application") 38 | .contact(new Contact("Juan Manuel Cintas", "https://github.com/juanmacintas", "hurone@gmail.com")) 39 | .license("Apache License Version 2.0") 40 | .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE") 41 | .version("2.0") 42 | .build(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /libros/src/main/resources/bootstrap.properties: -------------------------------------------------------------------------------- 1 | spring.cloud.config.uri=http://${CONFIG_HOST:localhost}:${CONFIG_PORT:8888} 2 | spring.application.name=libros 3 | spring.profiles.active=${PROFILE:default} 4 | endpoints.refresh.sensitive=false -------------------------------------------------------------------------------- /libros/src/main/resources/data.sql: -------------------------------------------------------------------------------- 1 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (1,'Los Pilares de la Tierra', 'Descripción de los Pilares de la Tierra', 10, 1, 1, true); 2 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (2,'Los Ritos del Agua', 'Descripción de Los Ritos del Agua', 8,2, 1, false); 3 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (3,'El guardián de recuerdos', 'Descripción de El guardián de recuerdos', 1, 3, 1, false); 4 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (4,'Ready Player One', 'Descripción de Ready Player One', 1,8, 8, false); 5 | 6 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (5,'Dracula', 'Descripción de Dracula', 3, 4, 7,false); 7 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (6,'El marciano', 'Descripción de El marciano', 1, 6, 1, false); 8 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (7,'Frankenstein', 'Descripción de Frankenstein', 1, 5, 7, false); 9 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (8,'Carrie', 'Descripción de Carrie', 3, 7, 3, true); 10 | 11 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (9,'It', 'Descripción de It', 3, 7, 3, true); 12 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (10,'El Paciente', 'Descripción de El Paciente', 7, 9, 9, true); 13 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (11,'La Leyenda del Ladrón', 'Descripción de La Leyenda del Ladrón', 10, 9, 9, true); 14 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (12,'El Nombre de la Rosa', 'Descripción de El Nombre de la Rosa', 10, 10, 3, false); 15 | 16 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (13,'La legión olvidada', 'Descripción de La legión olvidada', 10, 13, 2, false); 17 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (14,'Triple', 'Descripción de Triple', 10, 1, 2, false); 18 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (15,'Un Mundo Sin Fin', 'Descripción de Un Mundo Sin Fin', 10, 1, 2, false); 19 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (16,'Yo, Robot', 'Descripción de Yo, Robot', 1, 12, 10, false); 20 | 21 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (17,'Trilogía de la Fundación', 'Descripción de Trilogía de la Fundación', 1, 12, 3, false); 22 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (18,'Los muertos vivientes #1: Días pasados','Descripción de Los muertos vivientes #1: Días pasados', 6, 13, 11, false); 23 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (19,'Los muertos vivientes #2: Días pasados','Descripción de Los muertos vivientes #2: Días pasados', 6, 13, 11, false); 24 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (20,'Los muertos vivientes #3: Días pasados','Descripción de Los muertos vivientes #3: Días pasados', 6, 13, 11, false); 25 | 26 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (21,'El señor de los anillos: La Comunidad del anillo','Descripción de El señor de los anillos: La Comunidad del anillo', 11, 14, 5, false); 27 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (22,'El señor de los anillos: La Dos Torres','Descripción de El señor de los anillos: Las Dos Torres', 11, 14, 5, false); 28 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (23,'El señor de los anillos: El Retorno del Rey','Descripción de El señor de los anillos: El Retorno del Rey', 11, 14, 5, false); 29 | INSERT INTO LIBRO (id, titulo, descripcion, categoria, autor, editorial, favorite) values (24,'El Hobbit','Descripción de El Hobbit', 11, 14, 5, false); 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /libros/src/test/java/es/ejercicio/microservicios/libros/controller/LibrosControllerTest.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.libros.controller; 2 | 3 | import static org.hamcrest.Matchers.empty; 4 | import static org.hamcrest.Matchers.is; 5 | import static org.hamcrest.Matchers.not; 6 | import static org.junit.Assert.fail; 7 | import static org.mockito.Mockito.when; 8 | import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; 9 | import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; 10 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; 11 | import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 12 | 13 | import java.nio.charset.Charset; 14 | import java.util.ArrayList; 15 | import java.util.List; 16 | 17 | import org.junit.Before; 18 | import org.junit.Test; 19 | import org.junit.runner.RunWith; 20 | import org.mockito.InjectMocks; 21 | import org.springframework.beans.factory.annotation.Autowired; 22 | import org.springframework.boot.test.context.SpringBootTest; 23 | import org.springframework.boot.test.mock.mockito.MockBean; 24 | import org.springframework.http.MediaType; 25 | import org.springframework.test.context.junit4.SpringRunner; 26 | import org.springframework.test.context.web.WebAppConfiguration; 27 | import org.springframework.test.web.servlet.MockMvc; 28 | import org.springframework.test.web.servlet.ResultActions; 29 | import org.springframework.test.web.servlet.setup.MockMvcBuilders; 30 | import org.springframework.web.context.WebApplicationContext; 31 | 32 | import com.fasterxml.jackson.core.JsonProcessingException; 33 | 34 | import es.ejercicio.microservicios.libros.LibrosApplication; 35 | import es.ejercicio.microservicios.libros.entity.Libro; 36 | import es.ejercicio.microservicios.libros.repository.LibroRepository; 37 | import es.ejercicio.microservicios.libros.service.LibroService; 38 | 39 | /** 40 | * @author Juan Manuel Cintas 41 | * 42 | */ 43 | @RunWith(SpringRunner.class) 44 | @SpringBootTest(classes = LibrosApplication.class) 45 | @WebAppConfiguration 46 | public class LibrosControllerTest { 47 | private MockMvc mockMvc; 48 | 49 | private MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(), 50 | MediaType.APPLICATION_JSON.getSubtype(), 51 | Charset.forName("utf8")); 52 | 53 | @Autowired 54 | private WebApplicationContext webApplicationContext; 55 | 56 | @MockBean 57 | private LibroRepository libroRepository; 58 | 59 | @MockBean 60 | LibroService libroService; 61 | 62 | 63 | @Before 64 | public void setup() throws Exception { 65 | this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); 66 | } 67 | 68 | 69 | @Test 70 | public void testGetAllLibros() { 71 | 72 | 73 | List listLibros = getLibrosTest(); 74 | 75 | when(libroRepository.findAll()).thenReturn(listLibros); 76 | when(libroService.findAll()).thenReturn(listLibros); 77 | try { 78 | ResultActions res = this.mockMvc.perform(get("/libros/getAll")) 79 | .andDo(print()) 80 | .andExpect(status().isOk()) 81 | .andExpect(jsonPath("$", not(empty()))) 82 | .andExpect(jsonPath("$.[0].id", is(1) )) 83 | .andExpect(jsonPath("$.[1].id", is(2) )); 84 | } catch (JsonProcessingException e1) { 85 | fail(e1.getMessage()); 86 | } catch (Exception e) { 87 | fail(e.getMessage()); 88 | } 89 | 90 | } 91 | 92 | @Test 93 | public void testGetAllLibrosFavoritos() { 94 | 95 | 96 | List listLibros = getLibrosTest(); 97 | 98 | when(libroRepository.findByFavoriteTrue()).thenReturn(listLibros); 99 | when(libroService.findByFavoriteTrue()).thenReturn(listLibros); 100 | try { 101 | ResultActions res = this.mockMvc.perform(get("/libros/getFavoritos")) 102 | .andDo(print()) 103 | .andExpect(status().isOk()) 104 | .andExpect(jsonPath("$", not(empty()))) 105 | .andExpect(jsonPath("$.[0].id", is(1) )); 106 | } catch (JsonProcessingException e1) { 107 | fail(e1.getMessage()); 108 | } catch (Exception e) { 109 | fail(e.getMessage()); 110 | } 111 | 112 | } 113 | 114 | private List getLibrosTest() { 115 | Libro autor1 = Libro.builder().id(1) 116 | .autor(1) 117 | .categoria(1) 118 | .descripcion("Libro 1") 119 | .editorial(1) 120 | .favorite(true) 121 | .build(); 122 | Libro autor2 = Libro.builder().id(2) 123 | .autor(1) 124 | .categoria(2) 125 | .descripcion("Libro 2") 126 | .editorial(1) 127 | .favorite(true) 128 | .build(); 129 | 130 | List listLibros = new ArrayList(); 131 | listLibros.add(autor1); 132 | listLibros.add(autor2); 133 | return listLibros; 134 | } 135 | 136 | } 137 | -------------------------------------------------------------------------------- /libros/src/test/java/es/ejercicio/microservicios/libros/controller/LibrosControllerTestIT.java: -------------------------------------------------------------------------------- 1 | package es.ejercicio.microservicios.libros.controller; 2 | 3 | import static org.junit.Assert.assertEquals; 4 | 5 | import java.net.URI; 6 | import java.net.URL; 7 | 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | import org.junit.runner.RunWith; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.boot.context.embedded.LocalServerPort; 13 | import org.springframework.boot.test.context.SpringBootTest; 14 | import org.springframework.boot.test.web.client.TestRestTemplate; 15 | import org.springframework.http.HttpEntity; 16 | import org.springframework.http.HttpHeaders; 17 | import org.springframework.http.HttpMethod; 18 | import org.springframework.http.MediaType; 19 | import org.springframework.http.ResponseEntity; 20 | import org.springframework.test.context.junit4.SpringRunner; 21 | import org.springframework.web.util.UriComponentsBuilder; 22 | 23 | import com.google.gson.Gson; 24 | 25 | import es.ejercicio.microservicios.dto.EditorialDTO; 26 | import es.ejercicio.microservicios.dto.LibroDTO; 27 | import es.ejercicio.microservicios.dto.OAuthDTO; 28 | 29 | 30 | /** 31 | * @author Juan Manuel Cintas 32 | * 33 | */ 34 | @RunWith(SpringRunner.class) 35 | @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 36 | public class LibrosControllerTestIT { 37 | 38 | @LocalServerPort 39 | private int port; 40 | 41 | private URL base; 42 | private URL baseFavoritos; 43 | private URL baseByExample; 44 | private URL baseToken; 45 | 46 | @Autowired 47 | private TestRestTemplate template; 48 | 49 | private final String NOMBRE_SERVICIO = "libros/getAll/"; 50 | private final String NOMBRE_SERVICIO_FAVORITOS = "libros/getFavoritos/"; 51 | private final String NOMBRE_SERVICIO_BY_EXAMPLE = "libros/getByExample/"; 52 | private final String NOMBRE_SERVICIO_TOKEN= "/uaa/oauth/token"; 53 | 54 | private final String STATUS_OK = "200"; 55 | private final Integer NUM_TOTAL_LIBROS = 24; 56 | private final Integer NUM_TOTAL_FAVORITOS = 5; 57 | 58 | private final Integer PORT_AUTHORIZATION_SERVER = 9000; 59 | 60 | private String token; 61 | 62 | private static final String AUTHORIZATION_HEADER = "Authorization"; 63 | private static final String BEARER = "Bearer "; 64 | private static final String CLIENT_ID = "client_id"; 65 | private static final String CLIENT_SECRET = "client_secret"; 66 | private static final String GRANT_TYPE = "grant_type"; 67 | 68 | @Before 69 | public void setUp() throws Exception { 70 | this.base = new URL("http://localhost:" + port + "/"+ NOMBRE_SERVICIO); 71 | this.baseFavoritos = new URL("http://localhost:" + port + "/"+ NOMBRE_SERVICIO_FAVORITOS); 72 | this.baseByExample = new URL("http://localhost:" + port + "/"+ NOMBRE_SERVICIO_BY_EXAMPLE); 73 | this.baseToken = new URL("http://localhost:" + PORT_AUTHORIZATION_SERVER + "/"+ NOMBRE_SERVICIO_TOKEN); 74 | //Se obtiene un token para las pruebas 75 | token = getAccessToken(); 76 | } 77 | 78 | @Test 79 | public void getListLibros() throws Exception { 80 | 81 | HttpHeaders headers = new HttpHeaders(); 82 | headers.setContentType(MediaType.APPLICATION_JSON); 83 | headers.add(AUTHORIZATION_HEADER,BEARER.concat(token)); 84 | 85 | ResponseEntity response = template.exchange(base.toString(), HttpMethod.GET, 86 | new HttpEntity<>(headers), Object[].class); 87 | 88 | assertEquals(STATUS_OK, response.getStatusCode().toString()); 89 | Object[] objects = response.getBody(); 90 | assertEquals(NUM_TOTAL_LIBROS.intValue(), objects.length); 91 | 92 | } 93 | 94 | @Test 95 | public void getListLibrosFavoritos() throws Exception { 96 | 97 | HttpHeaders headers = new HttpHeaders(); 98 | headers.setContentType(MediaType.APPLICATION_JSON); 99 | headers.add(AUTHORIZATION_HEADER,BEARER.concat(token)); 100 | 101 | ResponseEntity response = template.exchange(baseFavoritos.toString(), HttpMethod.GET, 102 | new HttpEntity<>(headers), Object[].class); 103 | 104 | assertEquals(STATUS_OK, response.getStatusCode().toString()); 105 | Object[] objects = response.getBody(); 106 | assertEquals(NUM_TOTAL_FAVORITOS.intValue(), objects.length); 107 | 108 | } 109 | 110 | @Test 111 | public void getListLibrosByExample() throws Exception { 112 | 113 | Gson gson = new Gson(); 114 | 115 | LibroDTO categoriaDTO = LibroDTO.builder() 116 | .autor(13) 117 | .categoria(6) 118 | .build(); 119 | String json = gson.toJson(categoriaDTO); 120 | 121 | HttpHeaders headers = new HttpHeaders(); 122 | headers.setContentType(MediaType.APPLICATION_JSON); 123 | headers.add(AUTHORIZATION_HEADER,BEARER.concat(token)); 124 | 125 | HttpEntity entity = new HttpEntity(json,headers); 126 | 127 | ResponseEntity response = template.postForEntity(baseByExample.toString(),entity, 128 | Object[].class); 129 | 130 | assertEquals(STATUS_OK, response.getStatusCode().toString()); 131 | Object[] objects = response.getBody(); 132 | assertEquals(3, objects.length); 133 | 134 | 135 | } 136 | 137 | private String getAccessToken() { 138 | HttpHeaders headers = new HttpHeaders(); 139 | headers.setContentType(MediaType.APPLICATION_JSON); 140 | 141 | HttpEntity request = new HttpEntity(headers); 142 | 143 | UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(baseToken.toString()) 144 | .queryParam(CLIENT_ID, "librosApp") 145 | .queryParam(CLIENT_SECRET, "secretLibros") 146 | .queryParam(GRANT_TYPE, "client_credentials"); 147 | 148 | URI myUri=builder.buildAndExpand().toUri(); 149 | 150 | ResponseEntity response = template.postForEntity(myUri, request, OAuthDTO.class); 151 | 152 | OAuthDTO autenticacion = (OAuthDTO) response.getBody(); 153 | 154 | 155 | return autenticacion.getAccess_token(); 156 | } 157 | 158 | } 159 | --------------------------------------------------------------------------------