segunda-feira, 3 de junho de 2013

Google Maps API - Marcando Pontos no Mapa (v3)

O código abaixo apresenta o script necessário para marcar dois pontos no mapa utilizando API GoogleMaps.

Para utilizar este script, é necessário ter um documento HTML iniciado com a tag <!DOCTYPE html> (Mostrando que trata-se de um documento HTML 5), importar o script (versão 3) da API do GoogleMaps (<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>) e possuir um HTML DIV com a propriedade id igual à map-canvas.

  var map;
  var geocoder;
  var directionsDisplay;
  var directionsService;
  function initialize() {
      geocoder = new google.maps.Geocoder();
   
   // MARCANDO PONTOS
   geocoder.geocode({'address':'Cidade Nova, Rio de Janeiro'}, function(results, status){
    if (status == google.maps.GeocoderStatus.OK) {
     map.setCenter(results[0].geometry.location);
     var marker = new google.maps.Marker({
      map: map,
      position: map.getCenter(),
      title: 'Cidade Nova',
      icon: 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png'
     });   
    }
   });
   // 
   geocoder.geocode({'address':'Lapa, Rio de Janeiro'}, function(results, status){
    if (status == google.maps.GeocoderStatus.OK) {
     map.setCenter(results[0].geometry.location);
     var marker = new google.maps.Marker({
      map: map,
      position: map.getCenter(),
      title: 'Lapa',
      icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
     });
    }
   }); 
   // INICIANDO MAPA
   var mapOptions = {
      zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
   };
   map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  }
  google.maps.event.addDomListener(window, 'load', initialize);
Escreva um arquivo HTML com as informações apresentadas anteriormente, ao abrir o mesmo no browser teremos o conteúdo conforme apresentado na Figura 1 (sem os destaques em vermelho).
Figura 1 - Resultado do Código JavaScript com GoogleMaps API
Observando o código com cuidado, vemos que uma variável do tipo google.maps.Geocoder é a responsável por solicitar ao serviço do googlemaps uma determinada coordenada de geolocalização. Isto é realizado com o método geocode que envia um endereço (no formato JSON) e ao final do processamento do endereço executa a função informada no segundo parâmetro.
A verificação de status igual à google.maps.GeocoderStatus.OK mostra que o serviço foi executado com sucesso. Note que após esta verificação é criada uma variável do tipo google.maps.Marker responsável por "pintar" uma marca no mapa. Podemos personalizar algumas características no google.maps.Marker, neste caso, foi escolhido apenas um ícone diferente do ícone vermelho padrão.

Uma vez que criamos os dois pontos no mapa, precisamos ainda informar a API para desenhar o mapa. A variável do tipo google.maps.Map é responsável por desenhar uma mapa em um objeto HTMLDivElement. Note que é possível passar algumas informações para personalizar o mapa no momento da geração do mesmo. Em nosso caso passamos zoom  igual à 15 e google.maps.MapTypeId.ROADMAP para o tipo do mapa.

O tipo padrão de mapa do google é o tipo ROADMAP, temos ainda os tipos SATELLITE (utilizado no aplicativo Google Earth), HYBRID (mistura dos tipos ROAPMAP e SATELLITE) e TERRAIN (utilizado para apresentar informações de relevo). Utilize os tipos de mapas e visualize a diferença no browser.

That's all folk's!

segunda-feira, 8 de abril de 2013

Ordem que as informações do arquivo web.xml são carregas.

É uma dúvida comum para muitos desenvolvedores o que acontece quando servidor de aplicações Java (Exemplo. Tomcat e Glassfish) iniciam o processo de deploy de uma aplicação.

O processo carrega todos os listeners, filters e servlets especificados no arquivo web.xml na seguinte ordem.


1º. Inicializa cada listener identificador pela tag <listener> que implementa a interface ServletContextListener na ordem que foram declarados no web.xml

2º.   Para cada listener inicializado chama o método contextInitialized().

3º.   Inicializa cada filter identificado pela tag <filter> na ordem que foram declarados no web.xml.

4º.   Para cada filter inicializado chama o método init().

