Mostrando entradas con la etiqueta Java. Mostrar todas las entradas
Mostrando entradas con la etiqueta Java. Mostrar todas las entradas

miércoles, 11 de diciembre de 2013

METODOS UTILES JAVA

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JComboBox;

import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.Months;
import org.joda.time.Years;

private final static String patron = "dd/MM/yyyy";
 private final static String patronFechaISO = "yyyy-MM-dd";

/*************
Con estos metodos utiles se podrá calcular la edad, la antiguedad, verificar si un objeto en particular es nulo, convertir las fechas, etc.
********************************************/
/**************** OBTENER EL AÑO ACTUAL *****************/
public static String getAnioActual() {
Calendar c = Calendar.getInstance();
return Integer.toString(c.get(Calendar.YEAR));
}

/****  OBTENER UNA FECHA DATE A STRING  *****/
public static final String getDateTime(String aMask, Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";

if (aDate == null) {
//Pintar Error
} else {
df = new SimpleDateFormat(aMask);
returnValue = df.format(aDate);
}
return (returnValue);
}

/*  OBTENER UNA FECHA STRING A DATE ******/
public static Date convertStringToDate(String val) {
SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
Date fecha = null;
try {
fecha = dateFormat.parse(val);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fecha;
}



/*** Calcular EDAD mediante una fecha de la clase DATE ****/
/* Se debe descargar la libreria
                 
                   joda-time
                   joda-time
                    2.3                
                   
                              
*/
public static int calcularEdad(Date fecNac) {
        if (!esNuloOVacio(fecNac)) {
            DateMidnight birthdate = new DateMidnight(fecNac.getTime());
            Years y = Years.yearsBetween(birthdate, new DateTime());
            return y.getYears();
        }
        return 0;
 }

/*** Calcular la antiguedad de un trabajador(en años y meses)  mediante una fecha de la clase DATE ****/
public static String calcularAntiguedad(Date fecIng) {
        String antiguedad = "";
        if (!esNuloOVacio(fecIng)) {
            DateMidnight fecIngreso = new DateMidnight(fecIng.getTime());
            Months m = Months.monthsBetween(fecIngreso, new DateTime());
            int meses = m.getMonths();
            Years y = Years.yearsBetween(fecIngreso, new DateTime());
            if (y.getYears() == 1) {
                antiguedad = y.getYears() + " año ";
            } else if (y.getYears() > 1) {
                antiguedad = y.getYears() + " años ";
            }
            meses = meses - 12 * y.getYears();
            if (meses == 1) {
                antiguedad += meses + " mes ";
            } else if (meses > 1) {
                antiguedad += meses + " meses ";
            }
        }
        return antiguedad;
 }

/**** Validar si un objeto de clase Object, String, Collection, Integer, Long es nulo o vacio **********/
public static boolean esNuloOVacio(Object objeto) {
boolean esNuloOVacio = false;
if (objeto == null) {
esNuloOVacio = true;
} else if(objeto instanceof Collection){
Collection listado = (Collection)objeto;
if(listado.isEmpty()){
esNuloOVacio=true;
}
}else if (objeto instanceof String) {
String cadena = (String) objeto;
if (cadena.trim().length() == 0) {
esNuloOVacio = true;
}
}else if(objeto instanceof Integer){
Integer entero = (Integer) objeto;
if(entero==0){
esNuloOVacio=true;
}
}else if(objeto instanceof Long){
Long largo = (Long) objeto;
if(largo==0){
esNuloOVacio=true;
}
}
return esNuloOVacio;
}

/*** Quitar los espacios en una cadena de texto ****/
public static String valorSinEspacios(String value) {
        return esNuloOVacio(value) ? value : value.trim();
}

/**** Convertir un objeto Set a un listado **********/
public static List convertToList(Set value){
return Lists.newArrayList(value);
}

/**** Convertir un arreglo de objetos a un Set **********/
public static Set convertArrayToSet(Object[] objetos) {
Set set=new HashSet();
for (Object object : objetos) {
set.add(object);
}
return set;
}

/**** Validar el correo electronico mediante Expresiones Regulares **********/
public static boolean esFormatoCorreo(String email) {
Pattern p = Pattern.compile("[-\\w\\.]+@\\w+\\.\\w+");
Matcher m = p.matcher(email);
return m.matches();
}

/**** Validar si es un valor numerico entero entero **********/
public static boolean esValorNumericoEntero(String val) {
Pattern p = Pattern.compile("[0-9]*");
Matcher m = p.matcher(val);
return m.matches();
}

/**** Validar si es un valor Alfa Numerico **********/
public static boolean esValorAlfaNumerico(String val) {
Pattern p = Pattern.compile("[A-Za-z0-9]*");
Matcher m = p.matcher(val);
return m.matches();
}

/**** Validar si es un valor del Alfabeto **********/
public static boolean esValorAlfabetico(String val) {
Pattern p = Pattern.compile("[A-Za-z]*");
Matcher m = p.matcher(val);
return m.matches();
}

/**** Validar si es un valor DNI **********/
public static boolean esValordeRuc(String val) {
Pattern p = Pattern.compile("\\d{11}");
Matcher m = p.matcher(val);
return m.matches();
}

/**** Validar si es un valor RUC **********/
public static boolean esValordeDNI(String val) {
Pattern p = Pattern.compile("\\d{8}");
Matcher m = p.matcher(val);
return m.matches();
}

/**** Convertir una cadena a long  **********/
public static long convertLong(String val) {
try{
return Long.parseLong(val);
}catch(Exception e){
return 0;
}
}
/**** Convertir una cadena a int  **********/
public static int convertInt(String val) {
try{
return Integer.parseInt(val);
}catch(Exception e){
return 0;
}
}
/**** Si el primer valor retorna el segundo parametro enviado  **********/
public static Object siPrimeroEsNuloRetornaSegundo(Object primerValor, Object segundoValor) {
Object value = primerValor;
if(esNuloOVacio(value)){
value = segundoValor;
}
return value;
}



viernes, 20 de marzo de 2009

Enviando correos desde JAVA..


A continuación un mini proyecto de como Enviar correos Electronicos:
Mediante una interfaz de Escritorio.

Que hemos usado?:
Debe de contar con un servidor de correo..
mail.jar
correo.jar
postgres... jar

JFileChooser para extraer los contactos desde un archivo XML o una BD,o un archivo Excel..
depende de _Ud que funcion desee usar.
Acceso a base de datos postgress.
Acceso a archivos Excel..
Acceso a archivos XML..




miércoles, 11 de marzo de 2009

Manejo de Archivos en JAVA

Aqui encontramos dos funciones genericas
que permiten realizar la funcionalidades siguientes:



public static String recuperar_entrada(
          File file) {
      String cadena = "";
      InputStream is = null;
      try {
          is = new FileInputStream(file);
      } catch (FileNotFoundException ex) {
          System.out.println("Archivo no encontrado");
      }

      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);

      String part;

      try {
          part = br.readLine();

          while (part != null) {
              cadena = cadena + part + "\n";
              part =
                      br.readLine();
          }


      } catch (IOException ex) {
          System.out.println("Error en I/O");
      }


      return cadena;
  }
  public static void escribir_archivo(File archivo,String cadena) {
      FileWriter fw;
      try {
          fw = new FileWriter(archivo);
          BufferedWriter bw = new BufferedWriter(fw);
          PrintWriter escribir = new PrintWriter(bw);
          escribir.println(cadena);

          escribir.flush();
          if (escribir != null) {
              escribir.close();
          }
          System.out.println("Ingreso correctamente");
      } catch (IOException ex) {
         System.out.println("Error en I/O");
      }

  }

