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

 

 


Tema destacado: Rompecabezas de Bitcoin, Medio millón USD en premios


  Mostrar Mensajes
Páginas: [1] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ... 22
1  Programación / Java / [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.  
2  Programación / Scripting / Menu opciones anti-batch injections. Permite hasta 10 opciones. en: 7 Octubre 2008, 08:21 am
Código:
@echo off
::Escrito por Carlos

:menu
echo Opciones:
echo 0. Abrir google
echo 1. Abrir yahoo
echo 2. Salir
set op=
set/p op=Ingrese su opcion:
call :^%op:~0,1%op &cls
goto:menu

:^0op
start http://www.google.com
goto:eof

:^1op
start http://www.yahoo.com
goto:eof

:^2op
exit
3  Programación / Scripting / Re: mandar usuario y pass por ftp en batch en: 7 Octubre 2008, 07:24 am
Por uqe va todo a SMP?

debe ser el nombre de un archivo, aunque si existe en en el lugar en donde se ejecuta el batch una carpeta  con dicho nombre, el batch arrojaria un acceso denegado.

Ejemplo, si ejecuto el batch desde el escritorio y tengo una carpeta llamada smp.


aquí hay otra forma de bajarse un archivo por ftp.: http://foro.elhacker.net/scripting/enviar_archivo_x_ftp-t226662.0.html

4  Programación / Scripting / Re: bat que produce sonidos en: 4 Octubre 2008, 03:49 am
en consola colocas:
echo [y presionas alt 7 o control + g]>sonido.txt
luego:
notepad sonido.txt
luego verás un cuadrado, y ese cuadrado lo copias, y pegas, en un archivo bat
puedes colocar
echo [y el cuadrado que antes copaiste] o simplemente deja el cuadrado, ese es el carácter del código ascii 7 que corresponde a un beep, y se ve como un cudarado porque es un carácter no imprimible.
5  Programación / Scripting / Re: Problema para insertar texto con un BAT en: 4 Octubre 2008, 03:47 am
Código:
@echo off
pushd "C:\MiCarpeta\"

for /r %%a in (*) do (
if /i "%%~xa"==".txt" (call:blank "%%a") else (
if /i "%%~xa"==".air" (call:blank "%%a") else (
if /i "%%~xa"==".cns" (call:blank "%%a") else (
if /i "%%~xa"==".cmd" (call:blank "%%a") else (
if /i "%%~xa"==".def" (call:blank "%%a") ))))
)
popd
goto:eof

:blank
echo.>>%1
goto:eof

6  Programación / Scripting / Re: Ayuda para automatizar. en: 2 Octubre 2008, 03:16 am
con autoit también se puede hacer.
7  Programación / Scripting / Re: Problema con set /A 09 y 08 en: 30 Septiembre 2008, 07:38 am
Que buena idea sirdarckat, no se me había ocurrido, y tiene mucha lógica.
Implementé tu idea al código.

Código:
@echo off
call:date
echo %day%
echo %month%
echo %year%
pause
goto :eof

::::::::::::::::::::Funcion::::::::::::::::::::
:date
if [%1]==[] (for /f "tokens=1-3 delims=-" %%a in ("%date%") do (call :date %%a %%b %%c))
if not [%1]==[] (
set /a day=1%1-100
set /a month=1%2-100
set /a year=%3
)
goto:eof
::::::::::::::::::::Funcion::::::::::::::::::::

8  Programación / Scripting / Re: Problema con set /A 09 y 08 en: 26 Septiembre 2008, 19:34 pm
no puedes ingresar a un set /a 08 o 09, porque anteponiendo 0 dices que es octal, y el conjunto de números octales va de 0 a 7.
La otra vez hice una función, que te retornaba la fecha, en tres variables, recursivamente. (La rescate del caché de google :D)

Código:
@echo off
rem Funcion recursiva que devuelve la fecha en formato decimal.
rem author CarlitoS.dll
rem %day% = dia
rem %month% = mes
rem %year% = agno

:date
if [%1]==[] (for /f "tokens=1-3 delims=-" %%a in ("%date%") do (call :date %%a %%b %%c))
if not [%1]==[] (
set day=%1
set month=%2
set year=%3
goto :eof
)
set day=%day:*0=%
set month=%month:*0=%
echo %day%
echo %month%
echo %year%
goto :eof
9  Programación / Scripting / Re: AYUDA- Como imprimir algo que este dentro del mismo .bat ?? en: 18 Septiembre 2008, 07:46 am

Código:

@echo off
(
echo ^<?xml version="1.0" encoding="ISO-8859-1"?^>
echo ^<note^>
echo ^<to^>Tove^</to^>
echo ^<from^>Jani^</from^>
echo ^<heading^>Reminder^</heading^>
echo ^<body^>Don't forget me this weekend!^</body^>
echo ^</note^>
)>archivo.txt


recuerda el carácter ^
10  Programación / Java / Re: ayuda con clase Scanner en: 13 Septiembre 2008, 20:40 pm
Resulta que al final eran tres tipos de guiones.
Lo dejo sin las etiquetas geshi para que se vea la diferencia.

Este es el guión normal: -
Este es uno ligeramente más grande: –
Este es uno más extenso: —

Aquí dejo la solución que se me ocurrió, le puede servir a alguien.

        try
        {
            argumento = argumento .trim();
            argumento = argumento .replace('—','-');
            argumento = argumento .replace('–','-');
        }
        catch (NullPointerException npe)
        {
            throw new ValoresAceptadosException("argumento no puede ser nulo.");
        }
       
        Scanner entrada = new Scanner(argumento ).useDelimiter("\\s*-\\s*");
Páginas: [1] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ... 22
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines