quinta-feira, 26 de novembro de 2020

DateUtil

 

Ref: https://balusc.omnifaces.org/2007/09/dateutil.html

DateUtil

Useful date utilities

An utility class with some fairly simple methods and some very useful methods (such as determineDateFormat()). This utility class partly wraps the CalendarUtil so that it can be used with Date and String objects.

The determineDateFormat() method supports the most commonly used date formats. You can always change or extend it to your taste, but take care that there should be no overlap in regexp patterns! Otherwise you'd like to use LinkedHashMap instead so that the regexps will be tested in the order as they've been put in the map, so that you can arrange the match preference.

package net.balusc.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TimeZone;

/**
 * Useful Date utilities.
 *
 * @author BalusC
 * @see CalendarUtil
 * @link http://balusc.omnifaces.org/2007/09/dateutil.html
 */
public final class DateUtil {

    // Init ---------------------------------------------------------------------------------------

    private static final Map<String, String> DATE_FORMAT_REGEXPS = new HashMap<String, String>() {{
        put("^\\d{8}$", "yyyyMMdd");
        put("^\\d{1,2}-\\d{1,2}-\\d{4}$", "dd-MM-yyyy");
        put("^\\d{4}-\\d{1,2}-\\d{1,2}$", "yyyy-MM-dd");
        put("^\\d{1,2}/\\d{1,2}/\\d{4}$", "MM/dd/yyyy");
        put("^\\d{4}/\\d{1,2}/\\d{1,2}$", "yyyy/MM/dd");
        put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}$", "dd MMM yyyy");
        put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}$", "dd MMMM yyyy");
        put("^\\d{12}$", "yyyyMMddHHmm");
        put("^\\d{8}\\s\\d{4}$", "yyyyMMdd HHmm");
        put("^\\d{1,2}-\\d{1,2}-\\d{4}\\s\\d{1,2}:\\d{2}$", "dd-MM-yyyy HH:mm");
        put("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{2}$", "yyyy-MM-dd HH:mm");
        put("^\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}:\\d{2}$", "MM/dd/yyyy HH:mm");
        put("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{2}$", "yyyy/MM/dd HH:mm");
        put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}\\s\\d{1,2}:\\d{2}$", "dd MMM yyyy HH:mm");
        put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}\\s\\d{1,2}:\\d{2}$", "dd MMMM yyyy HH:mm");
        put("^\\d{14}$", "yyyyMMddHHmmss");
        put("^\\d{8}\\s\\d{6}$", "yyyyMMdd HHmmss");
        put("^\\d{1,2}-\\d{1,2}-\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd-MM-yyyy HH:mm:ss");
        put("^\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{2}:\\d{2}$", "yyyy-MM-dd HH:mm:ss");
        put("^\\d{1,2}/\\d{1,2}/\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "MM/dd/yyyy HH:mm:ss");
        put("^\\d{4}/\\d{1,2}/\\d{1,2}\\s\\d{1,2}:\\d{2}:\\d{2}$", "yyyy/MM/dd HH:mm:ss");
        put("^\\d{1,2}\\s[a-z]{3}\\s\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd MMM yyyy HH:mm:ss");
        put("^\\d{1,2}\\s[a-z]{4,}\\s\\d{4}\\s\\d{1,2}:\\d{2}:\\d{2}$", "dd MMMM yyyy HH:mm:ss");
    }};

    private DateUtil() {
        // Utility class, hide the constructor.
    }

    // Converters ---------------------------------------------------------------------------------

    /**
     * Convert the given date to a Calendar object. The TimeZone will be derived from the local
     * operating system's timezone.
     * @param date The date to be converted to Calendar.
     * @return The Calendar object set to the given date and using the local timezone.
     */
    public static Calendar toCalendar(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.setTime(date);
        return calendar;
    }

    /**
     * Convert the given date to a Calendar object with the given timezone.
     * @param date The date to be converted to Calendar.
     * @param timeZone The timezone to be set in the Calendar.
     * @return The Calendar object set to the given date and timezone.
     */
    public static Calendar toCalendar(Date date, TimeZone timeZone) {
        Calendar calendar = toCalendar(date);
        calendar.setTimeZone(timeZone);
        return calendar;
    }

    /**
     * Parse the given date string to date object and return a date instance based on the given
     * date string. This makes use of the {@link DateUtil#determineDateFormat(String)} to determine
     * the SimpleDateFormat pattern to be used for parsing.
     * @param dateString The date string to be parsed to date object.
     * @return The parsed date object.
     * @throws ParseException If the date format pattern of the given date string is unknown, or if
     * the given date string or its actual date is invalid based on the date format pattern.
     */
    public static Date parse(String dateString) throws ParseException {
        String dateFormat = determineDateFormat(dateString);
        if (dateFormat == null) {
            throw new ParseException("Unknown date format.", 0);
        }
        return parse(dateString, dateFormat);
    }

    /**
     * Validate the actual date of the given date string based on the given date format pattern and
     * return a date instance based on the given date string.
     * @param dateString The date string.
     * @param dateFormat The date format pattern which should respect the SimpleDateFormat rules.
     * @return The parsed date object.
     * @throws ParseException If the given date string or its actual date is invalid based on the
     * given date format pattern.
     * @see SimpleDateFormat
     */
    public static Date parse(String dateString, String dateFormat) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat);
        simpleDateFormat.setLenient(false); // Don't automatically convert invalid date.
        return simpleDateFormat.parse(dateString);
    }

    // Validators ---------------------------------------------------------------------------------

    /**
     * Checks whether the actual date of the given date string is valid. This makes use of the
     * {@link DateUtil#determineDateFormat(String)} to determine the SimpleDateFormat pattern to be
     * used for parsing.
     * @param dateString The date string.
     * @return True if the actual date of the given date string is valid.
     */
    public static boolean isValidDate(String dateString) {
        try {
            parse(dateString);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    /**
     * Checks whether the actual date of the given date string is valid based on the given date
     * format pattern.
     * @param dateString The date string.
     * @param dateFormat The date format pattern which should respect the SimpleDateFormat rules.
     * @return True if the actual date of the given date string is valid based on the given date
     * format pattern.
     * @see SimpleDateFormat
     */
    public static boolean isValidDate(String dateString, String dateFormat) {
        try {
            parse(dateString, dateFormat);
            return true;
        } catch (ParseException e) {
            return false;
        }
    }

    // Checkers -----------------------------------------------------------------------------------

    /**
     * Determine SimpleDateFormat pattern matching with the given date string. Returns null if
     * format is unknown. You can simply extend DateUtil with more formats if needed.
     * @param dateString The date string to determine the SimpleDateFormat pattern for.
     * @return The matching SimpleDateFormat pattern, or null if format is unknown.
     * @see SimpleDateFormat
     */
    public static String determineDateFormat(String dateString) {
        for (String regexp : DATE_FORMAT_REGEXPS.keySet()) {
            if (dateString.toLowerCase().matches(regexp)) {
                return DATE_FORMAT_REGEXPS.get(regexp);
            }
        }
        return null; // Unknown format.
    }

    // Changers -----------------------------------------------------------------------------------

    /**
     * Add the given amount of years to the given date. It actually converts the date to Calendar
     * and calls {@link CalendarUtil#addYears(Calendar, int)} and then converts back to date.
     * @param date The date to add the given amount of years to.
     * @param years The amount of years to be added to the given date. Negative values are also
     * allowed, it will just go back in time.
     */
    public static Date addYears(Date date, int years) {
        Calendar calendar = toCalendar(date);
        CalendarUtil.addYears(calendar, years);
        return calendar.getTime();
    }

    /**
     * Add the given amount of months to the given date. It actually converts the date to Calendar
     * and calls {@link CalendarUtil#addMonths(Calendar, int)} and then converts back to date.
     * @param date The date to add the given amount of months to.
     * @param months The amount of months to be added to the given date. Negative values are also
     * allowed, it will just go back in time.
     */
    public static Date addMonths(Date date, int months) {
        Calendar calendar = toCalendar(date);
        CalendarUtil.addMonths(calendar, months);
        return calendar.getTime();
    }

    /**
     * Add the given amount of days to the given date. It actually converts the date to Calendar and
     * calls {@link CalendarUtil#addDays(Calendar, int)} and then converts back to date.
     * @param date The date to add the given amount of days to.
     * @param days The amount of days to be added to the given date. Negative values are also
     * allowed, it will just go back in time.
     */
    public static Date addDays(Date date, int days) {
        Calendar calendar = toCalendar(date);
        CalendarUtil.addDays(calendar, days);
        return calendar.getTime();
    }

    /**
     * Add the given amount of hours to the given date. It actually converts the date to Calendar
     * and calls {@link CalendarUtil#addHours(Calendar, int)} and then converts back to date.
     * @param date The date to add the given amount of hours to.
     * @param hours The amount of hours to be added to the given date. Negative values are also
     * allowed, it will just go back in time.
     */
    public static Date addHours(Date date, int hours) {
        Calendar calendar = toCalendar(date);
        CalendarUtil.addHours(calendar, hours);
        return calendar.getTime();
    }

    /**
     * Add the given amount of minutes to the given date. It actually converts the date to Calendar
     * and calls {@link CalendarUtil#addMinutes(Calendar, int)} and then converts back to date.
     * @param date The date to add the given amount of minutes to.
     * @param minutes The amount of minutes to be added to the given date. Negative values are also
     * allowed, it will just go back in time.
     */
    public static Date addMinutes(Date date, int minutes) {
        Calendar calendar = toCalendar(date);
        CalendarUtil.addMinutes(calendar, minutes);
        return calendar.getTime();
    }

    /**
     * Add the given amount of seconds to the given date. It actually converts the date to Calendar
     * and calls {@link CalendarUtil#addSeconds(Calendar, int)} and then converts back to date.
     * @param date The date to add the given amount of seconds to.
     * @param seconds The amount of seconds to be added to the given date. Negative values are also
     * allowed, it will just go back in time.
     */
    public static Date addSeconds(Date date, int seconds) {
        Calendar calendar = toCalendar(date);
        CalendarUtil.addSeconds(calendar, seconds);
        return calendar.getTime();
    }

    /**
     * Add the given amount of millis to the given date. It actually converts the date to Calendar
     * and calls {@link CalendarUtil#addMillis(Calendar, int)} and then converts back to date.
     * @param date The date to add the given amount of millis to.
     * @param millis The amount of millis to be added to the given date. Negative values are also
     * allowed, it will just go back in time.
     */
    public static Date addMillis(Date date, int millis) {
        Calendar calendar = toCalendar(date);
        CalendarUtil.addMillis(calendar, millis);
        return calendar.getTime();
    }

    // Comparators --------------------------------------------------------------------------------

    /**
     * Returns <tt>true</tt> if the two given dates are dated on the same year. It actually
     * converts the both dates to Calendar and calls
     * {@link CalendarUtil#sameYear(Calendar, Calendar)}.
     * @param one The one date.
     * @param two The other date.
     * @return True if the two given dates are dated on the same year.
     * @see CalendarUtil#sameYear(Calendar, Calendar)
     */
    public static boolean sameYear(Date one, Date two) {
        return CalendarUtil.sameYear(toCalendar(one), toCalendar(two));
    }

    /**
     * Returns <tt>true</tt> if the two given dates are dated on the same year and month. It
     * actually converts the both dates to Calendar and calls
     * {@link CalendarUtil#sameMonth(Calendar, Calendar)}.
     * @param one The one date.
     * @param two The other date.
     * @return True if the two given dates are dated on the same year and month.
     * @see CalendarUtil#sameMonth(Calendar, Calendar)
     */
    public static boolean sameMonth(Date one, Date two) {
        return CalendarUtil.sameMonth(toCalendar(one), toCalendar(two));
    }

    /**
     * Returns <tt>true</tt> if the two given dates are dated on the same year, month and day. It
     * actually converts the both dates to Calendar and calls
     * {@link CalendarUtil#sameDay(Calendar, Calendar)}.
     * @param one The one date.
     * @param two The other date.
     * @return True if the two given dates are dated on the same year, month and day.
     * @see CalendarUtil#sameDay(Calendar, Calendar)
     */
    public static boolean sameDay(Date one, Date two) {
        return CalendarUtil.sameDay(toCalendar(one), toCalendar(two));
    }

    /**
     * Returns <tt>true</tt> if the two given dates are dated on the same year, month, day and
     * hour. It actually converts the both dates to Calendar and calls
     * {@link CalendarUtil#sameHour(Calendar, Calendar)}.
     * @param one The one date.
     * @param two The other date.
     * @return True if the two given dates are dated on the same year, month, day and hour.
     * @see CalendarUtil#sameHour(Calendar, Calendar)
     */
    public static boolean sameHour(Date one, Date two) {
        return CalendarUtil.sameHour(toCalendar(one), toCalendar(two));
    }

    /**
     * Returns <tt>true</tt> if the two given dates are dated on the same year, month, day, hour
     * and minute. It actually converts the both dates to Calendar and calls
     * {@link CalendarUtil#sameMinute(Calendar, Calendar)}.
     * @param one The one date.
     * @param two The other date.
     * @return True if the two given dates are dated on the same year, month, day, hour and minute.
     * @see CalendarUtil#sameMinute(Calendar, Calendar)
     */
    public static boolean sameMinute(Date one, Date two) {
        return CalendarUtil.sameMinute(toCalendar(one), toCalendar(two));
    }

    /**
     * Returns <tt>true</tt> if the two given dates are dated on the same year, month, day, hour,
     * minute and second. It actually converts the both dates to Calendar and calls
     * {@link CalendarUtil#sameSecond(Calendar, Calendar)}.
     * @param one The one date.
     * @param two The other date.
     * @return True if the two given dates are dated on the same year, month, day, hour, minute and
     * second.
     * @see CalendarUtil#sameSecond(Calendar, Calendar)
     */
    public static boolean sameSecond(Date one, Date two) {
        return CalendarUtil.sameSecond(toCalendar(one), toCalendar(two));
    }

    // Calculators --------------------------------------------------------------------------------

    /**
     * Retrieve the amount of elapsed years between the two given dates. It actually converts the
     * both dates to Calendar and calls {@link CalendarUtil#elapsedYears(Calendar, Calendar)}.
     * @param before The first date with expected date before the second date.
     * @param after The second date with expected date after the first date.
     * @return The amount of elapsed years between the two given dates
     * @throws IllegalArgumentException If the first date is dated after the second date.
     * @see CalendarUtil#elapsedYears(Calendar, Calendar)
     */
    public static int elapsedYears(Date before, Date after) {
        return CalendarUtil.elapsedYears(toCalendar(before), toCalendar(after));
    }

    /**
     * Retrieve the amount of elapsed months between the two given dates. It actually converts the
     * both dates to Calendar and calls {@link CalendarUtil#elapsedMonths(Calendar, Calendar)}.
     * @param before The first date with expected date before the second date.
     * @param after The second date with expected date after the first date.
     * @return The amount of elapsed months between the two given dates.
     * @throws IllegalArgumentException If the first date is dated after the second date.
     * @see CalendarUtil#elapsedMonths(Calendar, Calendar)
     */
    public static int elapsedMonths(Date before, Date after) {
        return CalendarUtil.elapsedMonths(toCalendar(before), toCalendar(after));
    }

    /**
     * Retrieve the amount of elapsed days between the two given dates. It actually converts the
     * both dates to Calendar and calls {@link CalendarUtil#elapsedDays(Calendar, Calendar)}.
     * @param before The first date with expected date before the second date.
     * @param after The second date with expected date after the first date.
     * @return The amount of elapsed days between the two given dates.
     * @throws IllegalArgumentException If the first date is dated after the second date.
     * @see CalendarUtil#elapsedDays(Calendar, Calendar)
     */
    public static int elapsedDays(Date before, Date after) {
        return CalendarUtil.elapsedDays(toCalendar(before), toCalendar(after));
    }

    /**
     * Retrieve the amount of elapsed hours between the two given dates. It actually converts the
     * both dates to Calendar and calls {@link CalendarUtil#elapsedHours(Calendar, Calendar)}.
     * @param before The first date with expected date before the second date.
     * @param after The second date with expected date after the first date.
     * @return The amount of elapsed hours between the two given dates.
     * @throws IllegalArgumentException If the first date is dated after the second date.
     * @see CalendarUtil#elapsedHours(Calendar, Calendar)
     */
    public static int elapsedHours(Date before, Date after) {
        return CalendarUtil.elapsedHours(toCalendar(before), toCalendar(after));
    }

    /**
     * Retrieve the amount of elapsed minutes between the two given dates. It actually converts the
     * both dates to Calendar and calls {@link CalendarUtil#elapsedMinutes(Calendar, Calendar)}.
     * @param before The first date with expected date before the second date.
     * @param after The second date with expected date after the first date.
     * @return The amount of elapsed minutes between the two given dates.
     * @throws IllegalArgumentException If the first date is dated after the second date.
     * @see CalendarUtil#elapsedMinutes(Calendar, Calendar)
     */
    public static int elapsedMinutes(Date before, Date after) {
        return CalendarUtil.elapsedMinutes(toCalendar(before), toCalendar(after));
    }

    /**
     * Retrieve the amount of elapsed seconds between the two given dates. It actually converts the
     * both dates to Calendar and calls {@link CalendarUtil#elapsedSeconds(Calendar, Calendar)}.
     * @param before The first date with expected date before the second date.
     * @param after The second date with expected date after the first date.
     * @return The amount of elapsed seconds between the two given dates.
     * @throws IllegalArgumentException If the first date is dated after the second date.
     * @see CalendarUtil#elapsedSeconds(Calendar, Calendar)
     */
    public static int elapsedSeconds(Date before, Date after) {
        return CalendarUtil.elapsedSeconds(toCalendar(before), toCalendar(after));
    }

    /**
     * Retrieve the amount of elapsed milliseconds between the two given dates. It actually converts
     * the both dates to Calendar and calls {@link CalendarUtil#elapsedMillis(Calendar, Calendar)}.
     * @param before The first date with expected date before the second date.
     * @param after The second date with expected date after the first date.
     * @return The amount of elapsed milliseconds between the two given dates.
     * @throws IllegalArgumentException If the first date is dated after the second date.
     * @see CalendarUtil#elapsedMillis(Calendar, Calendar)
     */
    public static long elapsedMillis(Date before, Date after) {
        return CalendarUtil.elapsedMillis(toCalendar(before), toCalendar(after));
    }

    /**
     * Calculate the total of elapsed time from years up to seconds between the two given dates. It
     * Returns an int array with the elapsed years, months, days, hours, minutes and seconds
     * respectively. It actually converts the both dates to Calendar and calls
     * {@link CalendarUtil#elapsedTime(Calendar, Calendar)}.
     * @param before The first date with expected date before the second date.
     * @param after The second date with expected date after the first date.
     * @return The elapsed time between the two given dates in years, months, days, hours, minutes
     * and seconds.
     * @throws IllegalArgumentException If the first date is dated after the second date.
     * @see CalendarUtil#elapsedTime(Calendar, Calendar)
     */
    public static int[] elapsedTime(Date before, Date after) {
        return CalendarUtil.elapsedTime(toCalendar(before), toCalendar(after));
    }

}

terça-feira, 30 de outubro de 2018

JSP hot-deploy in Jboss / Wildfly


To enable hot-deploy of JSPs in Wildfly, i.e. to automatically publish any changes to JSPs in ${WILDFLY_ROOT}/standalone/tmp/vfs/temp/tempxxxxxxx/content-xxxxxxx without requiring redeployment of war, set the development attribute of jsp-config within undertow subsystem to true as below:
<subsystem xmlns=”urn:jboss:domain:undertow:3.0″>
<servlet-container name=”default” default-encoding=”UTF-8″>
        <jsp-config development=”true” tag-pooling=”false”/>        <websockets/>
</servlet-container>

Ref: https://ohioedge.com/2018/01/31/jsp-hot-deploy-in-wildfly/

sexta-feira, 26 de outubro de 2018

Recursively display all 'csv' files in a list of directories


private static final String CONST_SUFFIX = "csv";
....
//method
for (String directoryPath : folders) {
if (Paths.get(directoryPath).toFile().isDirectory()) {
Files.list(Paths.get(directoryPath)).filter(Files::isRegularFile).forEach(path -> {
if(path.endsWith(CONST_SUFFIX) || path.toString().toLowerCase().endsWith(CONST_SUFFIX)){
System.out.println(path.getFileName());
}
});
}
}

segunda-feira, 22 de outubro de 2018

How to call the same methods from difference classes

public class Teste1 {

public String valor1;

public String getValor1() {
return valor1;
}

public void setValor1(String valor1) {
this.valor1 = valor1;
}
}
#########################################################################
public class Teste2 {

public String valor1;

public String getValor1() {
return valor1;
}

public void setValor1(String valor1) {
this.valor1 = valor1;
}

}

#########################################################################


import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class GenericTest {

public static void main(String[] args) {

Teste1 t1 = new Teste1();
t1.setValor1("valor1");

Teste2 t2 = new Teste2();
t2.setValor1("valor2");

System.out.println(testeMetodo(t1, Teste1.class));
System.out.println(testeMetodo(t2, Teste2.class));
}
public static String testeMetodo(Object objecInstance, Class<?> clazz) {
String retorno = "";
try {
Method metodo = clazz.getMethod("getValor1");
retorno = (String) metodo.invoke(objecInstance, null);

} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retorno;
}

}

sábado, 20 de outubro de 2018

how to check if attribute has '@notNull' annotation dynamic

This solution was used in a java project with String jdbcTemplate following the idea of @NotNull JPA Annotation to check ScreenMapper from Controller and @All attributes need to have the same name column in Database.


public Boolean validationRequiredFieldsInMapper(Class<?> clazz, final Map<String, Object> screenFieldMap) {
Boolean isError = false;

Object objValue = null;
Field field = null;
String strValue = "";
for (String column : screenFieldMap.keySet()) {
field = clazz.getDeclaredField(column);
if (field != null) {
if (field.isAnnotationPresent(NotNull.class)) {
objValue = screenFieldMap.get(column);
strValue = (String) objValue;
if (StringUtils.isBlank(strValue)) {
isError = true;
break;
}
}
}
}
}

Class:

@NotNull
private Integer sap;
@NotNull
private String address;
@NotNull
private Date dateRegister;

Map: 

@RequestMapping(value="examplecontroller", method=RequestMethod.POST)
public @ResponseBody ReturnObject setData(
@RequestParam(value="sap",required= true ) String sap,
@RequestParam(value="address", required= true) String address,
@RequestParam(value="dateRegister", required= true) String dateRegister,

Map<String,Object> screenFieldMap = new HashMap<String,Object>();
screenFieldMap.put("sap",sap);
screenFieldMap.put("address",address);
screenFieldMap.put("dateRegister",dateRegister);




sexta-feira, 28 de setembro de 2018

Return Generic Type with jdbcTemplate.queryForObject - Generic Dao with jdbcTemplate


public Class TestClass  implements Serializable{
private int id;
private Usuario usuario;
private Date      data_hora;
private Fila id_fila;
private Integer sap;
...
 //omitted getter and setters  }

##################################################################

Method getObjectByID:

public <T> T getObjectByID(Class<? extends T> classe, String tableName, Integer id){

Object response= null;

try{
StringBuffer sql = new StringBuffer();
                        sql.append("SELECT * FROM );
                        sql.append(tableName);
                        sql.append(" WHERE ID = ?");

                        Object[] parametros = new Object[] {id};

response= jdbcTemplate.queryForObject(sql.toString(),parametros, new GenericRowMapper(classe));

}catch(Exception ex){
LOGGER.error("Error "+ex.getMessage(), ex);
}
return (T) response;
}
}

##################################################################
Class GenericRowMapper:

public class GenericRowMapper<T> implements RowMapper<T> {

  private Class<T> mappedClass;

  public GenericRowMapper(Class<T> mappedClass) {
    this.mappedClass = mappedClass;
  }

  @Override
  public T mapRow(ResultSet rs, int rowNum) throws SQLException {

    T mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);

    bw.setAutoGrowNestedPaths(true);

    ResultSetMetaData meta_data = rs.getMetaData();
    int columnCount = meta_data.getColumnCount();

    for (int index = 1; index <= columnCount; index++) {

      try {

        String column = JdbcUtils.lookupColumnName(meta_data, index);
        Object value = JdbcUtils.getResultSetValue(rs, index, Class.forName(meta_data.getColumnClassName(index)));

        bw.setPropertyValue(column, value);

      } catch (TypeMismatchException | NotWritablePropertyException | ClassNotFoundException e) {
         // Ignore
      }
    }

    return mappedObject;
  }
}

##################################################################
search --->
TestClass  testClass  =  (TestClass ) genericDAO.getObjectByID(TestClass.class,"TableName",1);

#######################################################

Method  getListByStatus :

public <T> List<T> getListByStatus(Class<? extends T> classe, String tableName, String status) {
Object response = null;
try{
sql.append("SELECT * FROM );
                        sql.append(tableName);
                        sql.append(" WHERE status = ?");

                       response = jdbcTemplate.query(sql.toString(), new GenericRowMapper<T>((Class<T>) classe));

}catch(Exception ex){
LOGGER.error("Error "+ex.getMessage(), ex);
}
return (List<T>) response;
}

#######################################################

search:
List<TestClass> testList  =  (List<TestClass>) genericDAO.getListByStatus(TestClass.class,"TableName", StatusEnum.cancel);




quinta-feira, 13 de setembro de 2018

Validação com regular expression



import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

public class Blp01_41Validator extends AbstractValidator{


//CONSTANT for : Beginning method is validate
private static final String  C_BEGINNING_METHOD_IS_VALIDATE = "Beginning method is validate";
//CONSTANT for : Validation of the
private static final String  C_VALIDATION_OF_THE = "Validation of the ";
//CONSTANT for :  field with the RegularExpressionValidator validator.
private static final String  C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR = " field with the RegularExpressionValidator validator.";
//CONSTANT for : (null)|(\\d{0,4})
private static final String  C_NULL_D_0_4 = "(null)|(\\d{0,4})";
//CONSTANT for : [SN]
private static final String  C_SN = "[SN]";  //1 letra dentro desse conjunto
//CONSTANT for : [A-Z]{2}
private static final String  C_A_Z_2 = "[A-Z]{2}"; //2 letras de A à Z
//CONSTANT for : \\d{3,11}
private static final String  C_D_3_11 = "\\d{3,11}"; //valor decima (minimo 3 e no máx 11 digitos)
//CONSTANT for : (null)|(\\d{0,9})
private static final String  C_NULL_D_0_9 = "(null)|(\\d{0,9})"; //valor decimal não obrigatorio com no máx 9 digitos
//CONSTANT for : (null)|(\\d{2,8})
private static final String  C_NULL_D_2_8 = "(null)|(\\d{2,8})"; //valor decimal não obrigatorio com no minumo 2 e no máx 8 digitos
//CONSTANT for : (null)|(1)|(2)|(3)|(4)|(5)|(6)|(7)|(8)|(9)|(10)|(11)|(12)|(13)|(14)|(15)|(16)
private static final String  C_NULL_1_2_3_4_5_6_7_8_9_10_11_12_13_14_15_16 = "(null)|(1)|(2)|(3)|(4)|(5)|(6)|(7)|(8)|(9)|(10)|(11)|(12)|(13)|(14)|(15)|(16)"; //nao obrigatorio com um valor de 1 à 16.
//CONSTANT for : \\d{7,8}
private static final String  C_D_7_8 = "\\d{7,8}";
//CONSTANT for : [MF]
private static final String  C_MF = "[MF]"; //
//CONSTANT for : \\d{4,8}
private static final String  C_D_4_8 = "\\d{4,8}";
//CONSTANT for : (1)|(2)|(3)
private static final String  C_1_2_3 = "(1)|(2)|(3)";
//CONSTANT for : \\d{2,7}
private static final String  C_D_2_7 = "\\d{2,7}";
//CONSTANT for : \\d{1,10}
private static final String  C_D_1_10 = "\\d{1,10}";
//CONSTANT for : \\d{2,8}
private static final String  C_D_2_8 = "\\d{2,8}";
//CONSTANT for : Ending method validate the form
private static final String  C_ENDING_METHOD_VALIDATE_THE_FORM = "Ending method validate the form";

// LOGGER for the class Blp01_41Validator
private static final Logger LOGGER = Logger.getLogger( Blp01_41Validator.class);

/**
* Operation validate for Blp01_41Form
* @param obj : the current form (Blp01_41Form)
* @param errors : The spring errors to return for the form Blp01_41Form
*/
public void validate(final Object obj,final Errors errors){
if (LOGGER.isInfoEnabled()) {
// For : Blp01_41Validator
LOGGER.info(C_BEGINNING_METHOD_IS_VALIDATE);
}
Blp01_41Form cBlp01_41Form = (Blp01_41Form)obj;

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinmMunRed", "", "Municipio: NAO INFORMADO");

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinuTelDddRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuTelDddRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuTelDddRed()),C_NULL_D_0_4)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinuTelDddRed", "", "DDD: formato inválido");
}

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oTlaConfRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oTlaConfRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oTlaConfRed()),C_SN)== 0 ){
errors.rejectValue("inputScreen.pt41oTlaConfRed", "", "Confirmação: FORA DE FAIXA");
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinmSiglaUfRed", "", "UF: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqinmSiglaUfRed")== null){

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinmSiglaUfRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinmSiglaUfRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinmSiglaUfRed()),C_A_Z_2)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinmSiglaUfRed", "", "UF: FORA DE FAIXA");
}
}

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oJornadaRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oJornadaRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oJornadaRed()),C_SN)== 0 ){
errors.rejectValue("inputScreen.pt41oJornadaRed", "", "Dupla Jornada: FORA DE FAIXA");
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinmBairroRed", "", "Bairro: NAO INFORMADO");

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinuCpf1Red", "", "CPF: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqinuCpf1Red")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinuCpf1Red"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuCpf1Red())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuCpf1Red()),C_D_3_11)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinuCpf1Red", "", "CPF: formato inválido");
}
}

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinuTelRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuTelRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuTelRed()),C_NULL_D_0_9)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinuTelRed", "", "Telefone: FORMATO INVÁLIDO");
}

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqiidOlSegundaJornadaRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqiidOlSegundaJornadaRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqiidOlSegundaJornadaRed()),C_NULL_D_2_8)== 0 ){
errors.rejectValue("inputScreen.pt41oMqiidOlSegundaJornadaRed", "", "OL da Segunda Jornada: formato inválido");
}

