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! :)

segunda-feira, 18 de março de 2013

RAD 7.5 não realiza publish no Ubuntu

Este post tem o objetivo de apresentar um erro bastante incomum  para o desenvolvedor que trabalha com a IDE RAD no Linux(Ubuntu). A Figura 1 mostra a seguinte mensagem: Failure uploading archive to server: 504 Gateway Time-out (for:  /home/<usuario>/Desktop/workspace/.metadata/.plugins/com.ibm.etools.wrd.websphere.v7/tmp<timestamp>/update.zip).

Toda vez que o desenvolvedor tenta realizar o republish o RAD exibe tal mensagem.

Figura 1 - Erro ao tentar realizar a operação de publish

Esse erro pode ter diversos motivos, contudo, no meu caso ocorre por causa do plugin subclipse (plugin para trabalhar com projetos que utilizam o versionador SVN).  Se você não quiser ter esse problema disconecte o projeto do SVN sem deletar os arquivos (.svn). Para isso clique com o botão direito no projeto, selecione a opção Team > Disconnect, confirme a operação assegurando que a opção "Do not delete de SVN meta information (e. g, SVN sub-directories)" esta marcada.

Seguindo esses passos você poderá alterar e publicar o projeto a vontade, e quando chegar o momento de commitar as alterações basta associar o projeto ao SVN novamente.