5º.  Inicializa cada servlet identificado pela tag <servlet> que possui o elemento <load-on-startup> definido. Usando-o para definir à ordem (do menor para o maior) que cada servlet será inicializado. O valor elemento <load-on-startup> é definido com um número inteiro, por exemplo, <load-on-startup>3</load-on-startup>, neste caso, significa que o servlet será o terceiro servlet a ser inicializado.

6º.   Para cada servlet inicializado chama o método init().

domingo, 7 de abril de 2013

Gerar cores em hexdecimal aletóriamente com JavaScript

Have Fun ;P

/*
 * Gerar cores em hexdecimal aleatóriamente
 */
function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

sábado, 6 de abril de 2013

Formatar e Validar CPF e CNPJ com Javascript

Have Fun :)

Coloque o conteúdo abaixo dentro de um arquivo de script chamado CPFCNPJUtil.js e utilize  a instrução <script type="text/javascript" src="CPFCNPJUtil.js"></script> no seu arquivo HTML.

CPFCNPFUtil : (function() {
  
      function CPFCNPFUtil() {
      };
      
   // [private fields]
   
      var VALUE_CANNOT_BE_NULL_OR_UNDEFINED      = "value cannot be null or undefined";
  
      var VALUE_CANNOT_BE_NULL_OR_EMPTY          = "value cannot be null or empty";
  
      var SIZE_OF_VALUE_CANNOT_BE_BIGGER_THEN_14 = "size of value cannot be bigger then 14";
  
      var VALUE_IS_NOT_A_VALID_CPF_OR_CPNJ       = "value is not a valid CPF or CPNJ";
  
      var weightCPF                              = [ 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 ];
  
      var weightCNPJ                             = [ 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 ];
   
      // [private functions]
  
      /**
       * Preenche com zeros à direita. Ex: _fillWithZeros('123',5) irá retornar 00123
       * 
       * @param value [string] será preenchido com zeros a direta até que possua tamanho igual ao @param [size - 1]. 
       * 
       * @param size [numero] limite do tamanho da string
       */
      var _fillWithZeros = function(value, size) {
       var limit = size-1;
       while (value.length < size-1) value = '0'.concat(value);
       return value;
      };
      
      /**
    * Calcula digito verificador para CPF or CPNJ
    * 
    * @param stringBase
    *            [string] base do calculo do digito verificador
    * 
    * @param weight
    *            array[int] representa os peso de cada caracter que compõe um
    *            CPF ou CNPJ
    * 
    * @return [int] digito verificador
    */
   var _calcDigit = function(stringBase, weight) {
    var sum = 0;
    for (var index = stringBase.length - 1, digit; index >= 0; index--) {
     digit = parseInt(stringBase.substring(index, index + 1));
     sum += digit * weight[weight.length - stringBase.length + index];
    }
    sum = 11 - sum % 11;
    return sum > 9 ? 0 : sum;
      };
      
      // [public functions]
      
      /**
    * Verifica se um valor corresponde à um CPF.
    * 
    * @param value
    *            [long] valor à ser testado
    * 
    * @return [boolean] true caso seja um valor válido, false caso contrário
    */ 
      var _isCPF = function(value) {
       var CPF = _fillWithZeros(value, 12);
       
    var firstPart = _calcDigit(CPF.substring(0, 9), weightCPF);
    var lastPart = _calcDigit(CPF.substring(0, 9) + firstPart, weightCPF);
  
    return CPF.substring(9) == firstPart +''+ lastPart;
      };
  
   /**
    * Verifica se um valor corresponde à um CNPJ.
    * 
    * @param value
    *            [long] valor à ser testado
    * 
    * @return [boolean] true caso seja um valor válido, false caso contrário
    */
      var _isCNPJ = function(value) {
       
       var CNPJ = _fillWithZeros(value, 15);
       
    var firstPart = _calcDigit(CNPJ.substring(0, 12), weightCNPJ);
    var lastPart  = _calcDigit(CNPJ.substring(0, 12) + firstPart, weightCNPJ);
  
    return CNPJ.substring(12) == firstPart +''+ lastPart;
      };
      
   /**
    * Formata valor para CPF 000.000.000-00 ou CNPJ 00.000.000/0000-00
    * 
    * @param value
    *            [string] representa um CPF ou CNPJ
    * 
    * @param check
    *            [boolean] [default=true] se true verifica se é um CPF ou CNPJ valido, se
    *            false apenas realiza a formatação
    * 
    * @return CPF ou CNPJ formatado
    */
   CPFCNPFUtil.prototype.formatCPForCPNJ = function(value, check) {
    if (check == null || value == undefined) {
     check = true;
    }
    if (value == null || value == undefined) {
     throw VALUE_CANNOT_BE_NULL_OR_UNDEFINED;
    }
    
    value = value.replace(/[^0-9]+/,'');
    var valueSize = value.length;
    if (valueSize > 14) {
     throw SIZE_OF_VALUE_CANNOT_BE_BIGGER_THEN_14;
    }
  
    if (check && !this.isCPForCPNJ(value)) {
     throw VALUE_IS_NOT_A_VALID_CPF_OR_CPNJ;
    }
  
    var fullValue = '';
    var isCPF = valueSize < 12;
    if (isCPF) {
     fullValue = _fillWithZeros(value, 12);
     fullValue = fullValue.replace(/([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{2})/, "$1.$2.$3-$4");
    } else {
     fullValue = _fillWithZeros(value, 15);
     fullValue = fullValue.replace(/([0-9]{2})([0-9]{3})([0-9]{3})([0-9]{4})([0-9]{2})/, "$1.$2.$3/$4-$5");
    }
  
    return fullValue;
   };
  
   /**
    * Verifica se um valor corresponde à um CPF ou CNPJ válido.
    * 
    * @param value
    *            [string] valor à ser testado
    * 
    * @return [boolean] true caso seja um valor válido, false caso contrário
    */
   CPFCNPFUtil.prototype.isCPForCPNJ     = function(value) {
    
    if (value == null || value.length == 0) {
     throw VALUE_CANNOT_BE_NULL_OR_EMPTY;
    }
    
    value = value.replace(/[^0-9]+/,'');
    var valueSize = value.length;
    if (valueSize > 14) {
     return false;
    }
  
    var isCPF = valueSize < 12;
    return isCPF ? _isCPF(value) : _isCNPJ(value);
   };
      
      return CPFCNPFUtil;
  })();

Segue trecho de código que pode ser utilizado para entender o funcionamento desse objeto.

var test = new CPFCNPFUtil();

alert(test.isCPForCPNJ('92534262000154')); // Verificando CNPJ
alert(test.formatCPForCPNJ('92534262000154')); // Verificando e Formatando CPF
alert(test.formatCPForCPNJ('925342-[]=62000154')); // Verificando e Formatando CPF
alert(test.formatCPForCPNJ('9253426200015')); // Error ao tentar formatar
alert(test.formatCPForCPNJ('9253426200015',false)); // Apenas Formatando

alert(test.isCPForCPNJ('28765254619')); // Verificando CPF
alert(test.formatCPForCPNJ('28765254619')); // Verificando e Formatando CPF
alert(test.formatCPForCPNJ('2()_=8765254619')); // Verificando e Formatando CPF
alert(test.formatCPForCPNJ('2876525461')); // Error ao tentar formatar
alert(test.formatCPForCPNJ('2876525461',false)); // Apenas Formatando

Formatar e Validar CPF e CNPJ com Java

Have Fun :)
import java.text.DecimalFormat;

