Mostrando entradas con la etiqueta Util. Mostrar todas las entradas
Mostrando entradas con la etiqueta Util. 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;
}



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");
      }

  }

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());">