BrightSide Workbench Full Report + Source Code
grid/RendererOnDemand.java
Go to the documentation of this file.
1 /*
2  * TurrĂ³ i Cutiller Foundation. License notice.
3  * Copyright (C) 2011 Lluis TurrĂ³ Cutiller <http://www.turro.org/>
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Affero General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU Affero General Public License for more details.
14  *
15  * You should have received a copy of the GNU Affero General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 package org.turro.jpa.grid;
19 
20 import java.lang.reflect.ParameterizedType;
21 import java.util.function.Supplier;
22 import org.turro.jpa.Dao;
23 import org.zkoss.zul.Group;
24 import org.zkoss.zul.Row;
25 import org.zkoss.zul.RowRenderer;
26 
33 public abstract class RendererOnDemand<T, ID> implements RowRenderer {
34 
35  private final Class<T> entityClass;
36  private final Class<ID> idClass;
37  private final Supplier<Dao> onDao;
38 
39  public RendererOnDemand(Supplier<Dao> onDao) {
40  entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
41  idClass = (Class<ID>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
42  this.onDao = onDao;
43  }
44 
45  @Override
46  public void render(Row row, Object data, int index) throws Exception {
47  T obj = null;
48  if(data.getClass().isAssignableFrom(idClass)) {
49  obj = getDao().find(entityClass, getId((ID) data));
50  } else if(data.getClass().isAssignableFrom(entityClass)) {
51  obj = (T) data;
52  }
53  if(obj != null) {
54  if(row instanceof Group) {
55  renderGroup((Group) row, obj);
56  } else {
57  renderRow(row, obj);
58  }
59  }
60  }
61 
62  protected Object getId(ID id) {
63  return id;
64  }
65 
66  protected void renderGroup(Group group, T value) {
67  // nothing to do
68  }
69 
70  protected abstract void renderRow(Row row, T value);
71 
72  /* Dao */
73 
74  private Dao dao;
75 
76  protected Dao getDao() {
77  if(dao == null) {
78  dao = onDao.get();
79  }
80  return dao;
81  }
82 
83 }
abstract void renderRow(Row row, T value)
void render(Row row, Object data, int index)