Links

   Quran Explorer - Interactive Audio Recitations & Translations

Wednesday, September 10, 2014

Programaticaly creating/initializing Primefaces Gridform

Another one for you Mike,

This should guide you on how to dynamicaly create p:gridform

1:  public static HtmlPanelGrid buildGridForm(XMLElement pg, LazyModel _model, DataSource d, HashMap<String,String> _props, int _userId, int _orgId){  
2:            setDs(d);  
3:            FacesContext fc = FacesContext.getCurrentInstance();  
4:            Application application = fc.getApplication();  
5:            ExpressionFactory ef = application.getExpressionFactory();  
6:            ELContext elc = fc.getELContext();  
7:            HtmlPanelGrid pGrid = new HtmlPanelGrid();  
8:            boolean embedded = false;  
9:             String user = pg.getAttribute("user");  
10:             if(user != null){  
11:             log.info("Building GRIDFORM.. user=" + user + ",_userId = " + _userId);  
12:              _props.put(user,"" + _userId + "");  
13:              }  
14:            if(_model != null)  
15:              embedded = true;  
16:            if(embedded)     //if xpandable  
17:              pGrid.setId("xgf" + pg.getAttribute("key","x") + pg.getAttribute("keyfield","kf").replace("_",""));  
18:            else  
19:              pGrid.setId("gf" + pg.getAttribute("key","x") + pg.getAttribute("keyfield","kf").replace("_",""));  
20:            pGrid.setColumns(Integer.parseInt(pg.getAttribute("columns","4")));  
21:            pGrid.setTitle(pg.getAttribute("title","NO TITLE"));  
22:            pGrid.setStyle(pg.getAttribute("style","font-size:11px; text-align:left; padding-right:0px"));  
23:            pGrid.setStyleClass(pg.getAttribute("styleclass",""));  
24:            pGrid.setCellpadding(pg.getAttribute("cellpadding","0 px"));  
25:            pGrid.setCellspacing(pg.getAttribute("cellspacing","5 px"));  
26:            pGrid.setRendered(Boolean.parseBoolean(pg.getAttribute("visible","true")));  
27:            LazyModel parentModel = null;  
28:            boolean isChild = false;     //linked to another datatable  
29:            //boolean isInput = false;     //gets input from another datatable  
30:            //boolean isNested = false; //has nested children table within a table  
31:            //boolean isNew = Boolean.parseBoolean(pg.getAttribute("new","false"));  
32:            String link = pg.getAttribute("link","");  
33:            String input = pg.getAttribute("input","");  
34:            if(!link.equals("")){     //if a child  
35:               //log.info("PARENT for FORM link = " + link);  
36:               DataTable parent = (DataTable)FacesAccessor.getUIComponent("mainForm:dt" + link.split(":")[0] + (link.split(":")[1]).replace("_",""));  
37:               //log.info("FOUND parent id = " + parent.getId());     //  
38:               isChild = true;  
39:               parentModel = (LazyModel)parent.getValue();  
40:               }  
41:            else if(!input.equals("")){     //if a child  
42:               //log.info("PARENT for FORM link = " + link);  
43:               DataTable parent = (DataTable)FacesAccessor.getUIComponent("mainForm:dt" + input.split(":")[0] + (input.split(":")[1]).replace("_",""));  
44:               //log.info("FOUND parent id = " + parent.getId());     //  
45:               //isChild = true;  
46:               parentModel = (LazyModel)parent.getValue();  
47:               }  
48:            //activiti task variables  
49:            Map<String,Object> tVars = new HashMap<String, Object>();  
50:            for(XMLElement el : pg.getElements()) {  
51:               //label first  
52:               OutputLabel label = new OutputLabel();  
53:               label.setId("lbl" + pGrid.getId() + "_" + el.getValue());  
54:               label.setValue(el.getAttribute("title"));  
55:               pGrid.getChildren().add(label);  
56:               boolean isInput = false;  
57:               if(el.getAttribute("input","false").equals("true"))  
58:                  isInput = true;  
59:               //activiti task variables  
60:               if(!el.getAttribute("var","").equals("")){  
61:                  //get XML ELEMENTS marked with var="true" and use as Activiti Task Variables  
62:                  tVars.put(el.getAttribute("var"),"");  
63:                  }  
64:  //              if(el.getName().equals("USERFIELD")){  
65:  //                 InputText txtUser = new InputText();  
66:  //                 txtUser.setId("txt" + pGrid.getId() + "_" + el.getValue());  
67:  //                 txtUser.setValue("loggedInUser");  
68:  //                 }  
69:  //              else if(el.getName().equals("DEFAULT")){  
70:  //                  InputText txtDefault = new InputText();  
71:  //                  txtDefault.setId("txt" + pGrid.getId() + "_" + el.getValue());  
72:  //                  txtUser.setValue("loggedInUser");  
73:  //                  }  
74:               String defaultVal = el.getAttribute("defaultvalue");  
75:               if(el.getName().equals("TEXTFIELD")){  
76:                  if(embedded){  
77:                      InputText txt = new InputText();  
78:                      txt.setId("txt" + pGrid.getId() + "_" + el.getValue());  
79:                      txt.setSize(Integer.parseInt(el.getAttribute("w","25")));  
80:                      //ValueExpression embVE = FacesAccessor.createValueExpression(elc, "#{item[" + _model.getDataIndex(el.getValue()) + "]}", String.class);  
81:                      ValueExpression embVE = FacesAccessor.createValueExpression(elc, "#{item[" + _model.getDataIndex(el.getValue()) + "]}", String.class);  
82:                      txt.setValueExpression("value",embVE);  
83:                      txt.addClientBehavior("save", EventsManager.createAjaxBehaviour("inplaceUpdate","@parent"));  
84:                      //txt.addClientBehavior("cancel", EventsManager.createAjaxBehaviour("inPlaceSave","@none"));  
85:                      if(!el.getAttribute("tooltip","").equals(""))  
86:                        txt.setTitle(el.getAttribute("tooltip"));  
87:                      //txt.setValidator();  
88:                      if(!el.getAttribute("requiredmessage","").equals("")){     //if there is a requiredmessage  
89:                        txt.setRequired(true);  
90:                        txt.setRequiredMessage(el.getAttribute("requiredmessage"));  
91:                        }  
92:                      label.setFor("txt" + pGrid.getId() + "_" + el.getValue());  
93:                      Inplace inp = new Inplace();  
94:                      //inp.setLabel(el.getAttribute("title","No Title"));  
95:                      //inp.setValueExpression("label",FacesAccessor.createValueExpression(elc, "#{item[" + _model.getDataIndex(el.getValue()) + "]}", String.class));  
96:                      inp.setValueExpression("label",FacesAccessor.createValueExpression(elc, "#{item[" + _model.getDataIndex(el.getValue()) + "]}", String.class));  
97:                      inp.setEmptyLabel("EMPTY");  
98:                      inp.setEditor(true);  
99:                      inp.setSaveLabel("Save");  
100:                      inp.setCancelLabel("Cancel");  
101:                      inp.setEvent(el.getAttribute("event","click"));  
102:                      inp.setToggleable(true);  
103:                      inp.getChildren().add(txt);  
104:                      pGrid.getChildren().add(inp);  
105:                      }  
106:                  else if(el.getAttribute("inline","false").equals("false")){  
107:                      //log.info("FOUND TEXTFIELD value = " + el.getValue());  
108:                      InputText txt = new InputText();  
109:                      txt.setId("txt" + pGrid.getId() + "_" + el.getValue());  
110:                      txt.setSize(Integer.parseInt(el.getAttribute("w","20")));  
111:                      if (isChild || isInput){          //CORRECTION NEEDED HERE... if isInput i need to use onNewValue event  
112:                        txt.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", String.class));  
113:                        txt.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onValueChange","@none"));  
114:                        //if isInput look for mechanism to inject the value directly to newDataMap in DashboardBacker  
115:                        }  
116:                       else{     //means new  
117:                         txt.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onNewValue","@none"));  
118:                        if (defaultVal != null){  
119:                           txt.setValue(defaultVal);  
120:                           }  
121:                         }  
122:                      if(!el.getAttribute("tooltip","").equals(""))  
123:                        txt.setTitle(el.getAttribute("tooltip"));  
124:                      //txt.setValidator();  
125:                      if(!el.getAttribute("requiredmessage","").equals("")){     //if there is a requiredmessage  
126:                        txt.setRequired(true);  
127:                        txt.setRequiredMessage(el.getAttribute("requiredmessage"));  
128:                        }  
129:                      label.setFor("txt" + pGrid.getId() + "_" + el.getValue());  
130:                      // attach message component  
131:                      // Message msg = new Message();  
132:                      // msg.setId("msg_" + pGrid.getId() + "_" + el.getValue());  
133:                      // msg.setFor("txt" + pGrid.getId() + "_" + el.getValue());  
134:                      // pGrid.getChildren().add(msg);  
135:                      pGrid.getChildren().add(txt);  
136:                      }  
137:                  else{     //if inline .. this is only usable when EDITING  
138:                      InputText txt = new InputText();  
139:                      txt.setId("txt" + pGrid.getId() + "_" + el.getValue());  
140:                      txt.setSize(Integer.parseInt(el.getAttribute("w","20")));  
141:                      if (isChild || isInput){  
142:                        txt.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", String.class));  
143:                        txt.addClientBehavior("save", EventsManager.createAjaxBehaviour("inplaceUpdate","@parent"));  
144:                        }  
145:                      //txt.setValidator();  
146:                      if(!el.getAttribute("requiredmessage","").equals("")){     //if there is a requiredmessage  
147:                        txt.setRequired(true);  
148:                        txt.setRequiredMessage(el.getAttribute("requiredmessage"));  
149:                        }  
150:                      label.setFor("txt" + pGrid.getId() + "_" + el.getValue());  
151:                      Inplace inp = new Inplace();  
152:                      //inp.setLabel(el.getAttribute("title","No Title"));  
153:                      inp.setValueExpression("label",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", String.class));  
154:                      inp.setEmptyLabel("EMPTY");  
155:                      inp.setEditor(Boolean.parseBoolean(el.getAttribute("editorbuttons","false")));  
156:                      inp.setSaveLabel("Save");  
157:                      inp.setCancelLabel("Cancel");  
158:                      inp.setEvent(el.getAttribute("event","click"));  
159:                      inp.setToggleable(true);  
160:                      inp.getChildren().add(txt);  
161:                      pGrid.getChildren().add(inp);  
162:                      }  
163:                   }  
164:               else if(el.getName().equals("AUTOCOMPLETE")){  
165:                   log.info("FOUND AUTOCOMPLETE");  
166:                   //AutoComplete autoComp = new AutoComplete();  
167:                   //MyAutoComplete autoComp = new MyAutoComplete();     //my implementation  
168:                   AutoComplete autoComp = new AutoComplete();  
169:                   autoComp.setId("ac" + pGrid.getId() + "_" + el.getValue());  
170:                   autoComp.setForceSelection(true);  
171:                   autoComp.setRequired(true);  
172:                   autoComp.setRequiredMessage(el.getAttribute("requiredmessage","Required"));  
173:                   autoComp.setMinQueryLength(Integer.parseInt(el.getAttribute("querylength","3")));  
174:                   autoComp.setMaxlength(Integer.parseInt(el.getAttribute("maxlength","10")));  
175:                   autoComp.setMultiple(Boolean.parseBoolean(el.getAttribute("multiple","false")));  
176:                   autoComp.setQueryDelay(Integer.parseInt(el.getAttribute("delay","500")));  
177:                   //autoComp.setDropdown(true);  
178:                   //autoComp.setConverter(el.getAttribute("converter","org.elegance.primetime.util.DefaultConverter"));  
179:                   //autoComp.setValueChangeListener()  
180:                   //autoComp.setVar("obj");  
181:                   //autoComp.setItemLabel("#{obj.toString()}");  
182:                   //autoComp.setItemValue("#{obj}");  
183:                   //autoComp.setProcess();  
184:                   //autoComp.setValue("testvalue");  
185:                   //autoComp.setLptable(el.getAttribute("lptable"));  
186:                   //autoComp.setLpfield(el.getAttribute("lpfield"));  
187:                   //autoComp.setLpkey(el.getAttribute("lpkey"));  
188:                   //MethodExpression cME = FacesAccessor.createMethodExpression("#{eventManager.onComplete(\"" + autoComp.getValue() + "\",\"" + el.getAttribute("lptable") + "\",\"" + el.getAttribute("lpfield") + "\")}",List.class, String.class);  
189:                   MethodExpression cME = FacesAccessor.createMethodExpression("#{eventManager.onComplete}",List.class, String.class);  
190:                   autoComp.setCompleteMethod(cME);  
191:  //                  MethodExpression cVE = FacesAccessor.createMethodActionListener("#{eventManager.onValueChange}",Void.class, String.class);  
192:  //                  autoComp.setValueChangeListener(cVE);  
193:                   //ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{imageBean.getImageBytes(\"select " + el.getValue() + " from " + pg.getAttribute("table","table") + " where " + pg.getAttribute("keyfield","kf") + " = ?\")}", DefaultStreamedContent.class);  
194:                   //START TESTING params  
195:  //                     UIParameter paramTable = new UIParameter();  
196:  //                     UIParameter paramField = new UIParameter();  
197:  //                     UIParameter paramKey = new UIParameter();  
198:  //  
199:  //                     paramTable.setName("lptable");  
200:  //                     //paramTable.setValue(el.getAttribute("lptable"));  
201:  //                     paramTable.setValue("p_entity");  
202:  //  
203:  //                     paramField.setName("lpfield");  
204:  //                     paramField.setValue(el.getAttribute("lpfield"));  
205:  //  
206:  //                     paramKey.setName("lpkey");  
207:  //                     paramKey.setValue(el.getAttribute("lpkey"));  
208:  //  
209:  //                     autoComp.getChildren().add(paramTable);  
210:  //                     autoComp.getChildren().add(paramField);  
211:  //                     autoComp.getChildren().add(paramKey);  
212:                   //END TESTING params  
213:                   label.setFor("ac" + pGrid.getId() + "_" + el.getValue());  
214:  //                  if (isChild || isInput){          //CORRECTION NEEDED HERE... if isInput i need to use onNewValue event  
215:  //                     autoComp.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", String.class));  
216:  //                     autoComp.addClientBehavior("itemSelect", EventsManager.createAjaxBehaviour("onValueChange","@none"));  
217:  //                     }  
218:  //                  else{  
219:  //                     autoComp.addClientBehavior("itemSelect", EventsManager.createAjaxBehaviour("onNewValue","@none"));  
220:  //                     }  
221:                   pGrid.getChildren().add(autoComp);  
222:                   }  
223:               else if(el.getName().equals("TEXTAREA")){  
224:                   InputTextarea txtA = new InputTextarea();  
225:                   txtA.setId("txtA" + pGrid.getId() + "_" + el.getValue());  
226:                   txtA.setLabel("INLINE LABEL");  
227:                   if (isChild || isInput){  
228:                       txtA.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", String.class));  
229:                       txtA.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onValueChange","@parent"));  
230:                       }  
231:                    else{     //means new  
232:                        txtA.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onNewValue","@form"));  
233:                       //TESTING ROBOT.. WORKS PERFECTLY  
234:                       //txtA.addClientBehavior("focus", EventsManager.createAjaxBehaviour("runRobot","@this"));  
235:                       if (defaultVal != null){  
236:                         txtA.setValue(defaultVal);  
237:                         }  
238:                        }  
239:                   txtA.setRows(Integer.parseInt(el.getAttribute("rows","5")));  
240:                   txtA.setCols(Integer.parseInt(el.getAttribute("cols","25")));  
241:                   //txtA.setRendered(Boolean.parseBoolean(el.getAttribute("visible","true")));  
242:                   label.setFor("txtA" + pGrid.getId() + "_" + el.getValue());  
243:                   pGrid.getChildren().add(txtA);  
244:                   }  
245:               else if(el.getName().equals("CHECKBOX")){  
246:                   SelectBooleanCheckbox chk = new SelectBooleanCheckbox();  
247:                   chk.setId("chk" + pGrid.getId() + "_" + el.getValue());  
248:                   chk.setLabel("INLINE LABEL");  
249:                   if (isChild || isInput){  
250:                       chk.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", String.class));  
251:                       chk.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onValueChange","@parent"));  
252:                       }  
253:                    else{     //means new  
254:                        chk.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onNewValue","@form"));  
255:                       //TESTING ROBOT.. WORKS PERFECTLY  
256:                       //txtA.addClientBehavior("focus", EventsManager.createAjaxBehaviour("runRobot","@this"));  
257:                       if (defaultVal != null){  
258:                         chk.setValue(defaultVal);  
259:                         }  
260:                        }  
261:                   label.setFor("chk" + pGrid.getId() + "_" + el.getValue());  
262:                   pGrid.getChildren().add(chk);  
263:                   }  
264:               else if(el.getName().equals("TEXTDECIMAL")){  
265:                   InputText txtD = new InputText();  
266:                   txtD.setId("txtD" + pGrid.getId() + "_" + el.getValue());  
267:                   txtD.setType("number");  
268:                   txtD.setSize(Integer.parseInt(el.getAttribute("w","20")));  
269:                   txtD.setStyle(el.getAttribute("style","text-align: right"));  
270:                   if(!el.getAttribute("tooltip","").equals(""))  
271:                      txtD.setTitle(el.getAttribute("tooltip"));  
272:                    if (isChild || isInput){  
273:                      txtD.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", Double.class));  
274:                      txtD.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onValueChange","@form"));  
275:                      }  
276:                    else{     //means new  
277:                       txtD.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onNewValue","@none"));  
278:                      if (defaultVal != null){  
279:                        txtD.setValue(defaultVal);  
280:                        }  
281:                       }  
282:                   if(!el.getAttribute("requiredmessage","").equals("")){     //if there is a requiredmessage  
283:                      txtD.setRequired(true);  
284:                      txtD.setRequiredMessage(el.getAttribute("requiredmessage"));  
285:                      }  
286:                   txtD.setRendered(Boolean.parseBoolean(el.getAttribute("visible","true")));  
287:                   label.setFor("txtD" + pGrid.getId() + "_" + el.getValue());  
288:                   pGrid.getChildren().add(txtD);  
289:                   }  
290:               else if(el.getName().equals("INPUTMASK")){  
291:                   InputMask txtMask = new InputMask();  
292:                   txtMask.setId("mask" + pGrid.getId() + "_" + el.getValue());  
293:                   txtMask.setSize(Integer.parseInt(el.getAttribute("w","20")));  
294:                   if(!el.getAttribute("style","").equals("")){  
295:                      txtMask.setStyle(el.getAttribute("style"));  
296:                      }  
297:                   if (isChild || isInput){  
298:                        txtMask.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", String.class));  
299:                        txtMask.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onValueChange","@form"));  
300:                        }  
301:                    else{     //means new  
302:                         txtMask.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onNewValue","@none"));  
303:                         }  
304:                   txtMask.setMask(el.getAttribute("mask",""));  
305:                   label.setFor("mask" + pGrid.getId() + "_" + el.getValue());  
306:                   pGrid.getChildren().add(txtMask);  
307:                  }  
308:  // else if(el.getName().equals("GMAP")){  
309:  //    log.info("CREATING map");  
310:  //  
311:  //      GMap map = new GMap();  
312:  //      MapModel model = new DefaultMapModel();  
313:  //  
314:  //      map.setId("map" + pGrid.getId() + "_" + el.getValue());  
315:  //      map.setWidgetVar(map.getId());  
316:  //      map.setCenter(el.getAttribute("center","41.381542, 2.122893"));  
317:  //      map.setZoom(Integer.parseInt(el.getAttribute("zoom","15")));  
318:  //      map.setType(el.getAttribute("type","hybrid"));  
319:  //        map.setStyle(el.getAttribute("style","width:400px;height:300px"));  
320:  //  
321:  //      model.addOverlay(new Marker(new LatLng(36.879466, 30.667648), "M1"));  
322:  //      map.setModel(model);  
323:  //  
324:  //   pGrid.getChildren().add(map);  
325:  // }  
326:               else if(el.getName().equals("EDITOR")){          //'component does not implement Behaviour Interface'  
327:                   Editor edt = new Editor();  
328:                   //MethodExpression ee = FacesAccessor.createMethodExpression("#{eventManager.onNewValue}",Void.class, new Class[0]);  
329:                   //edt.setValueChangeListener(ee);  
330:                   edt.setId("edt" + pGrid.getId() + "_" + el.getValue());  
331:                   if (isChild || isInput){  
332:                        edt.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", String.class));  
333:                        //edt.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onValueChange","@form"));  
334:                        }  
335:                    //else{     //means new  
336:                   //edt.addClientBehavior("blur", EventsManager.createAjaxBehaviour("onNewValue","@form"));  
337:                   //}  
338:                   edt.setWidth(Integer.parseInt(el.getAttribute("width","200")));  
339:                   edt.setHeight(Integer.parseInt(el.getAttribute("heigth","100")));  
340:                  edt.setControls(el.getAttribute("controls","bold italic underline strikethrough"));  
341:                   edt.setRendered(Boolean.parseBoolean(el.getAttribute("visible","true")));  
342:                   label.setFor("edt" + pGrid.getId() + "_" + el.getValue());  
343:                   pGrid.getChildren().add(edt);  
344:                   }  
345:               else if(el.getName().equals("TEXTDATE")){  
346:                   //log.info("FOUND TEXTDATE value = " + el.getValue());  
347:                   Calendar cal = new Calendar();  
348:                   cal.setId("cal" + pGrid.getId() + "_" + el.getValue());  
349:                   cal.setPattern("yyyy MMM dd");  
350:                   cal.setNavigator(true);  
351:                   //cal.setPages(3);  
352:                   cal.setMode(el.getAttribute("mode","popup"));          //button,inline,popup  
353:                   //cal.setShowOn(String here);  
354:                   cal.setYearRange(el.getAttribute("yearrange","1990:2020"));  
355:                   //cal.setTimeOnly(true);  
356:                   //cal.setShowWeek(true);          //show week number  
357:                   //cal.setShowButtonPanel(true);     //Show TODAY and DONE  
358:                   //cal.setImmediate(false);          //process validations logic isexecuted at apply request values phase for this component  
359:                   //cal.setSelectOtherMonths(true);  
360:                   //cal.setShowOtherMonths(true);  
361:                   //pattern="EEE, dd MMM, yyyy" showButtonPanel="true" navigator="true"  
362:                   cal.setSize(Integer.parseInt(el.getAttribute("w","20")));  
363:                   if (isChild || isInput){  
364:                        //Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);  
365:                        //log.info("Trying Java Date Formatter ... " + new SimpleDateFormat("yyyyy MMMMM dd", Locale.ENGLISH).parse(new Date()));  
366:                        cal.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", Date.class));  
367:                        cal.addClientBehavior("dateSelect", EventsManager.createAjaxBehaviour("onValueChange","@form"));     //or change or select  
368:                        }  
369:                    else{     //means new  
370:                         cal.addClientBehavior("dateSelect", EventsManager.createAjaxBehaviour("onNewValue","@none"));  
371:                        if (defaultVal != null){  
372:                         cal.setValue(defaultVal);  
373:                         }  
374:                         }  
375:                   cal.setRendered(Boolean.parseBoolean(el.getAttribute("visible","true")));  
376:                   label.setFor("cal" + pGrid.getId() + "_" + el.getValue());  
377:                   pGrid.getChildren().add(cal);  
378:                   }//end if TEXTDATE  
379:               else if(el.getName().equals("COMBOLIST")){  
380:                      SelectOneMenu cmblist = new SelectOneMenu();  
381:                      cmblist.setId("cmblist" + pGrid.getId() + "_" + el.getValue());  
382:                      label.setFor("cmblist" + pGrid.getId() + "_" + el.getValue());  
383:                      List<XMLElement> data = el.getElements();  
384:                      List<SelectItem> items = new ArrayList<SelectItem>();  
385:                      for(XMLElement dt : data) {  
386:                             if(dt.getName().equals("DATA")){     //HAS TO BE A DATA  
387:                                items.add(new SelectItem(dt.getAttribute("key","-1"), dt.getValue()));  
388:                               }//end if DATA  
389:                             }  
390:                      UISelectItems selectItems = new UISelectItems();  
391:                      selectItems.setValue(items);  
392:                      selectItems.setId("si" + pGrid.getId() + "_" + el.getValue());  
393:                      cmblist.getChildren().add(selectItems);  
394:                      if (isChild || isInput){  
395:                        //log.info("COMBOLIST parentModel = " + (parentModel==null?"NO PARENT":"OK"));  
396:                        cmblist.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", Object.class));  
397:                        cmblist.addClientBehavior("change", EventsManager.createAjaxBehaviour("onValueChange","@form"));  
398:                        }  
399:                       else{     //means new  
400:                         cmblist.addClientBehavior("change", EventsManager.createAjaxBehaviour("onNewValue","@none"));  
401:                         }  
402:                      pGrid.getChildren().add(cmblist);  
403:                   }  
404:               else if (el.getName().equals("COMBOBOX")){  
405:                      SelectOneMenu cmbbox = new SelectOneMenu();  
406:                      cmbbox.setId("cmbbox" + pGrid.getId() + "_" + el.getValue());  
407:                      //if heigtht is defined  
408:                      if(!el.getAttribute("h","").equals("")){  
409:                        cmbbox.setHeight(Integer.parseInt(el.getAttribute("h")));  
410:                        }  
411:                      label.setFor("cmbbox" + pGrid.getId() + "_" + el.getValue());  
412:                      String wheresql = el.getAttribute("wheresql");  
413:                      //the last argument is a 'suggestion/advice' as to the width of the array  
414:                      List<Object[]> cdata = IOService.getListFromResultSet(getDs(), "SELECT " + (el.getAttribute("lpkey",el.getValue())) + "," + el.getAttribute("lpfield") + " FROM " + el.getAttribute("lptable") + (wheresql==null?"":" WHERE " + wheresql));  
415:                      List<SelectItem> items = new ArrayList<SelectItem>();  
416:                      items.add(new SelectItem("-1", "Select"));  
417:                      for(Object[] dt : cdata) {  
418:                           items.add(new SelectItem((Integer)dt[0], (String)dt[1]));  
419:                             }  
420:                      UISelectItems selectItems = new UISelectItems();  
421:                      selectItems.setValue(items);  
422:                      selectItems.setId("si" + pGrid.getId() + "_" + el.getValue());  
423:                      cmbbox.getChildren().add(selectItems);  
424:                    if (isChild || isInput){  
425:                       if(el.getAttribute("input","false").equals("true")){  
426:                         cmbbox.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", Integer.class));  
427:                         cmbbox.setDisabled(true);  
428:                         }  
429:                       else{  
430:                         cmbbox.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(el.getValue()) + "]}", Integer.class));  
431:                         cmbbox.addClientBehavior("change", EventsManager.createAjaxBehaviour("onValueChange","@form")); //this may  
432:                         }  
433:                       }  
434:                     else{     //means new  
435:                         cmbbox.addClientBehavior("change", EventsManager.createAjaxBehaviour("onNewValue","@none"));  
436:                         }  
437:                      pGrid.getChildren().add(cmbbox);  
438:                   }  
439:               else if(el.getName().equals("FIELDSET")){  
440:                   log.info("FOUND FIELDSET id=" + el.getAttribute("id","no id"));  
441:                   Fieldset fs = new Fieldset();  
442:                   fs.setId("fs" + pGrid.getId() + "_" + el.getAttribute("id","k"));  
443:                   fs.setLegend(el.getAttribute("legend","No Legend"));  
444:                   HtmlPanelGrid fGrid = new HtmlPanelGrid();  
445:                   fGrid.setColumns(2);  
446:                   fGrid.setId("fgrid" + fs.getId());  
447:                   for(XMLElement ell : el.getElements()) {  
448:                       if(ell.getName().equals("TEXTFIELD")){  
449:                         log.info("FIELDSET CHILD = " + ell.getName());  
450:                         InputText fTxt = new InputText();  
451:                         fTxt.setLabel("TESTING");  
452:                         fTxt.setValue("TESTING");  
453:                         fGrid.getChildren().add(fTxt);  
454:                         }  
455:                       else if(ell.getName().equals("TEXTAREA")){  
456:                         fGrid.getChildren().add(new InputTextarea());  
457:                         }  
458:                       else if(ell.getName().equals("EDITOR")){  
459:                         fGrid.getChildren().add(new Editor());  
460:                         }  
461:                       }  
462:                   fs.getChildren().add(fGrid);  
463:                   pGrid.getChildren().add(fs);  
464:                   }//end if FIELDSET  
465:  //           else if(el.getName().equals("FEEDREADER")){  
466:  //                  log.info("FOUND FEEDREADER title = " + el.getAttribute("title"));  
467:  //  
468:  //                  FeedReader fd = new FeedReader();  
469:  //                  fd.setId("fd" + pGrid.getId() + "_" + el.getAttribute("key","k"));  
470:  //                  fd.setValue(el.getAttribute("source","http://rss.news.yahoo.com/rss/sports"));  
471:  //                  fd.setVar("feed");  
472:  //                  fd.setRendered(true);  
473:  //                  fd.setSize(Integer.parseInt(el.getAttribute("size","10")));  
474:  //  
475:  //  
476:  //                  ValueExpression titleVE = FacesAccessor.createValueExpression(elc, "#{feed.title}", Object.class);  
477:  //                  ValueExpression contentVE = FacesAccessor.createValueExpression(elc, "#{feed.description.value}", Object.class);  
478:  //  
479:  //                  HtmlOutputText fdTitle = new HtmlOutputText();//(HtmlOutputText)application.createComponent( HtmlOutputText.COMPONENT_TYPE );  
480:  //                  fdTitle.setValueExpression("value",titleVE);  
481:  //                  //fdTitle.setValue("#{feed.title}");  
482:  //  
483:  //                  HtmlOutputText fdContent = new HtmlOutputText();  
484:  //                  fdContent.setValueExpression("value",contentVE);  
485:  //                  //fdContent.setValue("#{feed.description.value}");  
486:  //  
487:  //                  UIOutput errorMessage = (UIOutput)application.createComponent(UIOutput.COMPONENT_TYPE);  
488:  //                  errorMessage.setValue("Something Went Wrong");  
489:  //  
490:  //                  fd.getChildren().add(fdTitle);  
491:  //                  fd.getChildren().add(fdContent);  
492:  //  
493:  //                  fd.getFacets().put("error", errorMessage);  
494:  //  
495:  //  
496:  //  
497:  //                  RequestContext reqContext = RequestContext.getCurrentInstance();  
498:  //                  reqContext.update("feed");  
499:  //  
500:  //                  pGrid.getChildren().add(fd);  
501:  //  
502:  //                  }//end if FEEDREADER  
503:  else if(el.getName().equals("IMAGE")){  
504:                   GraphicImage img = new GraphicImage();  
505:                   img.setId("img" + pGrid.getId() + "_" + el.getValue());  
506:                   FileUpload fup = new FileUpload();          //used when noimage present  
507:                   //img.setTitle(el.getAttribute("title","No Title"));  
508:                   img.setHeight(el.getAttribute("h","50"));  
509:                   img.setWidth(el.getAttribute("w","50"));  
510:                   img.setAlt("Photo Here");  
511:                   if (isChild || isInput){  
512:                      log.info("Trying to load image from database");  
513:                      ValueExpression imgValueExp = FacesAccessor.createValueExpression(elc, "#{imageBean.getImageBytes(\"select " + el.getValue() + " from " + pg.getAttribute("table","table") + " where " + pg.getAttribute("keyfield","kf") + " = ?\")}", DefaultStreamedContent.class);  
514:                      UIParameter param = new UIParameter();  
515:                      param.setName("pk");  
516:                      param.setName("148");  
517:                      //param.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{item[0]}", String.class));  
518:                      img.getChildren().add(param);  
519:                      FacesContext context = FacesContext.getCurrentInstance();  
520:                      if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {  
521:                        img.setValue(new DefaultStreamedContent());  
522:                        }  
523:                      else{  
524:                        img.setValueExpression("value", imgValueExp);  
525:                        }  
526:                      img.addClientBehavior("change", EventsManager.createAjaxBehaviour("onValueChange","@form"));  
527:                      }  
528:                   else{     //means new  
529:                      fup.setId("fup" + pGrid.getId() + "_" + el.getValue());  
530:                      fup.setAuto(Boolean.parseBoolean(el.getAttribute("autoupload","false")));  
531:                      fup.setLabel("Choose");  
532:                      //fup.setAllowTypes(el.getAttribute("uploadfilter","/(\.|\/)(gif|jpe?g|png)$/"));  
533:  //  
534:                      MethodExpression fl = FacesAccessor.createMethodExpression("#{eventManager.handleFileUpload}",Void.class, FileUploadEvent.class);  
535:                      fup.setFileUploadListener(fl);  
536:                      label.setFor("fup" + pGrid.getId() + "_" + el.getValue());  
537:  //                     log.info("Trying to load image from file");  
538:  //                     try{  
539:  //                       //if is child get from db  
540:  //                       //File imgFile = new File(el.getAttribute("file","no_file"));  
541:  //  
542:  //                       String missing = "file:///opt/tomcat7/webapps.labs/primetime/resources/images/missing_person.jpg";  
543:  //                       File imgFile = new File(new URI(el.getAttribute("file",missing)));  
544:  //                       log.info("Can Read ? = " + imgFile.canRead() + " Can Write ? = " + imgFile.canWrite());  
545:  //                       log.info("File = " + imgFile.getPath());  
546:  //                       StreamedContent strmImg;  
547:  //                       FacesContext context = FacesContext.getCurrentInstance();  
548:  //  
549:  //                       log.info("IMAGE phase = " + context.getCurrentPhaseId());  
550:  //  
551:  //                       if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {  
552:  //                            log.info("at Render Response");  
553:  //                            // So, we're rendering the view. Return a stub StreamedContent so that it will generate right URL.  
554:  //                            // strmImg = new DefaultStreamedContent();  
555:  //                            strmImg = new DefaultStreamedContent(new FileInputStream(missing), el.getAttribute("mimetype","image/jpg") ,"photo");  
556:  //                          }  
557:  //                       else{  
558:  //                          //strmImg = new DefaultStreamedContent(new FileInputStream(imgFile), el.getAttribute("mimetype","image/jpg") ,"photo");  
559:  //                          strmImg = new DefaultStreamedContent(new FileInputStream(missing), el.getAttribute("mimetype","image/jpg") ,"photo");  
560:  //                          //InputStream stream = this.getClass().getResourceAsStream("barcalogo.jpg");  
561:  //                          //image = new DefaultStreamedContent(stream, "image/jpeg");  
562:  //                          }  
563:  //                       //img.addClientBehavior("change", EventsManager.createAjaxBehaviour("onNewValue","@none"));  
564:  //                       log.info("StreamedContent name = " + strmImg.getName() + ", contentType = " + strmImg.getContentType() + ", stream = " + strmImg.getStream());  
565:  //  
566:  //                       //img.setValue(imgFile.getPath());  
567:  //                       img.setValue(strmImg.getStream());  
568:  // //                       if(strmImg != null)  
569:  // //                          img.setValue(strmImg);  
570:  // //                       else  
571:  // //                          log.severe("strmImg IS NULL");  
572:  /*  
573:                        }  
574:                      catch(FileNotFoundException e){  
575:                        log.severe("File Not Found : Message = " + e.getMessage());  
576:                        }  
577:                    catch(URISyntaxException ex){  
578:                        log.severe("Invalid URI = " + ex.getMessage());  
579:                        }*/  
580:                      }  
581:                   //pGrid.getChildren().add(img);  
582:                   pGrid.getChildren().add(fup);  
583:                   }//end if IMAGE  
584:               }  
585:            //new can be true (default for everyone), rolename(only members with a specified role)  
586:            if(pg.getAttribute("new","false").equals("true")){  
587:              //if(isChild == false){      //if its not a child  
588:              CommandButton btnNew = new CommandButton();  
589:              btnNew.setId("new_"+pg.getAttribute("table","no_table"));  
590:              btnNew.setValue("Save");  
591:              btnNew.setAjax(true);  
592:              btnNew.setAsync(true);  
593:              btnNew.setUpdate("@form");  
594:  //             CommandButton btnReset = new CommandButton();  
595:  //             btnReset.setId("reset_"+pg.getAttribute("table","no_table"));  
596:  //             btnReset.setValue("Clear");  
597:  //             btnReset.setTitle("Click to add entry");  
598:  //             btnReset.setType("reset");  
599:  //  
600:              //log.info("audit = " + pg.getAttribute("audit","false"));  
601:              //ButtonActionListener listener = new ButtonActionListener(pg.getAttribute("table","no_table"),_userId, _orgId);  
602:              ButtonActionListener listener = new ButtonActionListener(pg.getAttribute("table","no_table"),_props);  
603:              btnNew.addActionListener(listener);  
604:              if(!pg.getAttribute("input","").equals(""))          //if input is needed from a datatable.....  
605:                 listener.setInputField(pg.getAttribute("input").split(":")[1]);  
606:  //             if(!pg.getAttribute("user","").equals(""))  
607:  //                listener.setUserField(pg.getAttribute("user"));  
608:              //if either audit is true or if we want to relate loggedInUser with the new entry  
609:              if(pg.getAttribute("audit","false").equals("true") || !pg.getAttribute("user","").equals(""))  
610:                 listener.setAudit(true);  
611:              if(pg.getAttribute("tenant","false").equals("true"))  
612:                 listener.setTenant(true);  
613:              if(!pg.getAttribute("activiti","").equals(""))  
614:                 listener.setTaskVars(tVars);  
615:              /*  
616:              if(!pg.getAttribute("input","").equals(""))          //if input is needed from a datatable.....  
617:                 //btnNew.addActionListener(new ButtonActionListener(pg.getAttribute("input").split(":")[1]));  
618:                 inputField  
619:              else if(pg.getAttribute("audit","false").equals("true"))  
620:                 btnNew.addActionListener(new ButtonActionListener(_userId));  
621:              else  
622:                 btnNew.addActionListener(new ButtonActionListener());  
623:              */  
624:              //btnNew.addActionListener(EventsManager.getBlistener());  
625:              //btnNew.setActionExpression(FacesAccessor.createMethodExpression("#{dashboardBacker.onRowSelect}",Void.class, new Class[0]));  
626:              //item.setActionExpression(expFact.createMethodExpression(elCtx, "#{menuBean.add}", Void.class, new Class[]{Object.class,String.class}));  
627:              pGrid.getChildren().add(btnNew);  
628:              //pGrid.getChildren().add(btnReset);  
629:              }  
630:  //           else{          //UPDATE button needed  
631:  //             @TODO  
632:  //             CommandButton btnUpdate = new CommandButton();  
633:  //             btnNew.setId("update_"+pg.getAttribute("table","no_table"));  
634:  //             btnNew.setValue("Update");  
635:  //             btnNew.setAjax(true);  
636:  //             btnNew.setAsync(true);  
637:  //             //btnNew.setUpdate("@form");  
638:  //             btnNew.setUpdate("@form");  
639:  //             pGrid.getChildren().add(btnUpdate);  
640:  //             }  
641:            return pGrid;  
642:            }  