sábado, 7 de marzo de 2009

Exportar datos de una tabla a un archivo XML

Codigo Fuente: link_descargable
Clases: Sistemas UNI
Auth: Nilton Joaquin
usando JDOM

Pasos:
1. Crear una Pantalla en un formulario, luego crear un Boton:


New JFrame o new JDialog

3. Instanciar un Objeto JFileChooser.





4. LLamar a una funcion que obtenga el listado de los valores a migrar al Archivo XML



5. Asignar la ruta con el FileChooser, y guardarlo en la PC.







jueves, 26 de febrero de 2009

Adjuntando Archivos (Imagenes) Ejemplo


Muchas Veces hemos querido adjuntar archivos mediante JAVA.
A continuación explico el codigo para llevarlo a cabo.

Si usted usa Netbeans este codigo se resuce por los eventos.

Codigo1: Dentro del evento del boton, hacer lo siguiente.

JFileChooser fc = new JFileChooser();

fc.addChoosableFileFilter(new ImageFilter());
fc.setFileView(new ImageFileView());
JComponent jcom = new visual.ImagePreview(fc);
fc.setAccessory(jcom);

int returnVal = fc.showDialog(this,
"Adjuntar");

if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
log.append("Attaching file: " + file.getName() + "." + newline);
} else {
log.append("Attachment cancelled by user." + newline);
}


Codigo2:

import java.io.File;
import javax.swing.filechooser.FileFilter;
public class ImageFilter extends FileFilter {

//Accept all directories and all gif, jpg, tiff, or png files.
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}

String extension = Utils.getExtension(f);
if (extension != null) {
if (extension.equals(Utils.tiff) ||
extension.equals(Utils.tif) ||
extension.equals(Utils.gif) ||
extension.equals(Utils.jpeg) ||
extension.equals(Utils.jpg) ||
extension.equals(Utils.png)) {
return true;
} else {
return false;
}
}