/**
 * @autor salve ferris
 *
 * classe para formatação e validação de CPF e CNPJ 
 */
public class CPFCNPJUtil {

 private static final String VALUE_CANNOT_BE_NULL = "value cannot be null";

 private static final String VALUE_CANNOT_BE_NULL_OR_EMPTY = "value cannot be null or empty";

 private static final String SIZE_OF_VALUE_CANNOT_BE_BIGGER_THEN_14 = "size of value cannot be bigger then 14";

 private static final String VALUE_IS_NOT_A_VALID_CPF_OR_CPNJ = "value is not a valid CPF or CPNJ";

 private static final DecimalFormat CNPJ_NFORMAT = new DecimalFormat(
   "00000000000000");

 private static final DecimalFormat CPF_NFORMAT = new DecimalFormat(
   "00000000000");

 private static final int[] weightCPF = { 11, 10, 9, 8, 7, 6, 5, 4, 3, 2 };

 private static final int[] weightCNPJ = { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4,
   3, 2 };

 /**
  * Formata valor para CPF 000.000.000-00 ou CNPJ 00.000.000/0000-00 caso o
  * mesmo seja um CPF ou CNPJ válido
  * 
  * @param value
  *            [string] representa um CPF ou CNPJ
  * 
  * @return CPF ou CNPJ formatado
  */
 public static String formatCPForCPNJ(String value) {
  if (value == null || value.isEmpty()) {
   throw new IllegalArgumentException(VALUE_CANNOT_BE_NULL_OR_EMPTY);
  }
  return formatCPForCPNJ(Long.parseLong(value.replaceAll("[^0-9]+", "")),
    true);
 }

