0% encontró este documento útil (0 votos)
23 vistas10 páginas

Proyecto Final

Programacion Avanzada II

Cargado por

EduarSolano
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
0% encontró este documento útil (0 votos)
23 vistas10 páginas

Proyecto Final

Programacion Avanzada II

Cargado por

EduarSolano
Derechos de autor
© © All Rights Reserved
Nos tomamos en serio los derechos de los contenidos. Si sospechas que se trata de tu contenido, reclámalo aquí.
Formatos disponibles
Descarga como DOCX, PDF, TXT o lee en línea desde Scribd
Está en la página 1/ 10

HABITACION

_____________________________________________________________________________
__
package hn.uth.views.habitacion;

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.button.ButtonVariant;
import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.datepicker.DatePicker;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.grid.GridVariant;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Image;
import com.vaadin.flow.component.html.NativeLabel;
import com.vaadin.flow.component.icon.Icon;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.Notification.Position;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.splitlayout.SplitLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.data.binder.BeanValidationBinder;
import com.vaadin.flow.data.binder.ValidationException;
import com.vaadin.flow.data.converter.StringToIntegerConverter;
import com.vaadin.flow.data.renderer.LitRenderer;
import com.vaadin.flow.router.BeforeEnterEvent;
import com.vaadin.flow.router.BeforeEnterObserver;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.StreamResource;
import com.vaadin.flow.spring.data.VaadinSpringDataHelpers;
import hn.uth.data.SampleBook;
import hn.uth.views.MainLayout;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.Optional;
import org.springframework.data.domain.PageRequest;
import
org.springframework.orm.ObjectOptimisticLockingFailureException;

