RSS
Recortes: 23
jdbc
xml
hanoi
torres
juego
fechas
tomcat
consola
base-datos
Look_and_feel
debug
ssl
bd
URL
planificador
descargar
StringBuffer
jstl
byte
utilidades
ReplaceAll
documento
tarea
certificados
Skin
leer
sql
Se debe utilizar el siguiente parámetro de arranque:
-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n
Una vez tenemos el documento un array de bytes podremos hacer lo que queramos con él.
public static byte[] leerDocumento(URL url) throws IOException { URLConnection connection = url.openConnection(); InputStream in = null; try { in = connection.getInputStream(); } catch (FileNotFoundException e) { return null; } catch (ConnectException e) { e.printStackTrace(); return null; } int contentLength = connection.getContentLength(); ByteArrayOutputStream tmpOut; if (contentLength != -1) { tmpOut = new ByteArrayOutputStream(contentLength); } else { tmpOut = new ByteArrayOutputStream(16384); } byte[] buf = new byte[512]; while (true) { int len = in.read(buf); if (len == -1) { break; } tmpOut.write(buf, 0, len); } in.close(); tmpOut.close(); byte[] array = tmpOut.toByteArray(); return array; }
public static StringBuffer replaceAllenSB(StringBuffer original, String replaced, String replacement)
{
StringBuffer theSB = new StringBuffer(original);
int baseIndex = 0;
int badSignIndex = 0;
while ((badSignIndex = original.indexOf(replaced, badSignIndex)) != -1)
{
theSB.delete(badSignIndex + baseIndex, badSignIndex + baseIndex
+ replaced.length());
theSB.insert(badSignIndex + baseIndex, replacement);
baseIndex = baseIndex + replacement.length() – replaced.length();
badSignIndex = badSignIndex + replaced.length();
}
return theSB;
}
Pequeño algoritmo que resuelve el juego de las Torres de Hanoi con N discos. No tiene interfaz gráfica, todo lo hace desde la consola.
package hanoi; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; /** * * @author tauron */ public class Hanoi { public enum palo {izquierdo,central,derecho}; public static void Mover(int n,palo origen, palo auxiliar,palo destino) { if(n == 1) { System.out.println("Mueve el disco " + n + " desde el palo " + origen + " al " + destino); } else { Mover(n-1,origen,destino,auxiliar); System.out.println("Mueve el disco " + n + " desde el palo " + origen + " al " + destino); Mover(n-1,auxiliar,origen,destino); } } public static void main(String[] args) { BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in)); int numDiscos; String discos = ""; System.out.print("Introduce el número de discos: "); try{ discos = dataIn.readLine(); }catch(IOException e){ System.out.println("¡Error!"); } numDiscos = Integer.valueOf(discos); while (numDiscos < 1) { System.out.println("Vaya chorrada de número has metido. ERROR."); System.out.print("Inserta el número de discos: "); try{ discos = dataIn.readLine(); }catch(IOException e){ System.out.println("¡Error!"); } numDiscos = Integer.valueOf(discos); } // Fin del while Mover(numDiscos,palo.izquierdo,palo.central,palo.derecho); } }
String columnas[] = new String[2]; columnas[0] = id; columnas[1] = etiqueta; combo.addItem (columnas);Con esto nos guardará la información que necesitemos. Y con este otro nos mostrará tan solo lo que nosotros querramos.
combo.setRenderer (new DefaultListCellRenderer() { public java.awt.Component getListCellRendererComponent ( JList l,Object o,int i,boolean s, boolean f) { return new JLabel (((String[])o)[1]); } });
public final int Consecutivo(ConexionSGDB connDB, String NombreTabla, String Campo, String Condicion, MensajesError ME){ String NombreMetodo = "Consecutivo(ConexionSGDB connDB, String Condicion, MensajesError ME)"; Vector v = new Vector(); java.sql.ResultSet rs = null; String query = ""; int Consec = 0; try { query = " select ifnull(max(" +Campo +"), 0) + 1 as Consecutivo from " +NombreTabla +" " + Condicion ; System.out.println(query); rs = connDB.ejecutaConsulta(query); if (rs!=null) { while(rs.next()){ Consec = rs.getInt("Consecutivo"); } } } catch (Exception e){ System.out.println ("Utilerias - Consecutivo"); System.out.println ("Error: "+e.toString()); ME.setError( 1 , STR_CLASE , NombreMetodo, "Error al consultar el Consecutivo de la tabla x."); } return (Consec); }
<x:out select="$usuarios/usuario[nombre=$param:nombre]"/>En este ejemplo se accedería al parámetro "nombre" pasado al jsp.
$foo $param: $header: $cookie: $initParam: $pageScope: $requestScope: $sessionScope: $applicationScope:
import java.security.*; import javax.crypto.*; import javax.crypto.interfaces.*; import javax.crypto.spec.*; import java.io.*; public class EjemploDES { /* Ejemplo de uso de funciones de resumen Hash * carga el fichero que recibe como parametro y genera el resumen */ public static void main (String[] args) throws Exception { // Comprobar argumentos if (args.length !=1) { mensajeAyuda(); System.exit(1); } /* Cargar "provider" (sólo si no se usa el que viene por defecto) */ // Security.addProvider(new BouncyCastleProvider()); // Usa provider BC // /* PASO 1: Crear e inicializar clave */ KeyGenerator keyGen = KeyGenerator.getInstance("DES"); keyGen.init(56); SecretKey clave = keyGen.generateKey(); System.out.println("CLAVE:" + new String(clave.getEncoded()) + "\n"); /* PASO 2: Crear cifrador */ Cipher cifrador= Cipher.getInstance("DES/ECB/PKCS5Padding"); // Algoritmo DES // Modo : ECB (Electronic Code Book) // Relleno : PKCS5Padding // /* PASO 3a: Inicializar cifrador en modo CIFRADO */ cifrador.init(Cipher.ENCRYPT_MODE, clave); /* Leer fichero de 1k en 1k y pasar fragmentos leidos al cifrador */ byte[] bufferPlano = new byte[1000]; byte[] bufferCifrado; String textoCifradoTotal = new String(); FileInputStream in = new FileInputStream(args[0]); int bytesLeidos = in.read(bufferPlano,0, 1000); while(bytesLeidos != -1) { // Mientras no se llegue al final del fichero bufferCifrado = cifrador.update(bufferPlano, 0 , bytesLeidos); // Pasa texto claro leido al cifrador textoCifradoTotal = textoCifradoTotal + new String(bufferCifrado); // Acumular texto cifrado bytesLeidos = in.read(bufferPlano,0, 1000); } in.close(); bufferCifrado = cifrador.doFinal(); // Completar cifrado (puede devolver texto) textoCifradoTotal = textoCifradoTotal + new String(bufferCifrado); System.out.println("--------------- TEXTO CIFRADO ---------------"); System.out.println(textoCifradoTotal); // Mostrar texto cifrado System.out.println("---------------------------------------------"); System.out.println("--------------- TEXTO DESCIFRADO -------------"); /* PASO 3b: Poner cifrador en modo DESCIFRADO */ cifrador.init(Cipher.DECRYPT_MODE, clave); byte[] textoDescifrado = cifrador.update(textoCifradoTotal.getBytes()); // Pasar texto al descifrador System.out.print( new String(textoDescifrado) ); textoDescifrado = cifrador.doFinal(); // Completar descifrado (puede devolver texto) System.out.print( new String(textoDescifrado) ); System.out.println("----------------------------------------------"); } public static void mensajeAyuda() { System.out.println("Ejemplo cifrado DES"); System.out.println("\tSintaxis: java EjemploDES fichero"); System.out.println(); } }
// Codigo para leer la salida standard try { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String str = ""; while (str != null) { System.out.print("> prompt "); str = in.readLine(); process(str); } } catch (IOException e) { //Excepciones capturadas }
public void cargarSkin(String nombreFichero){ URL url = null; try{ url = SkinUtils.toURL(new File(nombreFichero)); SkinLookAndFeel.setSkin(SkinLookAndFeel.loadThemePack(url)); SkinLookAndFeel.enable(); }catch(Exception ex){ System.out.println("Error recogiendo skin : " + url); } SwingUtilities.updateComponentTreeUI(this); this.pack(); }Trozo de código para cargar una apariencia a partir de las clases de java.
try{ // CUALQUIERA DE ESTOS TRES MODELOS PUEDE SER CARGADO. ASTERISCAR LOS QUE NO // QUERAMOS HACERLOS VISUALES UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); //UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); SwingUtilities.updateComponentTreeUI(this); this.pack(); }catch(Exception error){ System.out.println("Error: " + error); }