1 /*
2 * Criado em 26/10/2004
3 *
4 */
5 package ecar.taglib.combos;
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 * Classe para geração de Combos Genérica.<br>
29 *
30 * Exemplo de Utilização:<br>
31 * <p>
32 * combo:ComboTag <br>
33 * nome="subArea"<br>
34 * objeto="ecar.pojo.AreaAre"<br>
35 * label="nomeAre" <br>
36 * value="codAre"<br>
37 * filters="indAtivoAre=S"<br>
38 * order="nomeAre" <br>
39 * selected="5"<br>
40 *
41 * @author felipev
42 */
43 public class ComboTag implements Tag {
44
45 /**
46 * Value selecionado por default
47 */
48 private String selected;
49
50 /**
51 * Nome da combo. Obrigatório
52 */
53 private String nome;
54
55 /**
56 * Objetos que serão listados para a criação da combo. Obrigatório.<br>
57 * Ex:<br>
58 * ecar.pojo.AreaAre
59 */
60 private String objeto;
61
62 /**
63 * Atributo do objeto que servirá como label para a combo. Obrigatório.
64 */
65 private String label;
66
67 /**
68 * Atributo do objeto que servirá como Value para a combo. Obrigatório;
69 */
70 private String value;
71
72 /**
73 * Atributo do objeto pelo qual será feita a ordenação dos registros na
74 * combo
75 */
76 private String order;
77
78 /**
79 * Filtros que podem ser usados para restringir a lista de registros da
80 * combo. Devem ser informados na forma "atributo=valor;atributo=valor".<br>
81 * Ex:<br>
82 * filters="indAtivoAre=S;nomeAre=Saúde"
83 */
84 private String filters;
85
86 /**
87 * Funcões javascrip que podem ser chamadas quando ocorrem eventos com a
88 * combo. Ex: scripts="onclick=\"funcao1()\" onchange=\"funcao2()\""
89 */
90 private String scripts;
91
92 /**
93 * Estilo da combo
94 */
95 private String style;
96
97 /**
98 * Coleção de registros que serão aprensentados na lista. Caso esse
99 * parâmetro seja informado o taglib não fará o select no objeto selecionado
100 * e retornará somente os elementos desta Collection.<br>
101 */
102 private Collection colecao;
103
104 /**
105 * Lista com objetos que não aparecerão na Check list.<br>
106 */
107 private Collection objetosExcluidos;
108
109 /**
110 * Se nulo mostra o primeiro option da combo em branco,
111 * Senão, omite este, e mostra o primeiro como valor
112 * Utilizado em combo com Multiplos valores (multiple).<br>
113 */
114 private String option;
115
116 /**
117 * Texto padrão para Option Vazia.<br>
118 */
119 private String textoPadrao;
120
121 private PageContext page = null;
122
123 private Logger logger = null;
124
125 private Boolean ignorarTagSelect = new Boolean(false);
126
127 private JspWriter writerParametro = null;
128
129 public ComboTag() {
130 super();
131 this.logger = Logger.getLogger(this.getClass());
132 }
133
134 public ComboTag(JspWriter writer) {
135 this.writerParametro = writer;
136 }
137
138 /**
139 * Inicializa a montagem da tag para ser adicionada na tela de HTML.<br>
140 *
141 * @author N/C
142 * @since N/C
143 * @version N/C
144 * @return int
145 * @throws JspException
146 */
147 public int doStartTag() throws JspException {
148 JspWriter writer = null;
149 if(writerParametro != null) {
150 writer = writerParametro;
151 } else {
152 writer = this.page.getOut();
153 }
154
155 StringBuffer s = new StringBuffer();
156 try {
157 /** Cria uma instância do objeto * */
158 Object obj = Class.forName(getObjeto()).newInstance();
159 Dao dao = new Dao();
160 Session session = dao.getSession();
161
162 List lista = new ArrayList();
163
164 if (getColecao() != null) {
165
166 lista.addAll(getColecao());
167
168 } else {
169
170 /** Cria um criteria para selecionar o objeto desejado * */
171 Criteria select = session.createCriteria(Class
172 .forName(getObjeto()));
173
174 /** Adiciona os parâmetros na query * */
175 if (filters != null && !"".equals(filters)) {
176 String parametros[] = filters.split(";");
177 for (int i = 0; i < parametros.length; i++) {
178 String[] chaveValor = parametros[i].split("=");
179 select.add(Expression
180 .like(chaveValor[0], chaveValor[1]));
181 }
182 }
183
184 /** Define a ordem dos resultados * */
185 select.addOrder(Order.asc(order));
186 lista = select.list();
187 }
188
189 /** Executa a query * */
190 Iterator it = lista.iterator();
191
192 if(!getIgnorarTagSelect().booleanValue()) {
193 /** Constroi a combo * */
194 s.append("<select name=\""+nome+"\" id=\""+nome+"\" ");
195
196 if(scripts != null && !"".equals(scripts))
197 s.append( scripts );
198
199 if (style != null && !"".equals(style))
200 s.append(" style=\"").append(style).append("\"");
201 s.append(">");
202 }
203
204 if (getOption() == null){
205 if (getTextoPadrao() != null)
206 s.append("<option value=\"\">").append(getTextoPadrao()).append("</option>");
207 else
208 s.append("<option value=\"\"></option>");
209 }
210
211 while (it.hasNext()) {
212 obj = it.next();
213 if ((objetosExcluidos == null)
214 || (objetosExcluidos != null && !objetosExcluidos
215 .contains(obj))) {
216 s.append("<option value=\"");
217 /**
218 * invoca o Método getXXXX para recuperar o valor do
219 * atributo value *
220 */
221 Object value = Class.forName(getObjeto()).getMethod(
222 "get" + Util.primeiraLetraToUpperCase(getValue()),
223 null).invoke(obj, null);
224 s.append(value);
225 s.append("\"");
226 if ((value.toString()).equals(selected))
227 s.append(" selected ");
228 s.append(">");
229 /**
230 * invoca o Método getXXXX para recuperar o valor do
231 * atributo label *
232 */
233 if (!this.isMultiLabel())
234 {
235 s.append(Class.forName(getObjeto()).getMethod(
236 "get" + Util.primeiraLetraToUpperCase(getLabel()),
237 null).invoke(obj, null));
238 }
239 else
240 {
241 Iterator itLabels = this.getLabels().iterator();
242 while (itLabels.hasNext())
243 {
244 s.append(Class.forName(getObjeto()).getMethod(
245 "get" + Util.primeiraLetraToUpperCase((String)itLabels.next()),
246 null).invoke(obj, null));
247 s.append(" - ");
248 }
249 s.deleteCharAt(s.length()-2);
250 }
251 s.append("</option>");
252 }
253 }
254 if(!getIgnorarTagSelect().booleanValue()) {
255 s.append("</select>");
256 }
257 writer.print(s.toString());
258 } catch (Exception e) {
259 this.logger.error(e);
260 try {
261 writer.print("Erro na geração da Combo: " + e.getMessage());
262 this.logger.error(e);
263 } catch (IOException ioE) {
264 this.logger.error(ioE);
265 }
266
267 }
268 return Tag.EVAL_BODY_INCLUDE;
269 }
270
271 /**
272 * Atribui valor especificado para PageContext page.<br>
273 *
274 * @author N/C
275 * @since N/C
276 * @version N/C
277 * @param PageContext arg0
278 */
279 public void setPageContext(PageContext arg0) {
280 this.page = arg0;
281 }
282
283 /**
284 *
285 *
286 * @author N/C
287 * @since N/C
288 * @version N/C
289 * @param Tag arg0
290 */
291 public void setParent(Tag arg0) {
292 }
293
294 /**
295 * Retorna null.<br>
296 *
297 * @author N/C
298 * @since N/C
299 * @version N/C
300 * @return Tag
301 */
302 public Tag getParent() {
303 return null;
304 }
305
306 /**
307 * Retorna String scripts.<br>
308 *
309 * @author N/C
310 * @since N/C
311 * @version N/C
312 * @return String - (Returns the scripts)
313 */
314 public String getScripts() {
315 return scripts;
316 }
317
318 /**
319 * Atribui valor especificado para String scripts.<br>
320 *
321 * @author N/C
322 * @since N/C
323 * @version N/C
324 * @param Scripts scripts - (The scripts to set)
325 */
326 public void setScripts(String scripts) {
327 this.scripts = scripts;
328 }
329
330 /**
331 * Retorna String value.<br>
332 *
333 * @author N/C
334 * @since N/C
335 * @version N/C
336 * @return String - (Returns the value)
337 */
338 public String getValue() {
339 return value;
340 }
341
342 /**
343 * Atribui valor especficado para String value.<br>
344 *
345 * @author N/C
346 * @since N/C
347 * @version N/C
348 * @param String value - (The value to set)
349 */
350 public void setValue(String value) {
351 this.value = value;
352 }
353
354 /**
355 * Encerra Tag.<br>
356 *
357 * @author N/C
358 * @since N/C
359 * @version N/C
360 * @return int
361 * @throws JspException
362 */
363 public int doEndTag() throws JspException {
364 return Tag.EVAL_PAGE;
365 }
366
367 /**
368 * Atribui null para selected.<br>
369 *
370 * @author N/C
371 * @since N/C
372 * @version N/C
373 */
374 public void release() {
375 this.selected = null;
376 }
377
378 /**
379 * Retorna String selected.<br>
380 *
381 * @author N/C
382 * @since N/C
383 * @version N/C
384 * @return String
385 */
386 public String getSelected() {
387 return selected;
388 }
389
390 /**
391 * Atribui valor especifcado para String selected.<br>
392 *
393 * @author N/C
394 * @since N/C
395 * @version N/C
396 * @param String string
397 */
398 public void setSelected(String string) {
399 selected = string;
400 }
401
402 /**
403 * Retorna String objeto.<br>
404 *
405 * @author N/C
406 * @since N/C
407 * @version N/C
408 * @return String - (Returns the objeto)
409 */
410 public String getObjeto() {
411 return objeto;
412 }
413
414 /**
415 * Atribui valor especificado para String objeto.<br>
416 *
417 * @author N/C
418 * @since N/C
419 * @version N/C
420 * @param String objeto - (The objeto to set)
421 */
422 public void setObjeto(String objeto) {
423 this.objeto = objeto;
424 }
425
426 /**
427 * Retorna PageContext page.<br>
428 *
429 * @author N/C
430 * @since N/C
431 * @version N/C
432 * @return PageContext - (Returns the page)
433 */
434 public PageContext getPage() {
435 return page;
436 }
437
438 /**
439 * Atribui valor especificado para PageContext page.<br>
440 *
441 * @author N/C
442 * @since N/C
443 * @version N/C
444 * @param PageContext page - (The page to set)
445 */
446 public void setPage(PageContext page) {
447 this.page = page;
448 }
449
450 /**
451 * Retorna String filters.<br>
452 *
453 * @author N/C
454 * @since N/C
455 * @version N/C
456 * @return String - (Returns the filters)
457 */
458 public String getFilters() {
459 return filters;
460 }
461
462 /**
463 * Atribui valor especificado para String filters.<br>
464 *
465 * @author N/C
466 * @since N/C
467 * @version N/C
468 * @param String filters - (The filters to set)
469 */
470 public void setFilters(String filters) {
471 this.filters = filters;
472 }
473
474 /**
475 * Retorna String label.<br>
476 *
477 * @author N/C
478 * @since N/C
479 * @version N/C
480 * @return String - (Returns the label)
481 */
482 public String getLabel() {
483 return label;
484 }
485
486 /**
487 * Atribui valor especificado para String label.<br>
488 *
489 * @author N/C
490 * @since N/C
491 * @version N/C
492 * @param String label - (The label to set)
493 */
494 public void setLabel(String label) {
495 this.label = label;
496 }
497
498 /**
499 * Retorna List de labels selecionados.<br>
500 *
501 * @author N/C
502 * @since N/C
503 * @version N/C
504 * @return List
505 */
506 public List getLabels()
507 {
508 String labelAux = this.label;
509 List labels = new ArrayList();
510 while(labelAux.lastIndexOf(",") != -1){
511 labels.add(labelAux.substring(0, labelAux.indexOf(",")));
512 labelAux = labelAux.substring(labelAux.indexOf(",") + 1);
513 }
514 labels.add(labelAux);
515
516 return labels;
517 }
518
519 /**
520 * Verifica se pode-se selecionar mais de um label.<br>
521 *
522 * @author N/C
523 * @since N/C
524 * @version N/C
525 * @return boolean
526 */
527 public boolean isMultiLabel()
528 {
529 if (this.getLabel().lastIndexOf(",") == -1)
530 return false;
531 return true;
532 }
533
534 /**
535 * Retorna String order.<br>
536 *
537 * @author N/C
538 * @since N/C
539 * @version N/C
540 * @return String - (Returns the order)
541 */
542 public String getOrder() {
543 return order;
544 }
545
546 /**
547 * Atrinui valor especificado para String order.<br>
548 *
549 * @author N/C
550 * @since N/C
551 * @version N/C
552 * @param String order - (The order to set)
553 */
554 public void setOrder(String order) {
555 this.order = order;
556 }
557
558 /**
559 * Retorna String nome.<br>
560 *
561 * @author N/C
562 * @since N/C
563 * @version N/C
564 * @return String - (Returns the nome)
565 */
566 public String getNome() {
567 return nome;
568 }
569
570 /**
571 * Atribui valor especificado para String nome.<br>
572 *
573 * @author N/C
574 * @since N/C
575 * @version N/C
576 * @param String nome - (The nome to set)
577 */
578 public void setNome(String nome) {
579 this.nome = nome;
580 }
581
582 /**
583 * Retorna String Style
584 *
585 * @author N/C
586 * @since N/C
587 * @version N/C
588 * @return String - (Returns the style)
589 */
590 public String getStyle() {
591 return style;
592 }
593
594 /**
595 * Atribui valor especificado para String style.<br>
596 *
597 * @author N/C
598 * @since N/C
599 * @version N/C
600 * @param String style - (The style to set)
601 */
602 public void setStyle(String style) {
603 this.style = style;
604 }
605
606 /**
607 * Retorna Collection colecao.<br>
608 *
609 * @author N/C
610 * @since N/C
611 * @version N/C
612 * @return Collection - (Returns the colecao)
613 */
614 public Collection getColecao() {
615 return colecao;
616 }
617
618 /**
619 * Atribui valor especificado para Collection colecao.<br>
620 *
621 * @author N/C
622 * @since N/C
623 * @version N/C
624 * @param Collection colecao - (The colecao to set)
625 */
626 public void setColecao(Collection colecao) {
627 this.colecao = colecao;
628 }
629
630 /**
631 * Retorna Collection objetosExcluidos.<br>
632 *
633 * @author N/C
634 * @since N/C
635 * @version N/C
636 * @return Collection - (Returns the objetosExcluidos)
637 */
638 public Collection getObjetosExcluidos() {
639 return objetosExcluidos;
640 }
641
642 /**
643 * Atribui valor especificado para Collection objetosExcluidos.<br>
644 *
645 * @author N/C
646 * @since N/C
647 * @version N/C
648 * @param Collection objetosExcluidos (The objetosExcluidos to set)
649 */
650 public void setObjetosExcluidos(Collection objetosExcluidos) {
651 this.objetosExcluidos = objetosExcluidos;
652 }
653
654 /**
655 * Retorna String option.<br>
656 *
657 * @author N/C
658 * @since N/C
659 * @version N/C
660 * @return String - (Returns the option)
661 */
662 public String getOption() {
663 return option;
664 }
665 /**
666 * Atribui valor especificado para String option.<br>
667 *
668 * @author N/C
669 * @since N/C
670 * @version N/C
671 * @param String option - (The option to set)
672 */
673 public void setOption(String option) {
674 this.option = option;
675 }
676 /**
677 * Retorna String textoPadrao.<br>
678 *
679 * @author N/C
680 * @since N/C
681 * @version N/C
682 * @return String - (Returns the textoPadrao)
683 */
684 public String getTextoPadrao() {
685 return textoPadrao;
686 }
687 /**
688 * Atribui valor especificado para String textoPadrao.<br>
689 *
690 * @author N/C
691 * @since N/C
692 * @version N/C
693 * @param String textoPadrao - (The textoPadrao to set)
694 */
695 public void setTextoPadrao(String textoPadrao) {
696 this.textoPadrao = textoPadrao;
697 }
698
699 /**
700 * Retorna Boolean ignorarTagSelect.<br>
701 *
702 * @author N/C
703 * @since N/C
704 * @version N/C
705 * @return Boolean
706 */
707 public Boolean getIgnorarTagSelect() {
708 return ignorarTagSelect;
709 }
710
711 /**
712 * Atribui valor especificado para Boolean ignorarTagSelect.<br>
713 *
714 * @author N/C
715 * @since N/C
716 * @version N/C
717 * @param Boolean ignorarTagSelect
718 */
719 public void setIgnorarTagSelect(Boolean ignorarTagSelect) {
720 this.ignorarTagSelect = ignorarTagSelect;
721 }
722 }