View Javadoc

1   /*
2    * Criado em 02/05/2005
3    */
4   package ecar.dao;
5   
6   import java.io.File;
7   import java.util.ArrayList;
8   import java.util.Collection;
9   import java.util.Date;
10  import java.util.HashSet;
11  import java.util.Iterator;
12  import java.util.List;
13  import java.util.Set;
14  
15  import javax.servlet.ServletContext;
16  import javax.servlet.http.HttpServletRequest;
17  
18  import org.apache.commons.fileupload.FileItem;
19  import org.hibernate.HibernateException;
20  import org.hibernate.Query;
21  import org.hibernate.Transaction;
22  
23  import comum.database.Dao;
24  import comum.util.Data;
25  import comum.util.FileUpload;
26  import comum.util.Mensagem;
27  import comum.util.Pagina;
28  
29  import ecar.exception.ECARException;
30  import ecar.pojo.DestaqueItemRelDtqir;
31  import ecar.pojo.DestaqueSubAreaDtqsa;
32  import ecar.pojo.SegmentoCategoriaSgtc;
33  import ecar.pojo.SegmentoItemFonteSgtif;
34  import ecar.pojo.SegmentoItemLeiauteSgtil;
35  import ecar.pojo.SegmentoItemSgti;
36  import ecar.pojo.SegmentoSgt;
37  import ecar.pojo.SisAtributoSatb;
38  import ecar.pojo.UsuarioUsu;
39  
40  /**
41   * @author evandro
42   */
43  public class SegmentoItemDao extends Dao {
44    /**
45     * Construtor. Chama o Session factory do Hibernate
46     */
47    public SegmentoItemDao(HttpServletRequest request) {
48      super();
49      this.request = request;
50    }
51  
52    /**
53     * Salva um registro de segmentoItem a partir de parâmetros recebidos por
54     * request por um formulário de Upload. Salva a coleção de aditorias do
55     * segmentoItem. Salva a coleção de tipos de acesso do segmentoItem. Salva a
56     * imagem selecionada em disco.
57     * @param segmento
58     * @param campos
59     * @param pathRaiz
60     * @param pathRelativo
61     * @param ServletContext
62     * @throws ECARException
63     */
64    public void salvar(SegmentoItemSgti segItem, List campos, String pathRaiz, String pathRelativo, ServletContext application) throws ECARException {
65      Transaction tx = null;
66  
67      try {
68        ArrayList objetos = new ArrayList();
69  
70        super.inicializarLogBean();
71  
72        tx = session.beginTransaction();
73  
74        setSegmentoItemUpload(segItem, campos, application, true);
75        segItem.setDataInclusaoSgti(Data.getDataAtual());
76  
77        if (("2".equalsIgnoreCase(segItem.getSegmentoSgt().getCodSgt().toString())) || ("3".equalsIgnoreCase(segItem.getSegmentoSgt().getCodSgt().toString())) || ("4".equalsIgnoreCase(segItem.getSegmentoSgt().getCodSgt().toString()))) {
78  
79          SegmentoItemLeiauteSgtil leiaute = new SegmentoItemLeiauteSgtil();
80          leiaute.setCodSgtil(segItem.getSegmentoSgt().getCodSgt());
81          segItem.setSegmentoItemLeiauteSgtil(leiaute);
82        }
83  
84        /* segItem.setUsuarioUsu(); */
85        session.save(segItem);
86        objetos.add(segItem);
87  
88        /*
89         * grava a(s) imagem(ns) e atualiza o segmentoItem para vincular o nome
90         * da(s) imagem(ns)
91         */
92        uploadImagem(segItem, campos, pathRaiz, pathRelativo);
93        session.update(segItem);
94        objetos.add(segItem);
95  
96        tx.commit();
97  
98        if (super.logBean != null) {
99          super.logBean.setCodigoTransacao(Data.getHoraAtual(false));
100         super.logBean.setOperacao("INC_ALT");
101         Iterator itObj = objetos.iterator();
102 
103         while (itObj.hasNext()) {
104           super.logBean.setObj(itObj.next());
105           super.loggerAuditoria.info(logBean.toString());
106         }
107       }
108     } catch (HibernateException e) {
109       if (tx != null)
110         try {
111           tx.rollback();
112         } catch (HibernateException r) {
113           this.logger.error(r);
114           throw new ECARException("erro.hibernateException");
115         }
116       this.logger.error(e);
117       throw new ECARException("erro.hibernateException");
118     }
119   }
120 
121   /**
122    * Altera um registro de segmentoItem a partir de parâmetros recebidos por
123    * request por um formulário de Upload. Altera a coleção de editorias do
124    * segmento. Altera a coleção de tipos de acesso do segmento. Salva a imagem
125    * selecionada em disco e apaga a uma imagem existente anteriormente.
126    * @param segmentoItem
127    * @param campos
128    * @param pathRaiz
129    * @param pathRelativo
130    * @param ServletContext
131    * @throws ECARException
132    */
133 
134   public void alterar(SegmentoItemSgti segItem, List campos, String pathRaiz, String pathRelativo, ServletContext application) throws ECARException {
135     Transaction tx = null;
136 
137     try {
138       ArrayList objetos = new ArrayList();
139 
140       super.inicializarLogBean();
141 
142       tx = session.beginTransaction();
143 
144       String flagImagem1 = "";
145       String flagCapa = "";
146       String flagImagem2 = "";
147       String flagImagem3 = "";
148       String flagAnexo = "";
149 
150       if (("".equals(FileUpload.verificaValorCampo(campos, "imagem1Sgti"))) && (!"".equals(FileUpload.verificaValorCampo(campos, "imagem1")))) {
151         if (segItem.getImagem1Stgi() != null) {
152 
153           if (!FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagem1Stgi(), ""))) {
154             throw new ECARException("erro.excluirArquivo");
155 
156           }
157         }
158 
159         flagImagem1 = "excluidaImagem1";
160 
161       }
162 
163       if (("".equals(FileUpload.verificaValorCampo(campos, "imagemCapaSgti"))) && (!"".equals(FileUpload.verificaValorCampo(campos, "imagemCapa")))) {
164         if (segItem.getImagemCapaSgti() != null) {
165 
166           if (!FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagemCapaSgti(), ""))) {
167             throw new ECARException("erro.excluirArquivo");
168 
169           }
170         }
171 
172         flagCapa = "excluidaCapa";
173 
174       }
175 
176       if (("".equals(FileUpload.verificaValorCampo(campos, "imagem2Sgti"))) && (!"".equals(FileUpload.verificaValorCampo(campos, "imagem2")))) {
177         if (segItem.getImagem2Sgti() != null) {
178 
179           if (!FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagem2Sgti(), ""))) {
180             throw new ECARException("erro.excluirArquivo");
181 
182           }
183         }
184 
185         flagImagem2 = "excluidaImagem2";
186 
187       }
188 
189       if (("".equals(FileUpload.verificaValorCampo(campos, "imagem3Sgti"))) && (!"".equals(FileUpload.verificaValorCampo(campos, "imagem3")))) {
190         if (segItem.getImagem3Sgti() != null) {
191 
192           if (!FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagem3Sgti(), ""))) {
193             throw new ECARException("erro.excluirArquivo");
194 
195           }
196         }
197 
198         flagImagem3 = "excluidaImagem3";
199       }
200 
201       if (("".equals(FileUpload.verificaValorCampo(campos, "anexoEnderecoSgti"))) && (!"".equals(FileUpload.verificaValorCampo(campos, "anexo")))) {
202         if (segItem.getAnexoEnderecoSgti() != null) {
203 
204           if (!FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getAnexoEnderecoSgti(), ""))) {
205             throw new ECARException("erro.excluirArquivo");
206 
207           }
208         }
209 
210         flagAnexo = "excluidoAnexo";
211       }
212 
213       setSegmentoItemUpload(segItem, campos, application, true);
214 
215       if ("excluidaImagem1".equalsIgnoreCase(flagImagem1)) {
216         segItem.setImagem1Stgi("");
217         session.save(segItem);
218         objetos.add(segItem);
219       }
220 
221       if ("excluidaCapa".equalsIgnoreCase(flagCapa)) {
222         segItem.setImagemCapaSgti("");
223         session.save(segItem);
224         objetos.add(segItem);
225       }
226 
227       if ("excluidaImagem2".equalsIgnoreCase(flagImagem2)) {
228         segItem.setImagem2Sgti("");
229         session.save(segItem);
230         objetos.add(segItem);
231       }
232 
233       if ("excluidaImagem3".equalsIgnoreCase(flagImagem3)) {
234         segItem.setImagem3Sgti("");
235         session.save(segItem);
236         objetos.add(segItem);
237       }
238 
239       if ("excluidoAnexo".equalsIgnoreCase(flagAnexo)) {
240         segItem.setAnexoEnderecoSgti("");
241         session.save(segItem);
242         objetos.add(segItem);
243       }
244 
245       if ("".equals(FileUpload.verificaValorCampo(campos, "legendaImag1Sgti"))) {
246         segItem.setLegendaImag1Sgti("");
247         session.save(segItem);
248         objetos.add(segItem);
249       }
250 
251       if ("".equals(FileUpload.verificaValorCampo(campos, "legendaImagCapaSgti"))) {
252         segItem.setLegendaImagCapaSgti("");
253         session.save(segItem);
254         objetos.add(segItem);
255       }
256 
257       if ("".equals(FileUpload.verificaValorCampo(campos, "legendaImag2Sgti"))) {
258         segItem.setLegendaImag2Sgti("");
259         session.save(segItem);
260         objetos.add(segItem);
261       }
262 
263       if ("".equals(FileUpload.verificaValorCampo(campos, "legendaImag3Sgti"))) {
264         segItem.setLegendaImag3Sgti("");
265         session.save(segItem);
266         objetos.add(segItem);
267       }
268 
269       if ("".equals(FileUpload.verificaValorCampo(campos, "anexoLegendaSgti"))) {
270         segItem.setAnexoLegendaSgti("");
271         session.save(segItem);
272         objetos.add(segItem);
273       }
274 
275       uploadImagem(segItem, campos, pathRaiz, pathRelativo);
276 
277       if (("2".equalsIgnoreCase(segItem.getSegmentoSgt().getCodSgt().toString())) || ("3".equalsIgnoreCase(segItem.getSegmentoSgt().getCodSgt().toString())) || ("4".equalsIgnoreCase(segItem.getSegmentoSgt().getCodSgt().toString()))) {
278 
279         SegmentoItemLeiauteSgtil leiaute = new SegmentoItemLeiauteSgtil();
280         leiaute.setCodSgtil(segItem.getSegmentoSgt().getCodSgt());
281         segItem.setSegmentoItemLeiauteSgtil(leiaute);
282 
283       }
284 
285       session.update(segItem);
286       objetos.add(segItem);
287 
288       tx.commit();
289 
290       if (super.logBean != null) {
291         super.logBean.setCodigoTransacao(Data.getHoraAtual(false));
292         super.logBean.setOperacao("INC_ALT");
293         Iterator itObj = objetos.iterator();
294 
295         while (itObj.hasNext()) {
296           super.logBean.setObj(itObj.next());
297           super.loggerAuditoria.info(logBean.toString());
298         }
299       }
300     } catch (Exception e) {
301       if (tx != null)
302         try {
303           tx.rollback();
304         } catch (HibernateException r) {
305           this.logger.error(r);
306           throw new ECARException("erro.hibernateException");
307         }
308       this.logger.error(e);
309       throw new ECARException("erro.hibernateException");
310     }
311   }
312 
313   /**
314    * Exclui um registro de segmentoItem. Exclui a(s) imagem(ns) e anexo caso
315    * existam.
316    * @param segmentoItem
317    * @param pathRaiz
318    * @throws ECARException
319    */
320   public void excluir(SegmentoItemSgti segItem, String pathRaiz) throws ECARException {
321     try {
322       if (segItem.getImagemCapaSgti() != null) {
323         if (!FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagemCapaSgti(), ""))) {
324           throw new ECARException("erro.excluirArquivo");
325         }
326       }
327       if (segItem.getImagem1Stgi() != null) {
328         if (!FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagem1Stgi(), ""))) {
329           throw new ECARException("erro.excluirArquivo");
330         }
331       }
332       if (segItem.getImagem2Sgti() != null) {
333         if (!FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagem2Sgti(), ""))) {
334           throw new ECARException("erro.excluirArquivo");
335         }
336       }
337       if (segItem.getImagem3Sgti() != null) {
338         if (!FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagem3Sgti(), ""))) {
339           throw new ECARException("erro.excluirArquivo");
340         }
341       }
342       if (segItem.getAnexoEnderecoSgti() != null) {
343         if (!FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getAnexoEnderecoSgti(), ""))) {
344           throw new ECARException("erro.excluirArquivo");
345         }
346       }
347       super.excluir(segItem);
348     } catch (Exception e) {
349       this.logger.error(e);
350       throw new ECARException("erro.exception");
351     }
352   }
353 
354   /**
355    * A partir de um List de campos obtidos na requsição de um formulário de
356    * upload popula um objeto SegmentoSgt
357    * @param segmento
358    * @param campos
359    * @param ServletContext
360    * @param criarCollection - boolean
361    * @throws ECARException
362    */
363   public void setSegmentoItemUpload(SegmentoItemSgti segItem, List campos, ServletContext application, boolean criarCollections) throws ECARException {
364 
365     try {
366       Mensagem properties = new Mensagem(application);
367 
368       /* codSegmento nunca deve estar vazio */
369       Long codSegmento = Long.valueOf(FileUpload.verificaValorCampo(campos, "codSegmento"));
370 
371       /*
372        * itensFixos são códigos definidos nos links do menu e no arquivo de
373        * properties
374        */
375       if (codSegmento.intValue() == (Long.valueOf(properties.getMensagem("admPortal.materias"))).intValue() || codSegmento.intValue() == (Long.valueOf(properties.getMensagem("admPortal.taxacoes"))).intValue() || codSegmento.intValue() == (Long.valueOf(properties.getMensagem("admPortal.pergFreq"))).intValue() || codSegmento.intValue() == (Long.valueOf(properties.getMensagem("admPortal.glossario"))).intValue())
376         segItem.setSegmentoSgt((SegmentoSgt) buscar(SegmentoSgt.class, codSegmento));
377       else {
378         /* combo de segmentos em itens livres */
379         if (!"".equals(FileUpload.verificaValorCampo(campos, "segmentoSgt")))
380           segItem.setSegmentoSgt((SegmentoSgt) buscar(SegmentoSgt.class, Long.valueOf(FileUpload.verificaValorCampo(campos, "segmentoSgt"))));
381       }
382 
383       /* objetos que independente de estar ou não na tela devem ser testados */
384       if (!"".equals(FileUpload.verificaValorCampo(campos, "segmentoCategoriaSgtc"))) {
385         segItem.setSegmentoCategoriaSgtc((SegmentoCategoriaSgtc) this.buscar(SegmentoCategoriaSgtc.class, Long.valueOf(FileUpload.verificaValorCampo(campos, "segmentoCategoriaSgtc"))));
386       }
387       if (!"".equals(FileUpload.verificaValorCampo(campos, "segmentoItemFonteSgtif"))) {
388         segItem.setSegmentoItemFonteSgtif((SegmentoItemFonteSgtif) this.buscar(SegmentoItemFonteSgtif.class, Long.valueOf(FileUpload.verificaValorCampo(campos, "segmentoItemFonteSgtif"))));
389       }
390       if (!"".equals(FileUpload.verificaValorCampo(campos, "segmentoItemLeiauteSgtil"))) {
391         segItem.setSegmentoItemLeiauteSgtil((SegmentoItemLeiauteSgtil) this.buscar(SegmentoItemLeiauteSgtil.class, Long.valueOf(FileUpload.verificaValorCampo(campos, "segmentoItemLeiauteSgtil"))));
392       }
393 
394       /* campos que estão em todas as telas */
395       segItem.setTituloSgti(FileUpload.verificaValorCampo(campos, "tituloSgti"));
396       segItem.setDataItemSgti(Data.parseDate(FileUpload.verificaValorCampo(campos, "dataItemSgti")));
397       segItem.setPalavrasChavesSgti(FileUpload.verificaValorCampo(campos, "palavrasChavesSgti"));
398       segItem.setIndUtilizTpAcessoSgti(FileUpload.verificaValorCampo(campos, "indUtilizTpAcessoSgti"));
399       segItem.setIndAtivoSgti(FileUpload.verificaValorCampo(campos, "indAtivoSgti"));
400 
401       /* campos não estão em todas as telas */
402       if (!"".equals(FileUpload.verificaValorCampo(campos, "integraSgti")))
403         segItem.setIntegraSgti(FileUpload.verificaValorCampo(campos, "integraSgti"));
404       if (!"".equals(FileUpload.verificaValorCampo(campos, "linhaApoioSgti")))
405         segItem.setLinhaApoioSgti(FileUpload.verificaValorCampo(campos, "linhaApoioSgti"));
406       if (!"".equals(FileUpload.verificaValorCampo(campos, "legendaImag1Sgti")))
407         segItem.setLegendaImag1Sgti(FileUpload.verificaValorCampo(campos, "legendaImag1Sgti"));
408       if (!"".equals(FileUpload.verificaValorCampo(campos, "legendaImag2Sgti")))
409         segItem.setLegendaImag2Sgti(FileUpload.verificaValorCampo(campos, "legendaImag2Sgti"));
410       if (!"".equals(FileUpload.verificaValorCampo(campos, "legendaImag3Sgti")))
411         segItem.setLegendaImag3Sgti(FileUpload.verificaValorCampo(campos, "legendaImag3Sgti"));
412       if (!"".equals(FileUpload.verificaValorCampo(campos, "legendaImagCapaSgti")))
413         segItem.setLegendaImagCapaSgti(FileUpload.verificaValorCampo(campos, "legendaImagCapaSgti"));
414       if (!"".equals(FileUpload.verificaValorCampo(campos, "anexoLegendaSgti")))
415         segItem.setAnexoLegendaSgti(FileUpload.verificaValorCampo(campos, "anexoLegendaSgti"));
416       if (!"".equals(FileUpload.verificaValorCampo(campos, "urlLinkSgti")))
417         segItem.setUrlLinkSgti(FileUpload.verificaValorCampo(campos, "urlLinkSgti"));
418       /* datas em branco são setadas null pelo parseDate */
419       segItem.setDataIniValidadeSgti(Data.parseDate(FileUpload.verificaValorCampo(campos, "dataIniValidadeSgti")));
420       segItem.setDataFimValidadeSgti(Data.parseDate(FileUpload.verificaValorCampo(campos, "dataFimValidadeSgti")));
421       if (!"".equals(FileUpload.verificaValorCampo(campos, "indSuperDestaqueSgti")))
422         segItem.setIndSuperDestaqueSgti(FileUpload.verificaValorCampo(campos, "indSuperDestaqueSgti"));
423       if (!"".equals(FileUpload.verificaValorCampo(campos, "indDestaqueSgti")))
424         segItem.setIndDestaqueSgti(FileUpload.verificaValorCampo(campos, "indDestaqueSgti"));
425 
426       if (criarCollections) {
427         criarCollectionEditorias(segItem, campos);
428         criarCollectionTipoAcesso(segItem, campos);
429       }
430     } catch (Exception e) {
431       this.logger.error(e);
432       throw new ECARException(e);
433     }
434 
435   }
436 
437   /**
438    * A partir de dados passados por request popula um objeto SegmentoItemSgti
439    * @param segmentoItem
440    * @param campos
441    * @param recuperarParametrosComoString indica se irá recuperar dados nulos
442    *          como String vazia
443    * @param ServletContext
444    * @param CriarCollection - boolean
445    * @throws ECARException
446    */
447   public void setSegmentoItem(SegmentoItemSgti segItem, HttpServletRequest campos, boolean recuperarParametrosComoString, ServletContext application, boolean criarCollections) throws ECARException {
448 
449     try {
450       Mensagem properties = new Mensagem(application);
451 
452       /* codSegmento nunca deve estar vazio */
453       Long codSegmento = Long.valueOf(Pagina.getParamStr(campos, "codSegmento"));
454 
455       /*
456        * itensFixos são códigos definidos nos links do menu e no arquivo de
457        * properties
458        */
459       if (codSegmento.intValue() == (Long.valueOf(properties.getMensagem("admPortal.materias"))).intValue() || codSegmento.intValue() == (Long.valueOf(properties.getMensagem("admPortal.taxacoes"))).intValue() || codSegmento.intValue() == (Long.valueOf(properties.getMensagem("admPortal.pergFreq"))).intValue() || codSegmento.intValue() == (Long.valueOf(properties.getMensagem("admPortal.glossario"))).intValue()) {
460 
461         SegmentoSgt segmento = (SegmentoSgt) buscar(SegmentoSgt.class, codSegmento);
462 
463         /*
464          * Fazemos um size na coleção de atributos para que o objeto seja
465          * carregado com a coleção pois na pesquisa, se não encontrar resultado,
466          * o objeto é incluído na sessão e sem esse procedimento, ao carregar a
467          * lista, ele se perde
468          */
469         if (segmento.getSisGrupoAtributoSga() != null)
470           if (segmento.getSisGrupoAtributoSga().getSisAtributoSatbs() != null)
471             segmento.getSisGrupoAtributoSga().getSisAtributoSatbs().size();
472 
473         if (segmento.getSegmentoCategoriaSgtcs() != null)
474           segmento.getSegmentoCategoriaSgtcs().size();
475 
476         segItem.setSegmentoSgt(segmento);
477       }
478       else {
479         /* combo de segmentos em itens livres */
480         if (!"".equals(Pagina.getParamStr(campos, "segmentoSgt"))) {
481           SegmentoSgt segmento = (SegmentoSgt) buscar(SegmentoSgt.class, Long.valueOf(Pagina.getParamStr(campos, "segmentoSgt")));
482 
483           /*
484            * Fazemos um size na coleção de atributos para que o objeto seja
485            * carregado com a coleção pois na pesquisa, se não encontrar
486            * resultado, o objeto é incluído na sessão e sem esse procedimento,
487            * ao carregar a lista, ele se perde
488            */
489           if (segmento.getSisGrupoAtributoSga() != null)
490             if (segmento.getSisGrupoAtributoSga().getSisAtributoSatbs() != null)
491               segmento.getSisGrupoAtributoSga().getSisAtributoSatbs().size();
492 
493           if (segmento.getSegmentoCategoriaSgtcs() != null)
494             segmento.getSegmentoCategoriaSgtcs().size();
495 
496           segItem.setSegmentoSgt(segmento);
497         }
498       }
499 
500       /* objetos que independente de estar ou não na tela devem ser testados */
501       if (!"".equals(Pagina.getParamStr(campos, "segmentoCategoriaSgtc"))) {
502         segItem.setSegmentoCategoriaSgtc((SegmentoCategoriaSgtc) this.buscar(SegmentoCategoriaSgtc.class, Long.valueOf(Pagina.getParamStr(campos, "segmentoCategoriaSgtc"))));
503       }
504       if (!"".equals(Pagina.getParamStr(campos, "segmentoItemFonteSgtif"))) {
505         segItem.setSegmentoItemFonteSgtif((SegmentoItemFonteSgtif) this.buscar(SegmentoItemFonteSgtif.class, Long.valueOf(Pagina.getParamStr(campos, "segmentoItemFonteSgtif"))));
506       }
507       if (!"".equals(Pagina.getParamStr(campos, "segmentoItemLeiauteSgtil"))) {
508         segItem.setSegmentoItemLeiauteSgtil((SegmentoItemLeiauteSgtil) this.buscar(SegmentoItemLeiauteSgtil.class, Long.valueOf(Pagina.getParamStr(campos, "segmentoItemLeiauteSgtil"))));
509       }
510 
511       if (recuperarParametrosComoString) {
512         /* campos que estão em todas as telas */
513         segItem.setTituloSgti(Pagina.getParamStr(campos, "tituloSgti"));
514         segItem.setDataItemSgti(Pagina.getParamDataBanco(campos, "dataItemSgti"));
515         segItem.setPalavrasChavesSgti(Pagina.getParamStr(campos, "palavrasChavesSgti"));
516         segItem.setIndUtilizTpAcessoSgti(Pagina.getParamStr(campos, "indUtilizTpAcessoSgti"));
517         segItem.setIndAtivoSgti(Pagina.getParamStr(campos, "indAtivoSgti"));
518 
519         /* campos não estão em todas as telas */
520         segItem.setLinhaApoioSgti(Pagina.getParamStr(campos, "linhaApoioSgti"));
521         segItem.setIntegraSgti(Pagina.getParamStr(campos, "integraSgti"));
522         segItem.setLegendaImag1Sgti(Pagina.getParamStr(campos, "legendaImag1Sgti"));
523         segItem.setLegendaImag2Sgti(Pagina.getParamStr(campos, "legendaImag2Sgti"));
524         segItem.setLegendaImag3Sgti(Pagina.getParamStr(campos, "legendaImag3Sgti"));
525         segItem.setLegendaImagCapaSgti(Pagina.getParamStr(campos, "legendaImagCapaSgti"));
526         segItem.setAnexoLegendaSgti(Pagina.getParamStr(campos, "anexoLegendaSgti"));
527         segItem.setUrlLinkSgti(Pagina.getParamStr(campos, "urlLinkSgti"));
528         /* datas em branco são setadas null */
529         segItem.setDataIniValidadeSgti(Pagina.getParamDataBanco(campos, "dataIniValidadeSgti"));
530         segItem.setDataFimValidadeSgti(Pagina.getParamDataBanco(campos, "dataFimValidadeSgti"));
531         segItem.setIndSuperDestaqueSgti(Pagina.getParamStr(campos, "indSuperDestaqueSgti"));
532         segItem.setIndDestaqueSgti(Pagina.getParamStr(campos, "indDestaqueSgti"));
533       }
534       else {
535         /* campos que estão em todas as telas */
536         segItem.setTituloSgti(Pagina.getParam(campos, "tituloSgti"));
537         segItem.setDataItemSgti(Pagina.getParamDataBanco(campos, "dataItemSgti"));
538         segItem.setPalavrasChavesSgti(Pagina.getParam(campos, "palavrasChavesSgti"));
539         segItem.setIndUtilizTpAcessoSgti(Pagina.getParam(campos, "indUtilizTpAcessoSgti"));
540         segItem.setIndAtivoSgti(Pagina.getParam(campos, "indAtivoSgti"));
541 
542         /* campos não estão em todas as telas */
543         segItem.setLinhaApoioSgti(Pagina.getParam(campos, "linhaApoioSgti"));
544         segItem.setIntegraSgti(Pagina.getParam(campos, "integraSgti"));
545         segItem.setLegendaImag1Sgti(Pagina.getParam(campos, "legendaImag1Sgti"));
546         segItem.setLegendaImag2Sgti(Pagina.getParam(campos, "legendaImag2Sgti"));
547         segItem.setLegendaImag3Sgti(Pagina.getParam(campos, "legendaImag3Sgti"));
548         segItem.setLegendaImagCapaSgti(Pagina.getParam(campos, "legendaImagCapaSgti"));
549         segItem.setAnexoLegendaSgti(Pagina.getParam(campos, "anexoLegendaSgti"));
550         segItem.setUrlLinkSgti(Pagina.getParam(campos, "urlLinkSgti"));
551         /* datas em branco são setadas null */
552         segItem.setDataIniValidadeSgti(Pagina.getParamDataBanco(campos, "dataIniValidadeSgti"));
553         segItem.setDataFimValidadeSgti(Pagina.getParamDataBanco(campos, "dataFimValidadeSgti"));
554         segItem.setIndSuperDestaqueSgti(Pagina.getParam(campos, "indSuperDestaqueSgti"));
555         segItem.setIndDestaqueSgti(Pagina.getParam(campos, "indDestaqueSgti"));
556       }
557 
558       if (criarCollections) {
559         if (campos.getParameterValues("editoriasSisAtributoSatb") != null)
560           criarCollectionEditoriasPesquisa(segItem, campos);
561         if (campos.getParameterValues("tpAcessoSisAtributoSatb") != null)
562           criarCollectionTipoAcessoPesquisa(segItem, campos);
563       }
564     } catch (Exception e) {
565       this.logger.error(e);
566       throw new ECARException(e);
567     }
568 
569   }
570 
571   /**
572    * Cria a coleção de atributos de Editorias de um SegmentoItem (Inclusão e
573    * alteração)
574    * @param segmentoItem
575    * @param request
576    */
577   private void criarCollectionEditorias(SegmentoItemSgti segItem, List campos) throws ECARException {
578     try {
579       Object[] codigosEditorias = FileUpload.verificaValorCampoArray(campos, "editoriasSisAtributoSatb");
580       segItem.setSegmentoSisAtribSgtsas(new HashSet());
581       for (int i = 0; i < codigosEditorias.length; i++) {
582         SisAtributoSatb atributo = (SisAtributoSatb) super.buscar(SisAtributoSatb.class, Long.valueOf(codigosEditorias[i].toString()));
583         segItem.getSegmentoSisAtribSgtsas().add(atributo);
584       }
585     } catch (Exception e) {
586       this.logger.error(e);
587       throw new ECARException(e);
588     }
589   }
590 
591   /**
592    * Cria a coleção de atributos de Tipo de Acesso de um SegmentoItem (inclusão
593    * e alteração)
594    * @param segmentoItem
595    * @param request
596    */
597   private void criarCollectionTipoAcesso(SegmentoItemSgti segItem, List campos) throws ECARException {
598     try {
599       Object[] codigosTpAcesso = FileUpload.verificaValorCampoArray(campos, "tpAcessoSisAtributoSatb");
600       segItem.setSegmentoItemTpacesSgtitas(new HashSet());
601       for (int i = 0; i < codigosTpAcesso.length; i++) {
602         SisAtributoSatb atributo = (SisAtributoSatb) super.buscar(SisAtributoSatb.class, Long.valueOf(codigosTpAcesso[i].toString()));
603         segItem.getSegmentoItemTpacesSgtitas().add(atributo);
604       }
605     } catch (Exception e) {
606       this.logger.error(e);
607       throw new ECARException(e);
608     }
609   }
610 
611   /**
612    * Cria a coleção de atributos de Editorias de um SegmentoItem para Pesquisa
613    * @param segmentoItem
614    * @param request
615    */
616   private void criarCollectionEditoriasPesquisa(SegmentoItemSgti segItem, HttpServletRequest campos) throws ECARException {
617     try {
618       Object[] codigosEditorias = campos.getParameterValues("editoriasSisAtributoSatb");
619       segItem.setSegmentoSisAtribSgtsas(new HashSet());
620       for (int i = 0; i < codigosEditorias.length; i++) {
621         SisAtributoSatb atributo = (SisAtributoSatb) super.buscar(SisAtributoSatb.class, Long.valueOf(codigosEditorias[i].toString()));
622         segItem.getSegmentoSisAtribSgtsas().add(atributo);
623       }
624     } catch (Exception e) {
625       this.logger.error(e);
626       throw new ECARException(e);
627     }
628   }
629 
630   /**
631    * Cria a coleção de atributos de Tipo de Acesso de um SegmentoItem para
632    * Pesquisa
633    * @param segmentoItem
634    * @param request
635    */
636   private void criarCollectionTipoAcessoPesquisa(SegmentoItemSgti segItem, HttpServletRequest campos) throws ECARException {
637     try {
638       Object[] codigosTpAcesso = campos.getParameterValues("tpAcessoSisAtributoSatb");
639       segItem.setSegmentoItemTpacesSgtitas(new HashSet());
640       for (int i = 0; i < codigosTpAcesso.length; i++) {
641         SisAtributoSatb atributo = (SisAtributoSatb) super.buscar(SisAtributoSatb.class, Long.valueOf(codigosTpAcesso[i].toString()));
642         segItem.getSegmentoItemTpacesSgtitas().add(atributo);
643       }
644     } catch (Exception e) {
645       this.logger.error(e);
646       throw new ECARException(e);
647     }
648   }
649 
650   /**
651    * Realiza o upload dos arquivos do Segmento Item. Seta no objeto segmentoItem
652    * referência para tal. Apaga o arquivo existente anteriormente em caso de
653    * alteração.
654    * @param segmentoItem
655    * @param campos
656    * @param pathRaiz
657    * @param pathRelativo
658    * @throws ECARException
659    */
660   public void uploadImagem(SegmentoItemSgti segItem, List campos, String pathRaiz, String pathRelativo) throws ECARException {
661     try {
662       Iterator it = campos.iterator();
663       while (it.hasNext()) {
664         FileItem fileItem = (FileItem) it.next();
665 
666         if (!fileItem.isFormField() && !"".equals(fileItem.getName())) {
667           if ("imagemCapaSgti".equals(fileItem.getFieldName())) {
668             if (segItem.getImagemCapaSgti() != null)
669               FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagemCapaSgti(), ""));
670 
671             File arquivoGravado = FileUpload.salvarNoDisco(fileItem, FileUpload.getPathFisico(pathRaiz, pathRelativo, segItem.getCodSgti() + "ic" + FileUpload.getNomeArquivo(fileItem)));
672 
673             segItem.setImagemCapaSgti(FileUpload.getPathFisico("", pathRelativo, segItem.getCodSgti() + "ic" + FileUpload.getNomeArquivo(fileItem)));
674 
675           }
676 
677           if ("imagem1Sgti".equals(fileItem.getFieldName())) {
678             if (segItem.getImagem1Stgi() != null)
679               FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagem1Stgi(), ""));
680 
681             File arquivoGravado = FileUpload.salvarNoDisco(fileItem, FileUpload.getPathFisico(pathRaiz, pathRelativo, segItem.getCodSgti() + "i1" + FileUpload.getNomeArquivo(fileItem)));
682 
683             segItem.setImagem1Stgi(FileUpload.getPathFisico("", pathRelativo, segItem.getCodSgti() + "i1" + FileUpload.getNomeArquivo(fileItem)));
684 
685           }
686 
687           if ("imagem2ScodUsugti".equals(fileItem.getFieldName())) {
688             if (segItem.getImagem2Sgti() != null)
689               FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagem2Sgti(), ""));
690 
691             File arquivoGravado = FileUpload.salvarNoDisco(fileItem, FileUpload.getPathFisico(pathRaiz, pathRelativo, segItem.getCodSgti() + "i2" + FileUpload.getNomeArquivo(fileItem)));
692 
693             segItem.setImagem2Sgti(FileUpload.getPathFisico("", pathRelativo, segItem.getCodSgti() + "i2" + FileUpload.getNomeArquivo(fileItem)));
694 
695           }
696 
697           if ("imagem3Sgti".equals(fileItem.getFieldName())) {
698             if (segItem.getImagem3Sgti() != null)
699               FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getImagem3Sgti(), ""));
700 
701             File arquivoGravado = FileUpload.salvarNoDisco(fileItem, FileUpload.getPathFisico(pathRaiz, pathRelativo, segItem.getCodSgti() + "i3" + FileUpload.getNomeArquivo(fileItem)));
702 
703             segItem.setImagem3Sgti(FileUpload.getPathFisico("", pathRelativo, segItem.getCodSgti() + "i3" + FileUpload.getNomeArquivo(fileItem)));
704 
705           }
706 
707           if ("anexoEnderecoSgti".equals(fileItem.getFieldName())) {
708             if (segItem.getAnexoEnderecoSgti() != null)
709               FileUpload.apagarArquivo(FileUpload.getPathFisico(pathRaiz, segItem.getAnexoEnderecoSgti(), ""));
710 
711             File arquivoGravado = FileUpload.salvarNoDisco(fileItem, FileUpload.getPathFisico(pathRaiz, pathRelativo, segItem.getCodSgti() + "an" + FileUpload.getNomeArquivo(fileItem)));
712 
713             segItem.setAnexoEnderecoSgti(FileUpload.getPathFisico("", pathRelativo, segItem.getCodSgti() + "an" + FileUpload.getNomeArquivo(fileItem)));
714 
715           }
716         }
717       }
718     } catch (Exception e) {
719       this.logger.error(e);
720       throw new ECARException(e);
721     }
722 
723   }
724 
725   /**
726    * Invoca o método pesquisar do Dao e itera sobre o resultado para inicializar
727    * as Collections de Tipo de Acesso e de Editorias de Cada objeto retornado.
728    * Para a pesquisa de itens livres, quando não informado o segmento não deve
729    * selecionar segmentoItem dos segmentos fixos.
730    * @param segmentoItem
731    * @param ServelContext
732    * @return
733    * @throws ECARException
734    */
735   public List pesquisar(SegmentoItemSgti segItem, ServletContext application) throws ECARException {
736     try {
737       List pesquisa = new ArrayList();
738 
739       pesquisa = super.pesquisar(segItem, new String[] { "tituloSgti", "asc" });
740 
741       if (segItem.getSegmentoSgt() == null) {
742         List itensFixos = new ArrayList();
743         Mensagem properties = new Mensagem(application);
744         StringBuilder select = new StringBuilder("select segItem from SegmentoItemSgti segItem").append(" where segItem.segmentoSgt.codSgt in (").append(properties.getMensagem("admPortal.itensFixos")).append(")");
745 
746         Query query = this.getSession().createQuery(select.toString());
747         itensFixos = query.list();
748         pesquisa.removeAll(itensFixos);
749       }
750 
751       if (segItem.getSegmentoSisAtribSgtsas() != null) {
752         /*
753          * Percorre o resultado e retira dele todas os segmentosItem onde dentro
754          * da coleção de SegmentoSisAtrib não existam todos os atributos de
755          * SegmentoSisAtrib passados no objeto de pesquisa
756          */
757         List atributosPesquisa = new ArrayList();
758         Iterator itAtbPesquisa = segItem.getSegmentoSisAtribSgtsas().iterator();
759         while (itAtbPesquisa.hasNext())
760           atributosPesquisa.add(((SisAtributoSatb) itAtbPesquisa.next()));
761 
762         Iterator it = pesquisa.iterator();
763         while (it.hasNext()) {
764           List atributosResultado = new ArrayList();
765           Iterator itAtribResultado = ((SegmentoItemSgti) it.next()).getSegmentoSisAtribSgtsas().iterator();
766 
767           while (itAtribResultado.hasNext())
768             atributosResultado.add((SisAtributoSatb) itAtribResultado.next());
769 
770           if (!atributosResultado.containsAll(atributosPesquisa))
771             it.remove();
772         }
773       }
774 
775       if (segItem.getSegmentoItemTpacesSgtitas() != null) {
776         /*
777          * Percorre o resultado e retira dele todas os segmentosItem onde dentro
778          * da coleção de SegmentoItemTpaces não existam todos os atributos de
779          * SegmentoItemTpaces passados no objeto de pesquisa
780          */
781         List atributosPesquisa = new ArrayList();
782         Iterator itAtbPesquisa = segItem.getSegmentoItemTpacesSgtitas().iterator();
783         while (itAtbPesquisa.hasNext())
784           atributosPesquisa.add(((SisAtributoSatb) itAtbPesquisa.next()));
785 
786         Iterator it = pesquisa.iterator();
787         while (it.hasNext()) {
788           List atributosResultado = new ArrayList();
789           Iterator itAtribResultado = ((SegmentoItemSgti) it.next()).getSegmentoItemTpacesSgtitas().iterator();
790 
791           while (itAtribResultado.hasNext())
792             atributosResultado.add((SisAtributoSatb) itAtribResultado.next());
793 
794           if (!atributosResultado.containsAll(atributosPesquisa))
795             it.remove();
796         }
797       }
798 
799       if (pesquisa.size() > 0) {
800         Iterator it = pesquisa.iterator();
801         while (it.hasNext()) {
802           SegmentoItemSgti sgti = (SegmentoItemSgti) it.next();
803           sgti.getSegmentoItemTpacesSgtitas().size();
804           sgti.getSegmentoSisAtribSgtsas().size();
805           sgti.getSegmentoSgt().getSegmentoCategoriaSgtcs().size();
806 
807           if (sgti.getSegmentoSgt().getSisGrupoAtributoSga() != null)
808             sgti.getSegmentoSgt().getSisGrupoAtributoSga().getSisAtributoSatbs().size();
809         }
810       }
811       return pesquisa;
812     } catch (Exception e) {
813       this.logger.error(e);
814       throw new ECARException(e);
815     }
816   }
817 
818   /**
819    * Retorna os código(IDs) dos atributos cadastrados em Tipo de Acesso para o
820    * segmentoItem
821    * @param segmentoItem
822    * @return lista
823    * @throws ECARException
824    */
825   public List getIdsTpAcessoSelecionados(SegmentoItemSgti segItem) throws ECARException {
826     List lista = new ArrayList();
827     List atributos = new ArrayList();
828 
829     if (segItem.getSegmentoItemTpacesSgtitas() != null && segItem.getSegmentoItemTpacesSgtitas().size() > 0)
830       atributos.addAll(segItem.getSegmentoItemTpacesSgtitas());
831 
832     Iterator it = atributos.iterator();
833 
834     while (it.hasNext()) {
835       SisAtributoSatb atb = (SisAtributoSatb) it.next();
836       lista.add(atb.getCodSatb());
837     }
838 
839     return lista;
840   }
841 
842   /**
843    * Retorna os código(IDs) dos atributos cadastrados em Editorias para o
844    * segmentoItem
845    * @param segmentoItem
846    * @return lista
847    * @throws ECARException
848    */
849   public List getIdsEditSelecionados(SegmentoItemSgti segItem) throws ECARException {
850     List lista = new ArrayList();
851     List atributos = new ArrayList();
852 
853     if (segItem.getSegmentoSisAtribSgtsas() != null && segItem.getSegmentoSisAtribSgtsas().size() > 0)
854       atributos.addAll(segItem.getSegmentoSisAtribSgtsas());
855 
856     Iterator it = atributos.iterator();
857 
858     while (it.hasNext()) {
859       SisAtributoSatb atb = (SisAtributoSatb) it.next();
860       lista.add(atb.getCodSatb());
861     }
862 
863     return lista;
864   }
865 
866   /**
867    * Método que cria a lista de editorias de um segmento
868    * @param segItem
869    * @return lista
870    */
871   public List getEditoriasBySegItem(SegmentoItemSgti segItem) {
872     List lista = new ArrayList();
873 
874     if (segItem.getSegmentoSgt() != null)
875       if (segItem.getSegmentoSgt().getSisGrupoAtributoSga() != null)
876         if (segItem.getSegmentoSgt().getSisGrupoAtributoSga().getSisAtributoSatbs() != null && segItem.getSegmentoSgt().getSisGrupoAtributoSga().getSisAtributoSatbs().size() > 0)
877           lista.addAll(segItem.getSegmentoSgt().getSisGrupoAtributoSga().getSisAtributoSatbs());
878 
879     return lista;
880   }
881 
882   /**
883    * Retorna lista com todos os itens de segmentos não vinculados a uma sub-área
884    * de destaque
885    * @param categoria
886    * @param destaqueSubArea
887    * @return
888    */
889   public Collection getSegmentosItemNaoVinculadosASubArea(SegmentoCategoriaSgtc categoria, DestaqueSubAreaDtqsa destaqueSubArea) throws ECARException {
890     try {
891       Query query = this.getSession().createQuery("select sgti from SegmentoItemSgti sgti " + "where sgti.indAtivoSgti = 'S' " + "and sgti.segmentoCategoriaSgtc.codSgtc = :codSgtc " + "order by sgti.dataItemSgti asc");
892       query.setLong("codSgtc", categoria.getCodSgtc().longValue());
893 
894       Collection itensDaCategoriaAtivos = query.list();
895       List itensDaSubArea = new ArrayList();
896       Iterator it = destaqueSubArea.getDestaqueItemRelDtqirs().iterator();
897       while (it.hasNext()) {
898         DestaqueItemRelDtqir destaque = (DestaqueItemRelDtqir) it.next();
899         if (destaque.getSegmentoItemSgti() != null)
900           itensDaSubArea.add(destaque.getSegmentoItemSgti());
901       }
902       itensDaCategoriaAtivos.removeAll(itensDaSubArea);
903       return itensDaCategoriaAtivos;
904     } catch (HibernateException e) {
905       this.logger.error(e);
906       throw new ECARException(e);
907     }
908   }
909 
910   /**
911    * Seleciona o SegmentoItem Matéria/Artigo para Destaque da capa do portal,
912    * seja o mais recente, e que esteja dentro da validade
913    * @param application
914    * @return
915    */
916   public SegmentoItemSgti getSegmentoItemSuperDestaque(ServletContext application) {
917     try {
918       Mensagem properties = new Mensagem(application);
919 
920       Date dataAtual = Data.getDataAtual();
921 
922       StringBuilder select = new StringBuilder("select segItem from SegmentoItemSgti segItem").append(" where segItem.segmentoSgt.codSgt = :codSgt").append(" and segItem.indSuperDestaqueSgti = 'S'").append(" and ( segItem.dataIniValidadeSgti <= :dataAtual").append(" and segItem.dataFimValidadeSgti >= :dataAtual )").append(" order by segItem.dataItemSgti desc");
923 
924       Query query = this.getSession().createQuery(select.toString());
925       query.setLong("codSgt", Long.valueOf(properties.getMensagem("admPortal.materias")).longValue());
926       query.setDate("dataAtual", dataAtual);
927       query.setMaxResults(1);
928 
929       // Date dataMaisRecenteSegItem =
930       // getDataMaisRecenteSegmentoItemSuperDestaque();
931       // if(dataMaisRecenteSegItem != null){
932       // String select = "select segItem from SegmentoItemSgti segItem" +
933       // " where segItem.indSuperDestaqueSgti = 'S'"
934       // +" + usuario.getCodUsu() + "
935       // " and segItem.dataItemSgti <= :dataMaisRecente" +
936       // " and ( segItem.dataIniValidade <= :dataAtual" +
937       // " and segItem.dataFimValidade >= :dataAtual )";
938       // Query query = this.getSession().createQuery(select);
939       // query.setDate("dataMaisRecente", dataMaisRecenteSegItem);
940       // query.setDate("dataAtual", dataAtual);
941 
942       List lista = query.list();
943       Iterator it = lista.iterator();
944 
945       if (it.hasNext()) {
946         SegmentoItemSgti segItem = (SegmentoItemSgti) it.next();
947         return segItem;
948       }
949       // }
950 
951       return null;
952     } catch (HibernateException e) {
953       this.logger.error(e);
954       return null;
955     }
956   }
957 
958   /**
959    * @return Date
960    */
961 
962   public Date getDataMaisRecenteSegmentoItemSuperDestaque() {
963     try {
964       StringBuilder select = new StringBuilder("select max(segItem.dataItemSgti) from SegmentoItemSgti segItem").append(" where segItem.indSuperDestaqueSgti = 'S'");
965 
966       Query query = this.getSession().createQuery(select.toString());
967       query.setMaxResults(1);
968 
969       return (Date) query.uniqueResult();
970 
971     } catch (HibernateException e) {
972       this.logger.error(e);
973       return null;
974     }
975   }
976 
977   /**
978    * Seleciona 3 (ou mais, se passado parametro "qtd") outras Matérias/Artigos
979    * mais recentes em SegmentoItem diferente da Capa Destaque e que esteja na
980    * validade
981    * @param application
982    * @return
983    */
984   public List getSegmentoItemMaisArtigos(ServletContext application, UsuarioUsu usuario) {
985     List lista = new ArrayList();
986     try {
987       Mensagem properties = new Mensagem(application);
988 
989       Date dataAtual = Data.getDataAtual();
990       SegmentoItemSgti segItemSuper = getSegmentoItemSuperDestaque(application);
991 
992       String todos = null;
993       try {
994         todos = Pagina.getParamStr(request, "todos");
995       } catch (NullPointerException ne) {
996         // não é necessário logar exceção aqui
997       }
998 
999       StringBuilder select = new StringBuilder("select i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append(" and ( i.dataIniValidadeSgti <= :dataAtual").append(" and i.dataFimValidadeSgti >= :dataAtual )").append(" and i.segmentoSgt.codSgt = :codSgt ").append("and ((i.indUtilizTpAcessoSgti = 'N') or ").append("(i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append("where b.comp_id.codSatb in (").append("select a.comp_id.codSatb from UsuarioAtributoUsua a ").append("where a.comp_id.codUsu = :codUsu))))");
1000 
1001       if ((segItemSuper != null) && (todos == null)) {
1002         select.append(" and i.codSgti != :codSgti");
1003         select.append(" and i.indSuperDestaqueSgti = 'S' ");
1004       }
1005 
1006       if (todos == "") {
1007         select.append(" and ((i.indDestaqueSgti = 'S') or (i.indDestaqueSgti = 'N' and i.indSuperDestaqueSgti = 'S')) ");
1008       }
1009 
1010       String order = " order by i.dataItemSgti desc";
1011 
1012       Query query = this.getSession().createQuery(select + order);
1013       query.setLong("codSgt", Long.valueOf(properties.getMensagem("admPortal.materias")).longValue());
1014       query.setDate("dataAtual", dataAtual);
1015       query.setLong("codUsu", usuario.getCodUsu().longValue());
1016 
1017       if ((segItemSuper != null) && (todos == null))
1018         query.setLong("codSgti", segItemSuper.getCodSgti().longValue());
1019 
1020       String qtd = null, qtdPag = null, numPag = null;
1021 
1022       try {
1023         qtd = Pagina.getParamStr(request, "qtd");
1024         qtdPag = Pagina.getParamStr(request, "qtdPag");
1025         numPag = Pagina.getParamStr(request, "numPag");
1026       } catch (NullPointerException ne) {
1027         // não é necessário logar exceção aqui
1028       }
1029 
1030       if ((qtd != null) && (!"".equals(qtd))) {
1031         if (!"00".equals(qtd))
1032           query.setMaxResults(Integer.parseInt(qtd));
1033       }
1034       // else query.setMaxResults(3);
1035       /*
1036        * if (((qtdPag != null)&&(!"".equals(qtdPag))) && (numPag !=
1037        * null)&&(!"".equals(numPag))) {
1038        * query.setMaxResults(Integer.parseInt(qtdPag)); query.setFirstResult(
1039        * ((Integer.parseInt(numPag)-1) * Integer.parseInt(qtdPag))); }
1040        */
1041       lista = query.list();
1042 
1043       return lista;
1044     } catch (HibernateException e) {
1045       this.logger.error(e);
1046       return lista;
1047     }
1048   }
1049 
1050   /**
1051    * Seleciona 3 outras Taxações/Clips mais recentes em SegmentoItem diferente
1052    * da Capa Destaque e que esteja na validade
1053    * @param application
1054    * @return
1055    */
1056   public List getTaxacaoClip(ServletContext application) {
1057     List lista = new ArrayList();
1058     try {
1059 
1060       Date dataAtual = Data.getDataAtual();
1061       SegmentoItemSgti segItemSuper = getSegmentoItemSuperDestaque(application);
1062 
1063       StringBuilder select = new StringBuilder("select segItem from SegmentoItemSgti segItem").append(" where segItem.segmentoSgt.codSgt = :codSgt").append(" and ( segItem.dataIniValidadeSgti <= :dataAtual").append(" and segItem.dataFimValidadeSgti >= :dataAtual )");
1064       if (segItemSuper != null) {
1065         select.append(" and segItem.codSgti != :codSgti");
1066       }
1067 
1068       select.append(" order by segItem.dataItemSgti desc");
1069 
1070       Query query = this.getSession().createQuery(select.toString());
1071       query.setLong("codSgt", 2);
1072       query.setDate("dataAtual", dataAtual);
1073       if (segItemSuper != null)
1074         query.setLong("codSgti", segItemSuper.getCodSgti().longValue());
1075       query.setMaxResults(3);
1076 
1077       lista = query.list();
1078 
1079       return lista;
1080     } catch (HibernateException e) {
1081       this.logger.error(e);
1082       return lista;
1083     }
1084   }
1085 
1086   /**
1087    * Devolve uma lista de ítens de dúvidas frequentes visíveis ao usuário
1088    * @return List
1089    */
1090   public List getListSegmentoItensVinculadosAoUsuario(SegmentoCategoriaSgtc categoria, UsuarioUsu usuario) throws ECARException {
1091     List lista = null;
1092 
1093     try {
1094 
1095       StringBuilder select = new StringBuilder("select i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append("and i.segmentoCategoriaSgtc.codSgtc = :codSgtc ").append(" and i.segmentoSgt.codSgt = 3 ").append("and ((i.indUtilizTpAcessoSgti = 'N') or ").append("(i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append("where b.comp_id.codSatb in (").append("select a.comp_id.codSatb from UsuarioAtributoUsua a ").append("where a.comp_id.codUsu = :codUsu))))").append(" order by i.dataItemSgti asc");
1096 
1097       Query query = this.getSession().createQuery(select.toString());
1098       query.setLong("codUsu", usuario.getCodUsu().longValue());
1099       query.setLong("codSgtc", categoria.getCodSgtc().longValue());
1100       lista = query.list();
1101 
1102     } catch (HibernateException e) {
1103       this.logger.error(e);
1104       throw new ECARException("erro.hibernateException");
1105     }
1106 
1107     return lista;
1108   }
1109 
1110   /**
1111    * Devolve uma lista de ítens de dúvidas frequentes para acesso publico
1112    * @return List
1113    */
1114   public List getListSegmentoItensAcessoPublico(SegmentoCategoriaSgtc categoria) throws ECARException {
1115     List lista = null;
1116 
1117     try {
1118       StringBuilder select = new StringBuilder("select i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append("and i.segmentoCategoriaSgtc.codSgtc = :codSgtc ").append(" and i.segmentoSgt.codSgt = 3 ").append("and ((i.indUtilizTpAcessoSgti = 'N') or ").append("(i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append("where b.comp_id.codSatb in (select cfg.sisAtributoSatbByCodSaAcesso.codSatb from ConfiguracaoCfg cfg ").append("))))").append(" order by i.dataItemSgti asc");
1119 
1120       Query query = this.getSession().createQuery(select.toString());
1121       query.setLong("codSgtc", categoria.getCodSgtc().longValue());
1122       lista = query.list();
1123     } catch (HibernateException e) {
1124       this.logger.error(e);
1125       throw new ECARException("erro.hibernateException");
1126     }
1127 
1128     return lista;
1129   }
1130 
1131   /**
1132    * Devolve uma lista de ítens do glossário visíveis ao usuário
1133    * @return List
1134    */
1135 
1136   public List getListSegmentoItensGlossarioVinculadosAoUsuario(SegmentoCategoriaSgtc categoria, UsuarioUsu usuario) throws ECARException {
1137     List lista = null;
1138 
1139     try {
1140 
1141       StringBuilder select = new StringBuilder("select i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append("and i.segmentoCategoriaSgtc.codSgtc = :codSgtc").append(" and i.segmentoSgt.codSgt = 4 ");
1142 
1143       if (usuario != null && usuario.getCodUsu() != null) {
1144         select.append("and ((i.indUtilizTpAcessoSgti = 'N') or ").append("(i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append("where b.comp_id.codSatb in (").append("select a.comp_id.codSatb from UsuarioAtributoUsua a ").append("where a.comp_id.codUsu = :codUsu))))");
1145       }
1146       else {
1147         select.append("and i.indUtilizTpAcessoSgti = 'N'");
1148       }
1149       select.append(" order by i.tituloSgti asc");
1150 
1151       Query query = this.getSession().createQuery(select.toString());
1152       query.setLong("codSgtc", categoria.getCodSgtc().longValue());
1153       if (usuario != null && usuario.getCodUsu() != null) {
1154         query.setLong("codUsu", usuario.getCodUsu().longValue());
1155       }
1156       lista = query.list();
1157 
1158     } catch (HibernateException e) {
1159       this.logger.error(e);
1160       throw new ECARException("erro.hibernateException");
1161     }
1162 
1163     return lista;
1164   }
1165 
1166   /**
1167    * Devolve uma lista de ítens do glossário para acesso público
1168    * @return List
1169    */
1170 
1171   public List getListSegmentoItensGlossarioAcessoPublico(SegmentoCategoriaSgtc categoria) throws ECARException {
1172     List lista = null;
1173 
1174     try {
1175 
1176       StringBuilder select = new StringBuilder("select i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append("and i.segmentoCategoriaSgtc.codSgtc = :codSgtc").append(" and i.segmentoSgt.codSgt = 4 ").append("and ((i.indUtilizTpAcessoSgti = 'N') or ").append("(i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append("where b.comp_id.codSatb in (").append("select cfg.sisAtributoSatbByCodSaAcesso.codSatb from ConfiguracaoCfg cfg ").append("))))").append(" order by i.tituloSgti asc");
1177 
1178       Query query = this.getSession().createQuery(select.toString());
1179       query.setLong("codSgtc", categoria.getCodSgtc().longValue());
1180       lista = query.list();
1181 
1182     } catch (HibernateException e) {
1183       this.logger.error(e);
1184       throw new ECARException("erro.hibernateException");
1185     }
1186 
1187     return lista;
1188   }
1189 
1190   /**
1191    * Retorna o numero de Matérias/Artigos mais recentes em SegmentoItem
1192    * diferente da Capa Destaque e que esteja na validade
1193    * @param application
1194    * @return List
1195    */
1196   public long getQtdSegmentoItemMaisArtigos(ServletContext application, UsuarioUsu usuario) {
1197     long ret = 0;
1198     List lista = new ArrayList();
1199     try {
1200       Mensagem properties = new Mensagem(application);
1201 
1202       Date dataAtual = Data.getDataAtual();
1203       SegmentoItemSgti segItemSuper = getSegmentoItemSuperDestaque(application);
1204       String todos = null;
1205       todos = Pagina.getParamStr(request, "todos");
1206 
1207       StringBuilder select = new StringBuilder("select i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append(" and ( i.dataIniValidadeSgti <= :dataAtual").append(" and i.dataFimValidadeSgti >= :dataAtual )").append(" and i.segmentoSgt.codSgt = :codSgt ").append("and ((i.indUtilizTpAcessoSgti = 'N') or ").append("(i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append("where b.comp_id.codSatb in (").append("select a.comp_id.codSatb from UsuarioAtributoUsua a ").append("where a.comp_id.codUsu = :codUsu))))");
1208 
1209       if ((segItemSuper != null) && (todos == null)) {
1210         // select = select + " and i.codSgti != :codSgti";
1211         select.append(" and i.indSuperDestaqueSgti = 'S' ");
1212       }
1213 
1214       if (todos == "") {
1215         select.append(" and ((i.indDestaqueSgti = 'S') or (i.indDestaqueSgti = 'N' and i.indSuperDestaqueSgti = 'S')) ");
1216       }
1217 
1218       select.append(" order by i.dataItemSgti desc");
1219 
1220       Query query = this.getSession().createQuery(select.toString());
1221       query.setLong("codSgt", Long.valueOf(properties.getMensagem("admPortal.materias")).longValue());
1222       query.setDate("dataAtual", dataAtual);
1223       query.setLong("codUsu", usuario.getCodUsu().longValue());
1224       // if (segItemSuper != null)
1225       // query.setInteger("codSgti", segItemSuper.getCodSgti().intValue());
1226 
1227       lista = query.list();
1228       ret = lista.size();
1229       return ret;
1230     } catch (HibernateException e) {
1231       this.logger.error(e);
1232       return ret;
1233     }
1234   }
1235 
1236   /**
1237    * Devolve uma lista de ítens de taxacoes
1238    * @return List
1239    */
1240   public List getListSegmentoItemTaxacoes(UsuarioUsu usuario) throws ECARException {
1241     List lista = null;
1242 
1243     try {
1244       StringBuilder select = new StringBuilder("select i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append(" and i.segmentoSgt.codSgt = 2 ").append(" and ( i.dataIniValidadeSgti <= :dataAtual").append(" and i.dataFimValidadeSgti >= :dataAtual ) ");
1245 
1246       String dt = "";
1247       try {
1248         dt = Pagina.getParamStr(request, "data");
1249       } catch (NullPointerException ne) {
1250         this.logger.error(ne);
1251       }
1252 
1253       if (!"00".equals(dt))
1254         select.append(" and i.dataItemSgti=:dataAtual ");
1255 
1256       select.append(" and ((i.indUtilizTpAcessoSgti = 'N') or ").append(" (i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("	select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append("	where b.comp_id.codSatb in (").append("		select a.comp_id.codSatb from UsuarioAtributoUsua a ").append("		where a.comp_id.codUsu = :codUsu))))").append(" order by i.dataItemSgti desc, i.dataInclusaoSgti desc ");
1257 
1258       Query query = this.getSession().createQuery(select.toString());
1259       query.setLong("codUsu", usuario.getCodUsu().longValue());
1260       query.setDate("dataAtual", Data.getDataAtual());
1261 
1262       String qtd = null;
1263       try {
1264         qtd = Pagina.getParamStr(request, "qtd");
1265       } catch (NullPointerException ne) {
1266         this.logger.error(ne);
1267       }
1268 
1269       if ((qtd != null) && (!"".equals(qtd))) {
1270         if (!"00".equals(qtd))
1271           query.setMaxResults(Integer.parseInt(qtd));
1272       }
1273       else
1274         query.setMaxResults(3);
1275 
1276       lista = query.list();
1277 
1278     } catch (HibernateException e) {
1279       this.logger.error(e);
1280       throw new ECARException("erro.hibernateException");
1281     }
1282 
1283     return lista;
1284   }
1285 
1286   /**
1287    * Devolve a quantidade de ítens de taxacoes
1288    * @return List
1289    */
1290   public long getQtdSegmentoItemTaxacoes(UsuarioUsu usuario) throws ECARException {
1291     long ret = 0;
1292 
1293     try {
1294       StringBuilder select = new StringBuilder("select i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append(" and i.segmentoSgt.codSgt = 2 ").append(" and ( i.dataIniValidadeSgti <= :dataAtual").append(" and i.dataFimValidadeSgti >= :dataAtual )").append(" and i.dataItemSgti=:dataAtual").append(" and ((i.indUtilizTpAcessoSgti = 'N') or ").append(" (i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("	select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append("	where b.comp_id.codSatb in (").append("		select a.comp_id.codSatb from UsuarioAtributoUsua a ").append("		where a.comp_id.codUsu = :codUsu))))").append(" order by i.dataInclusaoSgti desc");
1295 
1296       Query query = this.getSession().createQuery(select.toString());
1297       query.setDate("dataAtual", Data.getDataAtual());
1298       query.setLong("codUsu", usuario.getCodUsu().longValue());
1299       ret = (query.list()).size();
1300 
1301     } catch (HibernateException e) {
1302       this.logger.error(e);
1303       throw new ECARException("erro.hibernateException");
1304     }
1305 
1306     return ret;
1307   }
1308 
1309   /**
1310    * Devolve uma lista de ítens de taxacoes de acordo com os parâmetros
1311    * @return List
1312    */
1313   public List pesquisaTaxacoes(UsuarioUsu usuario) throws ECARException {
1314     List lista = null;
1315     List ret = new ArrayList();
1316 
1317     String palavra = Pagina.getParamStr(request, "palavra");
1318     String editoria = Pagina.getParamStr(request, "editorias");
1319     String fonte = null;
1320     String dtInicial = null;
1321     String dtFinal = null;
1322 
1323     try {
1324       fonte = Pagina.getParamStr(request, "fonte");
1325     } catch (NullPointerException ne) {
1326       this.logger.error(ne);
1327     }
1328     try {
1329       dtInicial = Pagina.getParamStr(request, "dataInicial");
1330     } catch (NullPointerException ne) {
1331       this.logger.error(ne);
1332     }
1333     try {
1334       dtFinal = Pagina.getParamStr(request, "dataFinal");
1335     } catch (NullPointerException ne) {
1336       this.logger.error(ne);
1337     }
1338 
1339     try {
1340 
1341       String[] palavras = palavra.split("\\s");
1342       String[] fontes = fonte.split("\\s");
1343 
1344       StringBuilder select = new StringBuilder("select distinct i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append(" and i.segmentoSgt.codSgt = 2 ").append(" and ( i.dataIniValidadeSgti <= :dataAtual").append(" and i.dataFimValidadeSgti >= :dataAtual )");
1345 
1346       select.append(" and ( ");
1347       for (int i = 0; i < palavras.length; i++) {
1348         select.append(" ( upper( i.tituloSgti ) like :palavra").append(i).append(" or upper( i.linhaApoioSgti ) like :palavra").append(i).append(" or upper( i.legendaImagCapaSgti ) like :palavra").append(i).append(" )");
1349         if ((i + 1) < palavras.length)
1350           select.append(" or ");
1351       }
1352       select.append(" ) ");
1353 
1354       if (fontes.length > 0) {
1355         select.append(" and ( ");
1356         for (int i = 0; i < fontes.length; i++) {
1357           select.append(" ( upper( i.segmentoItemFonteSgtif.descricaoSgtif ) like :fonte").append(i).append(" )");
1358           if ((i + 1) < fontes.length)
1359             select.append(" or ");
1360         }
1361         select.append(" ) ");
1362       }
1363       if ((dtInicial != null) && (!"".equals(dtInicial)))
1364         select.append(" and (i.dataItemSgti >= :dtInicial) ");
1365       if ((dtFinal != null) && (!"".equals(dtFinal)))
1366         select.append(" and (i.dataItemSgti <= :dtFinal) ");
1367 
1368       select.append(" and ((i.indUtilizTpAcessoSgti = 'N') or ").append(" (i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("	select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append("	   where b.comp_id.codSatb in (").append("		select a.comp_id.codSatb from UsuarioAtributoUsua a ").append("		where a.comp_id.codUsu = ").append(usuario.getCodUsu()).append("))))").append(" order by i.dataInclusaoSgti desc");
1369 
1370       Query query = this.getSession().createQuery(select.toString());
1371 
1372       for (int i = 0; i < palavras.length; i++) {
1373         query.setString("palavra" + i, "%" + palavras[i].toUpperCase() + "%");
1374       }
1375       for (int i = 0; i < fontes.length; i++) {
1376         query.setString("fonte" + i, "%" + fontes[i].toUpperCase() + "%");
1377       }
1378       if ((dtInicial != null) && (!"".equals(dtInicial)))
1379         query.setDate("dtInicial", Data.parseDate(dtInicial));
1380       if ((dtFinal != null) && (!"".equals(dtFinal)))
1381         query.setDate("dtFinal", Data.parseDate(dtFinal));
1382 
1383       query.setDate("dataAtual", Data.getDataAtual());
1384       lista = query.list();
1385 
1386       if (lista.size() > 0) {
1387         Iterator it = lista.iterator();
1388         while (it.hasNext()) {
1389           SegmentoItemSgti sgti = (SegmentoItemSgti) it.next();
1390 
1391           Set atb = sgti.getSegmentoSisAtribSgtsas();
1392 
1393           if ((atb != null) && !(atb.isEmpty())) {
1394             Iterator itAtb = atb.iterator();
1395             while (itAtb.hasNext()) {
1396               SisAtributoSatb atributo = (SisAtributoSatb) itAtb.next();
1397 
1398               String[] codSatb = editoria.split(",");
1399               for (int i = 0; i < codSatb.length; i++) {
1400                 if (atributo.getCodSatb().equals(Long.valueOf(codSatb[i]))) {
1401                   ret.add(sgti);
1402                 }
1403               }
1404             }
1405           }
1406         }
1407       }
1408     } catch (HibernateException e) {
1409       this.logger.error(e);
1410       throw new ECARException("erro.hibernateException");
1411     }
1412 
1413     return ret;
1414   }
1415 
1416   /**
1417    * Seleciona o SegmentoItem pelo codSgti
1418    * @param application
1419    * @return List
1420    */
1421   public SegmentoItemSgti getSegmentoItemCodSgti(long codSgti) {
1422     try {
1423 
1424       StringBuilder select = new StringBuilder("select segItem from SegmentoItemSgti segItem").append(" where segItem.codSgti = :codSgti");
1425       Query query = this.getSession().createQuery(select.toString());
1426       query.setMaxResults(1);
1427       query.setLong("codSgti", codSgti);
1428 
1429       List lista = query.list();
1430       Iterator it = lista.iterator();
1431 
1432       if (it.hasNext()) {
1433         SegmentoItemSgti segItem = (SegmentoItemSgti) it.next();
1434         return segItem;
1435       }
1436       return null;
1437     } catch (HibernateException e) {
1438       this.logger.error(e);
1439       return null;
1440     }
1441   }
1442 
1443   /**
1444    * Seleciona 3 outras Taxações/Clips mais recentes em SegmentoItem diferente
1445    * da Capa Destaque e que esteja na validade
1446    * @param application
1447    * @return List
1448    */
1449   public List getLeiautesNovos() {
1450     List lista = null;
1451     try {
1452 
1453       StringBuilder select = new StringBuilder("select segLeiaute from SegmentoItemLeiauteSgtil segLeiaute").append(" where segLeiaute.codSgtil >= 11").append(" order by segLeiaute.descricaoSgtil asc");
1454 
1455       Query query = this.getSession().createQuery(select.toString());
1456 
1457       lista = query.list();
1458 
1459       return lista;
1460     } catch (HibernateException e) {
1461       this.logger.error(e);
1462       return lista;
1463     }
1464   }
1465 
1466   /**
1467    * Método que cria a lista de editorias através dos codSatb
1468    * @return lista
1469    */
1470   public List getEditoriasByIds(String ids) {
1471     List lista = null;
1472     try {
1473       Query query = this.getSession().createQuery("select editoria from SisAtributoSatb editoria " + "where editoria.codSatb IN (" + ids + ")");
1474 
1475       lista = query.list();
1476 
1477       return lista;
1478     } catch (HibernateException e) {
1479       this.logger.error(e);
1480       return lista;
1481     }
1482   }
1483 
1484   /**
1485    * Devolve uma lista de SegmentoItem de acordo com os parâmetros passados por
1486    * request (palavra, dataInicial, dataFinal, segmentos) e o UsuarioUsu por
1487    * parâmetro do método
1488    * @return List
1489    */
1490   public List pesquisar(UsuarioUsu usuario) throws ECARException {
1491     List lista = new ArrayList();
1492 
1493     String[] palavras = Pagina.getParamStr(request, "palavra").split("\\s");
1494     String dtInicial = null;
1495     String dtFinal = null;
1496 
1497     try {
1498       dtInicial = Pagina.getParamStr(request, "dataInicial");
1499     } catch (NullPointerException ne) {
1500       this.logger.error(ne);
1501     }
1502     try {
1503       dtFinal = Pagina.getParamStr(request, "dataFinal");
1504     } catch (NullPointerException ne) {
1505       this.logger.error(ne);
1506     }
1507 
1508     try {
1509       StringBuilder select = new StringBuilder("select distinct i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append(" and ( i.dataIniValidadeSgti <= :dataAtual").append(" and i.dataFimValidadeSgti >= :dataAtual )").append(" and i.segmentoSgt.codSgt IN (").append(Pagina.getParamStr(request, "codSgtis")).append(")");
1510 
1511       select.append(" and ( ");
1512       for (int i = 0; i < palavras.length; i++) {
1513         select.append(" ( upper( i.tituloSgti ) like :palavra").append(i).append(" or upper( i.linhaApoioSgti ) like :palavra").append(i).append(" or upper( i.integraSgti ) like :palavra").append(i).append(" or upper( i.palavrasChavesSgti ) like :palavra").append(i).append(" or upper( i.anexoLegendaSgti ) like :palavra").append(i).append(" or upper( i.legendaImagCapaSgti ) like :palavra").append(i).append(" or upper( i.legendaImag1Sgti ) like :palavra").append(i).append(" or upper( i.legendaImag2Sgti ) like :palavra").append(i).append(" or upper( i.legendaImag3Sgti ) like :palavra").append(i).append(" ) or ");
1514 
1515         select.append(" ( upper( i.segmentoCategoriaSgtc.tituloSgtc ) like :palavra").append(i).append(" ").append(" or upper( i.segmentoCategoriaSgtc.descricaoSgtc ) like :palavra").append(i).append(" )");
1516 
1517         if ((i + 1) < palavras.length)
1518           select.append(" and ");
1519       }
1520       select.append(" ) ");
1521 
1522       if ((dtInicial != null) && (!"".equals(dtInicial)))
1523         select.append(" and (i.dataItemSgti >= :dtInicial) ");
1524       if ((dtFinal != null) && (!"".equals(dtFinal)))
1525         select.append(" and (i.dataItemSgti <= :dtFinal) ");
1526 
1527       select.append(" and ((i.indUtilizTpAcessoSgti = 'N') or ").append(" (i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("	select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append(" where b.comp_id.codSatb in (").append("		select a.comp_id.codSatb from UsuarioAtributoUsua a ").append("		where a.comp_id.codUsu = :codUsu))))").append(" order by i.dataInclusaoSgti desc");
1528 
1529       Query query = this.getSession().createQuery(select.toString());
1530       query.setLong("codUsu", usuario.getCodUsu().longValue());
1531 
1532       for (int i = 0; i < palavras.length; i++) {
1533         query.setString("palavra" + i, "%" + palavras[i].toUpperCase() + "%");
1534       }
1535       if ((dtInicial != null) && (!"".equals(dtInicial)))
1536         query.setDate("dtInicial", Data.parseDate(dtInicial));
1537       if ((dtFinal != null) && (!"".equals(dtFinal)))
1538         query.setDate("dtFinal", Data.parseDate(dtFinal));
1539 
1540       query.setDate("dataAtual", Data.getDataAtual());
1541       lista = query.list();
1542     } catch (HibernateException e) {
1543       this.logger.error(e);
1544       throw new ECARException("erro.hibernateException");
1545     }
1546 
1547     return lista;
1548   }
1549 
1550   /**
1551    * Seleciona 3 (ou mais, se passado parametro "qtd") outras Matérias/Artigos
1552    * mais recentes em SegmentoItem diferente da Capa Destaque e que esteja na
1553    * validade
1554    * @param application
1555    * @return List
1556    */
1557   public List getSegmentoItemTodosArtigos(ServletContext application, UsuarioUsu usuario) {
1558     List lista = new ArrayList();
1559     try {
1560       Mensagem properties = new Mensagem(application);
1561 
1562       Date dataAtual = Data.getDataAtual();
1563 
1564       String todos = null;
1565       try {
1566         todos = Pagina.getParamStr(request, "todos");
1567       } catch (NullPointerException ne) {
1568         this.logger.error(ne);
1569       }
1570 
1571       StringBuilder select = new StringBuilder("select i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append(" and i.dataFimValidadeSgti >= :dataAtual ").append(" and i.segmentoSgt.codSgt = :codSgt ").append("and ((i.indUtilizTpAcessoSgti = 'N') or ").append("(i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append("where b.comp_id.codSatb in (").append("select a.comp_id.codSatb from UsuarioAtributoUsua a ").append("where a.comp_id.codUsu = :codUsu))))");
1572 
1573       StringBuilder order = new StringBuilder(" order by i.dataItemSgti desc");
1574 
1575       Query query = this.getSession().createQuery(select.toString() + order);
1576       query.setLong("codSgt", Long.valueOf(properties.getMensagem("admPortal.materias")).longValue());
1577       query.setDate("dataAtual", dataAtual);
1578       query.setLong("codUsu", usuario.getCodUsu().longValue());
1579 
1580       String qtd = null, qtdPag = null, numPag = null;
1581 
1582       try {
1583         qtd = Pagina.getParamStr(request, "qtd");
1584         qtdPag = Pagina.getParamStr(request, "qtdPag");
1585         numPag = Pagina.getParamStr(request, "numPag");
1586       } catch (NullPointerException ne) {
1587         this.logger.error(ne);
1588       }
1589 
1590       if ((qtd != null) && (!"".equals(qtd))) {
1591         if (!"00".equals(qtd))
1592           query.setMaxResults(Integer.parseInt(qtd));
1593       }
1594       // else query.setMaxResults(3);
1595       /*
1596        * if (((qtdPag != null)&&(!"".equals(qtdPag))) && (numPag !=
1597        * null)&&(!"".equals(numPag))) {
1598        * query.setMaxResults(Integer.parseInt(qtdPag)); query.setFirstResult(
1599        * ((Integer.parseInt(numPag)-1) * Integer.parseInt(qtdPag))); }
1600        */
1601       lista = query.list();
1602 
1603       return lista;
1604     } catch (HibernateException e) {
1605       this.logger.error(e);
1606       return lista;
1607     }
1608   }
1609 
1610   /**
1611    * Método que cria a lista de editorias através dos codSatb
1612    * @return lista
1613    */
1614   public List getEditorias(String ids) {
1615     List lista = null;
1616     try {
1617       Query query = this.getSession().createQuery("select editoria from SisAtributoSatb editoria");
1618 
1619       lista = query.list();
1620 
1621       return lista;
1622     } catch (HibernateException e) {
1623       this.logger.error(e);
1624       return lista;
1625     }
1626   }
1627 
1628   /**
1629    * Seleciona 3 (ou mais, se passado parametro "qtd") outras Matérias/Artigos
1630    * mais recentes em SegmentoItem diferente da Capa Destaque e que esteja na
1631    * validade
1632    * @param application
1633    * @return List
1634    */
1635   public List getSegmentoItemArtigosPorEditoria(ServletContext application, UsuarioUsu usuario, String codSatb) {
1636     List lista = new ArrayList();
1637     try {
1638       Mensagem properties = new Mensagem(application);
1639 
1640       Date dataAtual = Data.getDataAtual();
1641       SegmentoItemSgti segItemSuper = getSegmentoItemSuperDestaque(application);
1642 
1643       List editorias = new ArrayList();
1644       List atributos = new ArrayList();
1645       String aspas = "";
1646 
1647       if (segItemSuper.getSegmentoSisAtribSgtsas() != null && segItemSuper.getSegmentoSisAtribSgtsas().size() > 0)
1648         atributos.addAll(segItemSuper.getSegmentoSisAtribSgtsas());
1649 
1650       Iterator it = atributos.iterator();
1651 
1652       while (it.hasNext()) {
1653         SisAtributoSatb atb = (SisAtributoSatb) it.next();
1654         aspas = "'" + atb.getCodSatb() + "'";
1655         editorias.add(aspas);
1656       }
1657 
1658       String todos = null;
1659       String teste = null;
1660       try {
1661         todos = Pagina.getParamStr(request, "todos");
1662         teste = Pagina.getParamStr(request, "codSatb");
1663       } catch (NullPointerException ne) {
1664         this.logger.error(ne);
1665       }
1666 
1667       StringBuilder select = new StringBuilder("select i from SegmentoItemSgti i where i.indAtivoSgti = 'S' ").append(" and ( i.dataIniValidadeSgti <= :dataAtual").append(" and i.dataFimValidadeSgti >= :dataAtual )").append(" and i.segmentoSgt.codSgt = :codSgt ").append(" and i.codSgti in (").append("select s.comp_id.codSgti from SegmentoSisAtribSgtsa s ").append("where s.comp_id.codSatb = :codSatb)").append(" and ((i.indUtilizTpAcessoSgti = 'N') or ").append("(i.indUtilizTpAcessoSgti = 'S' and i.codSgti in (").append("select b.comp_id.codSgti from SegmentoItemTpAcesSgtITA b ").append("where b.comp_id.codSatb in (").append("select a.comp_id.codSatb from UsuarioAtributoUsua a ").append("where a.comp_id.codUsu = :codUsu))))");
1668 
1669       // if ((segItemSuper != null)&&(todos == null)){
1670       // select = select + " and i.codSgti != :codSgti";
1671       // select = select + " and i.indSuperDestaqueSgti = 'S' ";
1672       // }
1673 
1674       // if (todos == ""){
1675       // select = select +
1676       // " and ((i.indDestaqueSgti = 'S') or (i.indDestaqueSgti = 'N' and i.indSuperDestaqueSgti = 'S')) ";
1677       // }
1678 
1679       StringBuilder order = new StringBuilder(" order by i.dataItemSgti desc");
1680 
1681       Query query = this.getSession().createQuery(select.toString() + order);
1682       query.setLong("codSgt", Long.valueOf(properties.getMensagem("admPortal.materias")).longValue());
1683       query.setDate("dataAtual", dataAtual);
1684       query.setLong("codUsu", usuario.getCodUsu().longValue());
1685       query.setLong("codSatb", Long.parseLong(codSatb));
1686 
1687       // if (segItemSuper != null)
1688       // query.setInteger("codSgti", segItemSuper.getCodSgti().intValue());
1689 
1690       String qtd = null, qtdPag = null, numPag = null;
1691 
1692       try {
1693         qtd = Pagina.getParamStr(request, "qtd");
1694         qtdPag = Pagina.getParamStr(request, "qtdPag");
1695         numPag = Pagina.getParamStr(request, "numPag");
1696       } catch (NullPointerException ne) {
1697         this.logger.error(ne);
1698       }
1699 
1700       if ((qtd != null) && (!"".equals(qtd))) {
1701         if (!"00".equals(qtd))
1702           query.setMaxResults(Integer.parseInt(qtd));
1703       }
1704 
1705       lista = query.list();
1706 
1707       return lista;
1708     } catch (HibernateException e) {
1709       this.logger.error(e);
1710       return lista;
1711     }
1712   }
1713 
1714 }