Programatically creating/initializing Primefaces Datatable with components

Ahoy,

This is for you Mike, and any other interested

This is very raw... (it works by the way).. i will clean it up for public use in a while...

Only look at the relevant part of the entire code...

This method should be part of a utility class (for creating datatables, schedules, gridforms, etc)...





1:   public static DataTable createDataTable(XMLElement pg, DataSource d, int _userId, int _orgId, boolean _superUser) {  
2:            setDs(d);  
3:            FacesContext fc = FacesContext.getCurrentInstance();  
4:            Application application = fc.getApplication();  
5:            ExpressionFactory ef = application.getExpressionFactory();  
6:            ELContext elc = fc.getELContext();  
7:            //Model  
8:            //if its not nested continue  
9:            //LazyModel model = new LazyModel(pg, _userId, _orgId, _superUser);          //original.. works but needs refactoring  
10:            LazyModel model = new LazyModel(getDs(), pg, _userId, _orgId, _superUser);  
11:            //model.setSuperUser(_superUser);  
12:            //if nested  
13:            //LazyModel model = new LazyModel(pg, _userId,);     //update the where in the xml dynamicaly  
14:            //Table  
15:            DataTable table = (DataTable) application.createComponent(DataTable.COMPONENT_TYPE);  
16:            table.setId("dt" + pg.getAttribute("key","x") + pg.getAttribute("keyfield","kf").replace("_",""));  
17:            //log.info("TABLE id = " + table.getId());  
18:            //table.setPrependId(false);  
19:            table.setValue(model);  
20:            table.setVar("item");  
21:            //if nopages is true or if rows is not defined.....  
22:            if(pg.getAttribute("nopages","false").equals("true") || pg.getAttribute("rows","").equals("")){  
23:              table.setPaginator(false);  
24:              }  
25:            else{  
26:              table.setPaginator(true);  
27:              table.setPaginatorPosition("bottom");  
28:              table.setRowsPerPageTemplate("5,10,15");  
29:              table.setPaginatorTemplate("{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}");  
30:              }  
31:            table.setRows(Integer.parseInt(pg.getAttribute("rows","10")));  
32:            table.setLazy(true);  
33:            table.setResizableColumns(true);  
34:            table.setDraggableColumns(true);  
35:            table.setScrollable(false);  
36:            table.setLiveScroll(false);  
37:            //if no editor and toggler.. (USED TO disable rowselection)  
38:            if(pg.getAttribute("updatetable","").equals("") && pg.getAttribute("toggler","false").equals("false") && pg.getAttribute("noselection","false").equals("false")){  
39:              table.setSelectionMode(pg.getAttribute("selectionmode","single"));  
40:              table.setEditable(false);  
41:              }  
42:            //else if (pg.getAttribute("roweditor","false").equals("true")){  
43:            else if(!pg.getAttribute("updatetable","").equals("")){  
44:              table.setSelectionMode(pg.getAttribute("selectionmode","single"));     //testing edit + delete co-existance  
45:              table.setEditable(true);  
46:              }  
47:  //           else if(!pg.getAttribute("contextmenu","").equals("")){  
48:  //            table.setSelectionMode(pg.getAttribute("selectionmode","single"));     //testing edit + delete co-existance  
49:  //            table.setEditable(true);  
50:  //            }  
51:            table.setSelection(model.getSelectedRow());  
52:            table.setTableStyle(pg.getAttribute("tablestyle","font-size:11px;text-align:left;padding-top:0px;padding-bottom:0px;padding-left:0px"));  
53:            table.setRowStyleClass(pg.getAttribute("rowstyleclass","padding:0px 0px 0px 0px;"));  
54:            table.setEmptyMessage(pg.getAttribute("emptymessage","NO DATA TO DISPLAY"));  
55:            LazyModel parentModel = null;  
56:            String link = pg.getAttribute("link","");  
57:            boolean isChild = false;  
58:            if(!link.equals("")){     //if this is a child  
59:               DataTable parent = (DataTable)FacesAccessor.getUIComponent("mainForm:dt" + link.split(":")[0] + (link.split(":")[1]).replace("_",""));  
60:               parentModel = (LazyModel)parent.getValue();  
61:               boolean added = parentModel.addChild(model,parent,table.getId());          //no need to pass the parent  
62:               //boolean added = parentModel.addChild(model, parent.getId());  
63:               isChild = true;  
64:               }  
65:            //if(pg.getAttribute("roweditor","false").equals("false")){  
66:            if(pg.getAttribute("updatetable","").equals("")){     //if no updatetable  
67:              //log.info("NORMAL (un-editable) DATATABLE");  
68:              AjaxBehavior ajaxSelect = new AjaxBehavior();  
69:              MethodExpression se = FacesAccessor.createMethodExpression("#{eventManager.onRowSelect}",Void.class, new Class[0]);  
70:              ajaxSelect.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(se));  
71:              ajaxSelect.setUpdate("@form");  
72:              table.addClientBehavior("rowSelect", ajaxSelect);  
73:             //table.addClientBehavior("rowSelect", EventsManager.createAjaxBehaviour("onRowSelect","@this")); use this  
74:              }  
75:             //else if(pg.getAttribute("roweditor","false").equals("true")){  
76:            else if(!pg.getAttribute("updatetable","").equals("") && pg.getAttribute("contextmenu","").equals("") ){     //if there is updatetable and no contextmenu  
77:              //log.info("updatetable WITHOUT contextmenu");  
78:               AjaxBehavior ajaxEdit = new AjaxBehavior();  
79:               MethodExpression ee = FacesAccessor.createMethodExpression("#{eventManager.onRowEdit}",Void.class, new Class[0]);  
80:               ajaxEdit.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(ee));  
81:               ajaxEdit.setUpdate("@this");          //  
82:               table.addClientBehavior("rowEdit", ajaxEdit);  
83:              //table.addClientBehavior("rowEdit", EventsManager.createAjaxBehaviour("onRowEdit","@this")); use this  
84:               }  
85:             //if both updatetable and contextmenu  
86:            else if(!pg.getAttribute("updatetable","").equals("") && !pg.getAttribute("contextmenu","").equals("")){     //if there is both contextmenu and updatetable  
87:              //log.info("BOTH updatetable and contextmenu PRESENT.....");  
88:               AjaxBehavior ajaxEdit = new AjaxBehavior();  
89:               MethodExpression ee = FacesAccessor.createMethodExpression("#{eventManager.onRowEdit}",Void.class, new Class[0]);  
90:               ajaxEdit.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(ee));  
91:              ajaxEdit.setUpdate("@none");  
92:               table.addClientBehavior("rowEdit", ajaxEdit);//rowEditInit  
93:              AjaxBehavior ajaxSelect = new AjaxBehavior();  
94:              MethodExpression se = FacesAccessor.createMethodExpression("#{eventManager.onRowSelect}",Void.class, new Class[0]);  
95:              ajaxSelect.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(se));  
96:              //ajaxSelect.setUpdate("@form");          //should be children only  
97:              ajaxSelect.setUpdate("@none");  
98:              //ajaxSelect.setUpdate(model.getChildrenId().toString());          //.. problem is.. by this time the children are not yet created  
99:              //log.info("ajaxSelect update = " + model.getChildrenId().toString());  
100:              //table.handleAttribute("dblClickSelect", new Boolean(true));  
101:              //table.setDblClickSelect(true);          //just to get around this race condition  
102:              table.addClientBehavior("rowSelect", ajaxSelect);  
103:               }  
104:            //this is actualy a summary row implementation  
105:            boolean group = false;  
106:            if(!pg.getAttribute("group","").equals("")){  
107:              group = true;  
108:              //table.setSortBy(parentModel.getDataIndex(pg.getAttribute("groupby")));  
109:              //if(isChild)  
110:              //table.setValueExpression("sortBy",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + model.getDataIndex(pg.getAttribute("group").split(":")[0]) + "]}", Object.class));  
111:              //table.setSortBy(model.getSelectedRow()[0]);  
112:              table.setValueExpression("sortBy", FacesAccessor.createValueExpression(elc, "#{item[" + model.getDataIndex(model.getGroupCol()) +"]}", Object.class));  
113:              table.setSortOrder("ascending");  
114:              table.addClientBehavior("sort", EventsManager.createAjaxBehaviour("onSort","@none"));  
115:              }  
116:            //Global Search (still in alpha testing)  
117:            if(pg.getAttribute("search","").equals("all")){  
118:              //table.setStyleClass(".ui-datatable .ui-datatable-header-search");  
119:              OutputPanel outPanel = new OutputPanel();  
120:              outPanel.setId("searchpanel_" + pg.getAttribute("table","no_table"));  
121:              //HtmlOutputText oText = new HtmlOutputText();  
122:              //oText.setValue("Search All Fields: ");  
123:              InputText sText = new InputText();  
124:              sText.setId("filterText");  
125:              sText.setStyle("width:150px");  
126:              //we may need p:defaultcommand instead of using the blur event..  
127:              //...or a search button that receives the table model search text and table id  
128:              sText.addClientBehavior("blur", EventsManager.createAjaxBehaviour("updateFTSSearchQuery",table.getId()));  
129:              //sText.addClientBehavior("keyup", EventsManager.createAjaxBehaviour("updateFTSSearchQuery",table.getId()));  
130:              CommandButton btnDTSearch = new CommandButton();  
131:              btnDTSearch.setId("search_" + pg.getAttribute("table","no_table"));  
132:              btnDTSearch.setValue("Search");  
133:              btnDTSearch.setAjax(true);  
134:              //btnDTSearch.setAsync(true);  
135:              btnDTSearch.setUpdate(table.getId());  
136:              btnDTSearch.addActionListener(new ButtonActionListener(model));          //search text, model  
137:              DefaultCommand dfCommand = new DefaultCommand();  
138:              dfCommand.setId("dfCommand_" + pg.getAttribute("table","no_table"));  
139:              dfCommand.setTarget(btnDTSearch.getId());  
140:              //dfCommand.setContext(outPanel.getId());          //id of parent  
141:              //outPanel.getChildren().add(oText);  
142:              outPanel.getChildren().add(sText);  
143:              outPanel.getChildren().add(btnDTSearch);  
144:              table.getFacets().put("header", outPanel);  
145:              }  
146:            if(!pg.getAttribute("header","").equals("")){  
147:              UIOutput tableTitle = (UIOutput)application.createComponent(UIOutput.COMPONENT_TYPE);  
148:              //tableTitle.setValue("Table Title");  
149:              tableTitle.setValue(pg.getAttribute("header"));  
150:              table.getFacets().put("header", tableTitle);  
151:              }  
152:            else if(isChild){     //it means we want a header here  
153:              try{  
154:                 UIOutput tableTitle = (UIOutput)application.createComponent(UIOutput.COMPONENT_TYPE);  
155:                 tableTitle.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(link.split(":")[2]) + "]}", String.class));  
156:                 //tableTitle.setStyle("font-color:blue");  
157:                 table.getFacets().put("header", tableTitle);  
158:                 }  
159:              catch(ArrayIndexOutOfBoundsException e){  
160:                 log.severe("Unable to set Child Header " + e.getMessage());  
161:                 }  
162:              }  
163:            //TABLE FOOTER  
164:            if(!pg.getAttribute("footer","").equals("")){  
165:               UIOutput tableFooter = (UIOutput)application.createComponent(UIOutput.COMPONENT_TYPE);  
166:               tableFooter.setValue(pg.getAttribute("footer"));  
167:               table.getFacets().put("footer", tableFooter);  
168:               }  
169:            if(pg.getAttribute("toggler","false").equals("true")){  
170:                 Column tcol = (Column) application.createComponent(Column.COMPONENT_TYPE);  
171:                 tcol.setId("t_col_" + pg.getAttribute("key"));  
172:                 RowToggler rt = new RowToggler();  
173:                 rt.setId("rt_id_" + pg.getAttribute("key"));  
174:                 rt.setRendered(true);  
175:                 tcol.getChildren().add(rt);  
176:                 table.getChildren().add(tcol);  
177:               }  
178:            int colIndex = 0;  
179:            for(XMLElement el : pg.getElements()) {  
180:              Column col = (Column) application.createComponent(Column.COMPONENT_TYPE);  
181:              //need to set id based on type of element.. especialy to facilitate report facility  
182:              if(el.getName().equals("JASPER"))  
183:                 col.setId("col_report" + colIndex + "_" + pg.getAttribute("key"));  
184:              else  
185:                 col.setId("col_" + el.getValue() + "_" + pg.getAttribute("key"));  
186:              if(!el.getAttribute("style","").equals("")){  
187:               col.setStyle(el.getAttribute("style"));  
188:               }  
189:               //buttons need to be added to the parent panel not to the datatable itself  
190:                if(el.getName().equals("ACTIONS")){  
191:                   //log.info("FOUND ACTIONS");  
192:                   col.setSelectionMode(pg.getAttribute("selectionmode","single"));  
193:                  table.setSelectionMode(null);  
194:                   table.getChildren().add(col);  
195:                 AjaxBehavior ajaxSelect = new AjaxBehavior();  
196:                 MethodExpression se = FacesAccessor.createMethodExpression("#{eventManager.onRowSelect}",Void.class, new Class[0]);  
197:                 ajaxSelect.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(se));  
198:                 ajaxSelect.setUpdate("@none");  
199:                 table.addClientBehavior("rowSelectRadio", ajaxSelect);  
200:                   continue;          //TO NEXT ITERATION  
201:                   }  
202:               if(el.getAttribute("selectionmode","").equals("multiple")){  
203:                   //log.info("FOUND ACTIONS");  
204:                   col.setSelectionMode("multiple");  
205:                  table.setSelectionMode(null);  
206:                 table.setSelection(model.getSelectedRows());  
207:                   table.getChildren().add(col);  
208:                  AjaxBehavior ajaxSelect = new AjaxBehavior();  
209:                  MethodExpression se = FacesAccessor.createMethodExpression("#{eventManager.onMultipleSelect}",Void.class, new Class[0]);  
210:                  ajaxSelect.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(se));  
211:                  ajaxSelect.setUpdate("@none");  
212:                  table.addClientBehavior("rowSelectCheckbox", ajaxSelect);  
213:  //                AjaxBehavior ajaxUnSelect = new AjaxBehavior();  
214:  //                MethodExpression ume = FacesAccessor.createMethodExpression("#{eventManager.onRowUnSelect}",Void.class, new Class[0]);  
215:  //                ajaxUnSelect.addAjaxBehaviorListener(new AjaxBehaviorListenerImpl(ume));  
216:  //                ajaxUnSelect.setUpdate("@none");  
217:  //                table.addClientBehavior("rowUnSelectCheckbox", ajaxUnSelect);  
218:                 //rowUnselectcheckbox  
219:                   //continue;          //TO NEXT ITERATION  
220:                   }  
221:              col.setValueExpression("sortBy", FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class));  
222:              UIOutput colTitle = (UIOutput)application.createComponent(UIOutput.COMPONENT_TYPE);  
223:              colTitle.setValue(el.getAttribute("title","No Title"));  
224:              col.getFacets().put("header", colTitle);  
225:              //if footer present  
226:              if(!el.getAttribute("footer","").equals("")){  
227:                 UIOutput colFooter = (UIOutput)application.createComponent(UIOutput.COMPONENT_TYPE);  
228:                 colFooter.setValue(el.getAttribute("footer"));  
229:                 col.getFacets().put("footer", colFooter);  
230:                 }  
231:              //search  
232:              if(!el.getAttribute("filtermode","").equals("")){  
233:                  col.setValueExpression("filterBy", FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class));  
234:                  col.setFilterMatchMode(el.getAttribute("filtermode","contains"));  
235:                 }  
236:              //col.getFacets().put("footer", colTitle);  
237:              if(pg.getAttribute("subtables","").equals("")){  
238:                 table.getChildren().add(col);  
239:                 }  
240:  /*  
241:              else{  
242:                 log.info("SUBTABLE FOUND");  
243:                 SubTable stable = new SubTable();  
244:                 UIOutput subTitle = (UIOutput)application.createComponent(UIOutput.COMPONENT_TYPE);  
245:                 //subTitle.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(pg.getAttribute("subtables")) + "]}", String.class));  
246:                 subTitle.setValue("Sub Header");  
247:                 stable.getFacets().put("header", subTitle);  
248:                 stable.setVar(table.getVar());  
249:                 stable.setValue(table.getValue());  
250:                 stable.getChildren().add(col);  
251:                 table.getChildren().add(stable);  
252:                 }*/  
253:              // Create <h:outputText value="#{dataItem.id}"> for the body of the column.  
254:              if(el.getName().equals("TEXTFIELD")){  
255:                 if(el.getAttribute("edit","false").equals("true")){  
256:                      //log.info("Found EDITABLE field: " + el.getAttribute("title"));  
257:                      CellEditor ce = new CellEditor();  
258:                      ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class);  
259:                      HtmlOutputText colOutput = new HtmlOutputText();//(HtmlOutputText)application.createComponent( HtmlOutputText.COMPONENT_TYPE );  
260:                      InputText colInput = new InputText();//(InputText)application.createComponent(InputText.COMPONENT_TYPE);  
261:                      //colInput.setSize(Integer.parseInt(el.getAttribute("w","20")));  
262:                      if(!el.getAttribute("style","").equals("")){  
263:                           colInput.setStyle(el.getAttribute("style"));  
264:                           colOutput.setStyle(el.getAttribute("style"));  
265:                           }  
266:                      colInput.setValueExpression("value", colValueExp);  
267:                      colOutput.setValueExpression("value", colValueExp);  
268:                      ce.getFacets().put("output", colOutput);  
269:                      ce.getFacets().put("input", colInput);  
270:                      col.getChildren().add(ce);  
271:                      }  
272:                 else{          //normal processing  
273:                    ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class);  
274:                    HtmlOutputText colOutput = (HtmlOutputText)application.createComponent(HtmlOutputText.COMPONENT_TYPE);  
275:                    colOutput.setValueExpression("value", colValueExp);  
276:                    //colOutput.setSize(Integer.parseInt(el.getAttribute("w","20")));  
277:                    if(!el.getAttribute("style","").equals(""))  
278:                           colOutput.setStyle(el.getAttribute("style"));  
279:                    col.getChildren().add(colOutput);  
280:                    }  
281:                 }  
282:              else if(el.getName().equals("TEXTDECIMAL")){  
283:                 col.setStyle(el.getAttribute("style","text-align:right"));  
284:                 if(el.getAttribute("edit","false").equals("true")){  
285:                      CellEditor ce = new CellEditor();  
286:                      ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class);  
287:                      HtmlOutputText colOutput = new HtmlOutputText();//(HtmlOutputText)application.createComponent( HtmlOutputText.COMPONENT_TYPE );  
288:                      InputText colInput = new InputText();//(InputText)application.createComponent(InputText.COMPONENT_TYPE);  
289:                      if(!el.getAttribute("style","").equals(""))  
290:                           colInput.setStyle(el.getAttribute("style"));  
291:                      colInput.setValueExpression("value", colValueExp);  
292:                      colOutput.setValueExpression("value", colValueExp);  
293:                      ce.getFacets().put("output", colOutput);  
294:                      ce.getFacets().put("input", colInput);  
295:                      col.getChildren().add(ce);  
296:                      }  
297:                   else{  
298:                      ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class);  
299:                      HtmlOutputText colOutput = (HtmlOutputText)application.createComponent(HtmlOutputText.COMPONENT_TYPE);  
300:                      colOutput.setValueExpression("value", colValueExp);  
301:                      //thousands separator using regex (make sure there are no more than two(2) decimal places  
302:                      //x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");  
303:                      col.getChildren().add(colOutput);  
304:                      }  
305:                   }  
306:                 else if(el.getName().equals("TEXTDATE")){  
307:                    if(el.getAttribute("edit","false").equals("true")){  
308:                         CellEditor ce = new CellEditor();  
309:                         ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class);  
310:                         HtmlOutputText colOutput = new HtmlOutputText();//(HtmlOutputText)application.createComponent( HtmlOutputText.COMPONENT_TYPE );  
311:                         Calendar colInput = new Calendar();  
312:                         colInput.setPattern("yyyy MMM dd");  
313:                         colInput.setShowButtonPanel(true);  
314:                         colInput.setNavigator(true);  
315:                         if(!el.getAttribute("style","").equals("")){  
316:                            colInput.setStyle(el.getAttribute("style"));  
317:                            colOutput.setStyle(el.getAttribute("style"));  
318:                            }  
319:                         colInput.setValueExpression("value", colValueExp);  
320:                         colOutput.setValueExpression("value", colValueExp);  
321:                         ce.getFacets().put("output", colOutput);  
322:                         ce.getFacets().put("input", colInput);  
323:                         col.getChildren().add(ce);  
324:                         }  
325:                      else{  
326:                         ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class);  
327:                         HtmlOutputText colOutput = (HtmlOutputText)application.createComponent(HtmlOutputText.COMPONENT_TYPE);  
328:                         colOutput.setValueExpression("value", colValueExp);  
329:                         if(!el.getAttribute("style","").equals("")){  
330:                            colOutput.setStyle(el.getAttribute("style"));  
331:                            }  
332:                         col.getChildren().add(colOutput);  
333:                         }  
334:                   }  
335:               else if(el.getName().equals("COMBOBOX")){  
336:                      //A COMBOBOX in a DataTable is always editable (otherwise just use TEXTFIELD)  
337:                      //log.info("Found EDITABLE field: " + el.getAttribute("title"));  
338:                      CellEditor ce = new CellEditor();  
339:                      SelectOneMenu cmbbox = new SelectOneMenu();  
340:                      cmbbox.setId("cmbbox" + "_" + el.getValue());  
341:                      String wheresql = el.getAttribute("wheresql");  
342:                      List<Object[]> cdata = IOService.getListFromResultSet(getDs(), "SELECT " + (el.getAttribute("lpkey",el.getValue())) + "," + el.getAttribute("lpfield") + " FROM " + el.getAttribute("lptable") + (wheresql==null?"":" WHERE " + wheresql));  
343:                      List<SelectItem> items = new ArrayList<SelectItem>();  
344:                      for(Object[] dt : cdata) {  
345:                           items.add(new SelectItem(dt[0], (String)dt[1]));  
346:                             }  
347:                      UISelectItems selectItems = new UISelectItems();  
348:                      selectItems.setValue(items);  
349:                      selectItems.setId("si" + "_" + el.getValue());  
350:                      cmbbox.getChildren().add(selectItems);  
351:                      ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class);  
352:                      HtmlOutputText colOutput = new HtmlOutputText();//(HtmlOutputText)application.createComponent( HtmlOutputText.COMPONENT_TYPE );  
353:                      SelectOneMenu colInput = cmbbox;  
354:                      if(!el.getAttribute("style","").equals("")){  
355:                           colInput.setStyle(el.getAttribute("style"));  
356:                           colOutput.setStyle(el.getAttribute("style"));  
357:                           }  
358:                      colInput.setValueExpression("value", colValueExp);  
359:                      colOutput.setValueExpression("value", colValueExp);  
360:                      ce.getFacets().put("output", colOutput);  
361:                      ce.getFacets().put("input", colInput);  
362:                      col.getChildren().add(ce);  
363:                      }  
364:               else if(el.getName().equals("COMBOLIST")){  
365:                   if(el.getAttribute("edit","false").equals("true")){  
366:                      //log.info("Found EDITABLE field: " + el.getAttribute("title"));  
367:                      CellEditor ce = new CellEditor();  
368:                      //combolist test  
369:                      SelectOneMenu cmblist = new SelectOneMenu();  
370:                      cmblist.setId("cmblist" + "_" + el.getValue());  
371:                      List<XMLElement> data = el.getElements();  
372:                      List<SelectItem> items = new ArrayList<SelectItem>();  
373:                      for(XMLElement dt : data) {  
374:                             if(dt.getName().equals("DATA")){     //HAS TO BE A DATA  
375:                                items.add(new SelectItem(dt.getAttribute("key","-1"), dt.getValue()));  
376:                               }//end if DATA  
377:                             }  
378:                      UISelectItems selectItems = new UISelectItems();  
379:                      selectItems.setValue(items);  
380:                      selectItems.setId("si" + "_" + el.getValue());  
381:                      cmblist.getChildren().add(selectItems);  
382:                      //end test  
383:                      ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class);  
384:                      HtmlOutputText colOutput = new HtmlOutputText();//(HtmlOutputText)application.createComponent( HtmlOutputText.COMPONENT_TYPE );  
385:                      //InputText colInput = new InputText();//(InputText)application.createComponent(InputText.COMPONENT_TYPE);  
386:                      SelectOneMenu colInput = cmblist;  
387:                      colInput.setValueExpression("value", colValueExp);  
388:                      colOutput.setValueExpression("value", colValueExp);  
389:                      //log.info("colInput value=" + colInput.getValue());  
390:                      //log.info("colOutput value=" + colOutput.getValue());  
391:                      ce.getFacets().put("output", colOutput);  
392:                      ce.getFacets().put("input", colInput);  
393:                      col.getChildren().add(ce);  
394:                      }  
395:                 else{          //normal processing  
396:                    ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class);  
397:                    HtmlOutputText colOutput = (HtmlOutputText)application.createComponent(HtmlOutputText.COMPONENT_TYPE);  
398:                    colOutput.setValueExpression("value", colValueExp);  
399:                    col.getChildren().add(colOutput);  
400:                    }  
401:                   }  
402:               else if(el.getName().equals("GRIDFORM")){  
403:                   childgrid = el;  
404:                   }  
405:               else if(el.getName().equals("JASPER")){  
406:                   Button jreport = new Button();  
407:                   jreport.setValue("Download");  
408:                    ValueExpression hrefValueExp = FacesAccessor.createValueExpression(elc, "report?jasper=" + el.getAttribute("jasper","jasper") + "&pdfname=" + el.getAttribute("pdfname","Report") + "&filterid=#{item[0]}", String.class);  
409:                   jreport.setValueExpression("href", hrefValueExp);  
410:                   jreport.setTitle(el.getAttribute("tooltip","Click to view"));  
411:                   col.getChildren().add(jreport);  
412:                   }  
413:               else if(el.getName().equals("CHECKBOX")){  
414:                 if(el.getAttribute("edit","false").equals("true")){  
415:                      CellEditor ce = new CellEditor();  
416:                      ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class);  
417:                      HtmlOutputText colOutput = new HtmlOutputText();//(HtmlOutputText)application.createComponent( HtmlOutputText.COMPONENT_TYPE );  
418:                      SelectBooleanCheckbox colInput = new SelectBooleanCheckbox();//(InputText)application.createComponent(InputText.COMPONENT_TYPE);  
419:                      colInput.setValueExpression("value", colValueExp);  
420:                      colOutput.setValueExpression("value", colValueExp);  
421:                      ce.getFacets().put("output", colOutput);  
422:                      ce.getFacets().put("input", colInput);  
423:                      col.getChildren().add(ce);  
424:                      }  
425:                   else{  
426:                      ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{item[" + colIndex + "]}", Object.class);  
427:                      HtmlOutputText colOutput = (HtmlOutputText)application.createComponent(HtmlOutputText.COMPONENT_TYPE);  
428:                      colOutput.setValueExpression("value", colValueExp);  
429:                      col.getChildren().add(colOutput);  
430:                      }  
431:                   }  
432:              else if(el.getName().equals("IMAGE")){  
433:                   GraphicImage colOutput = (GraphicImage)application.createComponent(GraphicImage.COMPONENT_TYPE);  
434:                   colOutput.setHeight(el.getAttribute("h","50"));  
435:                   colOutput.setWidth(el.getAttribute("w","50"));  
436:                   colOutput.setAlt("No Photo");  
437:                   ValueExpression colValueExp = FacesAccessor.createValueExpression(elc, "#{imageBean.getImageBytes(\"select " + el.getValue() + " from " + pg.getAttribute("table","table") + " where " + pg.getAttribute("keyfield","kf") + " = ?\")}", DefaultStreamedContent.class);  
438:                   UIParameter param = new UIParameter();  
439:                   param.setName("pk");  
440:                   param.setValueExpression("value",FacesAccessor.createValueExpression(elc, "#{item[0]}", String.class));     //this is OK coz pk is always at index 0  
441:                   //default image in case of missing photo ?  
442:                   UIParameter missing = new UIParameter();  
443:                   missing.setName("missing");  
444:                   missing.setValue("missing1.jpg");  
445:                   colOutput.getChildren().add(param);  
446:                   colOutput.getChildren().add(missing);  
447:                   FacesContext context = FacesContext.getCurrentInstance();  
448:                   if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {  
449:                      log.info("at RENDER RESPONSE");  
450:                      //colOutput.setValue(new DefaultStreamedContent());  
451:                      }  
452:                   else{  
453:                      colOutput.setValueExpression("value", colValueExp);  
454:                      }  
455:                   col.getChildren().add(colOutput);  
456:                  }  
457:              else if(el.getName().equals("DATATABLE")){  
458:                    ValueExpression nestValueExp = FacesAccessor.createValueExpression(elc, el.getAttribute("wheresql") + "= #{item[0]}", String.class);  
459:                   //ValueExpression wVE = FacesAccessor.createValueExpression(elc, "#{item[0]}", String.class);  
460:                   //el.removeAttribute("wheresql")  
461:                   //el.setAttribute("wheresql", (pg.getAttribute("keyfield") + "=5"));  
462:                   //el.setAttribute("wheresql", (innerTable.getAlt() + " " + wVE));  
463:                   //log.info("nesting link: " + el.getAttribute("wheresql"));  
464:                   //NESTED DATATABLEs SEEM technicaly INFEASIBLE !!!!!!!  
465:                   DataTable innerTable = createDataTable(el, getDs(), -1, _orgId, _superUser);  
466:                   innerTable.setValueExpression("emptyMessage",nestValueExp);  
467:                   //log.info("INNER TABLE emptyMessage = " + innerTable.getEmptyMessage());  
468:                   col.getChildren().add(innerTable);  
469:                   }  
470:              colIndex++;  
471:              if(el.getAttribute("visible","true").equals("false"))  
472:                  col.setRendered(false);  
473:              }  
474:            //if(pg.getAttribute("toggler","false").equals("true")){  
475:            if(childgrid != null){  
476:              //log.info("CREATING ROWEXPANSION...");  
477:              RowExpansion expCol = (RowExpansion) application.createComponent(RowExpansion.COMPONENT_TYPE);  
478:              expCol.setId("xpcol" + pg.getAttribute("key"));  
479:              HtmlPanelGrid xGrid = buildGridForm(childgrid,model,getDs(), new HashMap<String,String>(), _userId, _orgId);  
480:              //HtmlPanelGrid xGrid = buildGridForm(childgrid,true);  
481:              expCol.getChildren().add(xGrid);  
482:              table.getChildren().add(expCol);  
483:              }  
484:          //if(pg.getAttribute("roweditor","false").equals("true")){  
485:          if(!pg.getAttribute("updatetable","").equals("")){  
486:              //Testing row editor  
487:              Column rowCol = (Column) application.createComponent(Column.COMPONENT_TYPE);  
488:              RowEditor re = new RowEditor();  
489:              rowCol.getChildren().add(re);  
490:              table.getChildren().add(rowCol);  
491:              }  
492:          if(group){  
493:             SummaryRow sRow = new SummaryRow();  
494:             sRow.setId("sr" + table.getId());  
495:             MethodExpression MESummary = FacesAccessor.createMethodExpression("#{eventManager.summaryRowSum}",String.class, String.class);  
496:             sRow.setListener(MESummary);  
497:             Column col1 = (Column)application.createComponent(Column.COMPONENT_TYPE);  
498:             //col1.setColspan(2);  
499:             col1.setColspan(Integer.parseInt(pg.getAttribute("colspan","2")));  
500:             col1.setStyle("text-align:right");  
501:             HtmlOutputText sumLabel = new HtmlOutputText();     //summary label  
502:             //sumLabel.setValue("Summary");  
503:             sumLabel.setValue(pg.getAttribute("group").split(":")[2]);  
504:             col1.getChildren().add(sumLabel);  
505:             Column col2 = (Column)application.createComponent(Column.COMPONENT_TYPE);  
506:             //ValueExpression valExp = FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + parentModel.getDataIndex(pg.getAttribute("group").split(":")[1]) + "]}", Object.class);  
507:             //ValueExpression valExp = FacesAccessor.createValueExpression(elc, "#{eventManager.currentRow[" + model.getDataIndex(pg.getAttribute("group").split(":")[1]) + "]}", Object.class);  
508:             ValueExpression valExp = FacesAccessor.createValueExpression(elc, "#{eventManager.summary}", Object.class);  
509:             HtmlOutputText sumValue = new HtmlOutputText();  
510:             sumValue.setValueExpression("value", valExp);  
511:             col2.getChildren().add(sumValue);  
512:             //now add the columns to the summary row  
513:             sRow.getChildren().add(col1);  
514:             sRow.getChildren().add(col2);  
515:             table.getChildren().add(sRow);  
516:             }  
517:       return table;  
518:       }  