return false;
}

//The description of this filter
public String getDescription() {
return "Solo Images";
}
}

Codigo3:
import java.io.File;

/**
*
* @author njoaquin
*/
public class Utils {

static String tiff = "tiff";
static String tif = "tif";
static String gif = "gif";
static String jpg = "jpg";
static String png = "png";
static String jpeg = "jpeg";

static String getExtension(File f) {
String no_archiv=f.getName().trim();
int indice=no_archiv.indexOf(".");
String sub=no_archiv.substring(indice+1);

return sub;
}
}

Codigo4:
ImagePreview
Al final Quedara asi:

martes, 24 de febrero de 2009

JTable en JAVA


IDE usado : Netbeans
Para incrustar este codigo debes crear una JTable con su respectivo Scroll.
luego en la vista de diseño ---> click derecho ---> Customize code --> Ahi colocaras el codigo de abajo.


Estuve buscando en la internet codigo en JAVA que me permita darle una medida a las columnas de un JTable despues de investigar un poco encontre esta solucioón espero que les sea de mucha utilidad como para lo es en este momento.
tblProgramar = new javax.swing.JTable();

tblProgramar.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {

},
new String [] {
"Curso", "Docente", "Horario", "Vacantes"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};

public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}

public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
TableColumnModel dd = tblProgramar.getColumnModel();
TableColumn col;
col = dd.getColumn(0);
col.setMaxWidth(25);
col.setMinWidth(25);

col = dd.getColumn(1);
col.setMaxWidth(50);
col.setMinWidth(50);

col = dd.getColumn(2);
col.setMaxWidth(100);
col.setMinWidth(100);

col = dd.getColumn(3);
col.setMaxWidth(200);
col.setMinWidth(200);
tblProgramar.setColumnModel(dd);
jScrollPane2.setViewportView(tblProgramar);
Al final quedará algo como esto:

martes, 17 de febrero de 2009

Instalar JAVA con Eclipse y Tomcat 6.

1. Descargar JAVA de: JAVA
Escoges el sistema Operativo

2. Dar Permisos al archivo .bin(Linux) chmod 777, luego ejecutar en la consola de Linux
./Nombre_Archivo.bin
y presionar Enter hasta darle yes or No

3. Una vez instalado el java escribir los sgte:
javac -version.
Instalamos el tomcat: Descargar: Apache Tomcat

Descomprimes y Copias la carpeta en una ubicación: por ejemplo /home/mi_usuario/

4. Editamos el archivo /home/mi_usuario/carpeta_apache_tomcat/bin/catalina.sh,
previamente le damos un chmod 777 al archivo por configurar.

Dentro del contenido del archivo Escribimos
JAVA_HOME = Ruta_JAVA/ (Sin comillas)CATALINA_HOME = Ruta_TOMCAT/ (Sin comillas)
5. Arrancamos el Tomcat: Ruta_TOMCAT/bin/startup.sh
6. Probamos en el explorador: http://localhost:8080/

7. Seguidamente instalamos el Eclipse Europa JEE.
ECLIPSE_EUROPA

Descomprimimos y copiamos en una carpeta, por ejemplo:
   /home/mi_usuario/instaladores/

8. Dentro de la carpeta del eclipse existe un archivo eclipse,
ejecutamos este e ingresamos al IDE.
Nos pedira una ubicación para el Workspace, ubicación donde se alojara todos los proyectos.

9. Configuramos : El servidor Tomcat 6
Opcion: Servers -> Add Server - >Escogemos Tomcat 6-> asifnamos la ubicación del JRE.
Creamos un proyecto Web en Blanco , creamos una pagina index.jsp con algun contenido
dentro de la carpeta "WebContent" y probamos.

miércoles, 11 de febrero de 2009

Gestion y manejo de Excel en JAVA

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import dao.DBConnection;
import dao.Referi;

public class LeerExcel {
String path;

public LeerExcel() {
// TODO Auto-generated constructor stub
}
public LeerExcel(String path) {
// TODO Auto-generated constructor stub
this.path=path;
}

public void Leer(){
HSSF1 hf=new HSSF1();
HSSFWorkbook w= hf.getWorkbook(this.path);

HSSFSheet hoja = w.getSheetAt(0);

// Se crea una fila dentro de la hoja
HSSFRow fila;

// Se crea una celda dentro de la fila
HSSFCell celda;
Referi referi;
String no_valora="";
for(int i=1;i<127 i="">");
fila = hoja.getRow(i);
referi=new Referi();
for(short j=0;j<8 celda=" fila.getCell(j);" estado=" false;" j="" no_valora=" String.valueOf(celda.getNumericCellValue());">