This example shows how to implement lazy loading of child nodes - which is essential for big models.
<div class="card">
<h:form id="form">
<p:growl id="messages" showDetail="true"/>
<p:tree value="#{treeLazyLoadingView.root}" var="node" dynamic="true">
<p:treeNode>
<h:outputText value="#{node.name}"/>
</p:treeNode>
</p:tree>
</h:form>
</div>
@Named("treeLazyLoadingView")
@ViewScoped
public class LazyLoadingView implements Serializable {
private TreeNode<FileInfo> root;
@PostConstruct
public void init() {
FacesContext context = FacesContext.getCurrentInstance();
root = new LazyDefaultTreeNode<>(new FileInfo(context.getExternalContext().getRealPath("/"), true),
(fileInfo) -> listFiles(fileInfo),
(fileInfo) -> !fileInfo.isDirectory());
}
public static List<FileInfo> listFiles(FileInfo parentFolder) {
List<FileInfo> result = new ArrayList<>();
File[] files = new File(parentFolder.getPath()).listFiles();
if (files != null) {
for (File file : files) {
result.add(new FileInfo(file.getAbsolutePath(), file.isDirectory()));
}
}
return result;
}
public TreeNode getRoot() {
return root;
}
}
public class FileInfo implements Serializable {
private String path;
private String name;
private boolean directory;
public FileInfo(String path, boolean directory) {
this.path = path;
if (this.path.equals(File.separator)) {
this.name = this.path;
}
else {
String[] parts = path.split(File.separator.equals("\\") ? "\\\\" : File.separator);
this.name = parts[parts.length - 1];
}
this.directory = directory;
}
public String getPath() {
return path;
}
public String getName() {
return name;
}
public boolean isDirectory() {
return directory;
}
@Override
public String toString() {
return path + " / " + name;
}
}