<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <link href="https://getbootstrap.com/docs/5.0/assets/css/docs.css" rel="stylesheet" crossorigin="anonymous">

    <title>Codigo</title>
  </head>
  
  <body class="p-5">
    

<div class="card mb-2">
    <h5 class="card-header">PostgreSQL</h5>
    <div class="card-body">
        <h5 class="card-title">Crear Secuencia y Tabla</h5>
        <div class="highlight">
            <pre class="chroma">
                <code class="language-postgresql" data-lang="html">
                    CREATE SEQUENCE esq_examen.tb_cliente_seq
                    INCREMENT BY 1
                    MINVALUE 1
                    MAXVALUE 9223372036854775807
                    START 1;
                    
                    create table tb_cliente
                    (
                    	id_cliente integer not null default nextval( 'esq_examen.tb_cliente_seq' ),
                    	nombres character varying(150) default null,
                    	dni character varying(8) default null,
                    	primary key( id_cliente )
                    );
                </code>
            </pre>
        </div>
    </div>
</div>

<div class="card text-center mb-2" style="width: 35rem;">
    <div class="card-header">
        <img src="java_dependencia_inicial.jpg" class="card-img-top" alt="...">
    </div>
    <div class="card-body">
        <h5 class="card-title">Dependencias</h5>
        <p class="card-text">Imagen de referencia para nuevo Proyecto.</p>
        <a href="lombok.jar" class="btn btn-primary">Lombok</a>
    </div>
    <div class="card-footer text-muted"> &nbsp; </div>
</div>

<div class="card mb-2">
    <h5 class="card-header">application.yml</h5>
    <div class="card-body">
        <h5 class="card-title">Configurar conexion y puerto</h5>
        <div class="highlight">
            <pre class="chroma">
                <code class="language-postgresql" data-lang="java">
server:
  port: 8090

spring:
  application:
    name: examen
  datasource:
    url: jdbc:postgresql://localhost:5432/examen
    username: postgres
    password: mhwinv
    driver-class-name: org.postgresql.Driver
    hikari:
      auto-commit: false
      maximum-pool-size: 5
  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.PostgreSQLDialect
        '[format_sql]': true
        '[show_sql]': true
    hibernate:
      ddl-auto: none
                </code>
            </pre>
        </div>
    </div>
</div>

<div class="card mb-2">
    <h5 class="card-header">ExamenApplication.java</h5>
    <div class="card-body">
        <h5 class="card-title">Clase principal</h5>
        <div class="highlight">
            <pre class="chroma">
                <code class="language-java" data-lang="html">
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

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

	@Bean
    public WebMvcConfigurer corsConfigurer() 
    {
        return new WebMvcConfigurer() 
        {
            @Override
            public void addCorsMappings( CorsRegistry registry ) 
            {
                registry.addMapping( "/**" )
                .allowedMethods( "*" )
                .allowedOrigins( "*" )
                .allowedHeaders( "*" );
            }
        };
    }
}
                </code>
            </pre>
        </div>
    </div>
</div>

<div class="card mb-2">
    <h5 class="card-header">ClienteController.java</h5>
    <div class="card-body">
        <h5 class="card-title">Clase para manejar las solicitudes HTTP (como GET, POST, PUT, DELETE). Actúa como intermediario entre la vista (interfaz de usuario) y el modelo (datos). Registrar los endpoints</h5>
        <div class="highlight">
            <pre class="chroma">
                <code class="language-java" data-lang="html">
package com.example.demo.core.controller;

import java.util.List;
import java.util.Optional;

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.example.demo.core.model.Cliente;
import com.example.demo.core.repository.ClienteRepository;
import com.example.demo.core.request.dto.ReqCliente;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.AllArgsConstructor;

@AllArgsConstructor
@RestController
@RequestMapping( "api/v1/cliente" )
public class ClienteController
{
    private final ClienteRepository oClienteRepository;
    
    @PostMapping( path = { "/crearCliente" } )
    public Integer crearCliente( @RequestBody ReqCliente oReqCliente )
    {
        System.out.println( "Ingresa crearCliente" );
        
        ObjectMapper mapper = new ObjectMapper();
        Integer iResult = 0;
        try 
        {
            String json = mapper.writeValueAsString( oReqCliente );
            System.out.println( "Objeto en formato JSON: " + json );
            
            Cliente oCliente = new Cliente();
            oCliente.setNombres( oReqCliente.getNombres() );
            oCliente.setDni( oReqCliente.getDni() );
            oCliente = oClienteRepository.save( oCliente );
            iResult = oCliente.getIdCliente();
        } 
        catch ( Exception e ) 
        {
            e.printStackTrace();
            iResult = 0;
        }
        
        return iResult;
    }
    
    @GetMapping( "/listarClientes" )
    public List&lt;Cliente&gt; listarClientes()
    {
        System.out.println( "Listando clientes" );
        //para obtener el listado de clientes
        List&lt;Cliente&gt; oLstCliente = oClienteRepository.findAll();
        return oLstCliente;
    }
    
