Boa tarde galera...
Estou aprendendo a usar framework Primefaces, e gostaria de ajuda na implementação de um exemplo dado, um ShowCase - DataTable - Lazy, pelo próprio Primefaces.
Já implementei tudo, criei todas as Classes e a View, porém, o exemplo não esta funcionando, sendo mais específico, só a paginação funciona, já o Filter e o Sort Não.
ps: já olhei vários tópicos, em diferentes foruns, com próblemas semelhantes, mas gostaria que alguém pudesse me explicar mais detalhadamente.
Obrigado
Segue os Códigos:
index.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Hello JSF!</title>
</h:head>
<h:body>
<h:form id="form">
<p:dataTable var="car" value="#{dtLazyView.lazyModel}"
paginator="true" rows="10"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
rowsPerPageTemplate="5,10,15" selectionMode="single"
selection="#{dtLazyView.selectedCar}" id="carTable" lazy="true">
<p:ajax event="rowSelect" listener="#{dtLazyView.onRowSelect}"
update=":form:carDetail" oncomplete="PF('carDialog').show()" />
<p:column headerText="Id" sortBy="#{car.id}" filterBy="#{car.id}">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Year" sortBy="#{car.year}"
filterBy="#{car.year}">
<h:outputText value="#{car.year}" />
</p:column>
<p:column headerText="Brand" sortBy="#{car.brand}"
filterBy="#{car.brand}">
<h:outputText value="#{car.brand}" />
</p:column>
<p:column headerText="Color" sortBy="#{car.color}"
filterBy="#{car.color}">
<h:outputText value="#{car.color}" />
</p:column>
</p:dataTable>
<p:dialog header="Car Detail" widgetVar="carDialog" modal="true"
showEffect="fade" hideEffect="fade" resizable="false">
<p:outputPanel id="carDetail" style="text-align:center;">
<p:panelGrid columns="2"
rendered="#{not empty dtLazyView.selectedCar}"
columnClasses="label,value">
<f:facet name="header">
<p:graphicImage
name="demo/images/car/#{dtLazyView.selectedCar.brand}-big.gif" />
</f:facet>
<h:outputText value="Id:" />
<h:outputText value="#{dtLazyView.selectedCar.id}" />
<h:outputText value="Year" />
<h:outputText value="#{dtLazyView.selectedCar.year}" />
<h:outputText value="Color:" />
<h:outputText value="#{dtLazyView.selectedCar.color}"
style="color:#{dtLazyView.selectedCar.color}" />
<h:outputText value="Price:" />
<h:outputText value="#{dtLazyView.selectedCar.price}">
<f:convertNumber type="currency" currencySymbol="$" />
</h:outputText>
</p:panelGrid>
</p:outputPanel>
</p:dialog>
</h:form>
</h:body>
</html>
LazyView.java
package br.com.lazy.bean;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.LazyDataModel;
import br.com.lazy.entidade.Car;
import br.com.lazy.service.CarService;
import br.com.lazy.util.LazyCarDataModel;
@ManagedBean(name="dtLazyView")
@ViewScoped
public class LazyView implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private LazyDataModel<Car> lazyModel;
private Car selectedCar;
@ManagedProperty("#{carService}")
private CarService service;
@PostConstruct
public void init() {
lazyModel = new LazyCarDataModel(service.createCars(200));
}
public LazyDataModel<Car> getLazyModel() {
return lazyModel;
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
public void setService(CarService service) {
this.service = service;
}
public void onRowSelect(SelectEvent event) {
FacesMessage msg = new FacesMessage("Car Selected", ((Car) event.getObject()).getId());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
CarService.java
package br.com.lazy.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import br.com.lazy.entidade.Car;
@ManagedBean(name = "carService")
@ApplicationScoped
public class CarService {
private final static String[] colors;
private final static String[] brands;
static {
colors = new String[10];
colors[0] = "Black";
colors[1] = "White";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "Blue";
colors[5] = "Orange";
colors[6] = "Silver";
colors[7] = "Yellow";
colors[8] = "Brown";
colors[9] = "Maroon";
brands = new String[10];
brands[0] = "BMW";
brands[1] = "Mercedes";
brands[2] = "Volvo";
brands[3] = "Audi";
brands[4] = "Renault";
brands[5] = "Fiat";
brands[6] = "Volkswagen";
brands[7] = "Honda";
brands[8] = "Jaguar";
brands[9] = "Ford";
}
public List<Car> createCars(int size) {
List<Car> list = new ArrayList<Car>();
for(int i = 0 ; i < size ; i++) {
list.add(new Car(getRandomId(), getRandomBrand(), getRandomYear(), getRandomColor(), getRandomPrice(), getRandomSoldState()));
}
return list;
}
private String getRandomId() {
return UUID.randomUUID().toString().substring(0, 8);
}
private int getRandomYear() {
return (int) (Math.random() * 50 + 1960);
}
private String getRandomColor() {
return colors[(int) (Math.random() * 10)];
}
private String getRandomBrand() {
return brands[(int) (Math.random() * 10)];
}
public int getRandomPrice() {
return (int) (Math.random() * 100000);
}
public boolean getRandomSoldState() {
return (Math.random() > 0.5) ? true: false;
}
public List<String> getColors() {
return Arrays.asList(colors);
}
public List<String> getBrands() {
return Arrays.asList(brands);
}
}
LazyCarDataModel.java
package br.com.lazy.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;
import br.com.lazy.entidade.Car;
/**
* Dummy implementation of LazyDataModel that uses a list to mimic a real datasource like a database.
*/
public class LazyCarDataModel extends LazyDataModel<Car> {
/**
*
*/
private static final long serialVersionUID = 1L;
private List<Car> datasource;
public LazyCarDataModel(List<Car> datasource) {
this.datasource = datasource;
}
@Override
public Car getRowData(String rowKey) {
System.out.println("Entrou no RowData");
for(Car car : datasource) {
if(car.getId().equals(rowKey))
return car;
}
return null;
}
@Override
public Object getRowKey(Car car) {
return car.getId();
}
@Override
public List<Car> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
List<Car> data = new ArrayList<Car>();
//System.out.println(datasource);
//filter
for(Car car : datasource) {
boolean match = true;
if (filters != null) {
for (Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
try {
String filterProperty = it.next();
Object filterValue = filters.get(filterProperty);
String fieldValue = String.valueOf(car.getClass().getField(filterProperty).get(car));
if(filterValue == null || fieldValue.startsWith(filterValue.toString())) {
match = true;
}
else {
match = false;
break;
}
} catch(Exception e) {
match = false;
}
}
}
if(match) {
data.add(car);
}
}
//sort
if(sortField != null) {
System.out.println(sortField+", "+sortOrder);
Collections.sort(data, new LazySorter(sortField, sortOrder));
}
//rowCount
int dataSize = data.size();
this.setRowCount(dataSize);
//paginate
if(dataSize > pageSize) {
try {
return data.subList(first, first + pageSize);
}
catch(IndexOutOfBoundsException e) {
return data.subList(first, first + (dataSize % pageSize));
}
}
else {
return data;
}
}
}
LazySorter.java
package br.com.lazy.util;
import java.util.Comparator;
import org.primefaces.model.SortOrder;
import br.com.lazy.entidade.Car;
class LazySorter implements Comparator<Car> {
private String sortField;
private SortOrder sortOrder;
public LazySorter(String sortField, SortOrder sortOrder) {
this.sortField = sortField;
this.sortOrder = sortOrder;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public int compare(Car car1, Car car2) {
try {
Object value1 = Car.class.getField(this.sortField).get(car1);
Object value2 = Car.class.getField(this.sortField).get(car2);
int value = ((Comparable) value1).compareTo(value2);
return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
} catch (Exception e) {
throw new RuntimeException();
}
}
}