View Javadoc

1   /*
2    * Created on 05/10/2004
3    *
4    */
5   package comum.util;
6   
7   import java.lang.reflect.Field;
8   import java.lang.reflect.InvocationTargetException;
9   import java.lang.reflect.Method;
10  import java.net.URLEncoder;
11  import java.security.cert.CertificateException;
12  import java.security.cert.X509Certificate;
13  import java.text.DecimalFormat;
14  import java.text.NumberFormat;
15  import java.util.ArrayList;
16  import java.util.Collection;
17  import java.util.Date;
18  import java.util.List;
19  import java.util.Properties;
20  
21  import javax.mail.Message;
22  import javax.mail.MessagingException;
23  import javax.mail.Session;
24  import javax.mail.Transport;
25  import javax.mail.internet.AddressException;
26  import javax.mail.internet.InternetAddress;
27  import javax.mail.internet.MimeMessage;
28  import javax.net.ssl.HostnameVerifier;
29  import javax.net.ssl.HttpsURLConnection;
30  import javax.net.ssl.SSLContext;
31  import javax.net.ssl.SSLSession;
32  import javax.net.ssl.TrustManager;
33  import javax.net.ssl.X509TrustManager;
34  import javax.servlet.http.HttpServletRequest;
35  
36  import ecar.dao.ConfiguracaoDao;
37  import ecar.dao.CorDao;
38  import ecar.dao.EmailDao;
39  import ecar.exception.ECARException;
40  import ecar.pojo.ConfiguracaoCfg;
41  import ecar.pojo.Cor;
42  import ecar.pojo.Email;
43  import ecar.pojo.TipoFuncAcompTpfa;
44  import ecar.pojo.UsuarioUsu;
45  import ecar.util.Dominios;
46  
47  
48  /**
49   * @author garten
50   */
51  public class Util {
52  
53  	/**
54  	 * Lista os métodos get de um objeto passado como parâmetro.<br>
55  	 * 
56  	 * @author N/C
57  	 * @since N/C
58  	 * @version N/C
59  	 * @param Object o - objeto a ser verificado
60  	 * @return List - lista de métodos da classe Method 
61  	 */
62  	public static List<Method> listaMetodosGet(Object o) {
63  		return listaMetodos(o, Dominios.REGEXP_METODOS_GET);
64      }
65          
66  	/**
67  	 * Lista os métodos set de um objeto passado como parâmetro.<br>
68  	 * 
69  	 * @author N/C
70  	 * @since N/C
71  	 * @version N/C
72  	 * @param Object o - objeto a ser verificado
73  	 * @return List - lista de métodos da classe Method 
74  	 */
75  	public static List<Method> listaMetodosSet(Object o) {
76  		return listaMetodos(o, Dominios.REGEXP_METODOS_SET);
77  	}
78  
79  	/**
80  	 * Lista todos os métodos declarados de um objeto passado como parâmetro.<br>
81  	 * 
82  	 * @author N/C
83  	 * @since N/C
84  	 * @version N/C
85  	 * @param Object o - objeto a ser verificado
86  	 * @return List - lista de métodos da classe Method 
87  	 */
88  	public static List<Method> listaMetodos(Object o) {
89  		return listaMetodos(o, Dominios.REGEXP_TODOS);
90  	}
91  	
92  	
93  	/**
94  	 * Devolve uma lista de métodos declarados pelo programador em um objeto.<br>
95  	 * 
96  	 * @author N/C
97  	 * @since N/C
98  	 * @version N/C
99  	 * @param Object o - objeto a ser verificado
100 	 * @param String pattern - uma expressao regular dos métodos que desejam ser listados
101 	 * @return List - lista de métodos da classe Method<br>
102 	 * <p>
103 	 * Exemplo de utilização:<br>
104 	 * List l = new ArrayList();<br>
105 	 * l = Util.listaMetodos(new Object(), ".*");  // todos os metodos da classe Object<br>
106 	 * for (int i = 0; i < l.size(); i++)<br>
107 	 * 		System.out.println(((Method)l.get(i)).getName());<br>
108 	 */
109 	public static List<Method> listaMetodos(Object o, String pattern) {
110 		List<Method> l = new ArrayList<Method>();
111     		
112 		try {
113 			Method[] m = o.getClass().getDeclaredMethods();
114     		    
115 			for (int i = 0; i < m.length; i++)
116 				if (m[i].getName().matches(pattern))
117 					l.add(m[i]);
118     		    
119 		} catch (SecurityException s) {
120 			
121 		}
122     	
123 		return l;
124 	}
125 
126 	/**
127 	 * Lista os todos os atributos declarados de um objeto passado como parâmetro.<br>
128 	 * 
129 	 * @author N/C
130 	 * @since N/C
131 	 * @version N/C
132 	 * @param Object o - objeto a ser verificado
133 	 * @return List - lista de atributos da classe Method 
134 	 */
135 	
136 	public static List<Field> listaAtributos(Object o) {
137 		return listaAtributos(o, Dominios.REGEXP_TODOS);
138 	}
139 	
140 	
141 	/**
142 	 * Devolve uma lista de atributos declarados pelo programador em um objeto.<br>
143 	 * 
144 	 * @author N/C
145 	 * @since N/C
146 	 * @version N/C
147 	 * @param Object o - objeto a ser verificado
148 	 * @param String pattern - uma expressao regular dos atributos que desejam ser listados
149 	 * @return List - lista de atributos da classe Field<br>
150 	 * <p>
151 	 * Exemplo de utilização:<br>
152 	 * List l = new ArrayList();<br>
153 	 * l = Util.listaAtributos(new Object(), ".*");  // todos os atributos da classe Object<br>
154 	 * for (int i = 0; i < l.size(); i++)<br>
155 	 * 		System.out.println(((Field)l.get(i)).getName());<br>
156 	 */
157 	public static List<Field> listaAtributos(Object o, String pattern) {
158 		List<Field> l = new ArrayList<Field>();
159     		
160 		try {
161 			Field[] f = o.getClass().getDeclaredFields();
162     		    
163 			for (int i = 0; i < f.length; i++)
164 				if (f[i].getName().matches(pattern))
165 					l.add(f[i]);
166     		    
167 		} catch (SecurityException s) {
168 			
169 		}
170     	
171 		return l;
172 	}
173 	
174 	/**
175 	 * Invoca um metodo getXxxxx() para o objeto e o atributo informado.<br>
176 	 * 
177 	 * @author N/C
178 	 * @since N/C
179 	 * @version N/C
180 	 * @param Object o - o objeto cujo metodo get será chamado
181 	 * @param String atributo - o nome do atributo que identifica qual getter chamar
182 	 * @param Object[] objParams - os parametros que devem ser passados para a invocação do método - geralmente null
183 	 * @return Object
184 	 * @throws ECARException
185 	 */
186 	public static Object invocaGet(Object o, String atributo, Object[] objParams) throws ECARException {
187 	    String nomeGetter = "get" + primeiraLetraToUpperCase(atributo);
188         try {
189             /* supoe que existe apenas um unico metodo com esse nome, portanto passa null no array
190              * de classes do getMethod
191              */
192             return o.getClass().getMethod(nomeGetter, new Class[]{}).invoke(o, objParams);
193         } catch (IllegalArgumentException e) {
194             throw new ECARException("erro.exception");
195         } catch (SecurityException e) {
196            throw new ECARException("erro.exception");
197         } catch (IllegalAccessException e) {
198             throw new ECARException("erro.exception");
199         } catch (InvocationTargetException e) {
200             throw new ECARException("erro.exception");
201         } catch (NoSuchMethodException e) {
202             throw new ECARException("erro.exception");
203         }
204 	}
205 
206 	/**
207 	 * InvocaGet Simplificado, não recebe os parâmetros de invocação de um objeto.<br>
208 	 * 
209 	 * @author N/C
210 	 * @since N/C
211 	 * @version N/C
212 	 * @param Object o
213 	 * @param String atributo
214 	 * @return Object
215 	 * @throws ECARException
216 	 */
217 	public static Object invocaGet(Object o, String atributo) throws ECARException {
218 	    return invocaGet(o, atributo, null);
219 	}
220 
221 	/**
222 	 * Invoca o metodo setXxxx para o objeto e atributo informados.<br>
223 	 * 
224 	 * @author N/C
225 	 * @since N/C
226 	 * @version N/C
227 	 * @param Object o - o objeto a invocar o metodo set
228 	 * @param String atributo - o atributo cujo metodo set será invocado
229 	 * @param Object[] objParams - um array de objetos com os parametros do setter
230 	 * @return Object
231 	 * @throws ECARException
232 	 */
233 	public static Object invocaSet(Object o, String atributo, Object[] objParams) throws ECARException {
234 	    String nomeSetter = "set" + primeiraLetraToUpperCase(atributo);
235         try {
236             /* supoe que existe apenas um unico metodo com esse nome, portanto passa null no array
237              * de classes do getMethod
238              */
239             return o.getClass().getMethod(nomeSetter, new Class[]{}).invoke(o, objParams);
240         } catch (IllegalArgumentException e) {
241             throw new ECARException("erro.exception");
242         } catch (SecurityException e) {
243             throw new ECARException("erro.exception");
244         } catch (IllegalAccessException e) {
245             throw new ECARException("erro.exception");
246         } catch (InvocationTargetException e) {
247            throw new ECARException("erro.exception");
248         } catch (NoSuchMethodException e) {
249             throw new ECARException("erro.exception");
250         }
251 	}
252 		
253 	/**
254 	 * Retorna a String informada como parâmetro modificando sua primeira letra pra letra maiúscula.<br>
255 	 * 
256 	 * @author N/C
257 	 * @since N/C
258 	 * @version N/C
259 	 * @param String string  - a String a ser modificada
260 	 * @return String - a string modificada
261 	 */
262 	public static String primeiraLetraToUpperCase(String string){
263 	    return string.substring(0,1).toUpperCase().concat(string.substring(1));
264 	}
265 
266 	/**
267 	 * Retorna a String informada como parâmetro com a primeira letra em maiúscula e o restante minúscula.<br>
268 	 * 
269 	 * @author aleixo
270 	 * @since 12/07/2007
271 	 * @param string
272 	 * @return String
273 	 */
274 	public static String soPrimeiraLetraToUpperCase(String string){
275 		return primeiraLetraToUpperCase(string.toLowerCase());
276 	}
277 	
278 	/**
279 	 * Troca todas as primeiras letras de uma string para maíscula.<br>
280 	 * Exemplos:<br>
281 	 * String - Retorno<br>
282 	 * "TEXTO DE TESTE" - Texto de Teste<br>
283 	 * "texto de teste" - Texto de Teste<br>
284 	 * 
285 	 * @author aleixo
286 	 * @since 17/07/2007
287 	 * @param string
288 	 * @return String
289 	 */
290     public static String todasPrimeirasLetrasToUpperCase(String string){
291     	if(string == null || (string != null && "".equals(string.trim()))){
292     		return "";
293     	}
294     	
295     	string = string.trim().toLowerCase().replaceAll("\"", "");
296 	    	
297     	StringBuilder stringModificada = new StringBuilder();
298     	String[] temp = string.split(" ");
299     	
300     	for(int i = 0; i < temp.length; i++){
301     		String aux = temp[i].trim();
302     		if("".equals(aux))
303     			continue;
304     		
305     		if(!"de".equals(temp[i]) &&
306     		   !"da".equals(temp[i]) &&		
307     		   !"das".equals(temp[i]) &&		
308     		   !"do".equals(temp[i]) &&		
309     		   !"dos".equals(temp[i]) &&		
310     		   !"em".equals(temp[i]) &&		
311     		   !"no".equals(temp[i]) &&		
312     		   !"na".equals(temp[i]) && 		
313     		   !"nos".equals(temp[i]) &&
314     		   !"nas".equals(temp[i]) &&		
315     		   !"a".equals(temp[i]) &&		
316     		   !"e".equals(temp[i]) &&		
317     		   !"i".equals(temp[i]) &&		
318     		   !"o".equals(temp[i]) &&		
319     		   !"u".equals(temp[i]) &&		
320     		   !"com".equals(temp[i]) &&		
321     		   !"sem".equals(temp[i])		
322     		){
323     			aux = primeiraLetraToUpperCase(aux);
324     		}
325     		
326     		stringModificada.append(aux).append(" ");
327     	}
328     	return stringModificada.toString();
329     }
330 
331     /**
332      * Remove os espaços que estão sobrando em uma string.<br>
333      * 
334      * @author aleixo
335      * @since 30/08/2007
336      * @param string
337      * @return
338      */
339     public static String removeEspacosDuplicados(String string){
340     	if(string == null || (string != null && "".equals(string.trim()))){
341     		return "";
342     	}
343     	
344     	StringBuilder stringModificada = new StringBuilder();
345     	String[] temp = string.split(" ");
346     	
347     	for(int i = 0; i < temp.length; i++){
348     		String aux = temp[i].trim();
349     		if("".equals(aux))
350     			continue;
351     		
352     		stringModificada.append(aux).append(" ");
353     	}
354     	
355     	return stringModificada.toString().trim();
356     }
357 	
358 	/**
359 	 * Retorna se um determinado valorReferência está contido no intervalo entre
360 	 * outros dois valores (valor1 e valor2).<br>
361 	 * 
362 	 * @author N/C
363 	 * @since N/C
364 	 * @version N/C
365 	 * @param int valorReferencia
366 	 * @param int valor1
367 	 * @param int valor2
368 	 * @return boolean
369 	 */
370 
371 	public static boolean entre(int valorReferencia, int valor1, int valor2) 
372 	{
373 		try{
374 			if ((valor1 > valor2) 
375 			  && (valorReferencia < valor1)	 
376 			  && (valorReferencia > valor2))
377 				return true;
378 			if ((valor2 > valor1)
379 			 && (valorReferencia < valor2)	 
380 			 && (valorReferencia > valor1))
381 				return true;		
382 			return false;
383 			}catch (NumberFormatException e){
384 				return false;
385 		}
386 		
387 	}
388 	
389 	/**
390 	 * Retorna se um determinado valorReferência está contido no intervalo entre
391 	 * outros dois valores (valor1 e valor2).<br>
392 	 * Foi implementado para receber strings, pois existe a comparação com "inf" e "sup"
393 	 * que indicam se um valor limite são todos os menores que o outro, ou todos os
394 	 * maiores, respectivamente.<br>
395 	 * 
396 	 * @author N/C
397 	 * @since N/C
398 	 * @version N/C
399 	 * @param String valorReferencia
400 	 * @param String valor1
401 	 * @param String valor2
402 	 * @return boolean
403 	 */
404 
405 	public static boolean entre(String valorReferencia, String valor1, String valor2) 
406 	{
407 		try{
408 			return (entre(Integer.parseInt(valorReferencia), valor1, valor2));
409 		}catch (NumberFormatException e){
410 			return false;
411 		}
412 		
413 	}
414 	
415 	/**
416 	 * Retorna se um determinado valorReferência está contido no intervalo entre
417 	 * outros dois valores (valor1 e valor2).<br>
418 	 * Foi implementado para receber strings, pois existe a comparação com "inf" e "sup"
419 	 * que indicam se um valor limite são todos os menores que o outro, ou todos os
420 	 * maiores, respectivamente.<br>
421 	 * 
422 	 * @author N/C
423 	 * @since N/C
424 	 * @version N/C
425 	 * @param int valorReferencia
426 	 * @param String valor1
427 	 * @param String valor2
428 	 * @return boolean
429 	 */
430 
431 	public static boolean entre(int valorReferencia, String valor1, String valor2)
432 	{
433 		try{
434 			if (("sup".equals(valor1) && "inf".equals(valor2))
435 			 || ("sup".equals(valor2) && "inf".equals(valor1)))
436 				 	return true;			
437 			if ("sup".equals(valor1))
438 				if (valorReferencia > Integer.parseInt(valor2))
439 					return true;
440 			if ("inf".equals(valor1))
441 				if (valorReferencia < Integer.parseInt(valor2))
442 					return true;
443 			if ("sup".equals(valor2))
444 				if (valorReferencia > Integer.parseInt(valor1))
445 					return true;
446 			if ("inf".equals(valor2))
447 				if (valorReferencia < Integer.parseInt(valor1))
448 					return true;
449 			if ((Integer.parseInt(valor1) > Integer.parseInt(valor2))
450 			 && (valorReferencia < Integer.parseInt(valor1))	 
451 			 && (valorReferencia > Integer.parseInt(valor2)))
452 				return true;
453 			if ((Integer.parseInt(valor2) > Integer.parseInt(valor1))
454 			 && (valorReferencia < Integer.parseInt(valor2))	 
455 			 && (valorReferencia > Integer.parseInt(valor1)))
456 				return true;
457 			return false;
458 		} catch(NumberFormatException e) {
459 			return false;
460 		}
461 	}
462 	
463 	
464 	/**
465 	 * Retorna uma substring  da posicao inicio até a posicao fim ou até o comprimento maximo da string.<br>
466 	 * 
467 	 * @author N/C
468 	 * @since N/C
469 	 * @version N/C
470 	 * @param String string
471 	 * @param int inicio
472 	 * @param int fim
473 	 * @return String
474 	 */
475 	public static String substring(String string, int inicio, int fim) {
476 	    return string.substring(inicio, Math.min(fim, string.length()));
477 	}
478 	
479 	/**
480 	 * Retorna um número com formatação Monetária.<br>
481 	 * 
482 	 * @author N/C
483 	 * @since N/C
484 	 * @version N/C
485 	 * @param double number
486 	 * @return String
487 	 */
488 	public static String formataMoeda(double number){
489 	    NumberFormat formatter = new DecimalFormat("###,###,##0.00");	    
490 	    //NumberFormat fn = NumberFormat.getInstance(new Locale("pt", "BR"));	    
491 	    return formatter.format(number);
492 	}
493 	
494 	/**
495 	 * Retorna um número com formatação de unidades de milhar e casas decimais.<br>
496 	 * 
497 	 * @author N/C
498 	 * @since N/C
499 	 * @version N/C
500 	 * @param double number
501 	 * @return String
502 	 */
503 	public static String formataNumeroDecimal(double number){
504 	    NumberFormat formatter = new DecimalFormat("###,###,##0.##");	    
505 	    //NumberFormat fn = NumberFormat.getInstance(new Locale("pt", "BR"));	    
506 	    return formatter.format(number);
507 	}
508 
509 	public static String formataNumeroDecimal(Double number){
510 	    NumberFormat formatter = new DecimalFormat("###,###,##0.##");	    
511 	    //NumberFormat fn = NumberFormat.getInstance(new Locale("pt", "BR"));	    
512 	    return formatter.format(number);
513 	}
514 	
515 	/**
516 	 * Retorna um número com formatação de unidades de milhar e 
517 	 * casas decimais mas sem pontos e vírgulas, para valores de exportação.<br>
518 	 * 
519 	 * @author N/C
520 	 * @since N/C
521 	 * @version N/C
522 	 * @param double number
523 	 * @param int tamanho
524 	 * @return String
525 	 */
526 	public static String formataNumeroDecimalParaExportacao(double number, int tamanho){
527 		String temp = formataMoeda(number);
528 		String retorno = "";
529 		for(int i = 0; i < temp.length(); i++){
530 			if(temp.charAt(i) != '.' && temp.charAt(i) != ','){
531 				retorno += temp.charAt(i);
532 			}
533 		}
534 		int tam = retorno.length();
535 		for(int i = tam; i < tamanho; i++){
536 			retorno = " " + retorno;
537 		}
538 		return retorno;
539 	}
540 	
541 	/**
542 	 * Retorna um número com formatação sem casas decimais.<br>
543 	 * 
544 	 * @author N/C
545 	 * @since N/C
546 	 * @version N/C
547 	 * @param double number
548 	 * @return String
549 	 */
550 	public static String formataNumeroSemDecimal(double number){
551 	    NumberFormat formatter = new DecimalFormat("###,###,##0");	    
552 	    //NumberFormat fn = NumberFormat.getInstance(new Locale("pt", "BR"));	    
553 	    return formatter.format(number);
554 	}
555 
556 	/**
557 	 * Retorna um número com formatação das casas decimais (sem unidades de milhar).<br>
558 	 * 
559 	 * @author N/C
560 	 * @since N/C
561 	 * @version N/C
562 	 * @param double number
563 	 * @return String
564 	 */
565 	public static String formataNumeroDecimalSemMilhar(double number){
566 	    NumberFormat formatter = new DecimalFormat("#0.00");
567 	    return formatter.format(number);
568 	}
569 	
570 	/**
571 	 * Retorna um número com formatação sem casas decimais <br>
572 	 * 
573 	 * @author luanaoliveira
574 	 * @since N/C
575 	 * @version N/C
576 	 * @param double number
577 	 * @return String
578 	 */
579 	public static String formataNumeroInteiroSemMilhar(double number){
580 	    NumberFormat formatter = new DecimalFormat("#0");	    
581 	    //NumberFormat fn = NumberFormat.getInstance(new Locale("pt", "BR"));	    
582 	    return formatter.format(number);
583 	}
584 	
585 	/**
586 	 * formata o numero de acordo com o indQtd<br>
587 	 * se for qtd: #000
588 	 * se for valor: #0.00
589 	 * 
590 	 * @author luanaoliveira
591 	 * @param number
592 	 * @param indQtd
593 	 * @return String com o numero formatado
594 	 */
595 	public static String formataQtdValor(double number, String indQtd){
596 //		if(Dominios.IETTR_QUANTIDADE.equals(indQtd)){
597 //			return(formataNumeroInteiroSemMilhar(number));
598 //		}else{
599 			return formataMoeda(number);
600 //		}
601 	}
602 	
603     /**
604      * Função que retorna um número formatado com '.' para separação decimal e sem vírgulas.<br>
605      * 
606      * @author N/C
607 	 * @since N/C
608 	 * @version N/C
609      * @param String original
610      * @return String
611      */
612     public static String formataNumero(String original){       
613         original = original.replaceAll("\\.","");
614         original = original.replaceAll(",",".");
615         return original;        
616     }
617     
618     /**
619      * Retorna formatado a String do tamanho do arquivo em KB ou MB.<br>  
620      * 
621      * @author N/C
622 	 * @since N/C
623 	 * @version N/C
624      * @param Long bytes
625      * @return String
626      */
627     public static String formataByte(Long bytes){
628         double kb = converteParaKb(bytes.doubleValue());
629         if(kb > 1000){
630             return formataNumeroDecimal(converteParaMb(kb)) + " MB";
631         } else
632             return formataNumeroDecimal(kb) + " KB";
633     }
634     
635     /**
636      * Converte para KB.<br>
637      * 
638      * @author N/C
639 	 * @since N/C
640 	 * @version N/C
641      * @param double bytes
642      * @return double
643      */
644     public static double converteParaKb(double bytes){
645         return bytes / new Double(1024).doubleValue();
646     }
647 
648     /**
649      * Converte para MB.<br>
650      * 
651      * @author N/C
652 	 * @since N/C
653 	 * @version N/C
654      * @param double kBytes
655      * @return double
656      */
657     public static double converteParaMb(double kBytes){
658         return kBytes / new Double(1024).doubleValue();
659     }
660     
661     
662     /**
663      * Retorna uma coleção com os elementos de col1 que estão em col2
664      * (col1 e col2 devem ser listas de objetos da mesma classe).<br>
665      * 
666      * @author N/C
667 	 * @since N/C
668 	 * @version N/C
669      * @param Collection col1
670      * @param Collection col2
671      * @return Collection
672      */
673     public static Collection intersecao(Collection col1, Collection col2){
674         Collection a = new ArrayList(col1);
675         Collection b = new ArrayList(col2);
676         a.retainAll(b);
677         return a;
678     }
679     
680     /**
681      * Retorna uma coleção com os elementos de col1 que não estão em col2 ( col1 - col2)
682      * (col1 e col2 devem ser listas de objetos da mesma classe).<br>
683      * 
684      * @author N/C
685 	 * @since N/C
686 	 * @version N/C
687      * @param Collection col1
688      * @param Collection col2
689      * @return Collection
690      */
691     public static Collection<Object> diferenca(Collection<Object> col1, Collection<Object> col2){
692         Collection<Object> a = new ArrayList<Object>(col1);
693         Collection<Object> b = new ArrayList<Object>(col2);
694         a.removeAll(b);
695         return a;
696     } 
697 	
698     /**
699      * Retira acentuacao.<br>
700      * 
701      * @author N/C
702 	 * @since N/C
703 	 * @version N/C
704      * @param String string
705      * @return String
706      */
707 	public static String retiraAcentuacao(String string){
708 		return string.replace('à','a').
709 					  replace('á','a').
710 					  replace('é','e').					  
711 					  replace('í','i').
712 					  replace('ó','o').
713 					  replace('ú','u').
714 					  replace('ü','u');
715 	}
716 	
717 	/**
718 	 * Substitui espacos numa string por um caracter especificado.<br>
719 	 * 
720 	 * @author N/C
721 	 * @since N/C
722 	 * @version N/C
723 	 * @param String string
724 	 * @param String caracter
725 	 * @return String
726 	 */
727 	public static String trocarEspacoPorCaracter(String string, String caracter){
728 		return string.replaceAll(" ", caracter);
729 	}
730 	
731 	/**
732 	 * Método para substituir na variável uma barra "\" e colocar "\\"<br>
733 	 * 		Utilizado para passar para JavaScript<br>
734 	 * Funcionamento: o java interpreta uma string "\\\\" como sendo "\",<br>
735 	 * 			por isso a necessidade de tantas barras.<br>
736 	 * 
737 	 * @author N/C
738 	 * @since N/C
739 	 * @version N/C
740 	 * @param String texto
741 	 * @return String
742 	 */
743 	public static String trocaBarraParaDuasBarras(String texto){
744 		return texto.replaceAll("\\\\", "\\\\\\\\");
745 	}
746 	
747 	/**
748 	 * Calcula a média de valores Double contidos em uma lista.<br>
749 	 * 
750 	 * @author N/C
751 	 * @since N/C
752 	 * @version N/C
753 	 * @param Collection valores
754 	 * @return double
755 	 */
756 	public static double calculaMediaValores(Collection<Double> valores){
757 		double total = 0;
758 		for (Double valor: valores) {
759           total += valor.doubleValue();
760 		}
761 		return total / valores.size();
762 	}
763 
764 	/**
765 	 * Calcula a média de valores Integer contidos em uma lista.<br>
766 	 * 
767 	 * @author N/C
768 	 * @since N/C
769 	 * @version N/C
770 	 * @param Collection valores
771 	 * @return double
772 	 */
773 	public static double calculaMediaValoresInteger(Collection<Double> valores){
774 		double total = 0;
775 		for (Double valor: valores) {
776 			total += valor.intValue();
777 		}
778 		return total / valores.size();
779 	}
780     
781 	/**
782 	 * ????????
783 	 * 
784 	 * @author N/C
785 	 * @since N/C 
786 	 * @version N/C
787 	 * @param String palavra
788 	 * @param String original
789 	 * @param String novo
790 	 * @return String
791 	 */
792 	public static String trocar(String palavra, String original, String novo){
793 		String retorno = "";
794 		for(int i = 0; i< palavra.length(); i++){
795 			if(palavra.charAt(i) == original.charAt(0)){
796 				retorno += novo;
797 			} else {
798 				retorno += palavra.charAt(i);
799 			}
800 		}
801 		return retorno;
802 			
803 	}
804     
805 	/**
806 	* Enviar um e-mail no formato texto ou html.<br>
807 	* 
808 	* @author Cristiano
809 	* @since 16/09/05
810 	* @version N/C
811 	* @param String assunto - Descrição do assunto para o e-mail
812 	* @param String nomeRemetente - Nome do remetente
813 	* @param String remetente - Remetente do e-mail
814 	* @param String texto - Texto do conteúdo do e-mail
815 	* @param String destinatarioPara - Destinatário(s) do e-mail (se tiver mais de um endereço separar entre vírgula)
816 	* @param String destinatarioCc - Destinatário(s) que receberão cópia do e-mail (se tiver mais de um endereço separar entre vírgula)
817 	* @param String destinatarioBcc - Destinatário(s) que receberão cópia oculta do e-mail (se tiver mais de um endereço separar entre vírgula)
818 	* @throws AddressException - Endereço de e-mail inválido
819 	* @throws MessagingException - Não foi possível enviar e-mail
820 	* @throws Exception
821 	*/
822 	
823 	public static void enviarEmail(String assunto, String nomeRemetente, String remetente,
824 		String texto, String destinatarioPara, String destinatarioCc, String destinatarioBcc, UsuarioUsu usuario)
825 		throws AddressException, MessagingException, Exception, ECARException {
826 			ConfiguracaoCfg config = new ConfiguracaoDao(null).getConfiguracao();
827     		if(config.getEmailServer() == null || "".equals(config.getEmailServer().trim())) {
828     			throw new ECARException("erro.servidor.email.invalido");
829     		}
830     		
831             Properties mailProps = new Properties();
832             mailProps.put("mail.smtp.host", config.getEmailServer());
833 
834             Session mailSession = Session.getInstance(mailProps, null);
835             mailSession.setDebug(false);
836             Message email = new MimeMessage(mailSession);
837             email.setRecipients( Message.RecipientType.TO, InternetAddress.parse(destinatarioPara));
838             if (destinatarioCc != null && !"".equals(destinatarioCc.trim())) {
839                 email.setRecipients( Message.RecipientType.CC, InternetAddress.parse(destinatarioCc));
840             }
841             if (destinatarioBcc != null && !"".equals(destinatarioBcc.trim())) {
842                 email.setRecipients( Message.RecipientType.BCC, InternetAddress.parse(destinatarioBcc));
843             }
844             InternetAddress iAdd = new InternetAddress();
845          
846             if (remetente != null) iAdd.setAddress(remetente);
847             if (nomeRemetente != null) iAdd.setPersonal(nomeRemetente);
848             
849             email.setFrom(iAdd);
850             email.setSubject(assunto);
851             email.setContent(texto, "text/html");
852             
853             Transport.send(email);
854             
855             if (usuario != null){
856 				Email mailUsu = new Email(nomeRemetente, new Date(), assunto, destinatarioPara, destinatarioCc, destinatarioBcc, texto,"", usuario);
857 				EmailDao emailDao = new EmailDao();
858 				emailDao.salvar(mailUsu);
859             }
860     }
861 	
862 	/**
863 	 * Normaliza Chars:<br>
864 	 * Ex.:<br>
865 	 * de '<' para "&lt;"<br>
866 	 * 
867 	 * 
868 	 * @author N/C
869 	 * @since N/C
870 	 * @version N/C
871 	 * @param String s
872 	 * @param StringBuffer str
873 	 * @param int i
874 	 */
875 	public static void normalizeChars(String s, StringBuffer str, int i) {
876 		final char ch = s.charAt(i);
877 		switch (ch) {
878 			case 60: // '<'
879 				str.append("&lt;"); 
880 				break;
881 			case 62: // '>'
882 				str.append("&gt;"); 
883 				break;
884 			case 38: // '&'
885 				str.append("&amp;"); 
886 				break;
887 			case 34: // '"'
888 				str.append("&quot;"); 
889 				break;
890 			case 39: // '''
891 				str.append("&apos;"); 
892 				break;
893 			default:
894 				str.append(ch);
895 				break;
896 		}
897 	}
898 
899 	/**
900 	 * Normaliza Enter.<br>
901 	 * 
902 	 * @author N/C
903 	 * @since N/C
904 	 * @version N/C
905 	 * @param String s
906 	 * @param StringBuffer str
907 	 * @param int i
908 	 */
909 	public static void normalizeEnter(String s, StringBuffer str, int i) {
910 		final char ch = s.charAt(i);
911 		switch (ch) {
912 			case 10: // '\n'
913 			case 13: // '\r'
914 				//if(canonical) {
915 				str.append("&#"); 
916 				str.append(Integer.toString(ch));
917 				str.append(';');
918 		}
919 	}
920 
921 	/** Normaliza o String para apresenta-lo em HTML sem retirar o retorno de linha.<br>
922 	 * 
923 	 * @author N/C
924 	 * @since N/C
925 	 * @version N/C
926 	 * @param String s
927 	 * @return String
928 	 */
929 	public static String normalize(String s) {
930 		StringBuffer str = new StringBuffer();
931 		final int len = (s == null) ? 0 : s.length();
932 		for (int i = 0; i < len; i++) {
933 			normalizeChars(s, str, i);
934 			normalizeEnter(s, str, i);
935 		}
936 		return str.toString();
937 	}
938 
939 	/** Normaliza a quantidade de caracteres da quebra de linha.<br>
940 	 * Ex.: o conteúdo de um texto tem 4060 caracteres.<br>
941      *   	  A validação da pagina (permitir textos até 4000 caracteres) estava funcionando.<br>
942      *   	  Quando entrava nesta função, toda quebra de linha era representada por 2 caracteres ("\r" e "\n"),
943      *   		então um texto que tivesse 5 Enters, na validação em javascript seria cortado com 4000 caracteres,
944      *   		mas teria 5 caracteres a mais daqueles que foram validados no javascript (5 "\r" a mais).<br>
945      *   	  Como no java, o "\n" já representa uma quebra de linha, foi ignorado um eventual 
946      *   		"\r\n" (retorno de linha, quebra de linha)<br>
947      *   
948      * @author N/C
949 	 * @since N/C
950 	 * @version N/C
951 	 * @param String s
952 	 * @return String
953      */
954 	public static String normalizaQuebraDeLinha(String s) {
955 		return s.replaceAll("\r\n","\n");
956 	}
957 	
958 	/**
959 	 * Normaliza uma string para apresentação em HTML.<br>
960 	 * Troca "\n" por tag "&lt;br&gt;";
961 	 * @param s
962 	 * @return
963 	 */
964 	public static String normalizaQuebraDeLinhaHTML(String s){
965 		return (s != null) ? (normalizaQuebraDeLinha(s.trim())).replaceAll("\n", "<br>") : "";
966 	}
967 	
968 	/**
969 	 * Normaliza caracter Marcador.<br>
970 	 * 
971 	 * @author N/C
972 	 * @since N/C
973 	 * @version N/C
974 	 * @param String s
975 	 * @return String
976 	 */
977 	public static String normalizaCaracterMarcador(String s){
978 		if(s != null && !"".equals(s))
979 			return s.replace(Dominios.CARACTER_ESTRANHO_MARCADOR, "-").
980 					 replace(Dominios.CARACTER_ESTRANHO_MARCADOR2, "-").
981 					 replace(Dominios.CARACTER_ESTRANHO_ABREASPAS, "\"").
982 					 replace(Dominios.CARACTER_ESTRANHO_FECHAASPAS, "\"").
983 					 replace(Dominios.CARACTER_ESTRANHO_ABREASPAS_SIMPLES, "'").
984 					 replace(Dominios.CARACTER_ESTRANHO_FECHAASPAS_SIMPLES, "'");
985 		
986 		return "";
987 	}
988 	
989 	/**
990 	 * Completa um número com zeros à esquerda.<br>
991 	 * 
992 	 * @author N/C
993 	 * @since N/C
994 	 * @version N/C
995 	 * @param Long numero
996 	 * @param int tamanho
997 	 * @return String
998 	 */
999 	public static String completarZerosEsquerda(Long numero, int tamanho){
1000 		
1001 		String mascara = "";
1002 		for(int i = 0; i < tamanho; i++){
1003 			mascara = "0" + mascara;
1004 		}
1005 
1006 		NumberFormat nf = new DecimalFormat(mascara);
1007 		
1008 		if(numero != null)
1009 			return nf.format(numero.longValue());
1010 		else
1011 			return mascara;
1012 	}
1013 	
1014 	/**
1015 	 * Completa uma string com caracteres até o tamanho, seguindo uma direcao.<br>
1016 	 *
1017 	 * @author N/C
1018 	 * @since N/C
1019 	 * @version N/C
1020 	 * @param String string - string a ser completada
1021 	 * @param String caracter - Caracter para completar a string
1022 	 * @param int tamanho - Tamanho para completar a string com caracteres
1023 	 * @param String direcao - "D": Completa caracteres à direita, "E": Completa Caracteres à esquerda.
1024 	 * @return String
1025 	 */
1026 	public static String completarCaracteres(String string, String caracter, int tamanho, String direcao){
1027 		String retorno = string;
1028 		if(string.length() < tamanho){
1029 			if("E".equalsIgnoreCase(direcao)){
1030 				int tam = string.length();
1031 				for(int i = tam; i < tamanho; i++){
1032 					retorno = caracter + retorno;
1033 				}
1034 			}
1035 			if("D".equalsIgnoreCase(direcao)){
1036 				int tam = string.length();
1037 				for(int i = tam; i < tamanho; i++){
1038 					retorno = retorno + caracter;
1039 				}
1040 			}
1041 		}
1042 		return retorno;
1043 	}
1044 
1045 	/**
1046 	 * Retorna apenas o nome do arquivo, de acordo com a string do caminho completo ou relativo
1047 	 * informado como parâmetro do método.<br>
1048 	 * 
1049 	 * @author rogerio
1050 	 * @since 0.1, 06/03/2007
1051 	 * @version 0.1, 06/03/2007
1052 	 * @param String path
1053 	 * @return String
1054 	 */
1055 	public static String getNomeArquivo(String path) {
1056 		String nome = null;
1057 		
1058 		if( path != null ) {
1059 			if( path.lastIndexOf("/") != -1 ) 
1060 				nome = path.substring(path.lastIndexOf("/")+1);  // windows
1061 			else if( path.lastIndexOf("\\") != -1 )
1062 				nome = path.substring(path.lastIndexOf("\\")+1); // linux
1063 			else
1064 				nome = path;
1065 		}
1066 		
1067 		return nome;
1068 	} // fim getNomeArquivo
1069 	
1070 	/**
1071 	 * Retorna a tag usada para mostrar a imagem e a dica para a estrutura de telas do sistema. <br>
1072 	 * @author rogerio
1073 	 * @since 0.1, 22/03/2007
1074 	 * @version 0.1, 22/03/2007
1075 	 * @param nome - nome do atributo
1076 	 * @param contexto - conexto da aplicação
1077 	 * @param dica - texto usado no tooltip
1078 	 * @return String
1079 	 */
1080 	public static String getTagDica(String nome, String contexto, String dica) {
1081 		StringBuffer s = new StringBuffer("&nbsp;&nbsp;") ;
1082 
1083 		// Por Rogério. (05/04/2007. Mantis #9612.
1084 		// Bloco colocado dentro do TRY para tratar um possível retorno de erro na codificação da dica para ASCII.
1085 		// Na realidade nenhum erro é retornado para evitar problemas na compilação com o JSP.
1086 		try {
1087 	    	s.append("<label class=\"dica\" onmouseover=\"javascript:viewFieldTip(this, '"+nome+"SPAN');\"  onmouseout=\"javascript:noViewFieldTip('"+nome+"SPAN');\" >");
1088 	    	s.append("<img src=\""+contexto+"/images/dica.png\" align=\"absmiddle\" border=\"0\" onclick=\"javascript:viewFieldTipPopUp(\'" + URLEncoder.encode(dica, "ISO-8859-1") + "\')\" >" );
1089 	    	s.append("<span id=\""+nome+"SPAN\">" + dica + "</span></label>");
1090 		} catch (Exception e) {
1091 			// Ignora um retorno de erro, evitando problemas de compilação com a JSP.
1092 		}
1093 	
1094     	return s.toString();
1095 	} // fim getTagDica
1096 	
1097 	/**
1098 	 * 
1099 	 * @param nome - nome do atributo
1100 	 * @param contexto - 
1101 	 * @param urlImagem
1102 	 * @param dica
1103 	 * @return
1104 	 */
1105 	public static String getTagDicaComImagemParecer(String nome, String contexto, String urlImagem, String dica) {
1106 		StringBuffer s = new StringBuffer("&nbsp;&nbsp;") ;
1107 
1108 		// Por Rogério. (05/04/2007. Mantis #9612.
1109 		// Bloco colocado dentro do TRY para tratar um possível retorno de erro na codificação da dica para ASCII.
1110 		// Na realidade nenhum erro é retornado para evitar problemas na compilação com o JSP.
1111 		try {
1112 	    	s.append("<label class=\"dica\" onmouseover=\"javascript:viewFieldTip(this, '"+nome+"SPAN');\"  onmouseout=\"javascript:noViewFieldTip('"+nome+"SPAN');\" >");
1113 	    	if(urlImagem.equals(contexto))
1114 	    		s.append("<img src=\""+urlImagem+"/images/dica.png\" align=\"absmiddle\" border=\"0\"  onclick=\"javascript:viewFieldTipPopUp(\'" + URLEncoder.encode(dica, "ISO-8859-1") + "\')\" >" );
1115 	    	else 
1116 	    		s.append("<img src=\""+urlImagem+"\" align=\"absmiddle\" border=\"0\" style=\"width:16px;height:16px;\" onclick=\"javascript:viewFieldTipPopUp(\'" + URLEncoder.encode(dica, "ISO-8859-1") + "\')\" >" );
1117 	    	
1118 	    	s.append("<span id=\""+nome+"SPAN\">" + dica + "</span></label>");
1119 		} catch (Exception e) {
1120 			// Ignora um retorno de erro, evitando problemas de compilação com a JSP.
1121 		}
1122 	
1123     	return s.toString();
1124 	} // fim getTagDica
1125 
1126 	
1127 	
1128 	
1129 	/**
1130 	 * Retorna a tag usada para mostrar a imagem e a dica para a estrutura de telas do sistema. <br>
1131 	 * @author rogerio
1132 	 * @since 0.1, 22/03/2007
1133 	 * @version 0.1, 22/03/2007
1134 	 * @param nome - nome do atributo
1135 	 * @param contexto - conexto da aplicação
1136 	 * @param dica - texto usado no tooltip
1137 	 * @return String
1138 	 */
1139 	public static String getTagDica(String nome, String contexto, String urlImagem, String dica) {
1140 		StringBuffer s = new StringBuffer("&nbsp;&nbsp;") ;
1141 
1142 		// Por Rogério. (05/04/2007. Mantis #9612.
1143 		// Bloco colocado dentro do TRY para tratar um possível retorno de erro na codificação da dica para ASCII.
1144 		// Na realidade nenhum erro é retornado para evitar problemas na compilação com o JSP.
1145 		try {
1146 	    	s.append("<label class=\"dica\" onmouseover=\"javascript:viewFieldTip(this, '"+nome+"SPAN');\"  onmouseout=\"javascript:noViewFieldTip('"+nome+"SPAN');\" >");
1147 	    	if(contexto==null ||contexto.equals("") )
1148 	    		s.append("<img src=\""+urlImagem+"\" align=\"absmiddle\" border=\"0\" onclick=\"javascript:viewFieldTipPopUp(\'" + URLEncoder.encode(dica, "ISO-8859-1") + "\')\" >" );
1149 	    	else
1150 	    		s.append("<img src=\""+contexto+"/images/dica.png\" align=\"absmiddle\" border=\"0\" onclick=\"javascript:viewFieldTipPopUp(\'" + URLEncoder.encode(dica, "ISO-8859-1") + "\')\" >" );
1151 	    	s.append("<span id=\""+nome+"SPAN\">" + dica + "</span></label>");
1152 		} catch (Exception e) {
1153 			// Ignora um retorno de erro, evitando problemas de compilação com a JSP.
1154 		}
1155 	
1156     	return s.toString();
1157 	} // fim getTagDica
1158 
1159 	/* -- 
1160 	 * Métodos utilizados para contornar o problema com o https no e-CAR.
1161 	 * Dentro dos servlets dos relatórios, em cada local onde é realizada uma chamada a uma imagem, faz-se necessário chamar 
1162 	 *  o método "Util.liberarImagem(String imagePath);". Dessa forma a imagem será exibida no relatório quando o e-CAR estiver 
1163 	 *  sendo utilizado sob o protocolo SSL.
1164 	 * Estes métodos foram testados com a geração de relatórios em FOP.
1165 	 * -- */
1166 	
1167 	/**
1168 	 * Método para liberar as imagens utilizadas em relatórios sob protocolo SSL.<Br>
1169 	 * (Obtido em pesquisas na Internet).<br>
1170 	 * 
1171 	 * @author N/C
1172 	 * @since N/C
1173 	 * @version N/C
1174 	 * @throws ECARException
1175 	 */
1176 	public static void liberarImagem() throws ECARException {
1177 		try {
1178 			trustAllHttpsCertificates();
1179 			
1180 			HostnameVerifier hv = new HostnameVerifier() {
1181 		        public boolean verify(String urlHostName, SSLSession session) {
1182 		            //System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
1183 		            return true;
1184 		        }
1185 		    };
1186 			
1187 			HttpsURLConnection.setDefaultHostnameVerifier(hv);
1188 			
1189 			//URL url = new URL("");
1190 			//BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
1191 
1192 	        //int buff;
1193 	        //while( (buff = in.read()) != -1 ) {}
1194 	        //in.close();
1195 
1196 		} catch (Exception e) {
1197             new ECARException("erro.liberar.imagem.ssl");
1198         }
1199 	}
1200 	
1201 	/**
1202 	 * Método para liberar as imagens utilizadas em relatórios sob protocolo SSL.<Br>
1203 	 * (Obtido em pesquisas na Internet).<br>
1204 	 * 
1205 	 * @author N/C
1206 	 * @since N/C
1207 	 * @version N/C
1208 	 * @throws Exception
1209 	 */    
1210     private static void trustAllHttpsCertificates() throws Exception {
1211         //  Create a trust manager that does not validate certificate chains:
1212     	TrustManager[] trustAllCerts = new TrustManager[1];
1213         TrustManager tm = new miTM();
1214         trustAllCerts[0] = tm;
1215         SSLContext sc = SSLContext.getInstance("SSL");
1216         sc.init(null, trustAllCerts, null);
1217         HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
1218     }
1219 
1220 	/**
1221 	 * Método para liberar as imagens utilizadas em relatórios sob protocolo SSL.<br>
1222 	 * (Obtido em pesquisas na Internet).<br>
1223 	 * 
1224 	 * @author N/C
1225 	 * @since N/C
1226 	 * @version N/C
1227 	 */
1228     public static class miTM implements TrustManager, X509TrustManager {
1229 		public X509Certificate[] getAcceptedIssuers() { return null; }
1230 		public boolean isServerTrusted(X509Certificate[] certs) { return true; }	
1231 		public boolean isClientTrusted(X509Certificate[] certs) { return true; }
1232 		public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException { return; }
1233 		public void checkClientTrusted(X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; }
1234 	}
1235     
1236     
1237 	/**
1238 	 * = (TipoFuncAcompTpfa) tipoFuncAcompDao.buscar(TipoFuncAcompTpfa.class, codTpfa);
1239 	 * 
1240 	 * @param cor
1241 	 * @param request
1242 	 * @return
1243 	 * @throws ECARException 
1244 	 */
1245 	public static String getURLImagemAcompanhamento(Cor cor, HttpServletRequest request , TipoFuncAcompTpfa funcao ) throws ECARException{
1246 		String url=null;
1247 		CorDao corDao = new CorDao(request);
1248 				
1249 		if(cor.getIndPosicoesGeraisCor().equals("S")){ 
1250 			cor.getCodCor();
1251 			
1252 		url = corDao.getImagemPersonalizada(cor, funcao, "D");
1253 		if( url != null ) { 
1254 			url=request.getContextPath()+"/DownloadFile?tipo=open&RemoteFile="+ url ;
1255 		} else {
1256 			if( cor.getCodCor() != null ) { 
1257 				url =request.getContextPath() + "/images/" + corDao.getImagemSinal(cor,funcao)+ "" ;
1258 			}
1259 		} 
1260 	}
1261 		
1262 		return url;
1263 	}
1264     
1265 	/**
1266 	 * Retira os códigos html do texto passado e retorna somente o texto
1267 	 * substituindo o <br> por " " e &nbps; por " "
1268 	 * 
1269 	 * @param strHtml
1270 	 * @return newString 
1271 	 */
1272 	public static String stripHTML(String strHtml){
1273 		String newString = new String();
1274 		if (strHtml != null){
1275 			newString = strHtml.replaceAll("<br>", " ").replaceAll("&nbsp;", " ").replaceAll("<.*?>", "").trim();
1276 		} 
1277 						
1278 		return newString;
1279 	}
1280 	
1281 	/**
1282 	 * Verifica se a string é um valor numérico
1283 	 */ 
1284 
1285 	public static boolean ehValor( String str) {
1286 		try {
1287 			Float.parseFloat(str);
1288 			return true;
1289 		} catch (NumberFormatException e) {
1290 			return false;
1291 		}
1292 	}
1293 	
1294 	/**
1295 	 * Faz a divisão entre os argumentos
1296 	 * 
1297 	 * @param dividendo
1298 	 * @param divisor
1299 	 * @return
1300 	 */
1301 	public static double trataDivisaoPorZero(double dividendo, double divisor){
1302 		if (divisor  == 0)
1303 			return 0;
1304 		else {
1305 			return dividendo/divisor;
1306 		}
1307 	}
1308 	
1309 
1310 } // fim class