Compare commits

..

No commits in common. "85e0e44f4fd8320ed797b2247e949096b0b203ea" and "26af5f63c73699c26c956c250a7fc312d95a388c" have entirely different histories.

View File

@ -8,14 +8,13 @@ import com.primefactorsolutions.service.EmployeeService;
import com.vaadin.flow.component.Component; import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.combobox.ComboBox;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.component.upload.Upload; import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.component.upload.receivers.MemoryBuffer; import com.vaadin.flow.component.upload.receivers.MemoryBuffer;
import com.vaadin.flow.router.*; import com.vaadin.flow.router.*;
import com.vaadin.flow.server.StreamRegistration;
import com.vaadin.flow.server.StreamResource;
import com.vaadin.flow.spring.annotation.SpringComponent; import com.vaadin.flow.spring.annotation.SpringComponent;
import elemental.json.Json; import elemental.json.Json;
import elemental.json.JsonArray; import elemental.json.JsonArray;
@ -26,12 +25,10 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.vaadin.firitin.form.BeanValidationForm; import org.vaadin.firitin.form.BeanValidationForm;
import com.vaadin.flow.spring.security.AuthenticationContext; import com.vaadin.flow.spring.security.AuthenticationContext;
import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.Base64; import java.util.Base64;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
import java.io.InputStream;
@SpringComponent @SpringComponent
@PermitAll @PermitAll
@ -39,6 +36,8 @@ import java.io.InputStream;
@PageTitle("Document") @PageTitle("Document")
@Route(value = "/documents/:documentId?/:action?", layout = MainLayout.class) @Route(value = "/documents/:documentId?/:action?", layout = MainLayout.class)
public class DocumentView extends BeanValidationForm<Document> implements HasUrlParameter<String> { public class DocumentView extends BeanValidationForm<Document> implements HasUrlParameter<String> {
private final H2 title = new H2("Edit Documents");
private final TextField fileName = new TextField("Document Name"); private final TextField fileName = new TextField("Document Name");
private final ComboBox<DocumentType> documentType = new ComboBox<>("Document Type"); private final ComboBox<DocumentType> documentType = new ComboBox<>("Document Type");
private final ComboBox<Employee> employeeComboBox = new ComboBox<>("Employee"); private final ComboBox<Employee> employeeComboBox = new ComboBox<>("Employee");
@ -47,11 +46,11 @@ public class DocumentView extends BeanValidationForm<Document> implements HasUrl
private final DocumentService documentService; private final DocumentService documentService;
private final EmployeeService employeeService; private final EmployeeService employeeService;
private final AuthenticationContext authContext; private final AuthenticationContext authContext;
private boolean fileUploaded = false; private boolean fileUploaded = false;
private Button saveButton; private Button saveButton;
private Button viewDocumentButton; private Button viewDocumentButton;
public DocumentView(final DocumentService documentService, public DocumentView(final DocumentService documentService,
final EmployeeService employeeService, final EmployeeService employeeService,
final AuthenticationContext authContext) { final AuthenticationContext authContext) {
@ -67,6 +66,34 @@ public class DocumentView extends BeanValidationForm<Document> implements HasUrl
configureUploadButton(); configureUploadButton();
} }
private void configureComponents() {
setFileNameProperties();
setDocumentTypeProperties();
setEmployeeComboBoxProperties();
}
private void setFileNameProperties() {
fileName.setWidthFull();
}
private void setDocumentTypeProperties() {
documentType.setItems(DocumentType.values());
documentType.setWidthFull();
}
private void setEmployeeComboBoxProperties() {
List<Employee> employees = employeeService.findAllEmployees();
employeeComboBox.setItems(employees);
employeeComboBox.setItemLabelGenerator(employee -> employee.getFirstName() + " " + employee.getLastName());
employeeComboBox.setWidthFull();
}
private void configureUploadButton() {
uploadButton.setMaxFiles(1);
uploadButton.setAcceptedFileTypes(".pdf");
uploadButton.addSucceededListener(event -> handleUploadSuccess());
}
protected Button createSaveButton() { protected Button createSaveButton() {
saveButton = new Button("Save"); saveButton = new Button("Save");
saveButton.addClickListener(event -> saveDocument()); saveButton.addClickListener(event -> saveDocument());
@ -86,58 +113,43 @@ public class DocumentView extends BeanValidationForm<Document> implements HasUrl
return viewDocumentButton; return viewDocumentButton;
} }
private void setFileNameProperties() {
fileName.setWidthFull();
}
private void setDocumentTypeProperties() {
documentType.setItems(DocumentType.values());
documentType.setWidthFull();
}
private void setEmployeeComboBoxProperties() {
List<Employee> employees = employeeService.findAllEmployees();
employeeComboBox.setItems(employees);
employeeComboBox.setItemLabelGenerator(employee -> employee.getFirstName() + " " + employee.getLastName());
employeeComboBox.setWidthFull();
}
private void setDocumentCreator(final Document document) {
authContext.getAuthenticatedUser(UserDetails.class).ifPresent(user -> {
document.setCreator(user.getUsername());
});
}
private void setFieldsReadOnly(final boolean option) {
fileName.setReadOnly(option);
documentType.setReadOnly(option);
employeeComboBox.setReadOnly(option);
}
private void viewDocument() { private void viewDocument() {
StreamResource resource; Document document = getEntity();
try { if (document.getFileData() != null && document.getFileData().length > 0) {
InputStream inputStream = buffer.getInputStream(); String base64Data = Base64.getEncoder().encodeToString(document.getFileData());
if (inputStream != null && inputStream.available() > 0) { String jsCode = createJsCodeForDocument(base64Data);
resource = new StreamResource(fileName.getValue(), () -> new ByteArrayInputStream(readFileData())); getElement().executeJs(jsCode);
} else { } else {
byte[] fileData = getEntity().getFileData(); Notification.show("No file data available to view.");
resource = new StreamResource(fileName.getValue(), () -> new ByteArrayInputStream(fileData));
} }
resource.setContentType("application/pdf");
getUI().ifPresent(ui -> {
StreamRegistration registration = ui.getSession().getResourceRegistry().registerResource(resource);
ui.getPage().open(registration.getResourceUri().toString());
});
} catch (IOException e) {
Notification.show("Error reading file.");
} }
private String createJsCodeForDocument(final String base64Data) {
return "var byteCharacters = atob('" + base64Data + "');"
+ "var byteNumbers = new Array(byteCharacters.length);"
+ "for (var i = 0; i < byteCharacters.length; i++) {"
+ " byteNumbers[i] = byteCharacters.charCodeAt(i);"
+ "}"
+ "var byteArray = new Uint8Array(byteNumbers);"
+ "var blob = new Blob([byteArray], { type: 'application/pdf' });"
+ "var url = URL.createObjectURL(blob);"
+ "window.open(url, '_blank');";
}
private void closeForm() {
navigateToDocumentsListView();
} }
private void navigateToDocumentsListView() { private void navigateToDocumentsListView() {
getUI().ifPresent(ui -> ui.navigate(DocumentsListView.class)); getUI().ifPresent(ui -> ui.navigate(DocumentsListView.class));
} }
private void handleUploadSuccess() {
fileUploaded = true;
Notification.show("File uploaded successfully.");
viewDocumentButton.setEnabled(true);
}
private void saveDocument() { private void saveDocument() {
if (isFormValid()) { if (isFormValid()) {
Document document = getEntity(); Document document = getEntity();
@ -155,8 +167,10 @@ public class DocumentView extends BeanValidationForm<Document> implements HasUrl
} }
} }
private void closeForm() { private void setDocumentCreator(final Document document) {
navigateToDocumentsListView(); authContext.getAuthenticatedUser(UserDetails.class).ifPresent(user -> {
document.setCreator(user.getUsername());
});
} }
private boolean isFormValid() { private boolean isFormValid() {
@ -166,15 +180,6 @@ public class DocumentView extends BeanValidationForm<Document> implements HasUrl
&& fileUploaded; && fileUploaded;
} }
private void clearForm() {
fileName.clear();
documentType.clear();
employeeComboBox.clear();
fileUploaded = false;
uploadButton.getElement().setPropertyJson("files", Json.createArray());
viewDocumentButton.setEnabled(false);
}
private byte[] readFileData() { private byte[] readFileData() {
try { try {
return buffer.getInputStream().readAllBytes(); return buffer.getInputStream().readAllBytes();
@ -184,61 +189,29 @@ public class DocumentView extends BeanValidationForm<Document> implements HasUrl
} }
} }
private void clearForm() {
fileName.clear();
documentType.clear();
employeeComboBox.clear();
fileUploaded = false;
uploadButton.getElement().setPropertyJson("files", Json.createArray());
viewDocumentButton.setEnabled(false);
}
private void setFieldsReadOnly(final boolean option) {
fileName.setReadOnly(option);
documentType.setReadOnly(option);
employeeComboBox.setReadOnly(option);
}
private void preLoadFile(final Document document) { private void preLoadFile(final Document document) {
JsonArray jsonArray = Json.createArray(); JsonArray jsonArray = Json.createArray();
JsonObject jsonObject = Json.createObject(); JsonObject jsonObject = Json.createObject();
jsonObject.put("name", document.getFileName()); jsonObject.put("name", document.getFileName());
jsonObject.put("progress", 100); jsonObject.put("progress", 100);
jsonObject.put("complete", true); jsonObject.put("complete", true);
jsonObject.put("fileData", Base64.getEncoder().encodeToString(document.getFileData()));
jsonArray.set(0, jsonObject); jsonArray.set(0, jsonObject);
uploadButton.getElement().setPropertyJson("files", jsonArray); uploadButton.getElement().setPropertyJson("files", jsonArray);
fileUploaded = true;
}
private void updateSaveButtonState() {
boolean isModified = !fileName.getValue().equals(getEntity().getFileName())
|| documentType.getValue() != getEntity().getDocumentType()
|| employeeComboBox.getValue() != getEntity().getEmployee()
|| fileUploaded;
saveButton.setEnabled(isModified);
}
private void configureComponents() {
setFileNameProperties();
setDocumentTypeProperties();
setEmployeeComboBoxProperties();
fileName.addValueChangeListener(e -> updateSaveButtonState());
documentType.addValueChangeListener(e -> updateSaveButtonState());
employeeComboBox.addValueChangeListener(e -> updateSaveButtonState());
uploadButton.addSucceededListener(e -> updateSaveButtonState());
uploadButton.getElement().addEventListener("file-remove", event -> updateSaveButtonState());
}
private void configureUploadButton() {
uploadButton.setMaxFiles(1);
uploadButton.setAcceptedFileTypes(".pdf");
uploadButton.addSucceededListener(event -> {
fileUploaded = true;
updateSaveButtonState();
});
uploadButton.getElement().addEventListener("file-remove", event -> {
fileUploaded = false;
updateSaveButtonState();
});
}
private void configureViewOrEditAction(final String action, final String documentIdString) {
if ("edit".equals(action) && !documentIdString.isEmpty()) {
setFieldsReadOnly(false);
preLoadFile(getEntity());
viewDocumentButton.setEnabled(true);
} else if ("view".equals(action) && !documentIdString.isEmpty()) {
setFieldsReadOnly(true);
preLoadFile(getEntity());
saveButton.setEnabled(false);
viewDocumentButton.setEnabled(true);
}
} }
@Override @Override
@ -249,7 +222,6 @@ public class DocumentView extends BeanValidationForm<Document> implements HasUrl
if ("new".equals(action)) { if ("new".equals(action)) {
setEntityWithEnabledSave(new Document()); setEntityWithEnabledSave(new Document());
} else { } else {
assert documentIdString != null;
UUID documentId = UUID.fromString(documentIdString); UUID documentId = UUID.fromString(documentIdString);
Document document = documentService.getDocument(documentId); Document document = documentService.getDocument(documentId);
setEntity(document); setEntity(document);
@ -259,11 +231,22 @@ public class DocumentView extends BeanValidationForm<Document> implements HasUrl
} }
} }
private void configureViewOrEditAction(final String action, final String documentIdString) {
if ("edit".equals(action) && !documentIdString.isEmpty()) {
setFieldsReadOnly(false);
preLoadFile(getEntity());
} else if ("view".equals(action) && !documentIdString.isEmpty()) {
setFieldsReadOnly(true);
saveButton.setEnabled(false);
viewDocumentButton.setEnabled(true);
}
}
@Override @Override
protected List<Component> getFormComponents() { protected List<Component> getFormComponents() {
HorizontalLayout buttonLayout = new HorizontalLayout(); HorizontalLayout buttonLayout = new HorizontalLayout();
buttonLayout.add(uploadButton, createViewDocumentButton()); buttonLayout.add(uploadButton, createViewDocumentButton());
buttonLayout.setSpacing(true); buttonLayout.setSpacing(true);
return List.of(fileName, documentType, employeeComboBox, buttonLayout, createCloseButton()); return List.of(title, fileName, documentType, employeeComboBox, buttonLayout, createCloseButton());
} }
} }