 /**
  * Formata valor para CPF 000.000.000-00 ou CNPJ 00.000.000/0000-00
  * 
  * @param value
  *            [string] representa um CPF ou CNPJ
  * 
  * @param check
  *            [boolean] se true verifica se é um CPF ou CNPJ valido, se
  *            false apenas realiza a formatação
  * 
  * @return CPF ou CNPJ formatado
  */
 public static String formatCPForCPNJ(String value, boolean check) {
  if (value == null || value.isEmpty()) {
   throw new IllegalArgumentException(VALUE_CANNOT_BE_NULL_OR_EMPTY);
  }
  return formatCPForCPNJ(Long.parseLong(value.replaceAll("[^0-9]+", "")),
    check);
 }

 /**
  * Formata valor para CPF 000.000.000-00 ou CNPJ 00.000.000/0000-00 caso o
  * mesmo seja um CPF ou CNPJ válido
  * 
  * @param value
  *            [long] representa um CPF ou CNPJ
  * 
  * @return CPF ou CNPJ formatado
  */
 public static String formatCPForCPNJ(Long value) {
  return formatCPForCPNJ(value, true);
 }

 /**
  * Formata valor para CPF 000.000.000-00 ou CNPJ 00.000.000/0000-00
  * 
  * @param value
  *            [long] representa um CPF ou CNPJ
  * 
  * @param check
  *            [boolean] se true verifica se é um CPF ou CNPJ valido, se
  *            false apenas realiza a formatação
  * 
  * @return CPF ou CNPJ formatado
  */
 public static String formatCPForCPNJ(Long value, boolean check) {
  if (value == null) {
   throw new IllegalArgumentException(VALUE_CANNOT_BE_NULL);
  }

  final int valueSize = value.toString().length();
  if (valueSize > 14) {
   throw new IllegalArgumentException(
     SIZE_OF_VALUE_CANNOT_BE_BIGGER_THEN_14);
  }

  if (check && !isCPForCPNJ(value)) {
   throw new IllegalArgumentException(VALUE_IS_NOT_A_VALID_CPF_OR_CPNJ);
  }

  boolean isCPF = valueSize < 12;
  DecimalFormat formatDecimal = isCPF ? CPF_NFORMAT : CNPJ_NFORMAT;

  final String stringNumber = formatDecimal.format(value);

  return isCPF ? stringNumber.replaceAll(
    "([0-9]{3})([0-9]{3})([0-9]{3})([0-9]{2})", "$1.$2.$3-$4")
    : stringNumber.replaceAll(
      "([0-9]{2})([0-9]{3})([0-9]{3})([0-9]{4})([0-9]{2})",
      "$1.$2.$3/$4-$5");
 }

 /**
  * Verifica se um valor corresponde à um CPF ou CNPJ válido.
  * 
  * @param value
  *            [string] valor à ser testado
  * 
  * @return [boolean] true caso seja um valor válido, false caso contrário
  */
 public static boolean isCPForCPNJ(String value) {
  if (value == null || value.isEmpty()) {
   throw new IllegalArgumentException(VALUE_CANNOT_BE_NULL_OR_EMPTY);
  }
  return isCPForCPNJ(Long.parseLong(value.replaceAll("[^0-9]+", "")));
 }

 /**
  * Verifica se um valor corresponde à um CPF ou CNPJ válido.
  * 
  * @param value
  *            [long] valor à ser testado
  * 
  * @return [boolean] true caso seja um valor válido, false caso contrário
  */
 public static boolean isCPForCPNJ(Long value) {

  final int valueSize = value.toString().length();
  if (valueSize > 14) {
   return false;
  }

  boolean isCPF = valueSize < 12;

  return isCPF ? isCPF(value) : isCNPJ(value);
 }