    @PutMapping( "/actualizarCliente/{idCliente}" )
    public String actualizarCliente( @PathVariable Integer idCliente, @RequestBody ReqCliente oReqCliente )
    {
        System.out.println( "Actualizando cliente con ID: " + idCliente );
        
        ObjectMapper mapper = new ObjectMapper();
        String json;
        try
        {
            json = mapper.writeValueAsString( oReqCliente );
            System.out.println( "Objeto en formato JSON: " + json );
        }
        catch ( JsonProcessingException e )
        {
            e.printStackTrace();
        }
        
        //buscar cliente
        Optional&lt;Cliente&gt; oOptCliente = oClienteRepository.findById( idCliente );
        if( oOptCliente.isPresent() )
        {
            Cliente oCliente = oOptCliente.get();
            if( oReqCliente.getNombres() != null )
            {
                oCliente.setNombres( oReqCliente.getNombres() );
            }
            if( oReqCliente.getDni() != null )
            {
                oCliente.setDni( oReqCliente.getDni() );
            }
            oClienteRepository.save( oCliente );
            
            return "Cliente actualizado correctamente";
        }
        else
        {
            return "Cliente no encontrado";
        }
    }
    
    @DeleteMapping( "/eliminarCliente/{idCliente}" )
    public String eliminarCliente( @PathVariable Integer idCliente )
    {
        Optional&lt;Cliente&gt; oOptCliente = oClienteRepository.findById( idCliente );
        if( oOptCliente.isPresent() )
        {
            oClienteRepository.deleteById( idCliente );
            return "Cliente eliminado correctamente";
        }
        else
        {
            return "Cliente no encontrado";
        }
    }
}
                </code>
            </pre>
        </div>
        <a href="examen.zip" class="btn btn-primary">examen-java</a>
    </div>
</div>

<div class="card mb-2">
    <h5 class="card-header">ReqCliente.java</h5>
    <div class="card-body">
        <h5 class="card-title">Spring Boot deserializa un JSON (@RequestBody) en una instancia ReqCliente </h5>
        <div class="highlight">
            <pre class="chroma">
                <code class="language-java" data-lang="java">
package com.example.demo.core.request.dto;

import lombok.Data;

@Data
public class ReqCliente
{
    private String nombres;
    private String dni;
}
                </code>
            </pre>
        </div>
    </div>
</div>

<div class="card mb-2">
    <h5 class="card-header">Cliente.java</h5>
    <div class="card-body">
        <h5 class="card-title">Clase que represente la entidad en la base de datos. </h5>
        <div class="highlight">
            <pre class="chroma">
                <code class="language-java" data-lang="java">
package com.example.demo.core.model;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.SequenceGenerator;
import jakarta.persistence.Table;
import lombok.Data;

@Data
@Entity
@Table( name = "tb_cliente", schema = "esq_examen" )
public class Cliente
{
    @Id
    @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "cliente_seq" )
    @SequenceGenerator( name = "cliente_seq", sequenceName = "esq_examen.tb_cliente_seq", allocationSize = 1 )
    @Column( name = "id_cliente" )
    private Integer idCliente;

    @Column( name = "nombres" )
    private String nombres;

    @Column( name = "dni" )
    private String dni;
}
                </code>
            </pre>
        </div>
    </div>
</div>

<div class="card mb-2">
    <h5 class="card-header">ClienteRepository.java</h5>
    <div class="card-body">
        <h5 class="card-title">Clase repositorio que se encargará de las operaciones CRUD sobre la entidad Cliente </h5>
        <div class="highlight">
            <pre class="chroma">
                <code class="language-java" data-lang="java">
package com.example.demo.core.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.example.demo.core.model.Cliente;

@Repository
public interface ClienteRepository extends JpaRepository&lt;Cliente, Integer&gt; 
{
}
                </code>
            </pre>
        </div>
    </div>
</div>

<div class="card mb-2">
    <h5 class="card-header">Postman</h5>
    <div class="card-body">
        <h5 class="card-title">Para llamar a los APIs </h5>
        <div class="highlight">
            <pre class="chroma">
                <code class="language-java" data-lang="java">
POST http://localhost:8092/api/v1/cliente/crearCliente
Body:
{
    "nombres": "Maria Laura Taype Serrano",
    "dni": "00000000"
}

GET http://localhost:8092/api/v1/cliente/listarClientes

PUT http://localhost:8091/api/v1/cliente/actualizarCliente/2
Body:
{
    "nombres": "William L Taype Perez",
    "dni": "41288353"
}

DELETE http://localhost:8091/api/v1/cliente/eliminarCliente/1

                </code>
            </pre>
        </div>
    </div>
</div>

<div class="card mb-2">
    <h5 class="card-header">Angular</h5>
    <div class="card-body">
        <h5 class="card-title">Comandos para continuar con el proyecto.</h5>
        <div class="highlight">
            <pre class="chroma">
                <code class="language-java" data-lang="java">
//el angular tiene que estar instalado
# ng new cliente-app    //añadir Angular routing. Responde con Yes. | También selecciona SCSS 
# cd cliente-app
# ng g environments
# ng serve
# ng generate service services/cliente
# ng generate component components/listar-clientes
# ng generate component components/crear-cliente
# ng generate component components/actualizar-cliente
# ng generate component components/eliminar-cliente
                </code>
            </pre>
        </div>
        <a href="src-app.zip" class="btn btn-primary">clineten-app(src)</a>
    </div>
</div>

    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

    <!-- Option 2: Separate Popper and Bootstrap JS -->
    <!--
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
    -->
  </body>
</html>