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



No hay comentarios: