Customise TableCell in a tableView in javafx - uitableview
Let's consider we have the following informations :
As you see an article can be stored in many stores, and vice versa : a store can store many articles : that's the class model (UML )
some code :
FXML Part :
#FXML
private TableView<Article> tblArticles;
#FXML
private TableColumn<Article, String> colStore;
#FXML
private TableColumn<Article, Integer> colQuantity;
getters and setter :
colStore.setCellValueFactory(new PropertyValueFactory<>("store"));
colStore.setCellValueFactory(new PropertyValueFactory<>("quantity"));
I recieve the result seen in the first table but I am not able to do what is in the second table .
And what I want exactly should give the following informations :
So my question is it possible to do this in a TableView ?
Here is a sample app. It follows an MVVM style, which is appropriate for this kind of work. The app was built using Java 13 and will not work in earlier Java versions such as Java 8. It's a relatively long answer, but, ah well, sometimes that is what it takes.
The overall approach is not to create a tableview row for each store that an article is stored in. Instead, we just create a row for each article and we have a custom cell renderer which produces a single formatted cell for all the stores and quantities that that item is stored at.
Now, you could do an alternative implementation based upon a custom rowFactory. However, I do not recommend that approach for this particular task, as I believe it would be unnecessarily complicated to implement and maintain, without providing sufficient value.
Another way to do this is to use nested columns. This approach, when appropriate care is taken, does allow you to create a tableview row for each store that an article is stored in. If you do this, you need some way of populating different data depending on whether a row is either the first row in the group or not. You don't allow the user to reorder and sort data in the table, as that would be quite difficult to cater for because the notion of what is the "first row in the group" would be forever changing. To allow for appropriate rendering with nested columns, you end up with a slightly different view model (the FlatLineItem class below and the accompanying method in the LineItemService that retrieves them).
The image below demonstrates the output of a TableView with a custom cell renderer on the left and a TableView using nested columns on the right. Note how the selection works differently in each case. On the left when a row is selected, it includes all the stores that attached to that row. On the right when the nested columns are used, the row selection is only selecting a row for a given store.
Main application class
This sets up a couple of TableViews.
For the first table view, all it does is create a TableView with a column for each of the elements to be displayed. All the data is extracted from a LineItem view model class using a standard PropertyValueFactory. The slightly different thing is a custom cell renderer for a StoredQuantity field via the StoredQuantityTableCell, this is explained later.
The second view uses nested columns and works based upon the FlatLineItem view model class, also using a standard PropertyValueFactory and uses no custom cell renderer.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.util.List;
public class AggregateViewApp extends Application {
#Override
public void start(Stage stage) throws Exception {
LineItemService lineItemService = new LineItemService();
TableView<LineItem> tableView = createArticleTableView();
tableView.getItems().setAll(lineItemService.fetchAllLineItems());
TableView<FlatLineItem> nestedTableView = createNestedArticleTableView();
nestedTableView.getItems().setAll(lineItemService.fetchAllFlatLineItems());
HBox layout = new HBox(
40,
tableView,
nestedTableView
);
stage.setScene(new Scene(layout));
stage.show();
}
#SuppressWarnings("unchecked")
private TableView<LineItem> createArticleTableView() {
TableView tableView = new TableView();
TableColumn<LineItem, Long> articleIdCol = new TableColumn<>("Article ID");
articleIdCol.setCellValueFactory(new PropertyValueFactory<>("articleId"));
TableColumn<LineItem, String> nameCol = new TableColumn<>("Name");
nameCol.setCellValueFactory(new PropertyValueFactory<>("articleName"));
TableColumn<LineItem, List<StoredQuantity>> storedArticleCol = new TableColumn<>("Store Quantities");
storedArticleCol.setCellValueFactory(new PropertyValueFactory<>("storedQuantities"));
storedArticleCol.setCellFactory(lineItemStringTableColumn -> new StoredQuantityTableCell());
TableColumn<LineItem, DB.StoredArticle> totalCol = new TableColumn<>("Total");
totalCol.setCellValueFactory(new PropertyValueFactory<>("total"));
tableView.getColumns().addAll(articleIdCol, nameCol, storedArticleCol, totalCol);
tableView.setPrefSize(400, 150);
return tableView;
}
#SuppressWarnings("unchecked")
private TableView<FlatLineItem> createNestedArticleTableView() {
TableView tableView = new TableView();
TableColumn<FlatLineItem, Long> articleIdCol = new TableColumn<>("Article ID");
articleIdCol.setCellValueFactory(new PropertyValueFactory<>("articleId"));
articleIdCol.setSortable(false);
TableColumn<FlatLineItem, String> nameCol = new TableColumn<>("Name");
nameCol.setCellValueFactory(new PropertyValueFactory<>("articleName"));
nameCol.setSortable(false);
TableColumn<FlatLineItem, String> storeCol = new TableColumn<>("Store");
storeCol.setCellValueFactory(new PropertyValueFactory<>("storeName"));
storeCol.setSortable(false);
TableColumn<FlatLineItem, String> storeQuantityCol = new TableColumn<>("Quantity");
storeQuantityCol.setCellValueFactory(new PropertyValueFactory<>("storeQuantity"));
storeQuantityCol.setSortable(false);
TableColumn<FlatLineItem, List<StoredQuantity>> storedArticleCol = new TableColumn<>("Store Quantities");
storedArticleCol.getColumns().setAll(
storeCol,
storeQuantityCol
);
storedArticleCol.setSortable(false);
TableColumn<LineItem, DB.StoredArticle> totalCol = new TableColumn<>("Total");
totalCol.setCellValueFactory(new PropertyValueFactory<>("total"));
totalCol.setSortable(false);
tableView.getColumns().setAll(articleIdCol, nameCol, storedArticleCol, totalCol);
tableView.setPrefSize(400, 200);
return tableView;
}
public static void main(String[] args) {
launch(AggregateViewApp.class);
}
}
StoredQuantityTableCell.java
This takes a list of StoredQuantities which is a tuple of a store name and a quantity of things stored at that store and then renders that list into a single cell, formatting the display internally in a GridView. You could use whatever internal node layout or formatting you wish and add CSS styling to spice things up if necessary.
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.layout.GridPane;
import java.util.List;
class StoredQuantityTableCell extends TableCell<LineItem, List<StoredQuantity>> {
private GridPane storedQuantityPane;
public StoredQuantityTableCell() {
storedQuantityPane = new GridPane();
storedQuantityPane.setHgap(10);
storedQuantityPane.setVgap(5);
}
#Override
protected void updateItem(List<StoredQuantity> storedQuantities, boolean empty) {
super.updateItem(storedQuantities, empty);
if (storedQuantities == null) {
setGraphic(null);
return;
}
storedQuantityPane.getChildren().removeAll(storedQuantityPane.getChildren());
int row = 0;
for (StoredQuantity storedQuantity: storedQuantities) {
storedQuantityPane.addRow(
row,
new Label(storedQuantity.getStoreName()),
new Label("" + storedQuantity.getQuantity())
);
row++;
}
setGraphic(storedQuantityPane);
}
}
LineItem.java
A view model class representing a row in the table.
import java.util.Collections;
import java.util.List;
public class LineItem {
private long articleId;
private String articleName;
private List<StoredQuantity> storedQuantities;
public LineItem(long articleId, String articleName, List<StoredQuantity> storedQuantities) {
this.articleId = articleId;
this.articleName = articleName;
this.storedQuantities = storedQuantities;
}
public long getArticleId() {
return articleId;
}
public String getArticleName() {
return articleName;
}
public List<StoredQuantity> getStoredQuantities() {
return Collections.unmodifiableList(storedQuantities);
}
public int getTotal() {
return storedQuantities.stream()
.mapToInt(StoredQuantity::getQuantity)
.sum();
}
}
StoredQuantity.java
A view model class representing a store name and quantity of things in the store. This is used by the StoredQuantityTableCell to render the stored quantities for a line item.
public class StoredQuantity implements Comparable<StoredQuantity> {
private String storeName;
private int quantity;
StoredQuantity(String storeName, int quantity) {
this.storeName = storeName;
this.quantity = quantity;
}
public String getStoreName() {
return storeName;
}
public int getQuantity() {
return quantity;
}
#Override
public int compareTo(StoredQuantity o) {
return storeName.compareTo(o.storeName);
}
}
FlatLineItem.java
A view model class supporting a table view with nested columns. A flat line item which can be created for each store that an article is stored in.
public class FlatLineItem {
private Long articleId;
private String articleName;
private final String storeName;
private final Integer storeQuantity;
private final Integer total;
private final boolean firstInGroup;
public FlatLineItem(Long articleId, String articleName, String storeName, Integer storeQuantity, Integer total, boolean firstInGroup) {
this.articleId = articleId;
this.articleName = articleName;
this.storeName = storeName;
this.storeQuantity = storeQuantity;
this.total = total;
this.firstInGroup = firstInGroup;
}
public Long getArticleId() {
return articleId;
}
public String getArticleName() {
return articleName;
}
public String getStoreName() {
return storeName;
}
public Integer getStoreQuantity() {
return storeQuantity;
}
public Integer getTotal() {
return total;
}
public boolean isFirstInGroup() {
return firstInGroup;
}
}
LineItemService.java
This translates values from the database into view model objects (LineItems or FlatLineItems) which can be rendered by the views. Note how the getFlatLineItemsForLineItem which constructs the FlatLineItems for the nested column table view has a notion of what it the first row in a group of line items and propagates the the FlatLineItem appropriately based on that, leaving some values null if they are just repeated from the first item in the group, which results in a clean display.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class LineItemService {
private final DB db = DB.instance();
public List<LineItem> fetchAllLineItems() {
return db.findAllArticles()
.stream()
.map(article -> createLineItemForArticle(article.getArticleId()))
.collect(Collectors.toList());
}
public List<FlatLineItem> fetchAllFlatLineItems() {
return fetchAllLineItems().stream()
.flatMap(lineItem -> getFlatLineItemsForLineItem(lineItem).stream())
.collect(Collectors.toList());
}
private List<FlatLineItem> getFlatLineItemsForLineItem(LineItem lineItem) {
ArrayList<FlatLineItem> flatLineItems = new ArrayList<>();
boolean firstStore = true;
for (StoredQuantity storedQuantity: lineItem.getStoredQuantities()) {
FlatLineItem newFlatLineItem;
if (firstStore) {
newFlatLineItem = new FlatLineItem(
lineItem.getArticleId(),
lineItem.getArticleName(),
storedQuantity.getStoreName(),
storedQuantity.getQuantity(),
lineItem.getTotal(),
true
);
firstStore = false;
} else {
newFlatLineItem = new FlatLineItem(
null,
null,
storedQuantity.getStoreName(),
storedQuantity.getQuantity(),
null,
false
);
}
flatLineItems.add(newFlatLineItem);
}
return flatLineItems;
}
private LineItem createLineItemForArticle(long articleId) {
DB.Article article =
db.findArticleById(
articleId
).orElse(
new DB.Article(articleId, "N/A")
);
List<DB.StoredArticle> storedArticles =
db.findAllStoredArticlesForArticleId(articleId);
return new LineItem(
article.getArticleId(),
article.getName(),
getStoredQuantitesForStoredArticles(storedArticles)
);
}
private List<StoredQuantity> getStoredQuantitesForStoredArticles(List<DB.StoredArticle> storedArticles) {
return storedArticles.stream()
.map(storedArticle ->
new StoredQuantity(
db.findStoreById(storedArticle.getStoreId())
.map(DB.Store::getName)
.orElse("No Store"),
storedArticle.getQuantity()
)
)
.sorted()
.collect(
Collectors.toList()
);
}
}
Mock database class
Just a simple in-memory representation of the database class. In a real app, you would probably use something like SpringData with hibernate to provide the data access repositories using a JPA based object to relational mapping.
The database classes aren't related to the view at all but are just presented here so that a running app can be created within a MVVM style framework.
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
class DB {
private static final DB instance = new DB();
public static DB instance() {
return instance;
}
private List<Article> articles = List.of(
new Article(1, "Hp101"),
new Article(3, "Lenovo303"),
new Article(4, "Asus404")
);
private List<Store> stores = List.of(
new Store(1, "S1"),
new Store(2, "S2")
);
private List<StoredArticle> storedArticles = List.of(
new StoredArticle(1, 1, 30),
new StoredArticle(1, 2, 70),
new StoredArticle(3, 1, 50),
new StoredArticle(4, 2, 70)
);
public Optional<Article> findArticleById(long articleId) {
return articles.stream()
.filter(article -> article.getArticleId() == articleId)
.findFirst();
}
public Optional<Store> findStoreById(long storeId) {
return stores.stream()
.filter(store -> store.getStoreId() == storeId)
.findFirst();
}
public List<StoredArticle> findAllStoredArticlesForArticleId(long articleId) {
return storedArticles.stream()
.filter(storedArticle -> storedArticle.articleId == articleId)
.collect(Collectors.toList());
}
public List<Article> findAllArticles() {
return Collections.unmodifiableList(articles);
}
static class Article {
private long articleId;
private String name;
public Article(long articleId, String name) {
this.articleId = articleId;
this.name = name;
}
public long getArticleId() {
return articleId;
}
public String getName() {
return name;
}
}
static class Store {
private long storeId;
private String name;
public Store(long storeId, String name) {
this.storeId = storeId;
this.name = name;
}
public long getStoreId() {
return storeId;
}
public String getName() {
return name;
}
}
static class StoredArticle {
private long articleId;
private long storeId;
private int quantity;
public StoredArticle(long articleId, long storeId, int quantity) {
this.articleId = articleId;
this.storeId = storeId;
this.quantity = quantity;
}
public long getArticleId() {
return articleId;
}
public long getStoreId() {
return storeId;
}
public int getQuantity() {
return quantity;
}
}
}
Answers to some follow-up questions
Which Approach is the best for updating data ?
All of the approaches I have shown use read only data models and views. To make it read-write would be a bit more work (and out of scope for what I would be prepared to add to this already long answer). Probably, of the two approaches outlined above, the approach which uses a separate row for each store containing an item would be the easiest to adapt to making the data updatable.
Which approach in general I should use to update data ( data are stored for sure in db) ?
Defining a general approach to updating data in a database is out of scope for what I would answer here (it is a purely opinion based answer, as there are many different ways to accomplish this, and as such is off topic for StackOverflow). If it were me, I'd set up a SpringBoot based rest service that connected to the database and have my client app communicate with that. If the app does not need to communicate over the internet, but only communicate with a local DB over a LAN, then adding direct database access by making the app a SpringBoot app and using Spring Data repositories with the embedded H2 database is what I would use.
Is when modifying in a specific row modify in db or wait until user modify in the whole tableview and click on a save button ?
Either way would work, I don't have any strong opinion on one versus the other. I'd probably lean towards the immediate update scenario rather than a delayed save scenario, but it would depend on the app and desired user experience.
Please can you provide me with some code for either to draw a line under every cell or to make it just like usual tableView ( one row gray and one not etc ...)
You can ask that as a separate question. But, in general, use CSS styling. If you use the second approach outlined above which has a row per store, then everything is already a "usual tableView" in terms of styling, with one row gray and one row not, etc., so I don't know that any additional styling is really required in such a case.
Related
dom-if element not hiding when condition is false
In a grid I want to display different elements. Depending on the type of the element I want to use a different TemplateRenderer. One solution to this problem would be to use dom-if elements in the template. if the «if» parameter is false, the element should not get rendered. The problem is, that in my templates all the elements get rendered, even though the debugger shows me that the method, that is responsible for determining the truth value, sometimes returns false. every template gets rendered twice Here is my code for the grid: // these are the two javascript templates #JsModule("./src/views/parts/card/graphics-card-card.js") #JsModule("./src/views/parts/card/memory-card.js") public class PcPartsDomIfGrid extends Grid<AbstractPcPart> { private static final long serialVersionUID = 7474489703766322949L; public PcPartsDomIfGrid() { super(); initColumn(); } private boolean isMemory(AbstractPcPart pcPart) { return pcPart.getClass().equals(Memory.class); } private boolean isGraphicsCard(AbstractPcPart pcPart) { return pcPart.getClass().equals(GraphicsCard.class); } private void initColumn() { addColumn(Objects.requireNonNull(CardFactory.getTemplate()) .withProperty("partCard", CardFactory::create) .withProperty("isMemory", this::isMemory) .withProperty("isGraphicsCard", this::isGraphicsCard)); } } Here is the Code for the Factory: public class CardFactory { public static AbstractPcPartCard create(AbstractPcPart pcPart) { if (pcPart.getClass().equals(GraphicsCard.class)) { return GraphicsCardCard.create((GraphicsCard) pcPart); } else if (pcPart.getClass().equals(Memory.class)) { return MemoryCard.create((Memory) pcPart); } else { // different PC parts return null; } } public static TemplateRenderer<AbstractPcPart> getTemplate() { String memoryTemplate = MemoryCard.getTemplateString(); String graphicsCardTemplate = GraphicsCardCard.getTemplateString(); String combinedTemplate = memoryTemplate + graphicsCardTemplate; return TemplateRenderer.of(combinedTemplate); } } Both MemoryCard and GraphicsCardCard are similar, here is the code for MemoryCard: public class MemoryCard extends AbstractPcPartCard { Memory pcPart; public MemoryCard(Memory pcPart) { this.pcPart = pcPart; } public static MemoryCard create(Memory pcPart) { return new MemoryCard(pcPart); } // getters public static String getTemplateString() { return "<memory-card is='dom-if' if='[[item.isMemory]]'" + " part-card='[[item.partCard]]'>" + "</memory-card>"; } } The complete code can be found on github. The relevant view is located in the package: com.example.application.ui.views.partsDomIf
The dom-if attribute must be used on a <template> tag, such as <template is='dom-if' if='[[item.important]]'>this is shown when the item is <b>important</b></template> <template is='dom-if' if='[[!item.important]]'>this is shown when the item is <b>NOT important</b></template> Note that the !property.name negation is the only logical operation available, you can't use e.g. comparators there. The pattern of using a factory method CardFactory::create also does not make much sense to me. The Grid receives a list of items through the DataProvider (either through setItems or setDataProvider) and the Renderer just processes those items to show them in the UI. You should not create new data objects in the Renderer if you can avoid it.
How to create a Grid without POJO (dynamic columns)?
The question was asked here: https://vaadin.com/forum/thread/18095407/how-to-create-a-grid-without-binder However the vaadin's forum closed so i want to continue it here. On Vaadin 14, Any recommendation on the best way to implement grid with dynamic varying number of columns. Using column Index (1,2,3...) is not a good choice for me. Let say I have a simple Json file (only 1 level: key-value) to map to a grid and this Json has an unknown list of properties. which approach is better in term of performance ?: [Option 1] class Data { private Map<String, Object> values = new HashMap<>(); public void set(String key, Object val) { values.put(key, val); } public Object get(String key) { return values.get(key); } } Grid<Data> myGrid = new Grid<>(); [Option 2] public class GridDynamicValueProvider implements ValueProvider<GridDynamicRow, Object> { private int columnIndex; public GridDynamicValueProvider(int columnIndex) { this.columnIndex = columnIndex; } #Override public Object apply(GridDynamicRow dynamicRow) { return dynamicRow.getValue(columnIndex); } } public class GridDynamicRow { private List<Object> values = new ArrayList<>(); public void addValue(String value) { values.add(value); } public Object getValue(int columnIndex) { return values.get(columnIndex); } }
The SerializablePredicate of Vaadin accepts both function references and Lambdas, thus it is possible to use non-POJO data types with Grid and Binder in Vaadin, although that is a bit unconventional. The key ingredients are: Grid<Map<String, Integer>> grid = new Grid<>(); ... grid.addColumn(map -> map.get("column")).setHeader("Column"); You can also wrap the Map in custom class if you have need to protect the internals. class Data { private Map<String, Object> values = new HashMap<>(); public void set(String key, Object val) { values.put(key, val); } public Object get(String key) { return values.get(key); } } Grid<Data> myGrid = new Grid<>(); As for the performance, essentially, you're comparing between using a List where you fetch by index versus a HashMap where you fetch by key. Here's a related question: ArrayList .get faster than HashMap .get? You can use also ArrayList as Grid's type if you can index the columns with a number. The both approaches allow generating Grid's with varying dynamic number of columns, for example if you read the data directly from a file or have raw data backend queries.
Save a list in a property in an entity in xodus
I have not found how to save a general list of primitive types, e.g. ints, or strings, in a property of an entity. I might have missed something obvious... https://github.com/JetBrains/xodus/wiki/Entity-Stores described that "only Java primitive types, Strings, and ComparableSet values can be used by default". It seems not hard to convert an Iterable into a ComparableSet. However it is a Set. I will take a look into PersistentEntityStore.registerCustomPropertyType() to see if that helps. I just feel wrong to do that to just save a list of integers. Links seemed to be able to serve as a way of saving a list of Entitys. But it seems there is no addProperty() counterpart to addLink(). Appreciated if some one can share a way or a workaround for this, or maybe why this is not supported. Thanks
As mentioned in the comments, one workaround I came up with was to create a ComparableList, by adopting code from ComparableSet. The idea was to make a list that is able to convert to and from an ArrayByteIterable, and register it with .registerCustomPropertyType(). To do that, 2 classes are needed, ComparableList and ComparableListBinding. I'm sharing one iteration I used at the bottom. By the way, I made them immutable, comparing to the mutable ComparableSet. The newly implemented types should be registered once in a transaction of the store before using them. That should allow you to store and retrieve a list. However the items in ComparableList would not get indexed as they would when saved in a ComparableSet -- there are some special treatment for ComparableSet in the entity store implementation. So without modifying the library, indexing would work only with hacks like creating another property to just index the values. I was considering to implement a different entity store that could better support lists, on top of the xodus key-value store, bypassing the xodus entity store entirely. That might be a better solution to the list issue we are talking about here. ComparableList: #SuppressWarnings("unchecked") public class ComparableList<T extends Comparable<T>> implements Comparable<ComparableList<T>>, Iterable<T> { #Nonnull private final ImmutableList<T> list; public ComparableList(#Nonnull final Iterable<T> iterable) { list = ImmutableList.copyOf(iterable); } #Override public int compareTo(#Nonnull final ComparableList<T> other) { final Iterator<T> thisIt = list.iterator(); final Iterator<T> otherIt = other.list.iterator(); while (thisIt.hasNext() && otherIt.hasNext()) { final int cmp = thisIt.next().compareTo(otherIt.next()); if (cmp != 0) { return cmp; } } if (thisIt.hasNext()) { return 1; } if (otherIt.hasNext()) { return -1; } return 0; } #NotNull #Override public Iterator<T> iterator() { return list.iterator(); } #Nullable public Class<T> getItemClass() { final Iterator<T> it = list.iterator(); return it.hasNext() ? (Class<T>) it.next().getClass() : null; } #Override public String toString() { return list.toString(); } } ComparableListBinding: #SuppressWarnings({"unchecked", "rawtypes"}) public class ComparableListBinding extends ComparableBinding { public static final ComparableListBinding INSTANCE = new ComparableListBinding(); private ComparableListBinding() {} #Override public ComparableList readObject(#NotNull final ByteArrayInputStream stream) { final int valueTypeId = stream.read() ^ 0x80; final ComparableBinding itemBinding = ComparableValueType.getPredefinedBinding(valueTypeId); final ImmutableList.Builder<Comparable> builder = ImmutableList.builder(); while (stream.available() > 0) { builder.add(itemBinding.readObject(stream)); } return new ComparableList(builder.build()); } #Override public void writeObject(#NotNull final LightOutputStream output, #NotNull final Comparable object) { final ComparableList<? extends Comparable> list = (ComparableList) object; final Class itemClass = list.getItemClass(); if (itemClass == null) { throw new ExodusException("Attempt to write empty ComparableList"); } final ComparableValueType type = ComparableValueType.getPredefinedType(itemClass); output.writeByte(type.getTypeId()); final ComparableBinding itemBinding = type.getBinding(); list.forEach(o -> itemBinding.writeObject(output, o)); } /** * De-serializes {#linkplain ByteIterable} entry to a {#code ComparableList} value. * * #param entry {#linkplain ByteIterable} instance * #return de-serialized value */ public static ComparableList entryToComparableList(#NotNull final ByteIterable entry) { return (ComparableList) INSTANCE.entryToObject(entry); } /** * Serializes {#code ComparableList} value to the {#linkplain ArrayByteIterable} entry. * * #param object value to serialize * #return {#linkplain ArrayByteIterable} entry */ public static ArrayByteIterable comparableSetToEntry(#NotNull final ComparableList object) { return INSTANCE.objectToEntry(object); } }
Vaadin 11: refreshAll (again)
here is a good thread about DataProvider.refreshAll() on Vaadin 8.5.1, but it doesn't seem to work this way in Vaadin 11. I used this starter app to play around. It displays some imaginary product data in a grid. At first, I added a refresh command to SampleCrudView: public HorizontalLayout createTopBar() { ... HorizontalLayout topLayout = new HorizontalLayout(); Button btn = new Button("refresh"); btn.addClickListener(event -> dataProvider.refreshAll()); topLayout.add(btn); ... return topLayout; } The folks from vaadin override getId() in their ProductDataProvider like this to use it as an object identifier: #Override public Integer getId(Product product) { Objects.requireNonNull(product, "Cannot provide an id for a null product."); return product.getId(); } That ProductDataProvider extends ListDataProvider, which is initialized on startup with data from MockDataService, so that we always deal with the same objects. I changed that: public class MockDataService extends DataService { ... #Override public synchronized List<Product> getAllProducts() { //added -> MockDataGenerator.resetProductCounter(); //this one sets nextProductId = 1 products = MockDataGenerator.createProducts(categories); products.stream().forEach(p -> System.out.println(p.getId() + ", " + p.getProductName())); //<- added return products; } So now you will get new Product instances within the same ID range every time you call getAllProducts(): public class ProductDataProvider extends ListDataProvider<Product> { ... #Override public Stream<Product> fetch(Query<Product, SerializablePredicate<Product>> query) { //added -> this.getItems().clear(); this.getItems().addAll(DataService.get().getAllProducts()); //<- added return super.fetch(query); } So the point is, this doesn't work - the data in the grid is still the same after "refresh" has been clicked. Any suggestions? Regards, m_OO_m
This is caused by a bug that was fixed a couple a days ago. The fix will be included in the next maintenance release.
Displaying Many Jira issues using Issue Navigator
My question is similar to "Displaying Jira issues using Issue Navigator" But my concern is that sometimes my list of issues is quite long and providing the user with a link to the Issue Navigator only works if my link is shorter than the max length of URLs. Is there another way? Cookies? POST data? Perhaps programmatically creating and sharing a filter on the fly, and returning a link to the Issue Navigator that uses this filter? (But at some point I'd want to delete these filters so I don't have so many lying around.) I do have the JQL query for getting the same list of issues, but it takes a very (very) long time to run and my code has already done the work of finding out what the result is -- I don't want the user to wait twice for the same thing (once while I'm generating my snazzy graphical servlet view and a second time when they want to see the same results in the Issue Navigator).
The easiest way to implement this is to ensure that the list of issues is cached somewhere within one of your application components. Each separate list of issues should be identified by its own unique ID (the magicKey below) that you define yourself. You would then write your own JQL function that looks up your pre-calculated list of issues by that magic key, which then converts the list of issues into the format that the Issue Navigator requires. The buildUriEncodedJqlQuery() method can be used to create such an example JQL query dynamically. For example, if the magic key is 1234, it would yield this JQL query: issue in myJqlFunction(1234). You'd then feed the user a URL that looks like this: String url = "/secure/IssueNavigator.jspa?mode=hide&reset=true&jqlQuery=" + MyJqlFunction.buildUriEncodedJqlQuery(magicKey); The end result is that the user will be placed in the Issue Navigator looking at exactly the list of issues your code has provided. This code also specifically prevents the user from saving your JQL function as part of a saved filter, since it's assumed that the issue cache in your application will not be permanent. If that's not correct, you will want to empty out the sanitiseOperand part. In atlassian-plugins.xml: <jql-function key="myJqlFunction" name="My JQL Function" class="com.mycompany.MyJqlFunction"> </jql-function> JQL function: import com.atlassian.crowd.embedded.api.User; import com.atlassian.jira.JiraDataType; import com.atlassian.jira.JiraDataTypes; import com.atlassian.jira.jql.operand.QueryLiteral; import com.atlassian.jira.jql.query.QueryCreationContext; import com.atlassian.jira.plugin.jql.function.ClauseSanitisingJqlFunction; import com.atlassian.jira.plugin.jql.function.JqlFunction; import com.atlassian.jira.plugin.jql.function.JqlFunctionModuleDescriptor; import com.atlassian.jira.util.MessageSet; import com.atlassian.jira.util.MessageSetImpl; import com.atlassian.jira.util.NotNull; import com.atlassian.query.clause.TerminalClause; import com.atlassian.query.operand.FunctionOperand; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MyJqlFunction implements JqlFunction, ClauseSanitisingJqlFunction { private static final String JQL_FUNCTION_NAME = "myJqlFunctionName"; private static final int JQL_FUNCTION_MIN_ARG_COUNT = 1; private static final int JQL_FUNCTION_MAGIC_KEY_INDEX = 0; public MyJqlFunction() { // inject your app's other components here } #Override public void init(#NotNull JqlFunctionModuleDescriptor moduleDescriptor) { } #Override public JiraDataType getDataType() { return JiraDataTypes.ISSUE; } #Override public String getFunctionName() { return JQL_FUNCTION_NAME; } #Override public int getMinimumNumberOfExpectedArguments() { return JQL_FUNCTION_MIN_ARG_COUNT; } #Override public boolean isList() { return true; } /** * This function generates a URL-escaped JQL query that corresponds to the supplied magic key. * * #param magicKey * #return */ public static String buildUriEncodedJqlQuery(String magicKey) { return "issue%20in%20" + JQL_FUNCTION_NAME + "(%22" + magicKey + "%22%)"; } #Override public List<QueryLiteral> getValues(#NotNull QueryCreationContext queryCreationContext, #NotNull FunctionOperand operand, #NotNull TerminalClause terminalClause) { User searchUser = queryCreationContext.getUser(); MessageSet messages = new MessageSetImpl(); List<QueryLiteral> values = internalGetValues(searchUser, operand, terminalClause, messages, !queryCreationContext.isSecurityOverriden()); return values; } private List<QueryLiteral> internalGetValues(#NotNull User searchUser, #NotNull FunctionOperand operand, #NotNull TerminalClause terminalClause, #NotNull MessageSet messages, #NotNull Boolean checkSecurity) { List<QueryLiteral> result = new ArrayList<QueryLiteral>(); if (searchUser==null) { // handle anon user } List<String> args = operand.getArgs(); if (wasSanitised(args)) { messages.addErrorMessage("this function can't be used as part of a saved filter etc"); return result; } if (args.size() < getMinimumNumberOfExpectedArguments()) { messages.addErrorMessage("too few arguments, etc"); return result; } final String magicKey = args.get(JQL_FUNCTION_MAGIC_KEY_INDEX); // You need to implement this part yourself! This is where you use the supplied // magicKey to fetch a list of issues from your own internal data source. List<String> myIssueKeys = myCache.get(magicKey); for (String id : myIssueKeys) { result.add(new QueryLiteral(operand, id)); } return result; } #Override public MessageSet validate(User searcher, #NotNull FunctionOperand operand, #NotNull TerminalClause terminalClause) { MessageSet messages = new MessageSetImpl(); internalGetValues(searcher, operand, terminalClause, messages, true); return messages; } #Override public FunctionOperand sanitiseOperand(User paramUser, #NotNull FunctionOperand operand) { // prevent the user from saving this as a filter, since the results are presumed to be dynamic return new FunctionOperand(operand.getName(), Arrays.asList("")); } private boolean wasSanitised(List<String> args) { return (args.size() == 0 || args.get(JQL_FUNCTION_MAGIC_KEY_INDEX).isEmpty()); } }