if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41onmEspecialidadeRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41onmEspecialidadeRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41onmEspecialidadeRed()),C_NULL_1_2_3_4_5_6_7_8_9_10_11_12_13_14_15_16)== 0 ){
errors.rejectValue("inputScreen.pt41onmEspecialidadeRed", "", "Especialidade: FORA DE FAIXA");
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqiteEndRed", "", "Endereco: NAO INFORMADO");

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqid2AdmissRed", "", "Data de Admissao no : NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqid2AdmissRed")== null){


if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqid2AdmissRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqid2AdmissRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqid2AdmissRed()),C_D_7_8)== 0 ){
errors.rejectValue("inputScreen.pt41oMqid2AdmissRed", "", "Data de Admissao no : formato inválido");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oTipoSexoRed", "", "Sexo: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oTipoSexoRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oTipoSexoRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oTipoSexoRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oTipoSexoRed()),C_MF)== 0 ){
errors.rejectValue("inputScreen.pt41oTipoSexoRed", "", "Sexo: FORA DE FAIXA");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinuCepRed", "", "CEP: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqinuCepRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinuCepRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuCepRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuCepRed()),C_D_4_8)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinuCepRed", "", "CEP: formato inválido");
}
}




if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oHomologaRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oHomologaRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oHomologaRed()),C_SN)== 0 ){
errors.rejectValue("inputScreen.pt41oHomologaRed", "", "Apto a Homologacao: FORA DE FAIXA");
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqidtNascRed", "", "Data de Nascimento: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqidtNascRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqidtNascRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqidtNascRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqidtNascRed()),C_D_7_8)== 0 ){
errors.rejectValue("inputScreen.pt41oMqidtNascRed", "", "Data de Nascimento: formato inválido");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqicsFuncaoRed", "", "Funcao: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqicsFuncaoRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqicsFuncaoRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqicsFuncaoRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqicsFuncaoRed()),C_1_2_3)== 0 ){
errors.rejectValue("inputScreen.pt41oMqicsFuncaoRed", "", "Funcao: FORA DE FAIXA");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinum Red", "", "Numero Matricula  : NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqinum Red")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinum Red"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinum Red())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinum Red()),C_D_2_7)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinum Red", "", "Numero Matricula  : formato inválido");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqinuInsCrmRed", "", "Numero ICRM: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqinuInsCrmRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqinuInsCrmRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuInsCrmRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqinuInsCrmRed()),C_D_1_10)== 0 ){
errors.rejectValue("inputScreen.pt41oMqinuInsCrmRed", "", "Numero ICRM: formato inválido");
}
}

     ValidationUtils.rejectIfEmpty(errors, "inputScreen.pt41oMqiIdOlRed", "", "OL: NAO INFORMADO");
if(errors.getFieldError("inputScreen.pt41oMqiIdOlRed")== null){



if(LOGGER.isDebugEnabled()){
LOGGER.debug(C_VALIDATION_OF_THE+"inputScreen.pt41oMqiIdOlRed"+C_FIELD_WITH_THE_REGULAREXPRESSIONVALIDATOR_VALIDATOR);
}

if(StringUtils.isNotBlank(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqiIdOlRed())) && ValidatorsUtil.regularExpressionValidator(String.valueOf(cBlp01_41Form.getInputScreen().getPt41oMqiIdOlRed()),C_D_2_8)== 0 ){
errors.rejectValue("inputScreen.pt41oMqiIdOlRed", "", "OL: formato inválido");
}
}
}

}
}