1 package comum.database;
2
3 import java.io.Serializable;
4 import java.lang.reflect.InvocationTargetException;
5 import java.lang.reflect.Method;
6 import java.util.ArrayList;
7 import java.util.Collection;
8 import java.util.Iterator;
9 import java.util.List;
10 import java.util.Set;
11
12 import javax.servlet.http.HttpServletRequest;
13
14 import org.apache.log4j.Logger;
15 import org.hibernate.Criteria;
16 import org.hibernate.HibernateException;
17 import org.hibernate.ObjectNotFoundException;
18 import org.hibernate.Session;
19 import org.hibernate.Transaction;
20 import org.hibernate.criterion.Criterion;
21 import org.hibernate.criterion.Expression;
22 import org.hibernate.criterion.Order;
23
24 import comum.util.Data;
25 import comum.util.LogBean;
26 import comum.util.Util;
27
28 import ecar.exception.ECARException;
29 import ecar.login.SegurancaECAR;
30 import ecar.pojo.PaiFilho;
31
32
33
34
35
36
37
38
39 public class Dao {
40
41
42 public static final String ORDEM_ASC = "asc";
43 public static final String ORDEM_DESC = "desc";
44 protected Logger logger = null;
45 protected Logger loggerAuditoria = null;
46 protected LogBean logBean = null;
47
48
49 protected Session session;
50
51 protected HttpServletRequest request = null;
52
53
54
55
56
57
58
59
60
61
62 public Dao() {
63 try {
64 session = HibernateUtil.currentSession();
65 logger = Logger.getLogger(this.getClass());
66 } catch (Throwable t) {
67 t.printStackTrace();
68 logger
69 .fatal("Não foi possível inicializar uma sessão do hibernate adequadamente. Verifique e corrija o erro acima.");
70 }
71 }
72
73
74
75
76
77
78
79
80
81 public Session getSession() {
82 return session;
83 }
84
85
86
87
88
89
90
91
92
93
94 public void setSession(Session session) {
95 this.session = session;
96 }
97
98
99
100
101
102
103
104
105
106
107
108
109 @SuppressWarnings("unchecked")
110 public int contar(Collection col) throws ECARException {
111 try {
112 return ((Integer) session.createFilter(col, "select count(*)")
113 .iterate().next()).intValue();
114 } catch (HibernateException e) {
115 this.logger.error(e);
116 throw new ECARException("erro.hibernateException");
117 }
118 }
119
120
121
122
123
124
125
126
127
128
129 public long contarLong(Collection col) throws ECARException {
130 try {
131 return ((Long) session.createFilter(col, "select count(*)")
132 .iterate().next()).longValue();
133 } catch (HibernateException e) {
134 this.logger.error(e);
135 throw new ECARException("erro.hibernateException");
136 }
137 }
138
139
140
141
142
143
144
145
146
147
148
149
150 public void salvar(Object obj) throws ECARException {
151 inicializarLogBean();
152 Transaction tx = null;
153 try {
154 tx = session.beginTransaction();
155 session.save(obj);
156 tx.commit();
157 if (logBean != null) {
158 logBean.setCodigoTransacao(Data.getHoraAtual(false));
159 logBean.setObj(obj);
160 logBean.setOperacao("INC");
161 loggerAuditoria.info(logBean.toString());
162 }
163 } catch (HibernateException e) {
164 if (tx != null)
165 try {
166 tx.rollback();
167 } catch (HibernateException r) {
168 this.logger.error(r);
169 throw new ECARException("erro.hibernateException");
170 }
171 this.logger.error(e);
172 throw new ECARException("erro.hibernateException");
173 }
174 }
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190 @SuppressWarnings("unchecked")
191 public void salvar(Object obj, Collection lista) throws ECARException {
192 inicializarLogBean();
193 Transaction tx = null;
194 try {
195 ArrayList objetosInseridos = new ArrayList();
196 tx = session.beginTransaction();
197
198
199 session.save(obj);
200 objetosInseridos.add(obj);
201
202 Iterator it = lista.iterator();
203 while (it.hasNext()) {
204 PaiFilho object = (PaiFilho) it.next();
205 object.atribuirPKPai();
206
207 session.save(object);
208 objetosInseridos.add(object);
209 }
210 tx.commit();
211
212 if (logBean != null) {
213 logBean.setCodigoTransacao(Data.getHoraAtual(false));
214 logBean.setOperacao("INC");
215 Iterator it2 = objetosInseridos.iterator();
216
217 while (it2.hasNext()) {
218 logBean.setObj(it2.next());
219 loggerAuditoria.info(logBean.toString());
220 }
221 }
222
223 } catch (HibernateException e) {
224 if (tx != null)
225 try {
226 tx.rollback();
227 } catch (HibernateException r) {
228 this.logger.error(r);
229 throw new ECARException("erro.hibernateException");
230 }
231 this.logger.error(e);
232 throw new ECARException("erro.hibernateException");
233 }
234 }
235
236
237
238
239
240
241
242
243
244
245
246
247 public void salvarOuAlterar(Object obj) throws ECARException {
248 inicializarLogBean();
249 Transaction tx = null;
250 try {
251 tx = session.beginTransaction();
252 session.saveOrUpdate(obj);
253 tx.commit();
254
255 if (logBean != null) {
256 logBean.setCodigoTransacao(Data.getHoraAtual(false));
257 logBean.setObj(obj);
258 logBean.setOperacao("INC_ALT");
259 loggerAuditoria.info(logBean.toString());
260 }
261 } catch (HibernateException e) {
262 if (tx != null)
263 try {
264 tx.rollback();
265 } catch (HibernateException r) {
266 this.logger.error(r);
267 throw new ECARException("erro.hibernateException");
268 }
269 this.logger.error(e);
270 throw new ECARException("erro.hibernateException");
271 }
272 }
273
274
275
276
277
278
279
280
281
282
283
284
285
286 @SuppressWarnings("unchecked")
287 public void salvarOuAlterar(Collection lista) throws ECARException {
288 inicializarLogBean();
289 Transaction tx = null;
290 try {
291
292 tx = session.beginTransaction();
293
294 Iterator it = lista.iterator();
295 while (it.hasNext()) {
296 session.saveOrUpdate(it.next());
297 }
298 tx.commit();
299
300 if (logBean != null) {
301 it = lista.iterator();
302 logBean.setCodigoTransacao(Data.getHoraAtual(false));
303 logBean.setOperacao("INC_ALT");
304 while (it.hasNext()) {
305 logBean.setObj(it.next());
306 loggerAuditoria.info(logBean.toString());
307 }
308 }
309
310 } catch (HibernateException e) {
311 if (tx != null)
312 try {
313 tx.rollback();
314 } catch (HibernateException r) {
315 this.logger.error(r);
316 throw new ECARException("erro.hibernateException");
317 }
318 this.logger.error(e);
319 throw new ECARException("erro.hibernateException");
320 }
321 }
322
323
324
325
326
327
328
329
330
331
332
333
334 public void alterar(Object obj) throws ECARException {
335 inicializarLogBean();
336 Transaction tx = null;
337 try {
338
339 tx = session.beginTransaction();
340 session.update(obj);
341 tx.commit();
342 if (logBean != null) {
343 logBean.setCodigoTransacao(Data.getHoraAtual(false));
344 logBean.setObj(obj);
345 logBean.setOperacao("ALT");
346 loggerAuditoria.info(logBean.toString());
347 }
348 } catch (HibernateException e) {
349 if (tx != null)
350 try {
351 tx.rollback();
352 } catch (HibernateException r) {
353 this.logger.error(r);
354 throw new ECARException("erro.hibernateException");
355 }
356 this.logger.error(e);
357 throw new ECARException("erro.hibernateException");
358 }
359 }
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375 @SuppressWarnings("unchecked")
376 public void alterar(Object obj, Collection lista) throws ECARException {
377 inicializarLogBean();
378 Transaction tx = null;
379 try {
380 ArrayList objetosAlterados = new ArrayList();
381
382 tx = session.beginTransaction();
383 session.update(obj);
384 objetosAlterados.add(obj);
385
386 Iterator it = lista.iterator();
387 while (it.hasNext()) {
388 PaiFilho object = (PaiFilho) it.next();
389 object.atribuirPKPai();
390
391 session.save(object);
392 objetosAlterados.add(object);
393 }
394 tx.commit();
395
396 if (logBean != null) {
397 logBean.setCodigoTransacao(Data.getHoraAtual(false));
398 logBean.setOperacao("ALT");
399 Iterator it2 = objetosAlterados.iterator();
400
401 while (it2.hasNext()) {
402 logBean.setObj(it2.next());
403 loggerAuditoria.info(logBean.toString());
404 }
405 }
406 } catch (HibernateException e) {
407 if (tx != null)
408 try {
409 tx.rollback();
410 } catch (HibernateException r) {
411 this.logger.error(r);
412 throw new ECARException("erro.hibernateException");
413 }
414 this.logger.error(e);
415 throw new ECARException("erro.hibernateException");
416 }
417 }
418
419
420
421
422
423
424
425
426
427
428
429
430 @SuppressWarnings("unchecked")
431 public void alterar(Collection lista) throws ECARException {
432 inicializarLogBean();
433 Transaction tx = null;
434 try {
435
436 tx = session.beginTransaction();
437
438 Iterator it = lista.iterator();
439 while (it.hasNext()) {
440 session.update(it.next());
441 }
442 tx.commit();
443
444 if (logBean != null) {
445 it = lista.iterator();
446 logBean.setCodigoTransacao(Data.getHoraAtual(false));
447 logBean.setOperacao("ALT");
448 while (it.hasNext()) {
449 logBean.setObj(it.next());
450 loggerAuditoria.info(logBean.toString());
451 }
452 }
453 } catch (HibernateException e) {
454 if (tx != null)
455 try {
456 tx.rollback();
457 } catch (HibernateException r) {
458 this.logger.error(r);
459 throw new ECARException("erro.hibernateException");
460 }
461 this.logger.error(e);
462 throw new ECARException("erro.hibernateException");
463 }
464 }
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479 public void excluir(Object obj) throws ECARException {
480 inicializarLogBean();
481 Transaction tx = null;
482 try {
483 tx = session.beginTransaction();
484 session.delete(obj);
485 tx.commit();
486 if (logBean != null) {
487 logBean.setCodigoTransacao(Data.getHoraAtual(false));
488 logBean.setObj(obj);
489 logBean.setOperacao("EXC");
490 loggerAuditoria.info(logBean.toString());
491 }
492 } catch (HibernateException e) {
493 if (tx != null)
494 try {
495 tx.rollback();
496 } catch (HibernateException r) {
497 this.logger.error(r);
498 throw new ECARException("erro.hibernateException");
499 }
500 this.logger.error(e);
501 throw new ECARException("erro.hibernateException");
502 }
503 }
504
505
506
507
508
509
510
511
512
513
514
515
516
517 @SuppressWarnings("unchecked")
518 public void excluir(Collection lista) throws ECARException {
519 inicializarLogBean();
520 Transaction tx = null;
521 try {
522 tx = session.beginTransaction();
523 Iterator it = lista.iterator();
524 while (it.hasNext())
525 session.delete(it.next());
526 tx.commit();
527
528 if (logBean != null) {
529 it = lista.iterator();
530 logBean.setCodigoTransacao(Data.getHoraAtual(false));
531 logBean.setOperacao("EXC");
532 while (it.hasNext()) {
533 logBean.setObj(it.next());
534 loggerAuditoria.info(logBean.toString());
535 }
536 }
537 } catch (HibernateException e) {
538 if (tx != null)
539 try {
540 tx.rollback();
541 } catch (HibernateException r) {
542 this.logger.error(r);
543 throw new ECARException("erro.hibernateException");
544 }
545 this.logger.error(e);
546 throw new ECARException("erro.hibernateException");
547 }
548 }
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565 @SuppressWarnings("unchecked")
566 public Object buscar(Class cl, Serializable chave) throws ECARException {
567 Object obj = null;
568 try {
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587 obj = session.load(cl, chave);
588 } catch (ObjectNotFoundException e) {
589
590 throw new ECARException("erro.objectNotFound");
591 } catch (HibernateException e) {
592 this.logger.error(e);
593 throw new ECARException("erro.hibernateException");
594 } catch (Exception e) {
595 this.logger.error(e);
596 throw new ECARException("erro.exception");
597 }
598 return (obj);
599 }
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638 @SuppressWarnings("unchecked")
639 public List pesquisar(Object obj, String[] ordem) throws ECARException {
640
641 List list = new ArrayList();
642 Criteria select;
643
644 if (obj == null)
645 return list;
646
647 try {
648
649
650
651
652
653
654 select = session.createCriteria(obj.getClass());
655 List listaMetodos = Util.listaMetodosGet(obj);
656 Object auxObj;
657 String nomeAtributo;
658 String nomeMetodo;
659 String tipoRetorno;
660 for (int i = 0; i < listaMetodos.size(); i++) {
661 auxObj = ((Method) listaMetodos.get(i)).invoke(obj,
662 new Object[] {});
663
664 if (auxObj != null) {
665
666 nomeMetodo = ((Method) listaMetodos.get(i)).getName();
667 tipoRetorno = ((Method) listaMetodos.get(i))
668 .getReturnType().getName().toLowerCase();
669 nomeAtributo = nomeMetodo.substring(3, 4).toLowerCase()
670 + nomeMetodo.substring(4);
671
672 if (tipoRetorno.endsWith("string"))
673 select.add(Expression.ilike(nomeAtributo, "%" + auxObj
674 + "%"));
675 else {
676
677
678 if (!tipoRetorno.endsWith("set"))
679 select.add(Expression.eq(nomeAtributo, auxObj));
680 }
681 }
682 }
683
684 if (ordem != null)
685 for (int i = 0; i < ordem.length; i += 2)
686
687 if (ordem[i + 1].equalsIgnoreCase(Dao.ORDEM_ASC))
688 select.addOrder(Order.asc(ordem[i]));
689 else if (ordem[i + 1].equalsIgnoreCase(Dao.ORDEM_DESC))
690 select.addOrder(Order.desc(ordem[i]));
691
692 list = select.list();
693
694 } catch (HibernateException e) {
695 this.logger.error(e);
696 throw new ECARException("erro.hibernateException");
697 } catch (IllegalAccessException e) {
698 this.logger.error(e);
699 throw new ECARException("erro.exception");
700 } catch (IllegalArgumentException e) {
701 this.logger.error(e);
702 throw new ECARException("erro.exception");
703 } catch (InvocationTargetException e) {
704 this.logger.error(e);
705 throw new ECARException("erro.exception");
706 }
707
708 return list;
709 }
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734 @SuppressWarnings("unchecked")
735 public List pesquisarDuplos(Object obj, String[] nomeCamposNaoDuplos,
736 String nomeChave) throws ECARException {
737
738 List list = new ArrayList();
739 Criteria select;
740
741 if (obj == null)
742 return list;
743
744 try {
745
746
747
748
749
750
751
752
753 select = session.createCriteria(obj.getClass());
754 Object auxObj;
755 String nomeAtributo;
756 String tipoRetorno;
757 Criterion crit = Expression.sql("1 = 0");
758
759
760
761 for (int i = 0; i < nomeCamposNaoDuplos.length; i++) {
762 nomeAtributo = nomeCamposNaoDuplos[i];
763 auxObj = Util.invocaGet(obj, nomeAtributo);
764 tipoRetorno = auxObj.getClass().getName().toLowerCase();
765
766 if (auxObj != null) {
767 if (tipoRetorno.endsWith("string"))
768 crit = Expression.or(crit, Expression.ilike(
769 nomeAtributo, auxObj));
770 else {
771
772
773 if (!tipoRetorno.endsWith("set"))
774 crit = Expression.or(crit, Expression.eq(
775 nomeAtributo, auxObj));
776 }
777 }
778 }
779 select.add(crit);
780
781
782 auxObj = Util.invocaGet(obj, nomeChave);
783 if (auxObj != null)
784 select.add(Expression.not(Expression.eq(nomeChave, auxObj)));
785 list = select.list();
786
787 } catch (HibernateException e) {
788 this.logger.error(e);
789 throw new ECARException("erro.hibernateException");
790 } catch (IllegalArgumentException e) {
791 this.logger.error(e);
792 throw new ECARException("erro.exception");
793 }
794 return list;
795 }
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815 @SuppressWarnings("unchecked")
816 public List listar(Class cl, String[] ordem) throws ECARException {
817 List list = null;
818
819 if (cl == null)
820 return list;
821
822 try {
823
824
825
826
827
828
829
830 Criteria c = session.createCriteria(cl);
831
832 if (ordem != null)
833 for (int i = 0; i < ordem.length; i += 2)
834
835 if (ordem[i + 1].equalsIgnoreCase(Dao.ORDEM_ASC))
836 c.addOrder(Order.asc(ordem[i]));
837 else if (ordem[i + 1].equalsIgnoreCase(Dao.ORDEM_DESC))
838 c.addOrder(Order.desc(ordem[i]));
839
840 list = c.list();
841
842 } catch (HibernateException e) {
843 this.logger.error(e);
844 throw new ECARException("erro.hibernateException");
845 }
846 return list;
847 }
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864 @SuppressWarnings("unchecked")
865 public List ordenaSet(Set colecao, String campo, String ordem)
866 throws ECARException {
867 try {
868 return this.getSession().createFilter(colecao,
869 " order by " + campo + " " + ordem).list();
870 } catch (HibernateException e) {
871 this.logger.error(e);
872 throw new ECARException("erro.hibernateException");
873 }
874
875 }
876
877
878
879
880
881
882
883
884 public void inicializarLogBean() {
885 this.logBean = null;
886 if (this.request != null) {
887 this.loggerAuditoria = Logger.getLogger("AUDITORIA");
888 SegurancaECAR seguranca = (SegurancaECAR) this.request.getSession()
889 .getAttribute("seguranca");
890 this.logBean = new LogBean();
891 this.logBean.setIPUsuario(this.request.getRemoteAddr());
892 this.logBean.setUsuario(seguranca.getUsuario());
893 this.logBean.setCodigoSessao(this.request.getSession().getId());
894 }
895 }
896 }