/*-
* Copyright (c) 2008 Carlos
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of copyright holders nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.*;
/**
* ReglasDeNegocio.java
*
* Esta clase implementa una serie de métodos estáticos,
* para implementar reglas de negocio
* tales como sanitizar palabras, validar rut.
*
* @author Carlos
* @version 14-9-2008
*/
final class ReglasDeNegocio
{
/**
* Método sanitizador de Strings.
* @param Recibe:
* Un String con el String a sanitizar
* Un int con el tipo de sanitización
* Un String con el nombreDelAtributo que llama al método, en caso de que se lanzen excepciones
* 1 corresponde a limpieza para Strings de nombres.
* 2 corresponde a limpieza para Strings de direcciones.
* Ejemplo: si tengo una variable String nombre:
* Ejemplo: nombre = ReglasDeNegocio.filtro("Juan123456 Pérez###", 1, "nombre"),
* nombre tendrá el contenido: "Juan Pérez",
* si nombre es nulo se lanza una excepción diciendo: "nombre no puede ser nulo", nombre es el identificador de la variable.
* Ejemplo: filtro("Santa Rosa%%%%%////123", 2, "direccion") devuelve "Santa Rosa 123"
* autor: Carlos
*/
int opcion,
{
try
{
nombreVariable = nombreVariable.trim();
if (nombreVariable.length() < 1)
{
"el nombreVariable debe contener el nombre de la variable.");
}
}
{
throw new Exception("Error en los parámetros."); }
switch (opcion)
{
case 1 : {
patron
= new String("[^A-Za-záéíóúñÁÉÍÓÚÑüÜ -]"); break;
}
case 2 : {
patron
= new String("[^0-9A-Za-záéíóúñÁÉÍÓÚÑüÜ#° -]"); break;
}
default: {
}
}
try
{
argumento = argumento.trim();
if (argumento.length() < 1)
{
throw new Exception(nombreVariable
+ " está vacío."); }
}
{
throw new Exception(nombreVariable
+ " no puede ser nulo"); }
Scanner palabra = new Scanner(argumento).useDelimiter(patron);
while(palabra.hasNext())
{
reconstruccion = reconstruccion + palabra.next();
}
palabra.close();
while(tokens.hasMoreTokens())
{
argumento = argumento + " " + tokens.nextToken();
}
argumento = argumento.trim();
return argumento;
}
/**
* Método sanitizador y validador de rut.
* @param Recibe una cadena correspondiente al rut.
* @return Devuelve un rut sanitizado,
* en caso de que el digito verificador sea correcto, sino lanza una excepción.
* Ejemplo "123456789-2" lo devuelve correcto.
* "123456789-26999" lo devuelve como "123456789-2".
* "123456789-3" lanza excepción pues el digito verificador es 2.
* "00000123456789-2" lo devuelve como "123456789-2".
* autor: Carlos
* version: 1.1
*/
{
if (rut == null)
{
throw new Exception("rut no puede ser nulo"); }
rut = rut.replace('—','-').replace('–','-');
Scanner token = new Scanner(rut).useDelimiter("[[\\D]&&[^Kk-]]");
while (token.hasNext())
{
datosRut = datosRut + token.next();
}
if (tokens.countTokens() != 2)
{
throw new Exception("error de formato en el rut"); }
String datos
= tokens.
nextToken();
boolean comienzaConCero = datos.startsWith("0");
if (comienzaConCero)
{
int indice;
for (indice = 0; indice < datos.length() && comienzaConCero; indice++)
{
comienzaConCero = datos.substring(indice, indice + 1).equals("0");
}
datos = datos.substring(indice - 1);
}
try
{
int formato
= Integer.
parseInt(datos
); int contador = 2;
int calculo = 0;
for (int i = datos.length() - 1; i >= 0; i--)
{
contador = contador > 7 ? 2 : contador;
calculo
+= Integer.
parseInt(datos.
substring(i, i
+ 1)) * contador
++; }
calculo = 11 - (calculo % 11);
String digito
= new String(calculo
== 10 ? "K" : calculo
== 11 ? "0" : String.
valueOf(calculo
)); String digitoRecibido
= tokens.
nextToken().
substring(0,
1); if (digito.equalsIgnoreCase(digitoRecibido))
{
return rut = datos + "-" + digito;
}
else
{
throw new Exception("El digito verificador del rut no es correcto."); }
}
{
throw new Exception("Error de formato en el rut."); }
}
}