Wednesday, July 30, 2014

WorkmateHR


Payroll and HR management the easy way....

Let this short video say the rest....


WorkmateHR from Mabura ZeGuru on Vimeo.

Friday, June 27, 2014

Dynamic SQL UPDATE


NEED TO UPDATE table columns with dynamic values (not known in advance).

A. ORACLE 

i.Single-Column update
   [Working example.. just replace table names]

   UPDATE station s
        SET vhf_network_id = 
                (
                SELECT vhf_network_id
                FROM vhf_network v  
                WHERE s.client_license_id = v.client_license_id
                )
        WHERE s.station_charge_id = 5;
 
ii. Multiple update
    The key here is to maintain the order and count of the columns in the source columnlist and destination columnlist

  UPDATE
    SET () = 
          (
          SELECT
          FROM
          WHERE
          )
    WHERE ;





B. POSTGRES EQUIVALENT


   Working example (difference with the above is the absence of INNER SELECT)

  UPDATE station s
      SET vhf_network_id = v.vhf_network_id
    FROM vhf_network v
    WHERE s.client_license_id = vhf_network.client_license_id;


Friday, June 6, 2014

Delivery Reports (DLR) in kannel

Good Mawwwwwning nerdmigos,

You (name hidden) requested my assistance on doing DLR in kannel. There you are, kaz qwako