 /**
  * Verifica se um valor corresponde à um CPF.
  * 
  * @param value
  *            [long] valor à ser testado
  * 
  * @return [boolean] true caso seja um valor válido, false caso contrário
  */
 private static boolean isCPF(Long value) {

  String CPF = CPF_NFORMAT.format(value);

  int firstPart = calcDigit(CPF.substring(0, 9), weightCPF);
  int lastPart = calcDigit(CPF.substring(0, 9) + firstPart, weightCPF);

  return CPF.substring(9).equals(
    String.format("%d%d", firstPart, lastPart));
 }

 /**
  * Verifica se um valor corresponde à um CNPJ.
  * 
  * @param value
  *            [long] valor à ser testado
  * 
  * @return [boolean] true caso seja um valor válido, false caso contrário
  */
 private static boolean isCNPJ(Long value) {

  String CNPJ = CNPJ_NFORMAT.format(value);

  Integer firstPart = calcDigit(CNPJ.substring(0, 12), weightCNPJ);
  Integer lastPart = calcDigit(CNPJ.substring(0, 12) + firstPart,
    weightCNPJ);

  return CNPJ.substring(12).equals(
    String.format("%d%d", firstPart, lastPart));
 }

 /**
  * Calcula digito verificador para CPF or CPNJ
  * 
  * @param stringBase
  *            [string] base do calculo do digito verificador
  * 
  * @param weight
  *            array[int] representa os peso de cada caracter que compõe um
  *            CPF ou CNPJ
  * 
  * @return [int] digito verificador
  */
 private static int calcDigit(String stringBase, int[] weight) {
  int sum = 0;
  for (int index = stringBase.length() - 1, digit; index >= 0; index--) {
   digit = Integer.parseInt(stringBase.substring(index, index + 1));
   sum += digit * weight[weight.length - stringBase.length() + index];
  }
  sum = 11 - sum % 11;
  return sum > 9 ? 0 : sum;
 }
}

quarta-feira, 27 de março de 2013

Habilitar Cores no Terminal do Mac (OSX)

Habilitar Cores no Terminal do Mac (OSX)

Quem gosta de brincar no terminal de comandos do Ubuntu, já percebeu que o mesmo apresenta cores para identificar os tipos de arquivo quando executamos o comando "ls".

Significado das Cores (Padrão no terminal do Ubuntu)

Azul Diretório (directory)
Azul Claro 
Atalho (linked file)
Verde 
Arquivo Executável ou Arquivo de Dados (executable or recognized data file)
Red 
Arquivo Compactado [*.rar | *.zip] (archive file)
Rosa
Arquivo de Imagem (graphic image file)
Amarelo com fundo preto
Dispositivo Externo (external device) 

Não seria legal se fosse possível utilizar esse recurso no OSX também? Acontece que é possível, basta abrir o arquivo .profile - executando a instrução open .profile no terminal - e adicionar as instruções abaixo.

export CLICOLOR=1  #Habilita utilização de cores
export LSCOLORS=exfxcxdxbxegedabagacad #Gera um esquema de cores

Execute o comando source ˜/.profile ou source .profile para recarregar o arquivo, atualizando essas informações no sistema operacional e o novo esquema de cores já vai estar valendo! Have Fun ;)

Dica 01: Execute os comandos apresentados diretamente no terminal para habilitar as cores imediatamente.

Dica 02: Após executar a instrução export CLICOLOR=1, execute a instrução ls -l -a para ver o resultado.

Dica 03: Use o link http://geoff.greer.fm/lscolors/ para gerar um esquema de cores como desejar.


segunda-feira, 25 de março de 2013

Obter nome de todos os inputs de HTML com jquery

O código abaixo é capaz de obter os nomes de todos os objetos input de uum documento HTML. (entenda por objetos inout, objetos representados pelas tag input, select, checkbox, radio, textarea, button).

var HTMLObjects = $.find(':input');
for (var i = 0;i < $(HTMLObjects).length; i++) {

console.log($(HTMLObjects[i]).attr('name'));

// alert($(HTMLObjects[i]).attr('name'));

}

Esse trecho de código pode aprestar outros atributos, por exemplo, se quiser ver todos os ids troque .attr('name') por .attr('id') e seja feliz! :)