View Javadoc

1   package ecar.dao;
2   
3   import java.lang.reflect.InvocationTargetException;
4   import java.lang.reflect.Method;
5   import java.util.ArrayList;
6   import java.util.Collection;
7   import java.util.Iterator;
8   import java.util.List;
9   
10  import javax.servlet.http.HttpServletRequest;
11  
12  import org.hibernate.Criteria;
13  import org.hibernate.HibernateException;
14  import org.hibernate.Query;
15  import org.hibernate.criterion.Expression;
16  import org.hibernate.criterion.Order;
17  import org.hibernate.exception.ConstraintViolationException;
18  
19  import org.apache.log4j.Logger;
20  
21  import comum.database.Dao;
22  import comum.util.Util;
23  
24  import ecar.exception.ECARException;
25  import ecar.pojo.ConfigSisExecFinanCsef;
26  import ecar.pojo.ConfigSisExecFinanCsefv;
27  
28  /**
29   * Classe de manipulação de objetos da classe AtributoAtt.
30   * @author CodeGenerator - Esta classe foi gerada automaticamente
31   * @since 1.0
32   * @version 1.0, Fri Jan 27 07:54:28 BRST 2006
33   */
34  public class ConfigSisExecFinanCsefvDao extends Dao {
35    /**
36     * Construtor. Chama o Session factory do Hibernate
37     */
38    public ConfigSisExecFinanCsefvDao(HttpServletRequest request) {
39      super();
40      this.request = request;
41    }
42  
43    /**
44     * Retorna uma versão (ConfigSisExecFinanCsefv) de um sistema
45     * (ConfigSisExecFinanCsef) com base no sistema, mes e ano.
46     * @param ano
47     * @param mes
48     * @param sistema
49     * @return ConfigSisExecFinanCsefv
50     * @throws ECARException
51     */
52    public ConfigSisExecFinanCsefv getConfigSisExecFinanCsefv(Long ano, Long mes, ConfigSisExecFinanCsef sistema) throws ECARException {
53      try {
54        StringBuilder sql = new StringBuilder("from ConfigSisExecFinanCsefv versao").append(" where versao.configSisExecFinanCsef.codCsef = :codCsef").append("   and (versao.mesVersaoCsefv <= :mesVersao)").append("   and (versao.anoVersaoCsefv <= :anoVersao)").append("   order by versao.anoVersaoCsefv desc, versao.mesVersaoCsefv desc");
55  
56        Query q = this.session.createQuery(sql.toString());
57        q.setLong("codCsef", sistema.getCodCsef().longValue());
58        q.setLong("mesVersao", mes.longValue());
59        q.setLong("anoVersao", ano.longValue());
60  
61        q.setMaxResults(1);
62  
63        return (ConfigSisExecFinanCsefv) q.uniqueResult();
64      } catch (HibernateException e) {
65        Logger logger = Logger.getLogger(this.getClass());
66        logger.error(e);
67      }
68      return null;
69    }
70  
71    /**
72     * Retorna as versões que possuem sistemas ativos, ordenados pelo nome do
73     * sistema.
74     * @return List
75     * @throws ECARException
76     */
77    public List getCsefvOrderBySistema() throws ECARException {
78      List retorno = new ArrayList();
79      try {
80        StringBuilder sql = new StringBuilder("select versao from ConfigSisExecFinanCsefv versao").append(" join versao.configSisExecFinanCsef sistema").append(" where sistema.indAtivoCsef = 'S'").append("   and versao.indAtivoCsefv = 'S'").append(" order by versao.configSisExecFinanCsef.nomeCsef, versao.anoVersaoCsefv, versao.mesVersaoCsefv");
81  
82        Query q = this.session.createQuery(sql.toString());
83        retorno = q.list();
84      } catch (HibernateException e) {
85        Logger logger = Logger.getLogger(this.getClass());
86        logger.error(e);
87      }
88      return retorno;
89    }
90  
91    /**
92     * Retorna as versões que possuem sistemas ativos, ordenados pelo ano/mes da
93     * versao
94     * @return List
95     * @throws ECARException
96     */
97    public List getCsefvOrderByMesAno() throws ECARException {
98      List retorno = new ArrayList();
99      try {
100       StringBuilder sql = new StringBuilder("select versao from ConfigSisExecFinanCsefv versao").append(" join versao.configSisExecFinanCsef sistema").append(" where sistema.indAtivoCsef = 'S'").append("   and versao.indAtivoCsefv = 'S'").append(" order by versao.anoVersaoCsefv, versao.mesVersaoCsefv");
101 
102       Query q = this.session.createQuery(sql.toString());
103       retorno = q.list();
104     } catch (HibernateException e) {
105       Logger logger = Logger.getLogger(this.getClass());
106       logger.error(e);
107     }
108     return retorno;
109   }
110 
111   /**
112    * Descobre o até qual mes/ano pertence à uma versão e retorna uma string,
113    * sendo: CODVERSAO + | + MESINICIAL + | + ANOINICIAL + | + MESFINAL + | +
114    * ANOFINAL + CODSISTEMA
115    * @param versao
116    * @return
117    * @throws ECARException
118    */
119   public String getPeriodoByVersao(ConfigSisExecFinanCsefv versao) throws ECARException {
120 
121     String retorno = "";
122 
123     List versoesOrdenadasPelaData = this.getCsefvOrderByMesAno();
124     Iterator itVersoes = versoesOrdenadasPelaData.iterator();
125     boolean achou = false;
126     while (itVersoes.hasNext()) {
127       ConfigSisExecFinanCsefv v = (ConfigSisExecFinanCsefv) itVersoes.next();
128 
129       if (!v.getCodCsefv().equals(versao.getCodCsefv()) && !achou)
130         continue;
131 
132       if (v.getCodCsefv().equals(versao.getCodCsefv()))
133         achou = true;
134 
135       // if(achou && !v.getCodCsefv().equals(versao.getCodCsefv())){
136       if (achou) {
137         // É a próxima versão depois da versão informada no parametro.
138         String mesIni = (versao.getMesVersaoCsefv().longValue() < 10) ? "0" + String.valueOf(versao.getMesVersaoCsefv()) : String.valueOf(versao.getMesVersaoCsefv());
139         String mesFim = (v.getMesVersaoCsefv().longValue() < 10) ? "0" + String.valueOf(v.getMesVersaoCsefv()) : String.valueOf(v.getMesVersaoCsefv());
140         retorno = String.valueOf(versao.getCodCsefv()) + "|" + mesIni + "|" + String.valueOf(versao.getAnoVersaoCsefv()) + "|" + mesFim + "|" + String.valueOf(v.getAnoVersaoCsefv()) + "|" + String.valueOf(versao.getConfigSisExecFinanCsef().getCodCsef());
141         break;
142       }
143     }
144 
145     return retorno;
146   }
147 
148   public List pesquisar(Object obj, String[] ordem) throws ECARException {
149 
150     List list = new ArrayList(); // lista resultado
151     Criteria select; // select (do hibernate)
152 
153     if (obj == null)
154       return list;
155 
156     try {
157       /*
158        * limpa os objeto do cache antes de buscar, para garantir que a busca
159        * será no BD e nao no cache
160        */
161       /* TODO avaliar e utilizacao do cache */
162       // clearSession();
163       select = session.createCriteria(obj.getClass());
164       List listaMetodos = Util.listaMetodosGet(obj);
165 
166       // *************************************************************
167       // Lista de métodos que devem ser desconsiderados
168       // no resto do algoritmo
169       String[] listaExclusao = new String[] { "getSistemaVersaoCsefv" };
170 
171       // Rotina para eliminar os métodos desnecessários
172       for (int j = 0; j < listaExclusao.length; j++) {
173 
174         String nomeMetodo = listaExclusao[j];
175         Iterator x = listaMetodos.iterator();
176 
177         while (x.hasNext()) {
178 
179           Method metodo = (Method) x.next();
180 
181           if (metodo.getName().equals(nomeMetodo)) {
182             listaMetodos.remove(metodo);
183             break;
184           }
185         }
186       }
187       // *************************************************************
188 
189       Object auxObj;
190       String nomeAtributo;
191       String nomeMetodo;
192       String tipoRetorno;
193       for (int i = 0; i < listaMetodos.size(); i++) {
194         auxObj = ((Method) listaMetodos.get(i)).invoke(obj, null);
195         // somente adiciona um criterio se o conteudo for != vazio
196         if (auxObj != null) {
197           // obtem o nome do método para retirar o nome do atributo
198           nomeMetodo = ((Method) listaMetodos.get(i)).getName();
199           tipoRetorno = ((Method) listaMetodos.get(i)).getReturnType().getName().toLowerCase();
200           nomeAtributo = nomeMetodo.substring(3, 4).toLowerCase() + nomeMetodo.substring(4);
201 
202           if (tipoRetorno.endsWith("string"))
203             select.add(Expression.ilike(nomeAtributo, "%" + auxObj + "%"));
204           else {
205             // Se o atributo for Set não entra na pesquisa será filtrado depois
206             if (!tipoRetorno.endsWith("set"))
207               select.add(Expression.eq(nomeAtributo, auxObj));
208           }
209         }
210       }
211 
212       if (ordem != null)
213         for (int i = 0; i < ordem.length; i += 2)
214           // anda aos pares
215           if (ordem[i + 1].equalsIgnoreCase(Dao.ORDEM_ASC))
216             select.addOrder(Order.asc(ordem[i]));
217           else if (ordem[i + 1].equalsIgnoreCase(Dao.ORDEM_DESC))
218             select.addOrder(Order.desc(ordem[i]));
219 
220       list = select.list();
221 
222     } catch (HibernateException e) {
223       this.logger.error(e);
224       throw new ECARException("erro.hibernateException");
225     } catch (IllegalAccessException e) {
226       this.logger.error(e);
227       throw new ECARException("erro.exception");
228     } catch (IllegalArgumentException e) {
229       this.logger.error(e);
230       throw new ECARException("erro.exception");
231     } catch (InvocationTargetException e) {
232       this.logger.error(e);
233       throw new ECARException("erro.exception");
234     }
235 
236     return list;
237 
238   }
239 
240   /**
241    * Exclui um objeto passando a classe e a chave como parâmetro. Primeiro
242    * carrega o objeto<br>
243    */
244 
245   public void excluir(ConfigSisExecFinanCsefv obj) throws ECARException {
246 
247     try {
248 
249       boolean excluir = true;
250 
251       if ((contar(obj.getConfigExecFinanCefs()) > 0) || (contar(obj.getImportacaoImps()) > 0)) {
252         excluir = false;
253         throw new ECARException("integracaoFinanceira.versaoSistema.exclusao.erro");
254       }
255       if (excluir)
256         super.excluir(obj);
257     } catch (ECARException e) {
258       this.logger.error(e);
259       throw e;
260     }
261 
262   }
263 }