View Javadoc

1   /*
2    * Criado em 28/10/2004
3    *
4    */
5   package ecar.taglib.util;
6   
7   import java.io.IOException;
8   import java.util.ArrayList;
9   import java.util.Collection;
10  import java.util.Iterator;
11  import java.util.List;
12  
13  import javax.servlet.jsp.JspException;
14  import javax.servlet.jsp.JspWriter;
15  import javax.servlet.jsp.PageContext;
16  import javax.servlet.jsp.tagext.Tag;
17  
18  import org.apache.log4j.Logger;
19  import org.hibernate.Criteria;
20  import org.hibernate.Session;
21  import org.hibernate.criterion.Expression;
22  import org.hibernate.criterion.Order;
23  
24  import comum.database.Dao;
25  import comum.util.Util;
26  
27  /**
28   * @author felipev
29   * 
30   * Taglib para geração de listas para seleção múltipla (Checkbox)
31   *
32   */
33  public class CheckListTag implements Tag{
34      
35  	/**
36  	 * Nome dos checkbox. Obrigatório
37  	 */
38  	private String nome;
39  	/**
40  	 * Objetos que serão listados para a criação da lista. Obrigatório. Ex: ecar.pojo.AreaAre
41  	 */	
42  	private String objeto;	
43  	/**
44  	 * Vetor com os values selecionados por default
45  	 */
46  	private Collection selected;	
47  	/**
48  	 * Atributo do objeto que servirá como label para os checkbox. Obrigatório.
49  	 */
50  	private String label;
51  	/**
52  	 * Atributo do objeto que servirá como Value para os checkbox. Obrigatório;
53  	 */
54  	private String value;
55  	/**
56  	 * Atributo do objeto pelo qual será feita a ordenação dos registros na combo
57  	 */
58  	private String order;
59  	/**
60  	 * Filtros que podem ser usados para restringir a lista de registros apresentados. Devem ser informados na forma
61  	 * "atributo=valor;atributo=valor". Ex: filters="indAtivoAre=S;nomeAre=Saúde"
62  	 */
63  	private String filters;
64  	/**
65  	 * Funcões javascrip que podem ser chamadas quando ocorrem eventos com as opções.
66  	 * Ex: scripts="onclick=\"funcao1()\" onchange=\"funcao2()\""
67  	 */
68  	private String scripts;
69  	
70  	/**
71  	 * Coleção de registros que serão parensentados na lista. Caso esse parâmetro seja informado o taglib não fará o select no 
72  	 * objeto selecionado e retornará somente os elementos desta Collection
73  	 */
74  	private Collection colecao;
75  	
76  	/**
77  	 * Lista com objetos que não aparecerão na Check list
78  	 */
79  	private Collection objetosExcluidos;
80  	
81  	private PageContext page = null;	
82  	
83  	/**
84  	 * Inicializa a montagem da tag para ser adicionada na tela de HTML.<br>
85  	 * 
86  	 * @author N/C
87  	 * @since N/C
88  	 * @version N/C
89  	 * @return int
90  	 * @throws JspException
91  	 */
92  	public int doStartTag() throws JspException {
93  		JspWriter writer = this.page.getOut();
94  		StringBuffer s = new StringBuffer();
95  		try {
96  			
97  			List itensLista = new ArrayList();
98  			
99  			/** Cria uma instância do objeto **/	
100 		    Object obj = Class.forName(getObjeto()).newInstance();
101 		    Dao dao = new Dao();
102 		    Session session = dao.getSession();
103 			
104 			if (getColecao() == null){
105 			    /** Cria um criteria para selecionar o objeto desejado **/
106 			    Criteria select = session.createCriteria( Class.forName(getObjeto()) );
107 			    
108 			    /** Adiciona os parâmetros na query **/
109 			    if(filters != null && !"".equals(filters)){
110 			        String parametros[] = filters.split(";");
111 			        for(int i = 0; i < parametros.length; i++){
112 			            String[] chaveValor = parametros[i].split("=");
113 			            select.add(Expression.like(chaveValor[0], chaveValor[1]));		            
114 			        }
115 				 }
116 			    
117 			    /** Define a ordem dos resultados **/
118 			    select.addOrder(Order.asc(order));
119 			    itensLista = select.list();
120 			}else{
121 				itensLista.addAll(getColecao());
122 			}
123 		    
124 		    /** Executa a query **/
125 		    Iterator it = itensLista.iterator();
126 		     
127 		    while(it.hasNext()){
128 		        obj = it.next();
129 		        if( (objetosExcluidos == null) || ( objetosExcluidos != null && !objetosExcluidos.contains(obj) ) ){		            
130 				        s.append("<input type=\"checkbox\" class=\"form_check_radio\" name=\"").append(getNome()).append("\" value=\"");
131 				        /** invoca o Método getXXXX para recuperar o valor do atributo value **/
132 				        Object value = Class.forName(getObjeto()).getMethod("get"+ Util.primeiraLetraToUpperCase(getValue()), null).invoke(obj, null);
133 				        s.append(value);		        
134 				        s.append("\"");
135 				        if(getSelected()!= null){
136 				            Iterator itValue = getSelected().iterator();
137 				            while(itValue.hasNext()){
138 				                if( (itValue.next().toString()).equals(value.toString())){
139 				                    s.append(" checked ");        
140 				                }
141 				            }
142 				        }
143 				        if(scripts!= null && !"".equals(scripts))
144 				            s.append(" ").append(scripts);
145 				        s.append(">");
146 				        if (!this.isMultiLabel())
147 	                    {
148 				        	/** invoca o Método getXXXX para recuperar o valor do atributo label **/
149 				        	s.append(Class.forName(getObjeto()).getMethod("get"+ Util.primeiraLetraToUpperCase(getLabel()), null).invoke(obj, null));
150 	                    }
151 				        else
152 	                    {
153 	                    	Iterator itLabels = this.getLabels().iterator();
154 	                    	while (itLabels.hasNext())
155 	                    	{
156 					        	s.append(Class.forName(getObjeto()).getMethod("get"+ Util.primeiraLetraToUpperCase((String)itLabels.next()), null).invoke(obj, null));
157 	                        	s.append(" - ");
158 	                    	}
159 	                    	s.deleteCharAt(s.length()-2);                    	
160 	                    }
161 				        s.append("<br>");		           
162 		        }
163 		    }		    
164 		    writer.print(s.toString());
165 		} catch (Exception e) {
166         	Logger logger = Logger.getLogger(this.getClass());
167         	logger.error(e);
168 	    	try{
169 	    	    writer.print("Erro na geração da CheckList: " + e.getMessage());
170 	        	logger.error(e);
171 	    	}catch(IOException ioE){
172 	        	logger.error(ioE);
173 	    	}   	
174 		}
175 		return Tag.EVAL_BODY_INCLUDE;
176 	}
177 
178 	/**
179 	 * Retorna List labels.<br>
180 	 * 
181 	 * @author N/C
182 	 * @since N/C
183 	 * @version N/C
184 	 * @return List
185 	 */
186     public List getLabels()
187     {
188         String labelAux = label;
189         List labels = new ArrayList();
190     	while(labelAux.lastIndexOf(",") != -1){
191     		labels.add(labelAux.substring(0, labelAux.indexOf(",")));
192     		labelAux = labelAux.substring(labelAux.indexOf(",") + 1);
193         }      
194     	labels.add(labelAux);
195     	
196     	return labels;
197     }
198     
199     /**
200      * Verifica se e MultiLabel.<br>
201      * 
202      * @author N/C
203 	 * @since N/C
204 	 * @version N/C
205      * @return boolean
206      */
207     public boolean isMultiLabel()
208     {
209     	if (this.getLabel().lastIndexOf(",") == -1)
210     			return false;
211     	return true;
212     }
213 	
214 	/**
215 	 * Atribui valor especificado para PageContext page.<br>
216 	 * 
217 	 * @author N/C
218 	 * @since N/C
219 	 * @version N/C
220 	 * @param PageContext arg0
221 	 */
222 	public void setPageContext(PageContext arg0) {
223 		this.page = arg0;
224 	}
225 
226 	/**
227 	 * 
228 	 * 
229 	 * @author N/C
230 	 * @since N/C
231 	 * @version N/C
232 	 * @param Tag arg0
233 	 */
234 	public void setParent(Tag arg0) {
235 	}
236 
237 	/**
238 	 * Retorna null.<br>
239 	 * 
240 	 * @author N/C
241 	 * @since N/C
242 	 * @version N/C
243 	 * @return Tag
244 	 */
245 	public Tag getParent() {
246 		return null;
247 	}
248 	
249 	/**
250 	 * Encerra Tag.<br>
251 	 * 
252 	 * @author N/C
253 	 * @since N/C
254 	 * @version N/C
255 	 * @return int
256 	 * @throws JspException
257 	 */
258 	public int doEndTag() throws JspException {
259 		return Tag.EVAL_PAGE;
260 	}
261 
262 	/**
263 	 * 
264 	 * 
265 	 * @author N/C
266 	 * @since N/C
267 	 * @version N/C
268 	 */
269 	public void release() {
270 		//this.selected = null;
271 	}
272 	
273     /**
274      * Retorna PageContext page.<br>
275      * 
276      * @author N/C
277 	 * @since N/C
278 	 * @version N/C
279      * @return PageContext - (Returns the page).
280      */
281     public PageContext getPage() {
282         return page;
283     }
284     /**
285      * Atribui valor especificado para PageContext page.<br>
286      * 
287      * @author N/C
288 	 * @since N/C
289 	 * @version N/C
290      * @param PageContext page - (The page to set)
291      */
292     public void setPage(PageContext page) {
293         this.page = page;
294     }
295     /**
296      * Retorna String filters.<br>
297      * 
298      * @author N/C
299 	 * @since N/C
300 	 * @version N/C
301      * @return String - (Returns the filters)
302      */
303     public String getFilters() {
304         return filters;
305     }
306     
307     /**
308      * Atribui valor especificado para String filters.<br>
309      * 
310      * @author N/C
311 	 * @since N/C
312 	 * @version N/C
313      * @param String filters - (The filters to set)
314      */
315     public void setFilters(String filters) {
316         this.filters = filters;
317     }
318     
319     /**
320      * Retorna String label.<br>
321      * 
322      * @author N/C
323 	 * @since N/C
324 	 * @version N/C
325      * @return String - (Returns the label)
326      */
327     public String getLabel() {
328         return label;
329     }
330     
331     /**
332      * Atribui valor especificado para String label.<br>
333      * 
334      * @author N/C
335 	 * @since N/C
336 	 * @version N/C
337      * @param String label - (The label to set)
338      */
339     public void setLabel(String label) {
340         this.label = label;
341     }
342     
343     /**
344      * Retorna String nome.<br>
345      * 
346      * @author N/C
347 	 * @since N/C
348 	 * @version N/C
349      * @return String - (Returns the nome)
350      */
351     public String getNome() {
352         return nome;
353     }
354     
355     /**
356      * Atribui valor especificado para String nome.<br>
357      * 
358      * @author N/C
359 	 * @since N/C
360 	 * @version N/C
361      * @param String nome - (The nome to set)
362      */
363     public void setNome(String nome) {
364         this.nome = nome;
365     }
366     
367     /**
368      * Retorna String objeto.<br>
369      * 
370      * @author N/C
371 	 * @since N/C
372 	 * @version N/C
373      * @return String - (Returns the objeto)
374      */
375     public String getObjeto() {
376         return objeto;
377     }
378     
379     /**
380      * Atribui valor especificado para String objeto.<br>
381      * 
382      * @author N/C
383 	 * @since N/C
384 	 * @version N/C
385      * @param String objeto - (The objeto to set)
386      */
387     public void setObjeto(String objeto) {
388         this.objeto = objeto;
389     }
390     
391     /**
392      * Retorna String order.<br>
393      * 
394      * @author N/C
395 	 * @since N/C
396 	 * @version N/C
397      * @return String - (Returns the order)
398      */
399     public String getOrder() {
400         return order;
401     }
402     
403     /**
404      * Atribui valor especificado para String order.<br>
405      * 
406      * @author N/C
407 	 * @since N/C
408 	 * @version N/C
409      * @param String order - (The order to set)
410      */
411     public void setOrder(String order) {
412         this.order = order;
413     }
414     
415     /**
416      * Retorna String value.<br>
417      * 
418      * @author N/C
419 	 * @since N/C
420 	 * @version N/C
421      * @return String - (Returns the value)
422      */
423     public String getValue() {
424         return value;
425     }
426     
427     /**
428      * Atribui valor especificado para String value.<br>
429      * 
430      * @author N/C
431 	 * @since N/C
432 	 * @version N/C
433      * @param String value - (The value to set)
434      */
435     public void setValue(String value) {
436         this.value = value;
437     }
438     
439     /**
440      * Retorna Collection selected.<br>
441      * 
442      * @author N/C
443 	 * @since N/C
444 	 * @version N/C
445      * @return Collection- (Returns the selected)
446      */
447     public Collection getSelected() {
448         return selected;
449     }
450     
451     /**
452      * Atribui valor especificado para Collection selected.<br>
453      * 
454      * @author N/C
455 	 * @since N/C
456 	 * @version N/C
457      * @param Collection selected - (The selected to set)
458      */
459     public void setSelected(Collection selected) {
460         this.selected = selected;
461     }
462     
463     /**
464      * Retorna String scripts.<br>
465      * 
466      * @author N/C
467 	 * @since N/C
468 	 * @version N/C
469      * @return String - (Returns the scripts)s
470      */
471     public String getScripts() {
472         return scripts;
473     }
474     
475     /**
476      * Atribui valor especificado para String scripts.<br>
477      * 
478      * @author N/C
479 	 * @since N/C
480 	 * @version N/C
481      * @param String scripts - (The scripts to set)
482      */
483     public void setScripts(String scripts) {
484         this.scripts = scripts;
485     }
486     
487     /**
488      * Retorna Collection objetosExcluidos.<br>
489      * 
490      * @author N/C
491 	 * @since N/C
492 	 * @version N/C
493      * @return Collection - (Returns the objetosExcluidos)
494      */
495     public Collection getObjetosExcluidos() {
496         return objetosExcluidos;
497     }
498     
499     /**
500      * Atribui valor especificado para Collection objetosExcluidos.<br>
501      * 
502      * @author N/C
503 	 * @since N/C
504 	 * @version N/C
505      * @param Collection objetosExcluidos - (The objetosExcluidos to set)
506      */
507     public void setObjetosExcluidos(Collection objetosExcluidos) {
508         this.objetosExcluidos = objetosExcluidos;
509     }
510     
511 	/**
512 	 * Retorna Collection colecao.<br>
513 	 * 
514 	 * @author N/C
515 	 * @since N/C
516 	 * @version N/C
517 	 * @return Collection - (Returns the colecao)
518 	 */
519 	public Collection getColecao() {
520 		return colecao;
521 	}
522 	
523 	/**
524 	 * Atribui valor especificado para Collection colecao.<br>
525 	 * 
526 	 * @author N/C
527 	 * @since N/C
528 	 * @version N/C
529 	 * @param Collection colecao - (The colecao to set)
530 	 */
531 	public void setColecao(Collection colecao) {
532 		this.colecao = colecao;
533 	}
534 }