Commit 2cc6881c authored by Diego Convers's avatar Diego Convers

inicial commit

parents
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
FROM openjdk:11.0.12
#RUN addgroup spring
RUN adduser spring
USER spring:spring
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","app.jar"]
\ No newline at end of file
This diff is collapsed.
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.firefly-e.proyectos</groupId>
<artifactId>Proyectos</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Proyectos</name>
<description>Microservicio proyectos Firefly-e</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.fireflye.proyectos;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.support.serializer.JsonDeserializer;
import com.fireflye.proyectos.dto.Usuarios;
@EnableKafka
@Configuration
public class KafkaConsumerConfig {
@Value(value = "${kafka.bootstrapAddress}")
private String bootstrapAddress;
@Value(value = "${kafka.groupId}")
private String groupId;
@Bean
public ConsumerFactory<String, Usuarios> consumerFactory(){
JsonDeserializer<Usuarios> deserializer = new JsonDeserializer<>(Usuarios.class);
deserializer.setRemoveTypeHeaders(false);
deserializer.addTrustedPackages("*");
deserializer.setUseTypeMapperForKey(true);
Map<String, Object> config = new HashMap<>();
config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class);
return new DefaultKafkaConsumerFactory<>(config, new StringDeserializer(), deserializer);
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, Usuarios> kafkaListenerContainerFactory(){
ConcurrentKafkaListenerContainerFactory<String, Usuarios> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
return factory;
}
}
package com.fireflye.proyectos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProyectosApplication {
public static void main(String[] args) {
SpringApplication.run(ProyectosApplication.class, args);
}
}
package com.fireflye.proyectos.dto;
import java.util.Date;
import javax.validation.constraints.Future;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.PastOrPresent;
import javax.validation.constraints.Positive;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Proyectos {
@Positive(message = "El id tiene que ser un número positivo")
private Integer idProyecto;
@NotNull(message = "El nombre no puede ser vacio")
@NotEmpty(message = "El nombre no puede ser vacio")
private String nombre;
@Positive(message = "El id tiene que ser un número positivo")
private Integer idUsuario;
@PastOrPresent(message = "La fecha de inicio tiene que ser igual o menor a la del sistema")
private Date fechaInicio;
@Future(message = "La fecha de fin tiene que ser fecha mayor a la del sistema")
private Date fechaFin;
}
package com.fireflye.proyectos.dto;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Usuarios {
@NotNull(message = "El nombre no puede ser vacio")
@NotEmpty(message = "El nombre no puede ser vacio")
private String nombre;
@NotNull(message = "El apellido no puede ser vacio")
@NotEmpty(message = "El apellido no puede ser vacio")
private String apellido;
private String telefono;
@Email(message = "Email no válido")
private String email;
@Positive(message = "El id tiene que ser un número positivo")
private Integer idUsuario;
}
package com.fireflye.proyectos.rest;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fireflye.proyectos.dto.Proyectos;
import com.fireflye.proyectos.service.ProyectosException;
import com.fireflye.proyectos.service.ProyectosService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.extern.slf4j.Slf4j;
@RestController
@RequestMapping("/servicios/proyectos")
@Slf4j
public class ProyectosRest {
@Autowired
private ProyectosService proyectosService;
@PostMapping(value = "/")
@Operation(summary = "Agregar proyecto")
@ApiResponses(value = { @ApiResponse(responseCode = "202", description = "Proyecto agregado"),
@ApiResponse(responseCode = "400", description = "Datos recibidos inválidos", content = @Content),
@ApiResponse(responseCode = "500", description = "Error en procesamiento de información", content = @Content) })
public ResponseEntity<Void> addProyecto(@RequestBody @Valid Proyectos proyectos) {
try {
log.info("addProyecto", proyectos);
proyectosService.addProyecto(proyectos);
return ResponseEntity.accepted().body(null);
} catch (ProyectosException e) {
log.error("Exception", e);
return ResponseEntity.badRequest().body(null);
} catch (Exception e) {
log.error("Exception", e);
return ResponseEntity.internalServerError().body(null);
}
}
@Operation(summary = "Actualización de proyectos")
@ApiResponses(value = { @ApiResponse(responseCode = "202", description = "Proyecto actualizado"),
@ApiResponse(responseCode = "400", description = "Datos recibidos inválidos", content = @Content),
@ApiResponse(responseCode = "500", description = "Error en procesamiento de información", content = @Content) })
@PutMapping(value = "/")
public ResponseEntity<Void> updateProyecto(@RequestBody @Valid Proyectos proyectos) {
try {
log.info("updateProyecto", proyectos);
proyectosService.updateProyecto(proyectos);
return ResponseEntity.accepted().body(null);
} catch (Exception e) {
log.error("Exception", e);
return ResponseEntity.internalServerError().body(null);
}
}
@GetMapping(value = "/")
@Operation(summary = "Listado de proyecto")
@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Listado de proyectos"),
@ApiResponse(responseCode = "204", description = "No hay usuarios registrados en el sistema", content = @Content),
@ApiResponse(responseCode = "400", description = "Datos recibidos inválidos", content = @Content),
@ApiResponse(responseCode = "500", description = "Error en procesamiento de información", content = @Content) })
public ResponseEntity<List<Proyectos>> listProyectos() {
try {
log.info("listProyectos");
List<Proyectos> resultado = proyectosService.listProyectos();
if (resultado == null || resultado.isEmpty()) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok().body(resultado);
} catch (Exception e) {
log.error("Exception", e);
return ResponseEntity.internalServerError().body(null);
}
}
@GetMapping(value = "/{idProyecto}")
@Operation(summary = "Consulta de proyecto")
@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Proyecto consultado"),
@ApiResponse(responseCode = "404", description = "No se encuentra el usuario en el sistema", content = @Content),
@ApiResponse(responseCode = "400", description = "Datos recibidos inválidos", content = @Content),
@ApiResponse(responseCode = "500", description = "Error en procesamiento de información", content = @Content) })
public ResponseEntity<Proyectos> getProyecto(@PathVariable Integer idProyecto) {
try {
log.info("getProyecto", idProyecto);
Proyectos resultado = proyectosService.getProyecto(idProyecto);
if (resultado == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().body(resultado);
} catch (Exception e) {
log.error("Exception", e);
return ResponseEntity.internalServerError().body(null);
}
}
@DeleteMapping(value = "/{idProyecto}")
@Operation(summary = "Eliminación de proyectos")
@ApiResponses(value = { @ApiResponse(responseCode = "202", description = "Proyecto eliminado"),
@ApiResponse(responseCode = "400", description = "Datos recibidos inválidos", content = @Content),
@ApiResponse(responseCode = "500", description = "Error en procesamiento de información", content = @Content) })
public ResponseEntity<Void> deleteProyecto(@PathVariable Integer idProyecto) {
try {
log.info("deleteProyecto", idProyecto);
proyectosService.deleteProyecto(idProyecto);
return ResponseEntity.accepted().body(null);
} catch (Exception e) {
log.error("Exception", e);
return ResponseEntity.internalServerError().body(null);
}
}
}
package com.fireflye.proyectos.service;
public class ProyectosException extends Exception {
private static final long serialVersionUID = 1L;
}
package com.fireflye.proyectos.service;
import java.util.List;
import com.fireflye.proyectos.dto.Proyectos;
public interface ProyectosService {
public void addProyecto(Proyectos proyectos) throws ProyectosException;
public void deleteProyecto(Integer idProyecto);
public Proyectos getProyecto(Integer idProyecto);
public void updateProyecto(Proyectos proyectos) throws ProyectosException;
public List<Proyectos> listProyectos();
}
package com.fireflye.proyectos.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import com.fireflye.proyectos.dto.Proyectos;
import lombok.extern.slf4j.Slf4j;
@Service
@Scope("singleton")
@Slf4j
public class ProyectosServiceImpl implements ProyectosService {
private List<Proyectos> proyectosList = new ArrayList<>();
@Autowired
private UsuariosService usuariosService;
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void addProyecto(Proyectos proyectos) throws ProyectosException{
validateUsuario(proyectos.getIdUsuario());
// usuariosService.validarUsuario(proyectos.getIdUsuario());
proyectosList.add(proyectos);
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void deleteProyecto(Integer idProyecto) {
Proyectos userToDelete = null;
for (Proyectos usuarios : proyectosList) {
if (usuarios.getIdProyecto().equals(idProyecto)) {
userToDelete = usuarios;
}
}
if (userToDelete != null) {
proyectosList.remove(userToDelete);
}
}
@Override
@Transactional(readOnly = true)
public Proyectos getProyecto(Integer idProyecto) {
for (Proyectos usuarios : proyectosList) {
if (usuarios.getIdProyecto().equals(idProyecto)) {
return usuarios;
}
}
return null;
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void updateProyecto(Proyectos proyectos) throws ProyectosException {
deleteProyecto(proyectos.getIdProyecto());
addProyecto(proyectos);
}
@Override
@Transactional(readOnly = true)
public List<Proyectos> listProyectos() {
return proyectosList;
}
private void validateUsuario(Integer idUsuario) throws ProyectosException {
RestTemplate restTemplate = new RestTemplate();
String url = "http://super-usuarios/servicios/usuarios/validate/" + idUsuario;
ResponseEntity<Void> response = restTemplate.getForEntity(url, Void.class);
if (!response.getStatusCode().equals(HttpStatus.OK)) {
throw new ProyectosException();
}
}
}
package com.fireflye.proyectos.service;
public interface UsuariosService {
public void validarUsuario(Integer idUsuario) throws ProyectosException;
}
package com.fireflye.proyectos.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Scope;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
import com.fireflye.proyectos.dto.Usuarios;
import lombok.extern.slf4j.Slf4j;
@Service
@Scope("singleton")
@Slf4j
public class UsuariosServiceImpl implements UsuariosService{
private List<Usuarios> usuariosList = new ArrayList<>();
@Override
public void validarUsuario(Integer idUsuario) throws ProyectosException {
for (Usuarios usuarios : usuariosList) {
if (usuarios.getIdUsuario().equals(idUsuario)) {
return;
}
}
throw new ProyectosException();
}
@KafkaListener(topics = "alumno6", groupId = "test-consumer-group")
public void listenerUsuarios(Usuarios usuario) {
usuariosList.add(usuario);
}
}
server.port=9090
springdoc.swagger-ui.path=/servicios/proyectos/swagger-ui.html
kafka.bootstrapAddress=firefly.technology:9092
kafka.groupId=test-consumer-group
package com.fireflye.proyectos;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ProyectosApplicationTests {
@Test
void contextLoads() {
}
}
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
/*
* Copyright 2007-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
private static final String WRAPPER_VERSION = "0.5.6";
/**
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
*/
private static final String DEFAULT_DOWNLOAD_URL = "https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/"
+ WRAPPER_VERSION + "/maven-wrapper-" + WRAPPER_VERSION + ".jar";
/**
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
* use instead of the default one.
*/
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
".mvn/wrapper/maven-wrapper.properties";
/**
* Path where the maven-wrapper.jar will be saved to.
*/
private static final String MAVEN_WRAPPER_JAR_PATH =
".mvn/wrapper/maven-wrapper.jar";
/**
* Name of the property which should be used to override the default download url for the wrapper.
*/
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
public static void main(String args[]) {
System.out.println("- Downloader started");
File baseDirectory = new File(args[0]);
System.out.println("- Using base directory: " + baseDirectory.getAbsolutePath());
// If the maven-wrapper.properties exists, read it and check if it contains a custom
// wrapperUrl parameter.
File mavenWrapperPropertyFile = new File(baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH);
String url = DEFAULT_DOWNLOAD_URL;
if(mavenWrapperPropertyFile.exists()) {
FileInputStream mavenWrapperPropertyFileInputStream = null;
try {
mavenWrapperPropertyFileInputStream = new FileInputStream(mavenWrapperPropertyFile);
Properties mavenWrapperProperties = new Properties();
mavenWrapperProperties.load(mavenWrapperPropertyFileInputStream);
url = mavenWrapperProperties.getProperty(PROPERTY_NAME_WRAPPER_URL, url);
} catch (IOException e) {
System.out.println("- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'");
} finally {
try {
if(mavenWrapperPropertyFileInputStream != null) {
mavenWrapperPropertyFileInputStream.close();
}
} catch (IOException e) {
// Ignore ...
}
}
}
System.out.println("- Downloading from: " + url);
File outputFile = new File(baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH);
if(!outputFile.getParentFile().exists()) {
if(!outputFile.getParentFile().mkdirs()) {
System.out.println(
"- ERROR creating output directory '" + outputFile.getParentFile().getAbsolutePath() + "'");
}
}
System.out.println("- Downloading to: " + outputFile.getAbsolutePath());
try {
downloadFileFromURL(url, outputFile);
System.out.println("Done");
System.exit(0);
} catch (Throwable e) {
System.out.println("- Error downloading");
e.printStackTrace();
System.exit(1);
}
}
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
if (System.getenv("MVNW_USERNAME") != null && System.getenv("MVNW_PASSWORD") != null) {
String username = System.getenv("MVNW_USERNAME");
char[] password = System.getenv("MVNW_PASSWORD").toCharArray();
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
URL website = new URL(urlString);
ReadableByteChannel rbc;
rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
}
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.8.2/apache-maven-3.8.2-bin.zip
wrapperUrl=https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar
FROM openjdk:11.0.12
#RUN addgroup spring
RUN adduser spring
USER spring:spring
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar","app.jar"]
\ No newline at end of file
This diff is collapsed.
@REM ----------------------------------------------------------------------------
@REM Licensed to the Apache Software Foundation (ASF) under one
@REM or more contributor license agreements. See the NOTICE file
@REM distributed with this work for additional information
@REM regarding copyright ownership. The ASF licenses this file
@REM to you under the Apache License, Version 2.0 (the
@REM "License"); you may not use this file except in compliance
@REM with the License. You may obtain a copy of the License at
@REM
@REM https://www.apache.org/licenses/LICENSE-2.0
@REM
@REM Unless required by applicable law or agreed to in writing,
@REM software distributed under the License is distributed on an
@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@REM KIND, either express or implied. See the License for the
@REM specific language governing permissions and limitations
@REM under the License.
@REM ----------------------------------------------------------------------------
@REM ----------------------------------------------------------------------------
@REM Maven Start Up Batch script
@REM
@REM Required ENV vars:
@REM JAVA_HOME - location of a JDK home dir
@REM
@REM Optional ENV vars
@REM M2_HOME - location of maven2's installed home dir
@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands
@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending
@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven
@REM e.g. to debug Maven itself, use
@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000
@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files
@REM ----------------------------------------------------------------------------
@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on'
@echo off
@REM set title of command window
title %0
@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on'
@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO%
@REM set %HOME% to equivalent of $HOME
if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%")
@REM Execute a user defined script before this one
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre
@REM check for pre script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat"
if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd"
:skipRcPre
@setlocal
set ERROR_CODE=0
@REM To isolate internal variables from possible post scripts, we use another setlocal
@setlocal
@REM ==== START VALIDATION ====
if not "%JAVA_HOME%" == "" goto OkJHome
echo.
echo Error: JAVA_HOME not found in your environment. >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
:OkJHome
if exist "%JAVA_HOME%\bin\java.exe" goto init
echo.
echo Error: JAVA_HOME is set to an invalid directory. >&2
echo JAVA_HOME = "%JAVA_HOME%" >&2
echo Please set the JAVA_HOME variable in your environment to match the >&2
echo location of your Java installation. >&2
echo.
goto error
@REM ==== END VALIDATION ====
:init
@REM Find the project base dir, i.e. the directory that contains the folder ".mvn".
@REM Fallback to current working directory if not found.
set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR%
IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir
set EXEC_DIR=%CD%
set WDIR=%EXEC_DIR%
:findBaseDir
IF EXIST "%WDIR%"\.mvn goto baseDirFound
cd ..
IF "%WDIR%"=="%CD%" goto baseDirNotFound
set WDIR=%CD%
goto findBaseDir
:baseDirFound
set MAVEN_PROJECTBASEDIR=%WDIR%
cd "%EXEC_DIR%"
goto endDetectBaseDir
:baseDirNotFound
set MAVEN_PROJECTBASEDIR=%EXEC_DIR%
cd "%EXEC_DIR%"
:endDetectBaseDir
IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig
@setlocal EnableExtensions EnableDelayedExpansion
for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a
@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS%
:endReadAdditionalConfig
SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe"
set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar"
set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain
set DOWNLOAD_URL="https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
FOR /F "tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO (
IF "%%A"=="wrapperUrl" SET DOWNLOAD_URL=%%B
)
@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central
@REM This allows using the maven wrapper in projects that prohibit checking in binary data.
if exist %WRAPPER_JAR% (
if "%MVNW_VERBOSE%" == "true" (
echo Found %WRAPPER_JAR%
)
) else (
if not "%MVNW_REPOURL%" == "" (
SET DOWNLOAD_URL="%MVNW_REPOURL%/io/takari/maven-wrapper/0.5.6/maven-wrapper-0.5.6.jar"
)
if "%MVNW_VERBOSE%" == "true" (
echo Couldn't find %WRAPPER_JAR%, downloading it ...
echo Downloading from: %DOWNLOAD_URL%
)
powershell -Command "&{"^
"$webclient = new-object System.Net.WebClient;"^
"if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^
"$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^
"}"^
"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%DOWNLOAD_URL%', '%WRAPPER_JAR%')"^
"}"
if "%MVNW_VERBOSE%" == "true" (
echo Finished downloading %WRAPPER_JAR%
)
)
@REM End of extension
@REM Provide a "standardized" way to retrieve the CLI args that will
@REM work with both Windows and non-Windows executions.
set MAVEN_CMD_LINE_ARGS=%*
%MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %*
if ERRORLEVEL 1 goto error
goto end
:error
set ERROR_CODE=1
:end
@endlocal & set ERROR_CODE=%ERROR_CODE%
if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost
@REM check for post script, once with legacy .bat ending and once with .cmd ending
if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat"
if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd"
:skipRcPost
@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on'
if "%MAVEN_BATCH_PAUSE%" == "on" pause
if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE%
exit /B %ERROR_CODE%
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.firefly-e.usuarios</groupId>
<artifactId>Usuarios</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Usuarios</name>
<description>Microservicio usuarios Firefly-e</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.fireflye.usuarios;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;
import org.springframework.kafka.support.serializer.JsonSerializer;
import com.fireflye.usuarios.dto.Usuarios;
@Configuration
public class KafkaProducerConfig {
@Value(value = "${kafka.bootstrapAddress}")
private String bootstrapAddress;
@Bean
public ProducerFactory<String, Usuarios> producerFactory() {
Map<String, Object> config = new HashMap<>();
config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapAddress);
config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class);
return new DefaultKafkaProducerFactory<>(config);
}
@Bean
public KafkaTemplate<String, Usuarios> kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
}
package com.fireflye.usuarios;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class UsuariosApplication {
public static void main(String[] args) {
SpringApplication.run(UsuariosApplication.class, args);
}
}
package com.fireflye.usuarios.dto;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Usuarios {
@NotNull(message = "El nombre no puede ser vacio")
@NotEmpty(message = "El nombre no puede ser vacio")
private String nombre;
@NotNull(message = "El apellido no puede ser vacio")
@NotEmpty(message = "El apellido no puede ser vacio")
private String apellido;
private String telefono;
@Email(message = "Email no válido")
private String email;
@Positive(message = "El id tiene que ser un número positivo")
private Integer idUsuario;
}
package com.fireflye.usuarios.rest;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.fireflye.usuarios.dto.Usuarios;
import com.fireflye.usuarios.service.UsuariosException;
import com.fireflye.usuarios.service.UsuariosService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.extern.slf4j.Slf4j;
@RestController
@RequestMapping("/servicios/usuarios")
@Slf4j
public class UsuariosRest {
@Autowired
private UsuariosService usuariosService;
@PostMapping(value = "/")
@Operation(summary = "Agregar usuarios")
@ApiResponses(value = { @ApiResponse(responseCode = "202", description = "Usuario agregado"),
@ApiResponse(responseCode = "400", description = "Datos recibidos inválidos", content = @Content),
@ApiResponse(responseCode = "500", description = "Error en procesamiento de información", content = @Content) })
public ResponseEntity<Void> addUsuario(@RequestBody @Valid Usuarios usuarios) {
try {
log.info("addUsuario", usuarios);
usuariosService.addUsuario(usuarios);
return ResponseEntity.accepted().body(null);
} catch (Exception e) {
log.error("Exception", e);
return ResponseEntity.internalServerError().body(null);
}
}
@GetMapping(value = "/validate/{idUsuario}")
@Operation(summary = "Validación de usuarios")
@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Usuario validado correctamente"),
@ApiResponse(responseCode = "400", description = "Datos recibidos inválidos", content = @Content),
@ApiResponse(responseCode = "500", description = "Error en procesamiento de información", content = @Content) })
public ResponseEntity<Void> validateUsuario(@PathVariable Integer idUsuario) {
try {
log.info("addUsuario", idUsuario);
usuariosService.validateUsuario(idUsuario);
return ResponseEntity.ok().body(null);
} catch (UsuariosException e) {
log.error("Exception", e);
return ResponseEntity.badRequest().body(null);
} catch (Exception e) {
log.error("Exception", e);
return ResponseEntity.internalServerError().body(null);
}
}
@PutMapping(value = "/")
@Operation(summary = "Actualización de usuarios")
@ApiResponses(value = { @ApiResponse(responseCode = "202", description = "Usuario actualizado"),
@ApiResponse(responseCode = "400", description = "Datos recibidos inválidos", content = @Content),
@ApiResponse(responseCode = "500", description = "Error en procesamiento de información", content = @Content) })
public ResponseEntity<Void> updateUsuario(@RequestBody @Valid Usuarios usuarios) {
try {
log.info("updateUsuario", usuarios);
usuariosService.updateUsuario(usuarios);
return ResponseEntity.accepted().body(null);
} catch (Exception e) {
log.error("Exception", e);
return ResponseEntity.internalServerError().body(null);
}
}
@GetMapping(value = "/")
@Operation(summary = "Listado de usuarios")
@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Listado de usuarios"),
@ApiResponse(responseCode = "204", description = "No hay usuarios registrados en el sistema", content = @Content),
@ApiResponse(responseCode = "400", description = "Datos recibidos inválidos", content = @Content),
@ApiResponse(responseCode = "500", description = "Error en procesamiento de información", content = @Content) })
public ResponseEntity<List<Usuarios>> listUsuarios() {
try {
log.info("listUsuarios");
List<Usuarios> resultado = usuariosService.listUsuarios();
if (resultado == null || resultado.isEmpty()) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok().body(resultado);
} catch (Exception e) {
log.error("Exception", e);
return ResponseEntity.internalServerError().body(null);
}
}
@GetMapping(value = "/{idUsuario}")
@Operation(summary = "Consulta de usuario")
@ApiResponses(value = { @ApiResponse(responseCode = "200", description = "Usuario consultado"),
@ApiResponse(responseCode = "404", description = "No se encuentra el usuario en el sistema", content = @Content),
@ApiResponse(responseCode = "400", description = "Datos recibidos inválidos", content = @Content),
@ApiResponse(responseCode = "500", description = "Error en procesamiento de información", content = @Content) })
public ResponseEntity<Usuarios> getUsuario(@PathVariable Integer idUsuario) {
try {
log.info("getUsuario", idUsuario);
Usuarios resultado = usuariosService.getUsuario(idUsuario);
if (resultado == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().body(resultado);
} catch (Exception e) {
log.error("Exception", e);
return ResponseEntity.internalServerError().body(null);
}
}
@DeleteMapping(value = "/{idUsuario}")
@Operation(summary = "Eliminación de usuarios")
@ApiResponses(value = { @ApiResponse(responseCode = "202", description = "Usuario eliminado"),
@ApiResponse(responseCode = "400", description = "Datos recibidos inválidos", content = @Content),
@ApiResponse(responseCode = "500", description = "Error en procesamiento de información", content = @Content) })
public ResponseEntity<Void> deleteUsuario(@PathVariable Integer idUsuario) {
try {
log.info("deleteUsuario", idUsuario);
usuariosService.deleteUsuario(idUsuario);
return ResponseEntity.accepted().body(null);
} catch (Exception e) {
log.error("Exception", e);
return ResponseEntity.internalServerError().body(null);
}
}
}
package com.fireflye.usuarios.service;
public class UsuariosException extends Exception {
private static final long serialVersionUID = 1L;
}
package com.fireflye.usuarios.service;
import java.util.List;
import com.fireflye.usuarios.dto.Usuarios;
public interface UsuariosService {
public void addUsuario(Usuarios usuarios);
public void deleteUsuario(Integer idUsuario);
public Usuarios getUsuario(Integer idUsuario);
public void updateUsuario(Usuarios usuario);
public List<Usuarios> listUsuarios();
public void validateUsuario(Integer idUsuario) throws UsuariosException;
}
package com.fireflye.usuarios.service;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.fireflye.usuarios.dto.Usuarios;
import lombok.extern.slf4j.Slf4j;
@Service
@Scope("singleton")
@Slf4j
public class UsuariosServiceImpl implements UsuariosService {
@Autowired
private KafkaTemplate<String, Usuarios> kafkaTemplate;
private List<Usuarios> usuariosList = new ArrayList<>();
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void addUsuario(Usuarios usuarios) {
usuariosList.add(usuarios);
kafkaTemplate.send("alumno6", usuarios.getNombre(), usuarios);
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void deleteUsuario(Integer idUsuario) {
Usuarios userToDelete = null;
for (Usuarios usuarios : usuariosList) {
if (usuarios.getIdUsuario().equals(idUsuario)) {
userToDelete = usuarios;
}
}
if (userToDelete != null) {
usuariosList.remove(userToDelete);
}
}
@Override
@Transactional(readOnly = true)
public Usuarios getUsuario(Integer idUsuario) {
for (Usuarios usuarios : usuariosList) {
if (usuarios.getIdUsuario().equals(idUsuario)) {
return usuarios;
}
}
return null;
}
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void updateUsuario(Usuarios usuario) {
deleteUsuario(usuario.getIdUsuario());
addUsuario(usuario);
}
@Override
@Transactional(readOnly = true)
public List<Usuarios> listUsuarios() {
return usuariosList;
}
@Override
@Transactional(readOnly = true)
public void validateUsuario(Integer idUsuario) throws UsuariosException {
if (getUsuario(idUsuario) == null) {
throw new UsuariosException();
}
}
}
kafka.bootstrapAddress=firefly.technology:9092
springdoc.swagger-ui.path=/servicios/usuarios/swagger-ui.html
\ No newline at end of file
package com.fireflye.usuarios;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class UsuariosApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment