Skip to content

Commit

Permalink
chore: Improve code robustness
Browse files Browse the repository at this point in the history
  • Loading branch information
TatuJLund committed Nov 2, 2024
1 parent da8e3ab commit f32fcf8
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.ValoTheme;

Expand All @@ -43,6 +44,8 @@ public class AboutView extends VerticalLayout
private Label adminsNote;
private TextArea admionsNoteField;

private UI ui;

public AboutView() {
var aboutContent = createAboutContent();

Expand Down Expand Up @@ -154,7 +157,7 @@ public void enter(ViewChangeEvent event) {
@Override
public void eventFired(Object event) {
if (event instanceof Message) {
getUI().access(() -> {
Utils.access(ui, () -> {
if (admionsNoteField.isVisible()) {
admionsNoteField.setVisible(false);
adminsNote.setVisible(true);
Expand All @@ -168,6 +171,12 @@ public void eventFired(Object event) {
}
}

@Override
public void attach() {
super.attach();
ui = getUI();
}

@Override
public void detach() {
super.detach();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ public class BasicAccessControl implements AccessControl {

@Override
public boolean signIn(String username, String password) {
Objects.requireNonNull(username, password);
Objects.requireNonNull(username);
Objects.requireNonNull(password);
Optional<User> user = VaadinCreateUI.get().getUserService()
.findByName(username);
if (!user.isPresent()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ public Product getSelectedRow() {
}

private String htmlFormatAvailability(Product product) {
assert product != null : "Product must not be null";

var availability = product.getAvailability();
var text = availability.toString();

Expand All @@ -144,6 +146,8 @@ private String htmlFormatAvailability(Product product) {
}

private String formatCategories(Product product) {
assert product != null : "Product must not be null";

if (product.getCategory() == null || product.getCategory().isEmpty()) {
return "";
}
Expand Down Expand Up @@ -215,6 +219,8 @@ private void adjustColumns(int width) {
}

private String createTooltip(Product book) {
assert book != null : "Book must not be null";

// This is not actually a tooltip, but on hover popup. Vaadin 8 allows
// to use HTML in tooltips. which makes it possible to use them like
// this. When migrating to newer generations of Vaadin, this kind of
Expand Down Expand Up @@ -248,6 +254,8 @@ private String createTooltip(Product book) {

// Helper method to create a span with a caption
private static String getDescriptionCaptionSpan(String caption) {
assert caption != null : "Caption must not be null";

return String.format("<span class='%s'>%s:</span> ",
VaadinCreateTheme.BOOKVIEW_GRID_DESCRIPTIONCAPTION, caption);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.io.Serializable;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
Expand Down Expand Up @@ -165,6 +166,8 @@ public void unlockBook() {
* the ID of the book to lock for editing
*/
private void lockBook(Product book) {
assert book != null : "Book must not be null";

if (editing != null) {
unlockBook();
}
Expand Down Expand Up @@ -192,8 +195,7 @@ public void enter(String productId) {
newProduct();
} else {
try {
int pid = Integer.parseInt(productId);
lockAndEditIfExistsAndIsUnlocked(productId, pid);
lockAndEditIfExistsAndIsUnlocked(productId);
} catch (NumberFormatException e) {
view.showNotValidId(productId);
logger.warn("Attempt to edit invalid id '{}'", productId);
Expand All @@ -207,7 +209,10 @@ public void enter(String productId) {
// selected in the view. If the product does not exist, a notification will
// be shown in the view. If the product exists but is locked, a notification
// will be shown in the view.
private void lockAndEditIfExistsAndIsUnlocked(String productId, int pid) {
private void lockAndEditIfExistsAndIsUnlocked(String productId) {
assert productId != null;

int pid = Integer.parseInt(productId);
Product product = findProduct(pid);
if (product != null) {
if (getLockedBooks().isLocked(product) == null) {
Expand Down Expand Up @@ -246,9 +251,11 @@ public Product findProduct(int productId) {
* Saves the given product
*
* @param product
* The product to be saved.
* The product to be saved, not null.
*/
public Product saveProduct(Product product) {
Objects.requireNonNull(product, "Product must not be null");

accessControl.assertAdmin();
view.clearSelection();
boolean newBook = product.getId() == null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,12 @@ public BooksView() {
presenter.init();
}

private boolean filterCondition(Object object, String filterText) {
return object != null && object.toString().toLowerCase()
// Filter the grid data based on the filter text
private static <T> boolean filterCondition(T value, String filterText) {
assert filterText != null : "Filter text cannot be null";
assert value != null : "Value cannot be null";

return value != null && value.toString().toLowerCase()
.contains(filterText.toLowerCase());
}

Expand All @@ -126,6 +130,9 @@ private boolean filterCondition(Object object, String filterText) {
* otherwise.
*/
private boolean passesFilter(Product book, String filterText) {
assert filterText != null : "Filter text cannot be null";
assert book != null : "Book cannot be null";

filterText = filterText.trim();
return filterCondition(book.getProductName(), filterText)
|| filterCondition(book.getAvailability(), filterText)
Expand Down Expand Up @@ -422,7 +429,7 @@ public void editProduct(Product product) {
if (product != null) {
// Ensure the product is up-to-date
if (product.getId() != null) {
product = refreshProduct(product);
product = updateProductInDataProvider(product);
if (product == null) {
showError(getTranslation(I18n.Books.PRODUCT_DELETED));
return;
Expand Down Expand Up @@ -549,7 +556,9 @@ private boolean canPush() {
&& grid.getDataProvider() instanceof ListDataProvider;
}

private Product refreshProduct(Product product) {
private Product updateProductInDataProvider(Product product) {
assert product != null : "Product cannot be null";

var list = ((List<Product>) dataProvider.getItems());
var updatedProduct = presenter.findProduct(product.getId());
if (updatedProduct != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ private void updateDirtyIndicators() {
});
}

private static String convertValue(Object value) {
private static <T> String convertValue(T value) {
if (value == null) {
return "";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,8 +161,7 @@ private Component buildLoginForm() {

forgotPassword = new Button(getTranslation(I18n.Login.FORGOT_PASSWORD));
buttons.addComponent(forgotPassword);
forgotPassword.addClickListener(event -> showNotification(
new Notification(getTranslation(I18n.Login.HINT))));
forgotPassword.addClickListener(event -> showHintNotification());
forgotPassword.addStyleName(ValoTheme.BUTTON_LINK);

lang = new LanguageSelect();
Expand All @@ -184,12 +183,12 @@ private Component buildLoginForm() {
}

private CssLayout buildLoginInformation() {
var layout = new CssLayout();
layout.setStyleName(VaadinCreateTheme.LOGINVIEW_INFORMATION);
var infoLayout = new CssLayout();
infoLayout.setStyleName(VaadinCreateTheme.LOGINVIEW_INFORMATION);
loginInfoText = new Label(getLoginInfoText(), ContentMode.HTML);
loginInfoText.setSizeFull();
layout.addComponent(loginInfoText);
return layout;
infoLayout.addComponent(loginInfoText);
return infoLayout;
}

// Attempt to log in the user and fire an event to notify listeners.
Expand All @@ -198,17 +197,26 @@ private void login() {
passwordField.getValue())) {
fireEvent(new LoginEvent(this));
} else {
showNotification(
new Notification(getTranslation(I18n.Login.LOGIN_FAILED),
getTranslation(I18n.Login.LOGIN_FAILED_DESC),
Notification.Type.HUMANIZED_MESSAGE));
showLoginFailedNotification();
usernameField.focus();
}
}

private void showNotification(Notification notification) {
// keep the notification visible a little while after moving the
// mouse, or until clicked
private void showHintNotification() {
var notification = new Notification(getTranslation(I18n.Login.HINT));
// keep the notification visible a little while after moving the mouse,
// or until clicked
notification.setDelayMsec(2000);
notification.show(Page.getCurrent());
}

private void showLoginFailedNotification() {
var notification = new Notification(
getTranslation(I18n.Login.LOGIN_FAILED),
getTranslation(I18n.Login.LOGIN_FAILED_DESC),
Notification.Type.HUMANIZED_MESSAGE);
// keep the notification visible a little while after moving the mouse,
// or until clicked
notification.setDelayMsec(2000);
notification.show(Page.getCurrent());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public class StatsPresenter implements EventBusListener, Serializable {

private StatsView view;
private transient CompletableFuture<Void> future;
private static final String PRODUCTS_NOT_NULL = "Products must not be null";

public StatsPresenter(StatsView view) {
this.view = view;
Expand Down Expand Up @@ -73,6 +74,7 @@ public void requestUpdateStats() {
// brackets and product counts
private Map<String, Long> calculatePriceStats(
Collection<Product> products) {
assert products != null : PRODUCTS_NOT_NULL;
return getPriceBrackets(products).stream()
.collect(Collectors.toMap(PriceBracket::toString,
priceBracket -> products.stream()
Expand All @@ -85,6 +87,7 @@ private Map<String, Long> calculatePriceStats(
// category names and product counts
private Map<String, Long[]> calculateCategoryStats(
ProductDataService service, Collection<Product> products) {
assert products != null : PRODUCTS_NOT_NULL;
return service.getAllCategories().stream()
.collect(Collectors.toMap(Category::getName, category -> {
long titles = products.stream().filter(
Expand All @@ -101,6 +104,7 @@ private Map<String, Long[]> calculateCategoryStats(
// availability statuses and product counts
private Map<Availability, Long> calculateAvailabilityStats(
Collection<Product> products) {
assert products != null : PRODUCTS_NOT_NULL;
return Arrays.stream(Availability.values()).map(availability -> Map
.entry(availability, products.stream().filter(
product -> product.getAvailability() == availability)
Expand All @@ -118,6 +122,8 @@ public void cancelUpdateStats() {
}

private List<PriceBracket> getPriceBrackets(Collection<Product> products) {
assert products != null : PRODUCTS_NOT_NULL;

var brackets = new ArrayList<PriceBracket>();
var max = products.stream()
.max((p1, p2) -> p1.getPrice().compareTo(p2.getPrice())).get()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ private CssLayout createAvailabilityChart() {
}

private static void configureTooltip(Configuration conf) {
assert conf != null : "Configuration must not be null";
conf.getTooltip()
.setBackgroundColor(new SolidColor("rgba(50,50,50,0.9)"));
conf.getTooltip().getStyle().setColor(new SolidColor("white"));
Expand Down Expand Up @@ -152,6 +153,8 @@ public void updateStatsAsync(Map<Availability, Long> availabilityStats,

// Update the charts with the new data
private void updatePriceChart(Map<String, Long> priceStats) {
assert priceStats != null : "Price stats must not be null";

var priceSeries = priceSeries(priceStats);
priceSeries.setName(getTranslation(I18n.Stats.COUNT));
var conf = priceChart.getConfiguration();
Expand All @@ -160,6 +163,7 @@ private void updatePriceChart(Map<String, Long> priceStats) {

// Update the charts with the new data
private void updateCategoryChart(Map<String, Long[]> categoryStats) {
assert categoryStats != null : "Category stats must not be null";
var conf = categoryChart.getConfiguration();

// Show count of titles on primary axis
Expand All @@ -185,6 +189,8 @@ private void updateCategoryChart(Map<String, Long[]> categoryStats) {
// Update the charts with the new data
private void updateAvailabilityChart(
Map<Availability, Long> availabilityStats) {
assert availabilityStats != null : "Availability stats must not be null";

var availabilitySeries = availabilitySeries(availabilityStats);
availabilitySeries.setName(getTranslation(I18n.Stats.COUNT));
var conf = availabilityChart.getConfiguration();
Expand All @@ -198,6 +204,8 @@ private void updateAvailabilityChart(

private DataSeries categorySeries(Map<String, Long[]> categories,
int index) {
assert categories != null : "Categories must not be null";

var series = new DataSeries();
categories.forEach((category, count) -> {
var item = new DataSeriesItem(category, count[index]);
Expand All @@ -209,6 +217,8 @@ private DataSeries categorySeries(Map<String, Long[]> categories,

private DataSeries availabilitySeries(
Map<Availability, Long> availabilities) {
assert availabilities != null : "Availabilities must not be null";

var series = new DataSeries();
availabilities.forEach((availability, count) -> {
var item = new DataSeriesItem(availability.name(), count);
Expand All @@ -220,6 +230,8 @@ private DataSeries availabilitySeries(
}

private static SolidColor toColor(Availability availability) {
assert availability != null : "Availability must not be null";

String color;
switch (availability) {
case COMING:
Expand All @@ -236,6 +248,8 @@ private static SolidColor toColor(Availability availability) {
}

private DataSeries priceSeries(Map<String, Long> prices) {
assert prices != null : "Prices must not be null";

var series = new DataSeries();
prices.forEach((pricebracket, count) -> {
var item = new DataSeriesItem(pricebracket, count);
Expand Down

0 comments on commit f32fcf8

Please sign in to comment.