There are a few approaches but the following (and derivaties) has never let me down.

I dont know if its only me, but on kannel release 1.4.3 you are ONLY able to get DLR when u set dlr-mask to 31


The following approach (or similar) has never let me down...

a. kanne.conf

#TRIGGER
group = sms-service
keyword = trigger
aliases = triger
get-url = "http://192.168.1.45:8080/mwasima/trigger?keyword=%k&client=%s&service=%s&sender=%p&time=%t&dlrmask=31&dbtype=postgres&smsgateway=192.168.1.30"
omit-empty = true


and the following (proxy) function to push sms

b.  IOLogic.java


public static String sendSMS(int smsid, String receiver, String sms, boolean flash, String webapp, String smsgateway){
        String clean_sms = sms.replace(" ","%20");        //we can do better than this !!!!!
       
        String reply = "";

        log.info("ATTEMPTING to send [" + sms + "] to " + receiver);

        dlrurl = encodeURL(webapp + "/dlr?smsid=" + smsid + "&dest=" + receiver  + "&type=%d&dlr=%A");

       
        try{
       
            URL send_sms_url = new URL("http://" + smsgateway + ":13013/cgi-bin/sendsms?username=" + ux +"&password=" + px +(flash==true?"&mclass=0":"")+ "&to=" + receiver +"&text=" + clean_sms + "&dlr-mask=" + dlrmask + "&dlr-url=" + dlrurl);
            log.info("send sms url = " + send_sms_url);

            URLConnection url_con = send_sms_url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(url_con.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null){
                reply += inputLine;
                }

            in.close();
            return reply;
            }
        catch(IOException e){
            log.severe("Error at sendSMS(): " + e.getMessage());
            return "IOException [" + receiver + ", " + sms + "]";
            }
        }




