Commit 52348f94 by Adrian

Commit inicial

parents
/target/
!.mvn/wrapper/maven-wrapper.jar
/nbproject/
\ No newline at end of file
Versión httpClient, en las diapositivas pone la 4.2, pero han cambiado algo en spring que hace que salte el error "Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/http/client/protocol/HttpClientContext", hay que usar la 4.3.2 como mínimo, cambiando el constructor, consultar el código del repositorio.
Los certificados deben de incluir la url o de lo contrario sale un error indicando que no se corresponde el nombre con la url, hay que añadir "-ext SAN=DNS:localhost,IP:127.0.0.1" en el comando keytool para crear el certificado.
https://stackoverflow.com/questions/8839541/hostname-in-certificate-didnt-match
El certificado tiene que estar en el almacén de java para que permita los autofirmados, se baja del navegador y se sigue esto: https://stackoverflow.com/questions/21076179/pkix-path-building-failed-and-unable-to-find-valid-certification-path-to-requ
Ahora el restTemplate no devuelve los errores http, lanza excepciones que o se capturan y parsean o se usa un errorhandler, por tiempo estoy usando try/catch: https://www.baeldung.com/spring-rest-template-error-handling
Para usar el encoder de contraseña sin seguridad (NoOp), ha camdiado la sintaxis: ....jdbcAuthentication().passwordEncoder(NoOpPasswordEncoder.getInstance()).dataSource(dataSource).....
Importante usar el prefijo para los roles desde BBDD, ......authoritiesByUsernameQuery("select dni, 'USER' from cliente where dni=?").rolePrefix("ROLE_");
\ No newline at end of file
POST /ujacoin/clientes -> Alta de clientes (Se le crea cuenta por defecto)
GET /ujacoin/clientes/{dni} -> Validar y devolver cliente. (temporal hasta que se explique Spring Security)
PUT /ujacoin/clientes/{dni} -> Actualizar cliente.
POST /ujacoin/clientes/{dni}/tarjetas -> Registrar tarjeta
GET /ujacoin/clientes/{dni}/tarjetas-> Obtener listado de cuentas del usuario
GET /ujacoin/clientes/{dni}/tarjetas/{num} -> Obtener información de tarjeta
DELETE /ujacoin/clientes/{dni}/tarjetas/{num} -> Borrar tarjeta
POST /ujacoin/clientes/{dni}/cuentas -> Creación de cuenta adicional
GET /ujacoin/clientes/{dni}/cuentas-> Obtener listado de cuentas del usuario
GET /ujacoin/clientes/{dni}/cuentas/{num} -> Obtener información de cuenta
DELETE /ujacoin/clientes/{dni}/cuentas/{num} -> Borrar cuenta
POST /ujacoin/clientes/{dni}/cuentas/{num}/movimientos -> Añadir movimiento
GET /ujacoin/clientes/{dni}/cuentas/{num}/movimientos -> Listado de movimientos en la cuenta (se pueden acotar las fechas con parámetros de consulta, y debería devolverse paginado)
\ No newline at end of file
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>es.ujaen.dae</groupId>
<artifactId>UjaCoinConsoleClient</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.11.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-hateoas</artifactId>
<version>2.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.ujaen.dae.ujacoinconsoleclient.client;
import es.ujaen.dae.ujacoinconsoleclient.entidades.DTO.ClienteDTO;
import es.ujaen.dae.ujacoinconsoleclient.util.ErrorInterfaz;
import es.ujaen.dae.ujacoinconsoleclient.util.Pair;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
*
* @author adria
*/
@Component
public class InterfazAPIRest {
HttpClient httpClient;
ClientHttpRequestFactory reqFactory;
RestTemplate restTemplate;
//DNI del usuario
private String dni;
public InterfazAPIRest(String dni, String pass) {
this.dni = dni;
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials
= new UsernamePasswordCredentials(dni, pass);
provider.setCredentials(AuthScope.ANY, credentials);
httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build();
reqFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
restTemplate = new RestTemplate(reqFactory);
}
public Pair<ErrorInterfaz, ClienteDTO> checkConexion() {
String url = "https://localhost:8080/ujacoin/clientes/{dni}";
ResponseEntity<ClienteDTO> response = null;
try {
response = restTemplate.getForEntity(url, ClienteDTO.class, dni);
} catch (Exception ex) {
if (ex instanceof org.springframework.web.client.HttpClientErrorException && ex.getMessage().startsWith("404")) {
return new Pair<>(ErrorInterfaz.ErrorCredenciales, null);
} else {
return new Pair<>(ErrorInterfaz.ErrorConexion, null);
}
}
return new Pair<>(ErrorInterfaz.OK, response.getBody());
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.ujaen.dae.ujacoinconsoleclient.client;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.logging.LogManager;
import java.util.logging.Logger;
/**
*
* @author adria
*/
public class Launcher {
public static void main(String[] args) throws IOException, SecurityException {
UjaCoinClient cliente = new UjaCoinClient();
cliente.menuLogin();
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.ujaen.dae.ujacoinconsoleclient.client;
import es.ujaen.dae.ujacoinconsoleclient.entidades.DTO.ClienteDTO;
import es.ujaen.dae.ujacoinconsoleclient.util.ErrorInterfaz;
import es.ujaen.dae.ujacoinconsoleclient.util.Pair;
import java.util.Scanner;
/**
*
* @author adria
*/
public class UjaCoinClient {
private InterfazAPIRest interfaz;
ClienteDTO usuario;
Scanner scanner = new Scanner(System.in);
public void limpiarConsola() {
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
}
public void menuLogin() {
Pair<ErrorInterfaz, ClienteDTO> respuesta;
System.out.println("Bienvenido al cliente de consola del banco UjaCoin");
do {
System.out.println("Por favor escriba su DNI (incluyendo la letra): ");
String dni = scanner.nextLine();
System.out.println("Y su contraseña:");
String pass = scanner.nextLine();
System.out.println("\nComprobando credenciales...");
interfaz = new InterfazAPIRest(dni, pass);
respuesta = interfaz.checkConexion();
limpiarConsola();
if (respuesta.first == ErrorInterfaz.ErrorCredenciales) {
System.out.println("Credenciales incorrectas");
}
if (respuesta.first == ErrorInterfaz.ErrorConexion) {
System.out.println("Error conexion");
}
} while (respuesta.first != ErrorInterfaz.OK);
usuario = respuesta.second;
System.out.println("Login correcto");
menuUsuario();
}
private void menuUsuario() {
int opcion = 0;
limpiarConsola();
do {
System.out.println("Usuario " + usuario.getNombre());
System.out.println("Acciones:");
System.out.println("1->Detalles de usuario.");
System.out.println("2->Listado de cuentas.");
System.out.println("3->Listado de tarjetas.");
System.out.println("4->Salir");
System.out.println("Elija una opción:");
try {
opcion = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
opcion = 0;
}
switch (opcion) {
case 1:
menuDetalleUsuario();
break;
case 2:
menuCuentas();
break;
case 3:
menuTarjetas();
break;
case 4:
System.out.println("Adios.");
break;
default:
System.out.println("Opción no válida");
System.out.println("");
System.out.println("");
}
} while (opcion != 4);
}
private void menuDetalleUsuario() {
int opcion = 0;
limpiarConsola();
do {
System.out.println("Nombre:\t\t" + usuario.getNombre());
System.out.println("DNI:\t\t" + usuario.getDni());
System.out.println("Dirección:\t" + usuario.getDireccion());
System.out.println("Teléfono:\t" + usuario.getTelefono());
System.out.println("Email:\t\t" + usuario.getEmail());
System.out.println("F.Nac:\t\t" + usuario.getFechaNacimiento());
System.out.println("Acciones:");
System.out.println("1->Editar datos personales.");
System.out.println("2->Salir");
System.out.println("Elija una opción:");
try {
opcion = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
opcion = 0;
}
switch (opcion) {
case 1:
System.out.println("Opción no implementada, cliente en desarrollo");
break;
case 2:
break;
default:
System.out.println("Opción no válida");
System.out.println("");
System.out.println("");
}
} while (opcion != 2);
}
private void menuCuentas() {
}
private void menuTarjetas() {
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.ujaen.dae.ujacoinconsoleclient.entidades.DTO;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import org.springframework.hateoas.Link;
/**
* Clase cliente de UjaBank
*
* @author Adrian
*/
public class ClienteDTO {
private String dni;
private String nombre;
private LocalDate fechaNacimiento;
private String direccion;
private String telefono;
private String email;
private String clave;
private List<Link> cuentasAsociadas;
private List<Link> tarjetasAsociadas;
public ClienteDTO() {
}
public ClienteDTO(String dni, String nombre, LocalDate fechaNacimiento, String direccion, String telefono, String email, String clave) {
this.dni = dni;
this.nombre = nombre;
this.fechaNacimiento = fechaNacimiento;
this.direccion = direccion;
this.telefono = telefono;
this.email = email;
this.clave = clave;
this.cuentasAsociadas = new ArrayList<>();
this.tarjetasAsociadas = new ArrayList<>();
}
public String getDni() {
return dni;
}
public String getNombre() {
return nombre;
}
public LocalDate getFechaNacimiento() {
return fechaNacimiento;
}
public String getDireccion() {
return direccion;
}
public String getTelefono() {
return telefono;
}
public String getEmail() {
return email;
}
public String getClave() {
return clave;
}
public List<Link> getCuentasAsociadas() {
return cuentasAsociadas;
}
public List<Link> getTarjetasAsociadas() {
return tarjetasAsociadas;
}
public void añadirCuenta(Link cuenta){
cuentasAsociadas.add(cuenta);
}
public void añadirTarjeta(Link tarjeta){
cuentasAsociadas.add(tarjeta);
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.ujaen.dae.ujacoinconsoleclient.entidades.DTO;
/**
* Cuenta de UjaCoins
*
* @author Adrian
*/
public class CuentaDTO {
private String numero;
private float saldo;
public CuentaDTO() {
}
public CuentaDTO(String numero, float saldo) {
this.numero = numero;
this.saldo = saldo;
}
public String getNumero() {
return numero;
}
public float getSaldo() {
return saldo;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.ujaen.dae.ujacoinconsoleclient.entidades.DTO;
import es.ujaen.dae.ujacoinconsoleclient.util.TipoMovimiento;
import java.time.LocalDateTime;
/**
* Movimientos asociados a las cuentas
*
* @author Adrian
*/
public class MovimientoDTO {
private int identificador;
private TipoMovimiento tipo;
private float importe;
private LocalDateTime fechaHora;
private String tarjetaCuenta;
public MovimientoDTO() {
}
public MovimientoDTO(int identificador, TipoMovimiento tipo, float importe, LocalDateTime fechaHora, String tarjetaCuenta) {
this.identificador = identificador;
this.tipo = tipo;
this.importe = importe;
this.fechaHora = fechaHora;
this.tarjetaCuenta = tarjetaCuenta;
}
public MovimientoDTO(TipoMovimiento tipo, float importe, LocalDateTime fechaHora, String tarjetaCuenta) {
this.tipo = tipo;
this.importe = importe;
this.fechaHora = fechaHora;
}
public TipoMovimiento getTipo() {
return tipo;
}
public float getImporte() {
return importe;
}
public String getTarjetaCuenta() {
return tarjetaCuenta;
}
public int getIdentificador() {
return identificador;
}
public LocalDateTime getFechaHora() {
return fechaHora;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.ujaen.dae.ujacoinconsoleclient.entidades.DTO;
import java.time.LocalDate;
import java.util.Random;
/**
* Tarjetas de crédito asociadas a clientes
*
* @author Adrian
*/
public class TarjetaDTO {
private String numero;
private String titular;
private String cvc;
private LocalDate fechaCaducidad;
public TarjetaDTO() {
}
private static Random rand = new Random();
public TarjetaDTO(String numero, String titular, String cvc, LocalDate fechaCaducidad) {
this.numero = numero;
this.titular = titular;
this.cvc = cvc;
this.fechaCaducidad = fechaCaducidad;
}
public String getNumero() {
return numero;
}
public String getTitular() {
return titular;
}
public String getCvc() {
return cvc;
}
public LocalDate getFechaCaducidad() {
return fechaCaducidad;
}
/**
* Comprueba que el número de tarjeta es válido, 8 dígitos numéricos, la
* suma de los dígitos tiene que ser multiplo de 4.
*
* @param numero Numero de tarjeta a comprobar
* @return True si el número es válido, false en otro caso
*/
public static boolean checkNumeroTarjeta(String numero) {
if (numero.matches("[0-9]+") && numero.length() == 8) {
int suma = 0;
for (int i = 0; i < numero.length(); i++) {
suma += Integer.parseInt(numero.substring(i, i + 1));
}
if (suma % 4 == 0) {
return true;
}
}
return false;
}
public static String generadorTarjetasNuevas() {
boolean numeroValido = false;
String numeroCadena;
do {
int numero = rand.nextInt(99999999);
numeroCadena = String.valueOf(numero);
for (int i = numeroCadena.length(); i < 8; i++) {
numeroCadena = "0".concat(numeroCadena);
}
int codigo = 0;
for (int i = 0; i < 8; i++) {
codigo += Integer.parseInt(numeroCadena.substring(i, i + 1));
}
codigo = codigo % 4;
if ((numero % 10) > 5) {
numero -= codigo;
} else {
numero += 4 - codigo;
}
numeroCadena = String.valueOf(numero);
for (int i = numeroCadena.length(); i < 8; i++) {
numeroCadena = "0".concat(numeroCadena);
}
} while (!numeroValido);
return numeroCadena;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.ujaen.dae.ujacoinconsoleclient.util;
/**
*
* @author adria
*/
public enum ErrorInterfaz {
OK,
ErrorConexion,
ErrorCredenciales
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.ujaen.dae.ujacoinconsoleclient.util;
/**
*
* @author adria
*/
public class Pair<T,U> {
public T first;
public U second;
public Pair(T first, U second) {
this.first = first;
this.second = second;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package es.ujaen.dae.ujacoinconsoleclient.util;
/**
* Enum para el tipo de movimiento
*
* @author Adrian
*/
public enum TipoMovimiento {
TMIngreso,
TMReintegro,
TMTransferenciaEmitida,
TMTrasnferenciaRecibida
}
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 sign in to comment