elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.


Tema destacado: Únete al Grupo Steam elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  [JAVA] Sanitizador de palabras y verificador de RUT (Chile)
0 Usuarios y 4 Visitantes están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: [JAVA] Sanitizador de palabras y verificador de RUT (Chile)  (Leído 13,409 veces)
carlitos.dll

Desconectado Desconectado

Mensajes: 266



Ver Perfil
[JAVA] Sanitizador de palabras y verificador de RUT (Chile)
« en: 9 Octubre 2008, 15:53 pm »

Código
  1.  
  2. /*-
  3.  * Copyright (c) 2008 Carlos
  4.  * All rights reserved.
  5.  *
  6.  * Redistribution and use in source and binary forms, with or without
  7.  * modification, are permitted provided that the following conditions
  8.  * are met:
  9.  * 1. Redistributions of source code must retain the above copyright
  10.  *    notice, this list of conditions and the following disclaimer.
  11.  * 2. Redistributions in binary form must reproduce the above copyright
  12.  *    notice, this list of conditions and the following disclaimer in the
  13.  *    documentation and/or other materials provided with the distribution.
  14.  * 3. Neither the name of copyright holders nor the names of its
  15.  *    contributors may be used to endorse or promote products derived
  16.  *    from this software without specific prior written permission.
  17.  *
  18.  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19.  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
  20.  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  21.  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS
  22.  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  23.  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  24.  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  25.  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  26.  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  27.  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  28.  * POSSIBILITY OF SUCH DAMAGE.
  29.  */
  30.  
  31. import java.util.*;
  32.  
  33. /**
  34.  * ReglasDeNegocio.java
  35.  *
  36.  * Esta clase implementa una serie de métodos estáticos,
  37.  * para implementar reglas de negocio
  38.  * tales como sanitizar palabras, validar rut.
  39.  *
  40.  * @author Carlos
  41.  * @version 14-9-2008
  42.  */
  43. final class ReglasDeNegocio
  44. {
  45.   /**
  46.     * Método sanitizador de Strings.
  47.     * @param Recibe:
  48.     * Un String con el String a sanitizar
  49.     * Un int con el tipo de sanitización
  50.     * Un String con el nombreDelAtributo que llama al método, en caso de que se lanzen excepciones
  51.     * 1 corresponde a limpieza para Strings de nombres.
  52.     * 2 corresponde a limpieza para Strings de direcciones.
  53.     * Ejemplo: si tengo una variable String nombre:
  54.     * Ejemplo: nombre = ReglasDeNegocio.filtro("Juan123456 Pérez###", 1, "nombre"),
  55.     * nombre tendrá el contenido: "Juan Pérez",
  56.     * si nombre es nulo se lanza una excepción diciendo: "nombre no puede ser nulo", nombre es el identificador de la variable.
  57.     * Ejemplo: filtro("Santa Rosa%%%%%////123", 2, "direccion") devuelve "Santa Rosa 123"
  58.     * autor: Carlos
  59.     */
  60.   public static String filtro(
  61.                                String argumento,
  62.                                int opcion,
  63.                                String nombreVariable) throws Exception
  64.   {
  65.       try
  66.       {
  67.           nombreVariable = nombreVariable.trim();
  68.           if (nombreVariable.length() < 1)
  69.           {
  70.               throw new Exception(
  71.               "el nombreVariable debe contener el nombre de la variable.");
  72.           }
  73.       }
  74.       catch (NullPointerException npe)
  75.       {
  76.           throw new Exception("Error en los parámetros.");
  77.       }
  78.  
  79.       String patron;
  80.       switch (opcion)
  81.       {
  82.           case 1 : {
  83.                        patron = new String("[^A-Za-záéíóúñÁÉÍÓÚÑüÜ -]");
  84.                        break;
  85.                    }
  86.           case 2 : {
  87.                        patron = new String("[^0-9A-Za-záéíóúñÁÉÍÓÚÑüÜ#° -]");
  88.                        break;
  89.                    }
  90.           default: {
  91.                        throw new Exception(String.valueOf(opcion));
  92.                    }
  93.       }
  94.       try
  95.       {
  96.           argumento = argumento.trim();
  97.           if (argumento.length() < 1)
  98.           {
  99.               throw new Exception(nombreVariable + " está vacío.");
  100.           }
  101.       }
  102.       catch (NullPointerException npe)
  103.       {
  104.           throw new Exception(nombreVariable + " no puede ser nulo");
  105.       }
  106.  
  107.       Scanner palabra = new Scanner(argumento).useDelimiter(patron);
  108.       String reconstruccion = new String();
  109.       while(palabra.hasNext())
  110.       {
  111.           reconstruccion = reconstruccion + palabra.next();
  112.       }
  113.       palabra.close();
  114.  
  115.       argumento = new String();
  116.       StringTokenizer tokens = new StringTokenizer(reconstruccion);
  117.       while(tokens.hasMoreTokens())
  118.       {
  119.           argumento = argumento + " " + tokens.nextToken();
  120.       }
  121.       argumento = argumento.trim();
  122.       return argumento;
  123.   }
  124.  
  125.   /**
  126.     * Método sanitizador y validador de rut.
  127.     * @param Recibe una cadena correspondiente al rut.
  128.     * @return Devuelve un rut sanitizado,
  129.     * en caso de que el digito verificador sea correcto, sino lanza una excepción.
  130.     * Ejemplo "123456789-2" lo devuelve correcto.
  131.     * "123456789-26999" lo devuelve como "123456789-2".
  132.     * "123456789-3" lanza excepción pues el digito verificador es 2.
  133.     * "00000123456789-2" lo devuelve como "123456789-2".
  134.     * autor: Carlos
  135.     * version: 1.1
  136.     */
  137.    public static String validadorRut(String rut) throws Exception
  138.    {
  139.       if (rut == null)
  140.       {
  141.           throw new Exception("rut no puede ser nulo");
  142.       }
  143.  
  144.       rut = rut.replace('—','-').replace('–','-');
  145.  
  146.       String datosRut = new String();
  147.       Scanner token = new Scanner(rut).useDelimiter("[[\\D]&&[^Kk-]]");
  148.       while (token.hasNext())
  149.       {
  150.           datosRut = datosRut + token.next();
  151.       }
  152.       StringTokenizer tokens = new StringTokenizer(datosRut, "-");
  153.       if (tokens.countTokens() != 2)
  154.       {
  155.           throw new Exception("error de formato en el rut");
  156.       }
  157.  
  158.       String datos = tokens.nextToken();
  159.  
  160.       boolean comienzaConCero = datos.startsWith("0");
  161.       if (comienzaConCero)
  162.       {
  163.           int indice;  
  164.           for (indice = 0; indice < datos.length() && comienzaConCero; indice++)
  165.           {
  166.               comienzaConCero = datos.substring(indice, indice + 1).equals("0");
  167.           }
  168.           datos = datos.substring(indice - 1);
  169.       }
  170.  
  171.       String digitoVerificador = new String();
  172.       try
  173.       {
  174.           int formato = Integer.parseInt(datos);
  175.           int contador = 2;
  176.           int calculo = 0;
  177.           for (int i = datos.length() - 1; i >= 0; i--)
  178.           {
  179.               contador = contador > 7 ? 2 : contador;
  180.               calculo += Integer.parseInt(datos.substring(i, i + 1)) * contador++;
  181.           }
  182.           calculo = 11 - (calculo % 11);
  183.           String digito = new String(calculo == 10 ? "K" : calculo == 11 ? "0" : String.valueOf(calculo));
  184.           String digitoRecibido = tokens.nextToken().substring(0, 1);
  185.           if (digito.equalsIgnoreCase(digitoRecibido))
  186.           {
  187.               return rut = datos + "-" + digito;
  188.           }
  189.           else
  190.           {
  191.               throw new Exception("El digito verificador del rut no es correcto.");
  192.           }
  193.       }
  194.       catch (NumberFormatException nfe)
  195.       {
  196.           throw new Exception("Error de formato en el rut.");
  197.       }
  198.    }
  199.  
  200. }
  201.  
  202.  


