-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathAlertComponent.java
More file actions
75 lines (60 loc) · 2.32 KB
/
Copy pathAlertComponent.java
File metadata and controls
75 lines (60 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package de.tschuehly.example.fragments;
import de.tschuehly.spring.viewcomponent.core.component.ViewComponent;
import de.tschuehly.spring.viewcomponent.thymeleaf.ViewContext;
/**
* Advanced example showing fragment rendering for alert messages.
*
* Demonstrates:
* - Different data requirements for different contexts (e.g., ErrorAlert has stackTrace)
* - Compile-time safety (can't create ErrorAlert without stackTrace)
* - Single template with multiple presentation variants
*/
@ViewComponent
public class AlertComponent {
/**
* Informational alert - simple message display
*/
public record InfoAlert(String message) implements ViewContext {}
/**
* Warning alert - message with additional details
*/
public record WarningAlert(String message, String details) implements ViewContext {}
/**
* Error alert - message with stack trace
*/
public record ErrorAlert(String message, String stackTrace) implements ViewContext {}
/**
* Success alert - simple message for successful operations
*/
public record SuccessAlert(String message) implements ViewContext {}
public InfoAlert info(String message) {
return new InfoAlert(message);
}
public WarningAlert warning(String message, String details) {
return new WarningAlert(message, details);
}
public ErrorAlert error(String message, String stackTrace) {
return new ErrorAlert(message, stackTrace);
}
public SuccessAlert success(String message) {
return new SuccessAlert(message);
}
/**
* Convenience method to create error alerts from exceptions
*/
public ErrorAlert error(String message, Exception exception) {
var stackTrace = buildStackTrace(exception);
return new ErrorAlert(message, stackTrace);
}
private String buildStackTrace(Exception exception) {
var sb = new StringBuilder();
sb.append(exception.getClass().getName()).append(": ").append(exception.getMessage()).append("\n");
for (var element : exception.getStackTrace()) {
sb.append(" at ").append(element.toString()).append("\n");
}
if (exception.getCause() != null) {
sb.append("Caused by: ").append(buildStackTrace((Exception) exception.getCause()));
}
return sb.toString();
}
}