and the finaly the following function to persist DLR

c.  IOLogic.java

    //INSERT DELIVERY REPORTS
    public static void insDLR(DataSource d, int _smsID, String _smsText, String _dest, String _status, String _report){

           try{
              Connection con = null;
               con = d.getConnection();
               con.setAutoCommit(false);

              PreparedStatement ps = con.prepareStatement("INSERT INTO sms_dlr_log(sms_id, sms_text, destination, dlr_status, dlr_report) VALUES(?,?,?,?,?)");  

              ps.setInt(1, _smsID);
              ps.setString(2, _smsText);
              ps.setString(3, _dest);
              ps.setString(4, _status);
              ps.setString(5, _report);

              int u = ps.executeUpdate();

              con.commit();        //explicit commit

              con.setAutoCommit(true);
              con.close();
               }

          catch(SQLException ex){
               log.severe("Message:" + ex.getMessage() + ": Failed to log DLR");
              }
          catch(ClassCastException exx){
               log.severe("Message:" + exx.getMessage() + ": Failed to log DLR");
               }

        }



Easy isnt it ??
Question: what if a Servlet wants to reply directly (instead of calling sendsms url) to the request and at the same time ask for a DLR ?? 
Answer (tongue in cheek): we need to employ x-kannel-headers

In ur doGet() method do the following



public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {

      this.request = request;
        this.response = response;
        response.setContentType("text/html");

        webapp = "http://" + request.getServerName() + ":" + request.getLocalPort() + request.getContextPath();
    //We need to set accept-x-kannel-headers = true in kannel.conf
    response.addHeader("X-Kannel-DLR-Mask", "31");
        smsbody = request.getParameter("smsbody");       
    receiver = request.getParameter("receiver");

    dlrurl = webapp + "/dlr?smsid=1&dest=" + receiver + "&type=%d&dlr=%A&localsmsid=%I&remotesmsid=%F&smsuser=%n";
        response.addHeader("X-Kannel-DLR-Url", dlrurl);
        this.out = response.getWriter();

       //DO UR MAGIC HERE
    //then finaly send ur reply
        out.println("UR REPLY HERE");
    }



...NOW U CAN HUG URSELF