« Última modificación: 3 Noviembre 2011, 20:42 pm por Leyer » En línea

juancho77


Desconectado Desconectado

Mensajes: 455


rie con demencia


Ver Perfil
Re: [JAVA] Sanitizador de palabras y verificador de RUT (Chile)
« Respuesta #1 en: 11 Octubre 2008, 21:15 pm »

Y que se supone que hace?  :-*


En línea

Pablo Videla


Desconectado Desconectado

Mensajes: 2.274



Ver Perfil WWW
Re: [JAVA] Sanitizador de palabras y verificador de RUT (Chile)
« Respuesta #2 en: 12 Octubre 2008, 00:22 am »

Gracias! yo tenia esa duda , el programa calcula el digito verificador del rut chileno , yo soy chileno xD
En línea

Pablo Videla


Desconectado Desconectado

Mensajes: 2.274



Ver Perfil WWW
Re: [JAVA] Sanitizador de palabras y verificador de RUT (Chile)
« Respuesta #3 en: 12 Octubre 2008, 00:32 am »

 
Código
  1. public static void main(String args[])throws Exception
  2. {
  3. ReglasDeNegocio persona;
  4.  
  5. persona = new ReglasDeNegocio();
  6. persona.validadorRut("mirut");
  7. }
  8.  
  9. [/code=java]
  10. al agregar mi verdadero rut me lanza la excepcion
  11. --------------------Configuration: <Default>--------------------
  12. Exception in thread "main" java.lang.Exception: error de formato en el rut
  13.    at ReglasDeNegocio.validadorRut(ReglasDeNegocio.java:163)
  14.    at ReglasDeNegocio.main(ReglasDeNegocio.java:212)
  15.  
  16. Process completed.
  17.  
  18. y coloco mi rut real, claro que sin el digito verificador ni los puntos , por que se supone que me debe calcular el digito verificador , cual es el problema ..?
  19.  
  20. (no coloco nica me verdarero rut aca)