@PageTitle("Habitacion")
@Route(value = "Habitacion/:sampleBookID?/:action?(edit)", layout =
MainLayout.class)
public class HabitacionView extends Div implements BeforeEnterObserver
{

private final String SAMPLEBOOK_ID = "sampleBookID";


private final String SAMPLEBOOK_EDIT_ROUTE_TEMPLATE =
"Habitacion/%s/edit";

private final Grid<SampleBook> grid = new Grid<>(SampleBook.class,


false);

private TextField numerohabitacion;


private ComboBox<String> ocupacion;
private ComboBox<String> precio;
private ComboBox<String> tipohabitacion;

private final Button cancel = new Button("Cancelar");


private final Button save = new Button("Guardar",new
Icon(VaadinIcon.CHECK_CIRCLE));
private final Button delete = new Button("Eliminar",new
Icon(VaadinIcon.CLOSE_CIRCLE));

private SampleBook sampleBook;

public HabitacionView() {
addClassNames("habitacion-view");

// Create UI
SplitLayout splitLayout = new SplitLayout();

createGridLayout(splitLayout);
createEditorLayout(splitLayout);

add(splitLayout);

grid.addColumn("numerohabitacion").setAutoWidth(true);
grid.addColumn("ocupacion").setAutoWidth(true);
grid.addColumn("precio").setAutoWidth(true);
grid.addColumn("tipohabitacion").setAutoWidth(true);

grid.addThemeVariants(GridVariant.LUMO_NO_BORDER);

// when a row is selected or deselected, populate form


grid.asSingleSelect().addValueChangeListener(event -> {
if (event.getValue() != null) {

UI.getCurrent().navigate(String.format(SAMPLEBOOK_EDIT_ROUTE_TEMPLATE,
event.getValue().getId()));
} else {
clearForm();
UI.getCurrent().navigate(HabitacionView.class);
}
});

cancel.addClickListener(e -> {
clearForm();
refreshGrid();
});

save.addClickListener(e -> {
try {
if (this.sampleBook == null) {
this.sampleBook = new SampleBook();
}
clearForm();
refreshGrid();
Notification.show("Data updated");
UI.getCurrent().navigate(HabitacionView.class);
} catch (ObjectOptimisticLockingFailureException
exception) {
Notification n = Notification.show(
"Error updating the data. Somebody else has
updated the record while you were making changes.");
n.setPosition(Position.MIDDLE);
n.addThemeVariants(NotificationVariant.LUMO_ERROR);
}
});
}

@Override
public void beforeEnter(BeforeEnterEvent event) {
/*Optional<Long> sampleBookId =
event.getRouteParameters().get(SAMPLEBOOK_ID).map(Long::parseLong);
if (sampleBookId.isPresent()) {
Optional<SampleBook> sampleBookFromBackend =
sampleBookService.get(sampleBookId.get());
if (sampleBookFromBackend.isPresent()) {
populateForm(sampleBookFromBackend.get());
} else {
Notification.show(String.format("The requested
sampleBook was not found, ID = %s", sampleBookId.get()),
3000, Notification.Position.BOTTOM_START);
// when a row is selected but the data is no longer
available,
// refresh grid
refreshGrid();
event.forwardTo(HabitacionView.class);
}
}*/
}

private void createEditorLayout(SplitLayout splitLayout) {


Div editorLayoutDiv = new Div();
editorLayoutDiv.setClassName("editor-layout");

Div editorDiv = new Div();


editorDiv.setClassName("editor");
editorLayoutDiv.add(editorDiv);

FormLayout formLayout = new FormLayout();


numerohabitacion = new TextField("Numero habitacion");

numerohabitacion.setPrefixComponent(VaadinIcon.TICKET.create());
ocupacion = new ComboBox("Ocupacion");
ocupacion.setItems("Cama 1","Cama 2","Cama 3");
ocupacion.setPrefixComponent(VaadinIcon.BED.create());
precio = new ComboBox("Precio");
precio.setItems("L.2,300.00","L.3,100.00","L.4,200.00");
precio.setPrefixComponent(VaadinIcon.MONEY.create());
tipohabitacion = new ComboBox("Tipo Habitacion");
tipohabitacion.setItems("Individual","Doble","Triple");

tipohabitacion.setPrefixComponent(VaadinIcon.STORAGE.create());

formLayout.add(numerohabitacion,ocupacion,precio,tipohabitacion);
editorDiv.add(formLayout);
createButtonLayout(editorLayoutDiv);

splitLayout.addToSecondary(editorLayoutDiv);
}

private void createButtonLayout(Div editorLayoutDiv) {


HorizontalLayout buttonLayout = new HorizontalLayout();
buttonLayout.setClassName("button-layout");
cancel.addThemeVariants(ButtonVariant.LUMO_TERTIARY);
save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);

delete.addThemeVariants(ButtonVariant.LUMO_PRIMARY,ButtonVariant.LUMO_
ERROR);
buttonLayout.add(save,delete,cancel);

editorLayoutDiv.add(buttonLayout);
}

private void createGridLayout(SplitLayout splitLayout) {


Div wrapper = new Div();
wrapper.setClassName("grid-wrapper");
splitLayout.addToPrimary(wrapper);
wrapper.add(grid);
}

private void attachImageUpload(Upload upload, Image preview) {


ByteArrayOutputStream uploadBuffer = new
ByteArrayOutputStream();
upload.setAcceptedFileTypes("image/*");
upload.setReceiver((fileName, mimeType) -> {
uploadBuffer.reset();
return uploadBuffer;
});
upload.addSucceededListener(e -> {
StreamResource resource = new
StreamResource(e.getFileName(),
() -> new
ByteArrayInputStream(uploadBuffer.toByteArray()));
preview.setSrc(resource);
preview.setVisible(true);
if (this.sampleBook == null) {
this.sampleBook = new SampleBook();
}
// this.sampleBook.setImage(uploadBuffer.toByteArray());
});
preview.setVisible(false);
}

private void refreshGrid() {


grid.select(null);
grid.getDataProvider().refreshAll();
}

private void clearForm() {


populateForm(null);
}

private void populateForm(SampleBook value) {


this.sampleBook = value;
}

SAMPLE

package hn.uth.data;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Lob;

@Entity
public class SampleBook extends AbstractEntity {

@Lob
@Column(length = 1000000)

private String numerohabitacion;


private String ocupacion;
private String precio;
private String tipohabitacion;

public String getNumerohabitacion() {


return numerohabitacion;
}
public void setNumerohabitacion(String numerohabitacion) {
this.numerohabitacion = numerohabitacion;
}
public String getOcupacion() {
return ocupacion;
}
public void setOcupacion(String ocupacion) {
this.ocupacion = ocupacion;
}
public String getPrecio() {
return precio;
}
public void setPrecio(String precio) {
this.precio = precio;
}
public String getTipohabitacion() {
return tipohabitacion;
}
public void setTipohabitacion(String tipohabitacion) {
this.tipohabitacion = tipohabitacion;
}

}
TEST

package proyectohotel.test;

import static org.junit.jupiter.api.Assertions.assertTrue;


import static java.time.Duration.ofSeconds;
import static
org.openqa.selenium.support.ui.ExpectedConditions.titleIs;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

public class HotelTest {

@Test
public void testGuardarCliente() throws InterruptedException {
// Inicializa el WebDriver para Chrome
WebDriver driver = new ChromeDriver();

try{
// Abre la página web de empleados
driver.get("http://localhost:8080/Cliente");

int cantidadClienteInicial = 0;//CONSULTO LA CANTIDAD


DE EMPLEADOS REALES

new WebDriverWait(driver, ofSeconds(30),


ofSeconds(1)).until(titleIs("Empleados"));

//ESPERA 3 SEGUNDOS DESPUES DE CARGAR LA PANTALLA


//Thread.sleep(3000);

// Localiza el campo de entrada de nombre de usuario


WebElement cIdentidad =
driver.findElement(By.xpath("//vaadin-text-
field[@id='txt_identidad']/input"));
WebElement cNombre =
driver.findElement(By.xpath("//vaadin-text-field[@id='txt_nombre']/
input"));
WebElement cApellido =
driver.findElement(By.xpath("//vaadin-text-field[@id='txt_apellido']/
input"));
WebElement cCorreo =
driver.findElement(By.xpath("//vaadin-text-field[@id='txt_correo']/
input"));
WebElement cTelefono =
driver.findElement(By.xpath("//vaadin-text-field[@id='txt_telefono']/
input"));
WebElement cFechaCumpleaños =
driver.findElement(By.xpath("//vaadin-number-
field[@id='txt_FechaDeCumpleaños']/input"));
WebElement cSexo =
driver.findElement(By.xpath("//vaadin-text-field[@id='txt_Sexo']/input
"));
WebElement cNacionalidad =
driver.findElement(By.xpath("//vaadin-text-
field[@id='txt_Nacionalidad']/input"));
WebElement cLugarProcedencia =
driver.findElement(By.xpath("//vaadin-text-
field[@id='txt_LugarProcedencia']/input"));

WebElement bGuardar =
driver.findElement(By.xpath("//vaadin-button[@id='btn_guardar']"));
WebElement bCancelar =
driver.findElement(By.xpath("//vaadin-button[@id='btn_cancelar']"));
WebElement bEliminar =
driver.findElement(By.xpath("//vaadin-button[@id='btn_eliminar']"));

// Ingresa el nombre de usuario


cIdentidad.sendKeys("0801199912345");
cNombre.sendKeys("Pedro");
cApellido.sendKeys("Perez");
cCorreo.sendKeys("[email protected]");
cTelefono.sendKeys("99420000");
cFechaCumpleaños.sendKeys("23/09/1994");
cSexo.sendKeys("hombre");
cNacionalidad.sendKeys("hondureño");
cLugarProcedencia.sendKeys("roatan");

//ESPERA 3 SEGUNDOS LUEGO DE LLENAR LOS CAMPOS PARA


LUEGO DAR CLICK EN EL BOTON GUARDAR
//Thread.sleep(3000);

bGuardar.click();

int cantidadClienteFinal = 0;//CONSULTO LA CANTIDAD


DE EMPLEADOS REALES

//SI LA CANTIDAD DE EMPLEADOS AL DARLE CLICK A


GUARDAR AUMENTA EN 1
assertTrue(cantidadClienteFinal ==
(cantidadClienteInicial+1));
}finally {
//CIERRA EL NAVEGADOR ABIERTO
driver.close();
}
}
}

HABITACION

package proyectohotel.test;

import static org.junit.jupiter.api.Assertions.assertTrue;


import static java.time.Duration.ofSeconds;
import static
org.openqa.selenium.support.ui.ExpectedConditions.titleIs;

import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;

public class HotelTest {

@Test
public void testGuardarHabitacion() throws InterruptedException
{

WebDriver driver = new ChromeDriver();

try {

// Abre la página web de inicio de sesión


driver.get("http://localhost:8080/Habitacion");

int cantidadHabitacionInicial = 0;//CONSULTO LA CANTIDAD DE


HABITACION REALES

new WebDriverWait(driver, ofSeconds(30),


ofSeconds(1)).until(titleIs("Habitacion"));

// Localiza el campo de entrada de nombre de usuario


WebElement numerohabitacion =
driver.findElement(By.xpath("//vaadin-text-
field[@id='numerohabitacion']/input"));
WebElement ocupacion =
driver.findElement(By.xpath("//vaadin-combo-box[@id='ocupacion']/input
"));
WebElement precio = driver.findElement(By.xpath("//vaadin-
combo-box[@id='precio']/input"));
WebElement tipohabitacion =
driver.findElement(By.xpath("//vaadin-combo-
box[@id='tipohabitacion']/input"));

WebElement save = driver.findElement(By.xpath("//vaadin-


button:nth-child(1)"));
WebElement delete = driver.findElement(By.xpath("//vaadin-
button:nth-child(2)"));
WebElement cancel = driver.findElement(By.xpath("//vaadin-
button:nth-child(3)"));

// Ingresa el nombre de usuario


numerohabitacion.sendKeys("0045");
ocupacion.sendKeys("6 Camas");
precio.sendKeys("L.4,200.00");
tipohabitacion.sendKeys("Presidencial");

// ESPERAR 3 SEGUNDO LUEGO DE LLENAR LOS CAMPOS,PARA LUEGO


DAR CLICK EN EL BOTON
// GUARDAR
Thread.sleep(3000);

save.click();

int cantidadHabitacionFinal = 0;//CONSULTO LA CANTIDAD DE


EMPLEADOS REALES

//SI LA CANTIDAD DE EMPLEADOS AL DARLE CLICK A GUARDAR


AUMENTA EN 1
assertTrue(cantidadHabitacionFinal ==
(cantidadHabitacionInicial+1));

// ESPERAR 3 SEGUNDO LUEGO DE LLENAR LOS CAMPOS


Thread.sleep(3000);
} finally {
driver.close();
}
}
}

CONTROLLER

package hn.uth.controller;

import hn.uth.data.HabitacionResponse;

import hn.uth.model.DatabaseRepositoryImpl;

import hn.uth.views.habitacion.ViewModelHabitacion;

public class InteractorImplHabitacion implements InteractorHabitacion{

private DatabaseRepositoryImpl modelo;

private ViewModelHabitacion vista;

public InteractorImplHabitacion(ViewModelHabitacion view) {

super();

this.vista = view;

this.modelo =
DatabaseRepositoryImpl.getInstance("https://apex.oracle.com", 30000L);

@Override

public void consultarHabitacion() {

// TODO Auto-generated method stub

try {

HabitacionResponse respuesta =
this.modelo.consultarHabitacion();

if(respuesta == null ||respuesta.getCount() == 0 ||


respuesta.getItems() == null) {
this.vista.mostrarMensajeError("No hay Cliente
que mostrar");

}else {

this.vista.mostrarHabitacionEnGrid(respuesta.getItems());;

}catch (Exception error) {

error.printStackTrace();

También podría gustarte