pense que calculaba el digito verificador , pero solo comprueba si es el verdadero o no xD
« Última modificación: 12 Octubre 2008, 01:16 am por BadDevil » En línea

Gabriela005

Desconectado Desconectado

Mensajes: 2


Ver Perfil
Re: [JAVA] Sanitizador de palabras y verificador de RUT (Chile)
« Respuesta #4 en: Hoy a las 14:22 »

Aunque el tema es antiguo, lo dejo por si a alguien le sirve: el error que tuvo Pablo Videla ("error de formato en el rut") pasa porque el validador exige el guion para separar el dígito verificador. Se puede hacer más tolerante tomando siempre el último carácter como dígito verificador, sin depender del guion:

Código:
public static boolean validarRut(String rut) {
    rut = rut.toUpperCase().replaceAll("[^0-9K]", "");
    if (rut.length() < 2) return false;

    String cuerpo = rut.substring(0, rut.length() - 1);
    char dv = rut.charAt(rut.length() - 1);
    if (!cuerpo.matches("\\d+")) return false;

    int suma = 0, mul = 2;
    for (int i = cuerpo.length() - 1; i >= 0; i--) {
        suma += (cuerpo.charAt(i) - '0') * mul;
        mul = (mul == 7) ? 2 : mul + 1;
    }
    int res = 11 - (suma % 11);
    char esperado = (res == 11) ? '0' : (res == 10) ? 'K' : (char) ('0' + res);
    return dv == esperado;
}

Así acepta "12.345.678-5", "12345678-5" y "123456785" por igual. Eso sí, el número debe incluir el dígito verificador, sin él no hay nada que validar.

Más detalles sobre los formatos válidos y los errores típicos al escribir un RUT, en esta guía de formato del RUT en Chile.

Saludos.
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
Verificador de archivos enviados a un ftp
Scripting
morenochico 0 2,718 Último mensaje 5 Agosto 2008, 02:06 am
por morenochico
Verificador de dominios de .com.uy en PHP ..
PHP
[GB] 0 2,772 Último mensaje 9 Noviembre 2008, 17:37 pm
por [GB]
[Código-Python]Obtener dígito verificador del RUT en Chile - JaAViEr
Scripting
0x5d 3 17,983 Último mensaje Hoy a las 14:26
por Gabriela005
transformar y cambiar las palabras de un archivo.txt con java
Ejercicios
roby79 0 7,113 Último mensaje 11 Mayo 2012, 04:15 am
por roby79
programa rut verificador
Programación C/C++
Dani2304 1 2,420 Último mensaje 24 Abril 2018, 20:34 pm
por engel lex
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines